diff --git a/.gitignore b/.gitignore index a98ae2b44c3..c8d84b8c554 100644 --- a/.gitignore +++ b/.gitignore @@ -47,6 +47,7 @@ Thumbs.db /test/data/ch /test/data/mld /cmake/postinst +.gradle/ # Eclipse related files # ######################### diff --git a/CHANGELOG.md b/CHANGELOG.md index ded7286cbb8..9f713133f32 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,6 +1,7 @@ # Unreleased - Changes from 6.0.0 - Misc: + - CHANGED: Upgrade FlatBuffers from 24.3.25 to 25.2.10 [#7235](https://github.com/Project-OSRM/osrm-backend/pull/7235) - ADDED: Add husky pre-commit hook for compiling and linting staged JS files [#7228](https://github.com/Project-OSRM/osrm-backend/issues/7228) - CHANGED: Standardize linting configuration with ESM-specific rules [#7229](https://github.com/Project-OSRM/osrm-backend/issues/7229) - CHANGED: Convert scripts from CommonJS to modern ESM format [#7230](https://github.com/Project-OSRM/osrm-backend/pull/7230) diff --git a/features/support/fbresult_generated.js b/features/support/fbresult_generated.js index 37ea76215a5..d2d20e986ef 100644 --- a/features/support/fbresult_generated.js +++ b/features/support/fbresult_generated.js @@ -1,10 +1,13 @@ // automatically generated by the FlatBuffers compiler, do not modify +// JavaScript compatibility wrapper for FlatBuffers v25.2.10 + +import * as fb from './osrm/engine/api/fbresult.js'; /** * @const * @namespace */ -var osrm = osrm || {}; +const osrm = osrm || {}; /** * @const @@ -24,3948 +27,22 @@ osrm.engine.api = osrm.engine.api || {}; */ osrm.engine.api.fbresult = osrm.engine.api.fbresult || {}; -/** - * @enum {number} - */ -osrm.engine.api.fbresult.ManeuverType = { - Turn: 0, - NewName: 1, - Depart: 2, - Arrive: 3, - Merge: 4, - OnRamp: 5, - OffRamp: 6, - Fork: 7, - EndOfRoad: 8, - Continue: 9, - Roundabout: 10, - Rotary: 11, - RoundaboutTurn: 12, - Notification: 13, - ExitRoundabout: 14, - ExitRotary: 15, -}; - -/** - * @enum {string} - */ -osrm.engine.api.fbresult.ManeuverTypeName = { - 0: 'Turn', - 1: 'NewName', - 2: 'Depart', - 3: 'Arrive', - 4: 'Merge', - 5: 'OnRamp', - 6: 'OffRamp', - 7: 'Fork', - 8: 'EndOfRoad', - 9: 'Continue', - 10: 'Roundabout', - 11: 'Rotary', - 12: 'RoundaboutTurn', - 13: 'Notification', - 14: 'ExitRoundabout', - 15: 'ExitRotary', -}; - -/** - * @enum {number} - */ -osrm.engine.api.fbresult.Turn = { - None: 0, - UTurn: 1, - SharpRight: 2, - Right: 3, - SlightRight: 4, - Straight: 5, - SlightLeft: 6, - Left: 7, - SharpLeft: 8, -}; - -/** - * @enum {string} - */ -osrm.engine.api.fbresult.TurnName = { - 0: 'None', - 1: 'UTurn', - 2: 'SharpRight', - 3: 'Right', - 4: 'SlightRight', - 5: 'Straight', - 6: 'SlightLeft', - 7: 'Left', - 8: 'SharpLeft', -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Position = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Position} - */ -osrm.engine.api.fbresult.Position.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Position.prototype.longitude = function () { - return this.bb.readFloat32(this.bb_pos); -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Position.prototype.latitude = function () { - return this.bb.readFloat32(this.bb_pos + 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} longitude - * @param {number} latitude - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Position.createPosition = function ( - builder, - longitude, - latitude, -) { - builder.prep(4, 8); - builder.writeFloat32(latitude); - builder.writeFloat32(longitude); - return builder.offset(); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Uint64Pair = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Uint64Pair} - */ -osrm.engine.api.fbresult.Uint64Pair.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @returns {flatbuffers.Long} - */ -osrm.engine.api.fbresult.Uint64Pair.prototype.first = function () { - return this.bb.readUint64(this.bb_pos); -}; - -/** - * @returns {flatbuffers.Long} - */ -osrm.engine.api.fbresult.Uint64Pair.prototype.second = function () { - return this.bb.readUint64(this.bb_pos + 8); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Long} first - * @param {flatbuffers.Long} second - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Uint64Pair.createUint64Pair = function ( - builder, - first, - second, -) { - builder.prep(8, 16); - builder.writeInt64(second); - builder.writeInt64(first); - return builder.offset(); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Waypoint = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Waypoint} - */ -osrm.engine.api.fbresult.Waypoint.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Waypoint=} obj - * @returns {osrm.engine.api.fbresult.Waypoint} - */ -osrm.engine.api.fbresult.Waypoint.getRootAsWaypoint = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Waypoint()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Waypoint=} obj - * @returns {osrm.engine.api.fbresult.Waypoint} - */ -osrm.engine.api.fbresult.Waypoint.getSizePrefixedRootAsWaypoint = function ( - bb, - obj, -) { - return (obj || new osrm.engine.api.fbresult.Waypoint()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Waypoint.prototype.hint = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Waypoint.prototype.distance = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Waypoint.prototype.name = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {osrm.engine.api.fbresult.Position=} obj - * @returns {osrm.engine.api.fbresult.Position|null} - */ -osrm.engine.api.fbresult.Waypoint.prototype.location = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? (obj || new osrm.engine.api.fbresult.Position()).__init( - this.bb_pos + offset, - this.bb, - ) - : null; -}; - -/** - * @param {osrm.engine.api.fbresult.Uint64Pair=} obj - * @returns {osrm.engine.api.fbresult.Uint64Pair|null} - */ -osrm.engine.api.fbresult.Waypoint.prototype.nodes = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? (obj || new osrm.engine.api.fbresult.Uint64Pair()).__init( - this.bb_pos + offset, - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Waypoint.prototype.matchingsIndex = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Waypoint.prototype.waypointIndex = function () { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Waypoint.prototype.alternativesCount = function () { - const offset = this.bb.__offset(this.bb_pos, 18); - return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Waypoint.prototype.tripsIndex = function () { - const offset = this.bb.__offset(this.bb_pos, 20); - return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Waypoint.startWaypoint = function (builder) { - builder.startObject(9); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} hintOffset - */ -osrm.engine.api.fbresult.Waypoint.addHint = function (builder, hintOffset) { - builder.addFieldOffset(0, hintOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - */ -osrm.engine.api.fbresult.Waypoint.addDistance = function (builder, distance) { - builder.addFieldFloat32(1, distance, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} nameOffset - */ -osrm.engine.api.fbresult.Waypoint.addName = function (builder, nameOffset) { - builder.addFieldOffset(2, nameOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} locationOffset - */ -osrm.engine.api.fbresult.Waypoint.addLocation = function ( - builder, - locationOffset, -) { - builder.addFieldStruct(3, locationOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} nodesOffset - */ -osrm.engine.api.fbresult.Waypoint.addNodes = function (builder, nodesOffset) { - builder.addFieldStruct(4, nodesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} matchingsIndex - */ -osrm.engine.api.fbresult.Waypoint.addMatchingsIndex = function ( - builder, - matchingsIndex, -) { - builder.addFieldInt32(5, matchingsIndex, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} waypointIndex - */ -osrm.engine.api.fbresult.Waypoint.addWaypointIndex = function ( - builder, - waypointIndex, -) { - builder.addFieldInt32(6, waypointIndex, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} alternativesCount - */ -osrm.engine.api.fbresult.Waypoint.addAlternativesCount = function ( - builder, - alternativesCount, -) { - builder.addFieldInt32(7, alternativesCount, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} tripsIndex - */ -osrm.engine.api.fbresult.Waypoint.addTripsIndex = function ( - builder, - tripsIndex, -) { - builder.addFieldInt32(8, tripsIndex, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Waypoint.endWaypoint = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} hintOffset - * @param {number} distance - * @param {flatbuffers.Offset} nameOffset - * @param {flatbuffers.Offset} locationOffset - * @param {flatbuffers.Offset} nodesOffset - * @param {number} matchingsIndex - * @param {number} waypointIndex - * @param {number} alternativesCount - * @param {number} tripsIndex - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Waypoint.createWaypoint = function ( - builder, - hintOffset, - distance, - nameOffset, - locationOffset, - nodesOffset, - matchingsIndex, - waypointIndex, - alternativesCount, - tripsIndex, -) { - osrm.engine.api.fbresult.Waypoint.startWaypoint(builder); - osrm.engine.api.fbresult.Waypoint.addHint(builder, hintOffset); - osrm.engine.api.fbresult.Waypoint.addDistance(builder, distance); - osrm.engine.api.fbresult.Waypoint.addName(builder, nameOffset); - osrm.engine.api.fbresult.Waypoint.addLocation(builder, locationOffset); - osrm.engine.api.fbresult.Waypoint.addNodes(builder, nodesOffset); - osrm.engine.api.fbresult.Waypoint.addMatchingsIndex(builder, matchingsIndex); - osrm.engine.api.fbresult.Waypoint.addWaypointIndex(builder, waypointIndex); - osrm.engine.api.fbresult.Waypoint.addAlternativesCount( - builder, - alternativesCount, - ); - osrm.engine.api.fbresult.Waypoint.addTripsIndex(builder, tripsIndex); - return osrm.engine.api.fbresult.Waypoint.endWaypoint(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Metadata = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Metadata} - */ -osrm.engine.api.fbresult.Metadata.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Metadata=} obj - * @returns {osrm.engine.api.fbresult.Metadata} - */ -osrm.engine.api.fbresult.Metadata.getRootAsMetadata = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Metadata()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Metadata=} obj - * @returns {osrm.engine.api.fbresult.Metadata} - */ -osrm.engine.api.fbresult.Metadata.getSizePrefixedRootAsMetadata = function ( - bb, - obj, -) { - return (obj || new osrm.engine.api.fbresult.Metadata()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {number} index - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array} - */ -osrm.engine.api.fbresult.Metadata.prototype.datasourceNames = function ( - index, - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? this.bb.__string( - this.bb.__vector(this.bb_pos + offset) + index * 4, - optionalEncoding, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Metadata.prototype.datasourceNamesLength = - function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; - }; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Metadata.startMetadata = function (builder) { - builder.startObject(1); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} datasourceNamesOffset - */ -osrm.engine.api.fbresult.Metadata.addDatasourceNames = function ( - builder, - datasourceNamesOffset, -) { - builder.addFieldOffset(0, datasourceNamesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Metadata.createDatasourceNamesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Metadata.startDatasourceNamesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Metadata.endMetadata = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} datasourceNamesOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Metadata.createMetadata = function ( - builder, - datasourceNamesOffset, -) { - osrm.engine.api.fbresult.Metadata.startMetadata(builder); - osrm.engine.api.fbresult.Metadata.addDatasourceNames( - builder, - datasourceNamesOffset, - ); - return osrm.engine.api.fbresult.Metadata.endMetadata(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Annotation = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Annotation} - */ -osrm.engine.api.fbresult.Annotation.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Annotation=} obj - * @returns {osrm.engine.api.fbresult.Annotation} - */ -osrm.engine.api.fbresult.Annotation.getRootAsAnnotation = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Annotation()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Annotation=} obj - * @returns {osrm.engine.api.fbresult.Annotation} - */ -osrm.engine.api.fbresult.Annotation.getSizePrefixedRootAsAnnotation = function ( - bb, - obj, -) { - return (obj || new osrm.engine.api.fbresult.Annotation()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.distance = function (index) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.distanceLength = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Uint32Array} - */ -osrm.engine.api.fbresult.Annotation.prototype.distanceArray = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.duration = function (index) { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset - ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.durationLength = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Uint32Array} - */ -osrm.engine.api.fbresult.Annotation.prototype.durationArray = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.datasources = function (index) { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset - ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.datasourcesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Uint32Array} - */ -osrm.engine.api.fbresult.Annotation.prototype.datasourcesArray = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.nodes = function (index) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.nodesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Uint32Array} - */ -osrm.engine.api.fbresult.Annotation.prototype.nodesArray = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.weight = function (index) { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.weightLength = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Uint32Array} - */ -osrm.engine.api.fbresult.Annotation.prototype.weightArray = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.speed = function (index) { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Annotation.prototype.speedLength = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Float32Array} - */ -osrm.engine.api.fbresult.Annotation.prototype.speedArray = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? new Float32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {osrm.engine.api.fbresult.Metadata=} obj - * @returns {osrm.engine.api.fbresult.Metadata|null} - */ -osrm.engine.api.fbresult.Annotation.prototype.metadata = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset - ? (obj || new osrm.engine.api.fbresult.Metadata()).__init( - this.bb.__indirect(this.bb_pos + offset), - this.bb, - ) - : null; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Annotation.startAnnotation = function (builder) { - builder.startObject(7); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} distanceOffset - */ -osrm.engine.api.fbresult.Annotation.addDistance = function ( - builder, - distanceOffset, -) { - builder.addFieldOffset(0, distanceOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createDistanceVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Annotation.startDistanceVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} durationOffset - */ -osrm.engine.api.fbresult.Annotation.addDuration = function ( - builder, - durationOffset, -) { - builder.addFieldOffset(1, durationOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createDurationVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Annotation.startDurationVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} datasourcesOffset - */ -osrm.engine.api.fbresult.Annotation.addDatasources = function ( - builder, - datasourcesOffset, -) { - builder.addFieldOffset(2, datasourcesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createDatasourcesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Annotation.startDatasourcesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} nodesOffset - */ -osrm.engine.api.fbresult.Annotation.addNodes = function (builder, nodesOffset) { - builder.addFieldOffset(3, nodesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createNodesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Annotation.startNodesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} weightOffset - */ -osrm.engine.api.fbresult.Annotation.addWeight = function ( - builder, - weightOffset, -) { - builder.addFieldOffset(4, weightOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createWeightVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Annotation.startWeightVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} speedOffset - */ -osrm.engine.api.fbresult.Annotation.addSpeed = function (builder, speedOffset) { - builder.addFieldOffset(5, speedOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createSpeedVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addFloat32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Annotation.startSpeedVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} metadataOffset - */ -osrm.engine.api.fbresult.Annotation.addMetadata = function ( - builder, - metadataOffset, -) { - builder.addFieldOffset(6, metadataOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.endAnnotation = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} distanceOffset - * @param {flatbuffers.Offset} durationOffset - * @param {flatbuffers.Offset} datasourcesOffset - * @param {flatbuffers.Offset} nodesOffset - * @param {flatbuffers.Offset} weightOffset - * @param {flatbuffers.Offset} speedOffset - * @param {flatbuffers.Offset} metadataOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Annotation.createAnnotation = function ( - builder, - distanceOffset, - durationOffset, - datasourcesOffset, - nodesOffset, - weightOffset, - speedOffset, - metadataOffset, -) { - osrm.engine.api.fbresult.Annotation.startAnnotation(builder); - osrm.engine.api.fbresult.Annotation.addDistance(builder, distanceOffset); - osrm.engine.api.fbresult.Annotation.addDuration(builder, durationOffset); - osrm.engine.api.fbresult.Annotation.addDatasources( - builder, - datasourcesOffset, - ); - osrm.engine.api.fbresult.Annotation.addNodes(builder, nodesOffset); - osrm.engine.api.fbresult.Annotation.addWeight(builder, weightOffset); - osrm.engine.api.fbresult.Annotation.addSpeed(builder, speedOffset); - osrm.engine.api.fbresult.Annotation.addMetadata(builder, metadataOffset); - return osrm.engine.api.fbresult.Annotation.endAnnotation(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.StepManeuver = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.StepManeuver} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.StepManeuver=} obj - * @returns {osrm.engine.api.fbresult.StepManeuver} - */ -osrm.engine.api.fbresult.StepManeuver.getRootAsStepManeuver = function ( - bb, - obj, -) { - return (obj || new osrm.engine.api.fbresult.StepManeuver()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.StepManeuver=} obj - * @returns {osrm.engine.api.fbresult.StepManeuver} - */ -osrm.engine.api.fbresult.StepManeuver.getSizePrefixedRootAsStepManeuver = - function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.StepManeuver()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); - }; - -/** - * @param {osrm.engine.api.fbresult.Position=} obj - * @returns {osrm.engine.api.fbresult.Position|null} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.location = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? (obj || new osrm.engine.api.fbresult.Position()).__init( - this.bb_pos + offset, - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.bearingBefore = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.bearingAfter = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; -}; - -/** - * @returns {osrm.engine.api.fbresult.ManeuverType} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.type = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? /** @type {osrm.engine.api.fbresult.ManeuverType} */ ( - this.bb.readInt8(this.bb_pos + offset) - ) - : osrm.engine.api.fbresult.ManeuverType.Turn; -}; - -/** - * @returns {osrm.engine.api.fbresult.Turn} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.modifier = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? /** @type {osrm.engine.api.fbresult.Turn} */ ( - this.bb.readInt8(this.bb_pos + offset) - ) - : osrm.engine.api.fbresult.Turn.None; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.StepManeuver.prototype.exit = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset ? this.bb.readUint8(this.bb_pos + offset) : 0; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.StepManeuver.startStepManeuver = function (builder) { - builder.startObject(6); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} locationOffset - */ -osrm.engine.api.fbresult.StepManeuver.addLocation = function ( - builder, - locationOffset, -) { - builder.addFieldStruct(0, locationOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} bearingBefore - */ -osrm.engine.api.fbresult.StepManeuver.addBearingBefore = function ( - builder, - bearingBefore, -) { - builder.addFieldInt16(1, bearingBefore, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} bearingAfter - */ -osrm.engine.api.fbresult.StepManeuver.addBearingAfter = function ( - builder, - bearingAfter, -) { - builder.addFieldInt16(2, bearingAfter, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {osrm.engine.api.fbresult.ManeuverType} type - */ -osrm.engine.api.fbresult.StepManeuver.addType = function (builder, type) { - builder.addFieldInt8(3, type, osrm.engine.api.fbresult.ManeuverType.Turn); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {osrm.engine.api.fbresult.Turn} modifier - */ -osrm.engine.api.fbresult.StepManeuver.addModifier = function ( - builder, - modifier, -) { - builder.addFieldInt8(4, modifier, osrm.engine.api.fbresult.Turn.None); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} exit - */ -osrm.engine.api.fbresult.StepManeuver.addExit = function (builder, exit) { - builder.addFieldInt8(5, exit, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.StepManeuver.endStepManeuver = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} locationOffset - * @param {number} bearingBefore - * @param {number} bearingAfter - * @param {osrm.engine.api.fbresult.ManeuverType} type - * @param {osrm.engine.api.fbresult.Turn} modifier - * @param {number} exit - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.StepManeuver.createStepManeuver = function ( - builder, - locationOffset, - bearingBefore, - bearingAfter, - type, - modifier, - exit, -) { - osrm.engine.api.fbresult.StepManeuver.startStepManeuver(builder); - osrm.engine.api.fbresult.StepManeuver.addLocation(builder, locationOffset); - osrm.engine.api.fbresult.StepManeuver.addBearingBefore( - builder, - bearingBefore, - ); - osrm.engine.api.fbresult.StepManeuver.addBearingAfter(builder, bearingAfter); - osrm.engine.api.fbresult.StepManeuver.addType(builder, type); - osrm.engine.api.fbresult.StepManeuver.addModifier(builder, modifier); - osrm.engine.api.fbresult.StepManeuver.addExit(builder, exit); - return osrm.engine.api.fbresult.StepManeuver.endStepManeuver(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Lane = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Lane} - */ -osrm.engine.api.fbresult.Lane.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Lane=} obj - * @returns {osrm.engine.api.fbresult.Lane} - */ -osrm.engine.api.fbresult.Lane.getRootAsLane = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Lane()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Lane=} obj - * @returns {osrm.engine.api.fbresult.Lane} - */ -osrm.engine.api.fbresult.Lane.getSizePrefixedRootAsLane = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Lane()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {number} index - * @returns {osrm.engine.api.fbresult.Turn} - */ -osrm.engine.api.fbresult.Lane.prototype.indications = function (index) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? /** @type {osrm.engine.api.fbresult.Turn} */ ( - this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) - ) - : /** @type {osrm.engine.api.fbresult.Turn} */ (0); -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Lane.prototype.indicationsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Int8Array} - */ -osrm.engine.api.fbresult.Lane.prototype.indicationsArray = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? new Int8Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @returns {boolean} - */ -osrm.engine.api.fbresult.Lane.prototype.valid = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Lane.startLane = function (builder) { - builder.startObject(2); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} indicationsOffset - */ -osrm.engine.api.fbresult.Lane.addIndications = function ( - builder, - indicationsOffset, -) { - builder.addFieldOffset(0, indicationsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Lane.createIndicationsVector = function ( - builder, - data, -) { - builder.startVector(1, data.length, 1); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt8(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Lane.startIndicationsVector = function ( - builder, - numElems, -) { - builder.startVector(1, numElems, 1); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {boolean} valid - */ -osrm.engine.api.fbresult.Lane.addValid = function (builder, valid) { - builder.addFieldInt8(1, +valid, +false); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Lane.endLane = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} indicationsOffset - * @param {boolean} valid - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Lane.createLane = function ( - builder, - indicationsOffset, - valid, -) { - osrm.engine.api.fbresult.Lane.startLane(builder); - osrm.engine.api.fbresult.Lane.addIndications(builder, indicationsOffset); - osrm.engine.api.fbresult.Lane.addValid(builder, valid); - return osrm.engine.api.fbresult.Lane.endLane(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Intersection = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Intersection} - */ -osrm.engine.api.fbresult.Intersection.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Intersection=} obj - * @returns {osrm.engine.api.fbresult.Intersection} - */ -osrm.engine.api.fbresult.Intersection.getRootAsIntersection = function ( - bb, - obj, -) { - return (obj || new osrm.engine.api.fbresult.Intersection()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Intersection=} obj - * @returns {osrm.engine.api.fbresult.Intersection} - */ -osrm.engine.api.fbresult.Intersection.getSizePrefixedRootAsIntersection = - function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Intersection()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); - }; - -/** - * @param {osrm.engine.api.fbresult.Position=} obj - * @returns {osrm.engine.api.fbresult.Position|null} - */ -osrm.engine.api.fbresult.Intersection.prototype.location = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? (obj || new osrm.engine.api.fbresult.Position()).__init( - this.bb_pos + offset, - this.bb, - ) - : null; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.bearings = function (index) { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset - ? this.bb.readInt16(this.bb.__vector(this.bb_pos + offset) + index * 2) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.bearingsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Int16Array} - */ -osrm.engine.api.fbresult.Intersection.prototype.bearingsArray = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset - ? new Int16Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array} - */ -osrm.engine.api.fbresult.Intersection.prototype.classes = function ( - index, - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset - ? this.bb.__string( - this.bb.__vector(this.bb_pos + offset) + index * 4, - optionalEncoding, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.classesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {number} index - * @returns {boolean} - */ -osrm.engine.api.fbresult.Intersection.prototype.entry = function (index) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? !!this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) - : false; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.entryLength = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Int8Array} - */ -osrm.engine.api.fbresult.Intersection.prototype.entryArray = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? new Int8Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.inBearing = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.outBearing = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Lane=} obj - * @returns {osrm.engine.api.fbresult.Lane} - */ -osrm.engine.api.fbresult.Intersection.prototype.lanes = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset - ? (obj || new osrm.engine.api.fbresult.Lane()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Intersection.prototype.lanesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Intersection.startIntersection = function (builder) { - builder.startObject(7); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} locationOffset - */ -osrm.engine.api.fbresult.Intersection.addLocation = function ( - builder, - locationOffset, -) { - builder.addFieldStruct(0, locationOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} bearingsOffset - */ -osrm.engine.api.fbresult.Intersection.addBearings = function ( - builder, - bearingsOffset, -) { - builder.addFieldOffset(1, bearingsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Intersection.createBearingsVector = function ( - builder, - data, -) { - builder.startVector(2, data.length, 2); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt16(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Intersection.startBearingsVector = function ( - builder, - numElems, -) { - builder.startVector(2, numElems, 2); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} classesOffset - */ -osrm.engine.api.fbresult.Intersection.addClasses = function ( - builder, - classesOffset, -) { - builder.addFieldOffset(2, classesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Intersection.createClassesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Intersection.startClassesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} entryOffset - */ -osrm.engine.api.fbresult.Intersection.addEntry = function ( - builder, - entryOffset, -) { - builder.addFieldOffset(3, entryOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Intersection.createEntryVector = function ( - builder, - data, -) { - builder.startVector(1, data.length, 1); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt8(+data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Intersection.startEntryVector = function ( - builder, - numElems, -) { - builder.startVector(1, numElems, 1); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} inBearing - */ -osrm.engine.api.fbresult.Intersection.addInBearing = function ( - builder, - inBearing, -) { - builder.addFieldInt32(4, inBearing, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} outBearing - */ -osrm.engine.api.fbresult.Intersection.addOutBearing = function ( - builder, - outBearing, -) { - builder.addFieldInt32(5, outBearing, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} lanesOffset - */ -osrm.engine.api.fbresult.Intersection.addLanes = function ( - builder, - lanesOffset, -) { - builder.addFieldOffset(6, lanesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Intersection.createLanesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Intersection.startLanesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Intersection.endIntersection = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} locationOffset - * @param {flatbuffers.Offset} bearingsOffset - * @param {flatbuffers.Offset} classesOffset - * @param {flatbuffers.Offset} entryOffset - * @param {number} inBearing - * @param {number} outBearing - * @param {flatbuffers.Offset} lanesOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Intersection.createIntersection = function ( - builder, - locationOffset, - bearingsOffset, - classesOffset, - entryOffset, - inBearing, - outBearing, - lanesOffset, -) { - osrm.engine.api.fbresult.Intersection.startIntersection(builder); - osrm.engine.api.fbresult.Intersection.addLocation(builder, locationOffset); - osrm.engine.api.fbresult.Intersection.addBearings(builder, bearingsOffset); - osrm.engine.api.fbresult.Intersection.addClasses(builder, classesOffset); - osrm.engine.api.fbresult.Intersection.addEntry(builder, entryOffset); - osrm.engine.api.fbresult.Intersection.addInBearing(builder, inBearing); - osrm.engine.api.fbresult.Intersection.addOutBearing(builder, outBearing); - osrm.engine.api.fbresult.Intersection.addLanes(builder, lanesOffset); - return osrm.engine.api.fbresult.Intersection.endIntersection(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Step = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Step} - */ -osrm.engine.api.fbresult.Step.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Step=} obj - * @returns {osrm.engine.api.fbresult.Step} - */ -osrm.engine.api.fbresult.Step.getRootAsStep = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Step()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Step=} obj - * @returns {osrm.engine.api.fbresult.Step} - */ -osrm.engine.api.fbresult.Step.getSizePrefixedRootAsStep = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Step()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Step.prototype.distance = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Step.prototype.duration = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.polyline = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Position=} obj - * @returns {osrm.engine.api.fbresult.Position} - */ -osrm.engine.api.fbresult.Step.prototype.coordinates = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? (obj || new osrm.engine.api.fbresult.Position()).__init( - this.bb.__vector(this.bb_pos + offset) + index * 8, - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Step.prototype.coordinatesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Step.prototype.weight = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.name = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.ref = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.pronunciation = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 18); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.destinations = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 20); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.exits = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 22); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.mode = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 24); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {osrm.engine.api.fbresult.StepManeuver=} obj - * @returns {osrm.engine.api.fbresult.StepManeuver|null} - */ -osrm.engine.api.fbresult.Step.prototype.maneuver = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 26); - return offset - ? (obj || new osrm.engine.api.fbresult.StepManeuver()).__init( - this.bb.__indirect(this.bb_pos + offset), - this.bb, - ) - : null; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Intersection=} obj - * @returns {osrm.engine.api.fbresult.Intersection} - */ -osrm.engine.api.fbresult.Step.prototype.intersections = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 28); - return offset - ? (obj || new osrm.engine.api.fbresult.Intersection()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Step.prototype.intersectionsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 28); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.rotaryName = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 30); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Step.prototype.rotaryPronunciation = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 32); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @returns {boolean} - */ -osrm.engine.api.fbresult.Step.prototype.drivingSide = function () { - const offset = this.bb.__offset(this.bb_pos, 34); - return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Step.startStep = function (builder) { - builder.startObject(16); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - */ -osrm.engine.api.fbresult.Step.addDistance = function (builder, distance) { - builder.addFieldFloat32(0, distance, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} duration - */ -osrm.engine.api.fbresult.Step.addDuration = function (builder, duration) { - builder.addFieldFloat32(1, duration, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} polylineOffset - */ -osrm.engine.api.fbresult.Step.addPolyline = function (builder, polylineOffset) { - builder.addFieldOffset(2, polylineOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} coordinatesOffset - */ -osrm.engine.api.fbresult.Step.addCoordinates = function ( - builder, - coordinatesOffset, -) { - builder.addFieldOffset(3, coordinatesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Step.startCoordinatesVector = function ( - builder, - numElems, -) { - builder.startVector(8, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} weight - */ -osrm.engine.api.fbresult.Step.addWeight = function (builder, weight) { - builder.addFieldFloat32(4, weight, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} nameOffset - */ -osrm.engine.api.fbresult.Step.addName = function (builder, nameOffset) { - builder.addFieldOffset(5, nameOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} refOffset - */ -osrm.engine.api.fbresult.Step.addRef = function (builder, refOffset) { - builder.addFieldOffset(6, refOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} pronunciationOffset - */ -osrm.engine.api.fbresult.Step.addPronunciation = function ( - builder, - pronunciationOffset, -) { - builder.addFieldOffset(7, pronunciationOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} destinationsOffset - */ -osrm.engine.api.fbresult.Step.addDestinations = function ( - builder, - destinationsOffset, -) { - builder.addFieldOffset(8, destinationsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} exitsOffset - */ -osrm.engine.api.fbresult.Step.addExits = function (builder, exitsOffset) { - builder.addFieldOffset(9, exitsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} modeOffset - */ -osrm.engine.api.fbresult.Step.addMode = function (builder, modeOffset) { - builder.addFieldOffset(10, modeOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} maneuverOffset - */ -osrm.engine.api.fbresult.Step.addManeuver = function (builder, maneuverOffset) { - builder.addFieldOffset(11, maneuverOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} intersectionsOffset - */ -osrm.engine.api.fbresult.Step.addIntersections = function ( - builder, - intersectionsOffset, -) { - builder.addFieldOffset(12, intersectionsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Step.createIntersectionsVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Step.startIntersectionsVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} rotaryNameOffset - */ -osrm.engine.api.fbresult.Step.addRotaryName = function ( - builder, - rotaryNameOffset, -) { - builder.addFieldOffset(13, rotaryNameOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} rotaryPronunciationOffset - */ -osrm.engine.api.fbresult.Step.addRotaryPronunciation = function ( - builder, - rotaryPronunciationOffset, -) { - builder.addFieldOffset(14, rotaryPronunciationOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {boolean} drivingSide - */ -osrm.engine.api.fbresult.Step.addDrivingSide = function (builder, drivingSide) { - builder.addFieldInt8(15, +drivingSide, +false); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Step.endStep = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - * @param {number} duration - * @param {flatbuffers.Offset} polylineOffset - * @param {flatbuffers.Offset} coordinatesOffset - * @param {number} weight - * @param {flatbuffers.Offset} nameOffset - * @param {flatbuffers.Offset} refOffset - * @param {flatbuffers.Offset} pronunciationOffset - * @param {flatbuffers.Offset} destinationsOffset - * @param {flatbuffers.Offset} exitsOffset - * @param {flatbuffers.Offset} modeOffset - * @param {flatbuffers.Offset} maneuverOffset - * @param {flatbuffers.Offset} intersectionsOffset - * @param {flatbuffers.Offset} rotaryNameOffset - * @param {flatbuffers.Offset} rotaryPronunciationOffset - * @param {boolean} drivingSide - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Step.createStep = function ( - builder, - distance, - duration, - polylineOffset, - coordinatesOffset, - weight, - nameOffset, - refOffset, - pronunciationOffset, - destinationsOffset, - exitsOffset, - modeOffset, - maneuverOffset, - intersectionsOffset, - rotaryNameOffset, - rotaryPronunciationOffset, - drivingSide, -) { - osrm.engine.api.fbresult.Step.startStep(builder); - osrm.engine.api.fbresult.Step.addDistance(builder, distance); - osrm.engine.api.fbresult.Step.addDuration(builder, duration); - osrm.engine.api.fbresult.Step.addPolyline(builder, polylineOffset); - osrm.engine.api.fbresult.Step.addCoordinates(builder, coordinatesOffset); - osrm.engine.api.fbresult.Step.addWeight(builder, weight); - osrm.engine.api.fbresult.Step.addName(builder, nameOffset); - osrm.engine.api.fbresult.Step.addRef(builder, refOffset); - osrm.engine.api.fbresult.Step.addPronunciation(builder, pronunciationOffset); - osrm.engine.api.fbresult.Step.addDestinations(builder, destinationsOffset); - osrm.engine.api.fbresult.Step.addExits(builder, exitsOffset); - osrm.engine.api.fbresult.Step.addMode(builder, modeOffset); - osrm.engine.api.fbresult.Step.addManeuver(builder, maneuverOffset); - osrm.engine.api.fbresult.Step.addIntersections(builder, intersectionsOffset); - osrm.engine.api.fbresult.Step.addRotaryName(builder, rotaryNameOffset); - osrm.engine.api.fbresult.Step.addRotaryPronunciation( - builder, - rotaryPronunciationOffset, - ); - osrm.engine.api.fbresult.Step.addDrivingSide(builder, drivingSide); - return osrm.engine.api.fbresult.Step.endStep(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Leg = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Leg} - */ -osrm.engine.api.fbresult.Leg.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Leg=} obj - * @returns {osrm.engine.api.fbresult.Leg} - */ -osrm.engine.api.fbresult.Leg.getRootAsLeg = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Leg()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Leg=} obj - * @returns {osrm.engine.api.fbresult.Leg} - */ -osrm.engine.api.fbresult.Leg.getSizePrefixedRootAsLeg = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Leg()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Leg.prototype.distance = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Leg.prototype.duration = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Leg.prototype.weight = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Leg.prototype.summary = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {osrm.engine.api.fbresult.Annotation=} obj - * @returns {osrm.engine.api.fbresult.Annotation|null} - */ -osrm.engine.api.fbresult.Leg.prototype.annotations = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? (obj || new osrm.engine.api.fbresult.Annotation()).__init( - this.bb.__indirect(this.bb_pos + offset), - this.bb, - ) - : null; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Step=} obj - * @returns {osrm.engine.api.fbresult.Step} - */ -osrm.engine.api.fbresult.Leg.prototype.steps = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? (obj || new osrm.engine.api.fbresult.Step()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Leg.prototype.stepsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Leg.startLeg = function (builder) { - builder.startObject(6); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - */ -osrm.engine.api.fbresult.Leg.addDistance = function (builder, distance) { - builder.addFieldFloat64(0, distance, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} duration - */ -osrm.engine.api.fbresult.Leg.addDuration = function (builder, duration) { - builder.addFieldFloat64(1, duration, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} weight - */ -osrm.engine.api.fbresult.Leg.addWeight = function (builder, weight) { - builder.addFieldFloat64(2, weight, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} summaryOffset - */ -osrm.engine.api.fbresult.Leg.addSummary = function (builder, summaryOffset) { - builder.addFieldOffset(3, summaryOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} annotationsOffset - */ -osrm.engine.api.fbresult.Leg.addAnnotations = function ( - builder, - annotationsOffset, -) { - builder.addFieldOffset(4, annotationsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} stepsOffset - */ -osrm.engine.api.fbresult.Leg.addSteps = function (builder, stepsOffset) { - builder.addFieldOffset(5, stepsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Leg.createStepsVector = function (builder, data) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Leg.startStepsVector = function (builder, numElems) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Leg.endLeg = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - * @param {number} duration - * @param {number} weight - * @param {flatbuffers.Offset} summaryOffset - * @param {flatbuffers.Offset} annotationsOffset - * @param {flatbuffers.Offset} stepsOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Leg.createLeg = function ( - builder, - distance, - duration, - weight, - summaryOffset, - annotationsOffset, - stepsOffset, -) { - osrm.engine.api.fbresult.Leg.startLeg(builder); - osrm.engine.api.fbresult.Leg.addDistance(builder, distance); - osrm.engine.api.fbresult.Leg.addDuration(builder, duration); - osrm.engine.api.fbresult.Leg.addWeight(builder, weight); - osrm.engine.api.fbresult.Leg.addSummary(builder, summaryOffset); - osrm.engine.api.fbresult.Leg.addAnnotations(builder, annotationsOffset); - osrm.engine.api.fbresult.Leg.addSteps(builder, stepsOffset); - return osrm.engine.api.fbresult.Leg.endLeg(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.RouteObject = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.RouteObject} - */ -osrm.engine.api.fbresult.RouteObject.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.RouteObject=} obj - * @returns {osrm.engine.api.fbresult.RouteObject} - */ -osrm.engine.api.fbresult.RouteObject.getRootAsRouteObject = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.RouteObject()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.RouteObject=} obj - * @returns {osrm.engine.api.fbresult.RouteObject} - */ -osrm.engine.api.fbresult.RouteObject.getSizePrefixedRootAsRouteObject = - function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.RouteObject()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); - }; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.RouteObject.prototype.distance = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.RouteObject.prototype.duration = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.RouteObject.prototype.weight = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.RouteObject.prototype.weightName = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.RouteObject.prototype.confidence = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.RouteObject.prototype.polyline = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Position=} obj - * @returns {osrm.engine.api.fbresult.Position} - */ -osrm.engine.api.fbresult.RouteObject.prototype.coordinates = function ( - index, - obj, -) { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset - ? (obj || new osrm.engine.api.fbresult.Position()).__init( - this.bb.__vector(this.bb_pos + offset) + index * 8, - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.RouteObject.prototype.coordinatesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 16); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Leg=} obj - * @returns {osrm.engine.api.fbresult.Leg} - */ -osrm.engine.api.fbresult.RouteObject.prototype.legs = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 18); - return offset - ? (obj || new osrm.engine.api.fbresult.Leg()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.RouteObject.prototype.legsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 18); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.RouteObject.startRouteObject = function (builder) { - builder.startObject(8); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - */ -osrm.engine.api.fbresult.RouteObject.addDistance = function ( - builder, - distance, -) { - builder.addFieldFloat32(0, distance, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} duration - */ -osrm.engine.api.fbresult.RouteObject.addDuration = function ( - builder, - duration, -) { - builder.addFieldFloat32(1, duration, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} weight - */ -osrm.engine.api.fbresult.RouteObject.addWeight = function (builder, weight) { - builder.addFieldFloat32(2, weight, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} weightNameOffset - */ -osrm.engine.api.fbresult.RouteObject.addWeightName = function ( - builder, - weightNameOffset, -) { - builder.addFieldOffset(3, weightNameOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} confidence - */ -osrm.engine.api.fbresult.RouteObject.addConfidence = function ( - builder, - confidence, -) { - builder.addFieldFloat32(4, confidence, 0.0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} polylineOffset - */ -osrm.engine.api.fbresult.RouteObject.addPolyline = function ( - builder, - polylineOffset, -) { - builder.addFieldOffset(5, polylineOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} coordinatesOffset - */ -osrm.engine.api.fbresult.RouteObject.addCoordinates = function ( - builder, - coordinatesOffset, -) { - builder.addFieldOffset(6, coordinatesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.RouteObject.startCoordinatesVector = function ( - builder, - numElems, -) { - builder.startVector(8, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} legsOffset - */ -osrm.engine.api.fbresult.RouteObject.addLegs = function (builder, legsOffset) { - builder.addFieldOffset(7, legsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.RouteObject.createLegsVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.RouteObject.startLegsVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.RouteObject.endRouteObject = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} distance - * @param {number} duration - * @param {number} weight - * @param {flatbuffers.Offset} weightNameOffset - * @param {number} confidence - * @param {flatbuffers.Offset} polylineOffset - * @param {flatbuffers.Offset} coordinatesOffset - * @param {flatbuffers.Offset} legsOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.RouteObject.createRouteObject = function ( - builder, - distance, - duration, - weight, - weightNameOffset, - confidence, - polylineOffset, - coordinatesOffset, - legsOffset, -) { - osrm.engine.api.fbresult.RouteObject.startRouteObject(builder); - osrm.engine.api.fbresult.RouteObject.addDistance(builder, distance); - osrm.engine.api.fbresult.RouteObject.addDuration(builder, duration); - osrm.engine.api.fbresult.RouteObject.addWeight(builder, weight); - osrm.engine.api.fbresult.RouteObject.addWeightName(builder, weightNameOffset); - osrm.engine.api.fbresult.RouteObject.addConfidence(builder, confidence); - osrm.engine.api.fbresult.RouteObject.addPolyline(builder, polylineOffset); - osrm.engine.api.fbresult.RouteObject.addCoordinates( - builder, - coordinatesOffset, - ); - osrm.engine.api.fbresult.RouteObject.addLegs(builder, legsOffset); - return osrm.engine.api.fbresult.RouteObject.endRouteObject(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Table = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Table} - */ -osrm.engine.api.fbresult.Table.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Table=} obj - * @returns {osrm.engine.api.fbresult.Table} - */ -osrm.engine.api.fbresult.Table.getRootAsTable = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Table()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Table=} obj - * @returns {osrm.engine.api.fbresult.Table} - */ -osrm.engine.api.fbresult.Table.getSizePrefixedRootAsTable = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Table()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.durations = function (index) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.durationsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Float32Array} - */ -osrm.engine.api.fbresult.Table.prototype.durationsArray = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? new Float32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.rows = function () { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.cols = function () { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.distances = function (index) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? this.bb.readFloat32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.distancesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @returns {Float32Array} - */ -osrm.engine.api.fbresult.Table.prototype.distancesArray = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? new Float32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Waypoint=} obj - * @returns {osrm.engine.api.fbresult.Waypoint} - */ -osrm.engine.api.fbresult.Table.prototype.destinations = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? (obj || new osrm.engine.api.fbresult.Waypoint()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.destinationsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {number} index - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.fallbackSpeedCells = function (index) { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? this.bb.readUint32(this.bb.__vector(this.bb_pos + offset) + index * 4) - : 0; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.Table.prototype.fallbackSpeedCellsLength = - function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; - }; - -/** - * @returns {Uint32Array} - */ -osrm.engine.api.fbresult.Table.prototype.fallbackSpeedCellsArray = function () { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? new Uint32Array( - this.bb.bytes().buffer, - this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), - this.bb.__vector_len(this.bb_pos + offset), - ) - : null; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Table.startTable = function (builder) { - builder.startObject(6); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} durationsOffset - */ -osrm.engine.api.fbresult.Table.addDurations = function ( - builder, - durationsOffset, -) { - builder.addFieldOffset(0, durationsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Table.createDurationsVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addFloat32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Table.startDurationsVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} rows - */ -osrm.engine.api.fbresult.Table.addRows = function (builder, rows) { - builder.addFieldInt16(1, rows, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} cols - */ -osrm.engine.api.fbresult.Table.addCols = function (builder, cols) { - builder.addFieldInt16(2, cols, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} distancesOffset - */ -osrm.engine.api.fbresult.Table.addDistances = function ( - builder, - distancesOffset, -) { - builder.addFieldOffset(3, distancesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Table.createDistancesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addFloat32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Table.startDistancesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} destinationsOffset - */ -osrm.engine.api.fbresult.Table.addDestinations = function ( - builder, - destinationsOffset, -) { - builder.addFieldOffset(4, destinationsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Table.createDestinationsVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Table.startDestinationsVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} fallbackSpeedCellsOffset - */ -osrm.engine.api.fbresult.Table.addFallbackSpeedCells = function ( - builder, - fallbackSpeedCellsOffset, -) { - builder.addFieldOffset(5, fallbackSpeedCellsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Table.createFallbackSpeedCellsVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addInt32(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.Table.startFallbackSpeedCellsVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Table.endTable = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} durationsOffset - * @param {number} rows - * @param {number} cols - * @param {flatbuffers.Offset} distancesOffset - * @param {flatbuffers.Offset} destinationsOffset - * @param {flatbuffers.Offset} fallbackSpeedCellsOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Table.createTable = function ( - builder, - durationsOffset, - rows, - cols, - distancesOffset, - destinationsOffset, - fallbackSpeedCellsOffset, -) { - osrm.engine.api.fbresult.Table.startTable(builder); - osrm.engine.api.fbresult.Table.addDurations(builder, durationsOffset); - osrm.engine.api.fbresult.Table.addRows(builder, rows); - osrm.engine.api.fbresult.Table.addCols(builder, cols); - osrm.engine.api.fbresult.Table.addDistances(builder, distancesOffset); - osrm.engine.api.fbresult.Table.addDestinations(builder, destinationsOffset); - osrm.engine.api.fbresult.Table.addFallbackSpeedCells( - builder, - fallbackSpeedCellsOffset, - ); - return osrm.engine.api.fbresult.Table.endTable(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.Error = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.Error} - */ -osrm.engine.api.fbresult.Error.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Error=} obj - * @returns {osrm.engine.api.fbresult.Error} - */ -osrm.engine.api.fbresult.Error.getRootAsError = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Error()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.Error=} obj - * @returns {osrm.engine.api.fbresult.Error} - */ -osrm.engine.api.fbresult.Error.getSizePrefixedRootAsError = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.Error()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Error.prototype.code = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.Error.prototype.message = function (optionalEncoding) { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.Error.startError = function (builder) { - builder.startObject(2); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} codeOffset - */ -osrm.engine.api.fbresult.Error.addCode = function (builder, codeOffset) { - builder.addFieldOffset(0, codeOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} messageOffset - */ -osrm.engine.api.fbresult.Error.addMessage = function (builder, messageOffset) { - builder.addFieldOffset(1, messageOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Error.endError = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} codeOffset - * @param {flatbuffers.Offset} messageOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.Error.createError = function ( - builder, - codeOffset, - messageOffset, -) { - osrm.engine.api.fbresult.Error.startError(builder); - osrm.engine.api.fbresult.Error.addCode(builder, codeOffset); - osrm.engine.api.fbresult.Error.addMessage(builder, messageOffset); - return osrm.engine.api.fbresult.Error.endError(builder); -}; - -/** - * @constructor - */ -osrm.engine.api.fbresult.FBResult = function () { - /** - * @type {flatbuffers.ByteBuffer} - */ - this.bb = null; - - /** - * @type {number} - */ - this.bb_pos = 0; -}; - -/** - * @param {number} i - * @param {flatbuffers.ByteBuffer} bb - * @returns {osrm.engine.api.fbresult.FBResult} - */ -osrm.engine.api.fbresult.FBResult.prototype.__init = function (i, bb) { - this.bb_pos = i; - this.bb = bb; - return this; -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.FBResult=} obj - * @returns {osrm.engine.api.fbresult.FBResult} - */ -osrm.engine.api.fbresult.FBResult.getRootAsFBResult = function (bb, obj) { - return (obj || new osrm.engine.api.fbresult.FBResult()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @param {flatbuffers.ByteBuffer} bb - * @param {osrm.engine.api.fbresult.FBResult=} obj - * @returns {osrm.engine.api.fbresult.FBResult} - */ -osrm.engine.api.fbresult.FBResult.getSizePrefixedRootAsFBResult = function ( - bb, - obj, -) { - return (obj || new osrm.engine.api.fbresult.FBResult()).__init( - bb.readInt32(bb.position()) + bb.position(), - bb, - ); -}; - -/** - * @returns {boolean} - */ -osrm.engine.api.fbresult.FBResult.prototype.error = function () { - const offset = this.bb.__offset(this.bb_pos, 4); - return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; -}; - -/** - * @param {osrm.engine.api.fbresult.Error=} obj - * @returns {osrm.engine.api.fbresult.Error|null} - */ -osrm.engine.api.fbresult.FBResult.prototype.code = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 6); - return offset - ? (obj || new osrm.engine.api.fbresult.Error()).__init( - this.bb.__indirect(this.bb_pos + offset), - this.bb, - ) - : null; -}; - -/** - * @param {flatbuffers.Encoding=} optionalEncoding - * @returns {string|Uint8Array|null} - */ -osrm.engine.api.fbresult.FBResult.prototype.dataVersion = function ( - optionalEncoding, -) { - const offset = this.bb.__offset(this.bb_pos, 8); - return offset - ? this.bb.__string(this.bb_pos + offset, optionalEncoding) - : null; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.Waypoint=} obj - * @returns {osrm.engine.api.fbresult.Waypoint} - */ -osrm.engine.api.fbresult.FBResult.prototype.waypoints = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset - ? (obj || new osrm.engine.api.fbresult.Waypoint()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.FBResult.prototype.waypointsLength = function () { - const offset = this.bb.__offset(this.bb_pos, 10); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {number} index - * @param {osrm.engine.api.fbresult.RouteObject=} obj - * @returns {osrm.engine.api.fbresult.RouteObject} - */ -osrm.engine.api.fbresult.FBResult.prototype.routes = function (index, obj) { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset - ? (obj || new osrm.engine.api.fbresult.RouteObject()).__init( - this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), - this.bb, - ) - : null; -}; - -/** - * @returns {number} - */ -osrm.engine.api.fbresult.FBResult.prototype.routesLength = function () { - const offset = this.bb.__offset(this.bb_pos, 12); - return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; -}; - -/** - * @param {osrm.engine.api.fbresult.Table=} obj - * @returns {osrm.engine.api.fbresult.Table|null} - */ -osrm.engine.api.fbresult.FBResult.prototype.table = function (obj) { - const offset = this.bb.__offset(this.bb_pos, 14); - return offset - ? (obj || new osrm.engine.api.fbresult.Table()).__init( - this.bb.__indirect(this.bb_pos + offset), - this.bb, - ) - : null; -}; - -/** - * @param {flatbuffers.Builder} builder - */ -osrm.engine.api.fbresult.FBResult.startFBResult = function (builder) { - builder.startObject(6); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {boolean} error - */ -osrm.engine.api.fbresult.FBResult.addError = function (builder, error) { - builder.addFieldInt8(0, +error, +false); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} codeOffset - */ -osrm.engine.api.fbresult.FBResult.addCode = function (builder, codeOffset) { - builder.addFieldOffset(1, codeOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} dataVersionOffset - */ -osrm.engine.api.fbresult.FBResult.addDataVersion = function ( - builder, - dataVersionOffset, -) { - builder.addFieldOffset(2, dataVersionOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} waypointsOffset - */ -osrm.engine.api.fbresult.FBResult.addWaypoints = function ( - builder, - waypointsOffset, -) { - builder.addFieldOffset(3, waypointsOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.FBResult.createWaypointsVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.FBResult.startWaypointsVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} routesOffset - */ -osrm.engine.api.fbresult.FBResult.addRoutes = function (builder, routesOffset) { - builder.addFieldOffset(4, routesOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {Array.} data - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.FBResult.createRoutesVector = function ( - builder, - data, -) { - builder.startVector(4, data.length, 4); - for (let i = data.length - 1; i >= 0; i--) { - builder.addOffset(data[i]); - } - return builder.endVector(); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {number} numElems - */ -osrm.engine.api.fbresult.FBResult.startRoutesVector = function ( - builder, - numElems, -) { - builder.startVector(4, numElems, 4); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} tableOffset - */ -osrm.engine.api.fbresult.FBResult.addTable = function (builder, tableOffset) { - builder.addFieldOffset(5, tableOffset, 0); -}; - -/** - * @param {flatbuffers.Builder} builder - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.FBResult.endFBResult = function (builder) { - const offset = builder.endObject(); - return offset; -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} offset - */ -osrm.engine.api.fbresult.FBResult.finishFBResultBuffer = function ( - builder, - offset, -) { - builder.finish(offset); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {flatbuffers.Offset} offset - */ -osrm.engine.api.fbresult.FBResult.finishSizePrefixedFBResultBuffer = function ( - builder, - offset, -) { - builder.finish(offset, undefined, true); -}; - -/** - * @param {flatbuffers.Builder} builder - * @param {boolean} error - * @param {flatbuffers.Offset} codeOffset - * @param {flatbuffers.Offset} dataVersionOffset - * @param {flatbuffers.Offset} waypointsOffset - * @param {flatbuffers.Offset} routesOffset - * @param {flatbuffers.Offset} tableOffset - * @returns {flatbuffers.Offset} - */ -osrm.engine.api.fbresult.FBResult.createFBResult = function ( - builder, - error, - codeOffset, - dataVersionOffset, - waypointsOffset, - routesOffset, - tableOffset, -) { - osrm.engine.api.fbresult.FBResult.startFBResult(builder); - osrm.engine.api.fbresult.FBResult.addError(builder, error); - osrm.engine.api.fbresult.FBResult.addCode(builder, codeOffset); - osrm.engine.api.fbresult.FBResult.addDataVersion(builder, dataVersionOffset); - osrm.engine.api.fbresult.FBResult.addWaypoints(builder, waypointsOffset); - osrm.engine.api.fbresult.FBResult.addRoutes(builder, routesOffset); - osrm.engine.api.fbresult.FBResult.addTable(builder, tableOffset); - return osrm.engine.api.fbresult.FBResult.endFBResult(builder); -}; - -// Exports for Node.js, RequireJS, and ES modules -if (typeof module !== 'undefined' && module.exports) { - module.exports = { osrm }; -} else if (typeof this !== 'undefined') { - this.osrm = osrm; -} else if (typeof globalThis !== 'undefined') { - globalThis.osrm = osrm; -} - -// ES module export for compatibility -export { osrm }; +// Map new TypeScript exports to old JavaScript structure +osrm.engine.api.fbresult.FBResult = fb.FBResult; +osrm.engine.api.fbresult.Error = fb.Error; +osrm.engine.api.fbresult.Position = fb.Position; +osrm.engine.api.fbresult.Waypoint = fb.Waypoint; +osrm.engine.api.fbresult.RouteObject = fb.RouteObject; +osrm.engine.api.fbresult.TableResult = fb.TableResult; +osrm.engine.api.fbresult.Leg = fb.Leg; +osrm.engine.api.fbresult.Step = fb.Step; +osrm.engine.api.fbresult.StepManeuver = fb.StepManeuver; +osrm.engine.api.fbresult.ManeuverType = fb.ManeuverType; +osrm.engine.api.fbresult.Annotation = fb.Annotation; +osrm.engine.api.fbresult.Intersection = fb.Intersection; +osrm.engine.api.fbresult.Lane = fb.Lane; +osrm.engine.api.fbresult.Turn = fb.Turn; +osrm.engine.api.fbresult.Metadata = fb.Metadata; +osrm.engine.api.fbresult.Uint64Pair = fb.Uint64Pair; + +export { osrm }; \ No newline at end of file diff --git a/features/support/osrm/engine/api/fbresult.ts b/features/support/osrm/engine/api/fbresult.ts new file mode 100644 index 00000000000..32e5d5605f3 --- /dev/null +++ b/features/support/osrm/engine/api/fbresult.ts @@ -0,0 +1,20 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Annotation } from './engine/api/fbresult/annotation.js'; +export { Error } from './engine/api/fbresult/error.js'; +export { FBResult } from './engine/api/fbresult/fbresult.js'; +export { Intersection } from './engine/api/fbresult/intersection.js'; +export { Lane } from './engine/api/fbresult/lane.js'; +export { Leg } from './engine/api/fbresult/leg.js'; +export { ManeuverType } from './engine/api/fbresult/maneuver-type.js'; +export { Metadata } from './engine/api/fbresult/metadata.js'; +export { Position } from './engine/api/fbresult/position.js'; +export { RouteObject } from './engine/api/fbresult/route-object.js'; +export { Step } from './engine/api/fbresult/step.js'; +export { StepManeuver } from './engine/api/fbresult/step-maneuver.js'; +export { TableResult } from './engine/api/fbresult/table-result.js'; +export { Turn } from './engine/api/fbresult/turn.js'; +export { Uint64Pair } from './engine/api/fbresult/uint64-pair.js'; +export { Waypoint } from './engine/api/fbresult/waypoint.js'; diff --git a/features/support/osrm/engine/api/fbresult/error.ts b/features/support/osrm/engine/api/fbresult/error.ts new file mode 100644 index 00000000000..e5547df5736 --- /dev/null +++ b/features/support/osrm/engine/api/fbresult/error.ts @@ -0,0 +1,66 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +export class Error { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Error { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsError(bb:flatbuffers.ByteBuffer, obj?:Error):Error { + return (obj || new Error()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsError(bb:flatbuffers.ByteBuffer, obj?:Error):Error { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Error()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +code():string|null +code(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +code(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +message():string|null +message(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +message(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'osrm.engine.api.fbresult.Error'; +} + +static startError(builder:flatbuffers.Builder) { + builder.startObject(2); +} + +static addCode(builder:flatbuffers.Builder, codeOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, codeOffset, 0); +} + +static addMessage(builder:flatbuffers.Builder, messageOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, messageOffset, 0); +} + +static endError(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createError(builder:flatbuffers.Builder, codeOffset:flatbuffers.Offset, messageOffset:flatbuffers.Offset):flatbuffers.Offset { + Error.startError(builder); + Error.addCode(builder, codeOffset); + Error.addMessage(builder, messageOffset); + return Error.endError(builder); +} +} diff --git a/features/support/osrm/engine/api/fbresult/fbresult.ts b/features/support/osrm/engine/api/fbresult/fbresult.ts new file mode 100644 index 00000000000..f312712e5f7 --- /dev/null +++ b/features/support/osrm/engine/api/fbresult/fbresult.ts @@ -0,0 +1,142 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Error } from '../../../../osrm/engine/api/fbresult/error.js'; +import { RouteObject } from '../../../../osrm/engine/api/fbresult/route-object.js'; +import { TableResult } from '../../../../osrm/engine/api/fbresult/table-result.js'; +import { Waypoint } from '../../../../osrm/engine/api/fbresult/waypoint.js'; + + +export class FBResult { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):FBResult { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsFBResult(bb:flatbuffers.ByteBuffer, obj?:FBResult):FBResult { + return (obj || new FBResult()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsFBResult(bb:flatbuffers.ByteBuffer, obj?:FBResult):FBResult { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new FBResult()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +error():boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +code(obj?:Error):Error|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new Error()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +dataVersion():string|null +dataVersion(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +dataVersion(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +waypoints(index: number, obj?:Waypoint):Waypoint|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? (obj || new Waypoint()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +waypointsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +routes(index: number, obj?:RouteObject):RouteObject|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? (obj || new RouteObject()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +routesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +table(obj?:TableResult):TableResult|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? (obj || new TableResult()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +static getFullyQualifiedName():string { + return 'osrm.engine.api.fbresult.FBResult'; +} + +static startFBResult(builder:flatbuffers.Builder) { + builder.startObject(6); +} + +static addError(builder:flatbuffers.Builder, error:boolean) { + builder.addFieldInt8(0, +error, +false); +} + +static addCode(builder:flatbuffers.Builder, codeOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, codeOffset, 0); +} + +static addDataVersion(builder:flatbuffers.Builder, dataVersionOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, dataVersionOffset, 0); +} + +static addWaypoints(builder:flatbuffers.Builder, waypointsOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, waypointsOffset, 0); +} + +static createWaypointsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startWaypointsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addRoutes(builder:flatbuffers.Builder, routesOffset:flatbuffers.Offset) { + builder.addFieldOffset(4, routesOffset, 0); +} + +static createRoutesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startRoutesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addTable(builder:flatbuffers.Builder, tableOffset:flatbuffers.Offset) { + builder.addFieldOffset(5, tableOffset, 0); +} + +static endFBResult(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static finishFBResultBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset); +} + +static finishSizePrefixedFBResultBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, undefined, true); +} + +} diff --git a/generated/include/engine/api/flatbuffers/fbresult_generated.h b/generated/include/engine/api/flatbuffers/fbresult_generated.h index 0f01298198f..b80367f546e 100644 --- a/generated/include/engine/api/flatbuffers/fbresult_generated.h +++ b/generated/include/engine/api/flatbuffers/fbresult_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); #include "route_generated.h" diff --git a/generated/include/engine/api/flatbuffers/position_generated.h b/generated/include/engine/api/flatbuffers/position_generated.h index aa3ea2d8b21..e7d80fc0c48 100644 --- a/generated/include/engine/api/flatbuffers/position_generated.h +++ b/generated/include/engine/api/flatbuffers/position_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); namespace osrm { diff --git a/generated/include/engine/api/flatbuffers/route_generated.h b/generated/include/engine/api/flatbuffers/route_generated.h index 6ae492bd429..c800695de66 100644 --- a/generated/include/engine/api/flatbuffers/route_generated.h +++ b/generated/include/engine/api/flatbuffers/route_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); #include "waypoint_generated.h" diff --git a/generated/include/engine/api/flatbuffers/table_generated.h b/generated/include/engine/api/flatbuffers/table_generated.h index 30c6bd81ca8..09a2b7c2d8f 100644 --- a/generated/include/engine/api/flatbuffers/table_generated.h +++ b/generated/include/engine/api/flatbuffers/table_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); #include "waypoint_generated.h" diff --git a/generated/include/engine/api/flatbuffers/waypoint_generated.h b/generated/include/engine/api/flatbuffers/waypoint_generated.h index 3fae94975d7..38f90d46905 100644 --- a/generated/include/engine/api/flatbuffers/waypoint_generated.h +++ b/generated/include/engine/api/flatbuffers/waypoint_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); #include "position_generated.h" diff --git a/package-lock.json b/package-lock.json index 02b4c3fe3f9..4bcd4c073aa 100644 --- a/package-lock.json +++ b/package-lock.json @@ -36,7 +36,7 @@ "documentation": "^14.0.2", "eslint": "9.26.0", "faucet": "^0.0.4", - "flatbuffers": "24.3.25", + "flatbuffers": "^25.2.10", "husky": "^9.1.7", "jsonpath": "^1.1.1", "lint-staged": "^16.1.6", @@ -13120,9 +13120,9 @@ } }, "node_modules/flatbuffers": { - "version": "24.3.25", - "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-24.3.25.tgz", - "integrity": "sha512-3HDgPbgiwWMI9zVB7VYBHaMrbOO7Gm0v+yD2FV/sCKj+9NDeVL7BOBYUuhWAQGKWOzBo8S9WdMvV0eixO233XQ==", + "version": "25.2.10", + "resolved": "https://registry.npmjs.org/flatbuffers/-/flatbuffers-25.2.10.tgz", + "integrity": "sha512-7JlN9ZvLDG1McO3kbX0k4v+SUAg48L1rIwEvN6ZQl/eCtgJz9UylTMzE9wrmYrcorgxm3CX/3T/w5VAub99UUw==", "dev": true, "license": "Apache-2.0" }, diff --git a/package.json b/package.json index 51893bc223e..e22cf5b170a 100644 --- a/package.json +++ b/package.json @@ -59,7 +59,7 @@ "documentation": "^14.0.2", "eslint": "9.26.0", "faucet": "^0.0.4", - "flatbuffers": "24.3.25", + "flatbuffers": "^25.2.10", "husky": "^9.1.7", "jsonpath": "^1.1.1", "lint-staged": "^16.1.6", diff --git a/scripts/update_dependencies.sh b/scripts/update_dependencies.sh index 8a9137dc62d..a67189237b2 100755 --- a/scripts/update_dependencies.sh +++ b/scripts/update_dependencies.sh @@ -7,7 +7,7 @@ set -o nounset # Note: once the subtree merge from this script has been committed and pushed to # a branch do not attempt to rebase the branch back onto master or the subdirectory # structure will be lost. -# http://git.661346.n2.nabble.com/subtree-merges-lose-prefix-after-rebase-td7332850.html +# https://stackoverflow.com/questions/12858199/how-to-rebase-after-git-subtree-add OSMIUM_PATH="osmcode/libosmium" OSMIUM_TAG=v2.20.0 @@ -31,8 +31,9 @@ FMT_PATH="fmtlib/fmt" FMT_TAG=v10.2.1 FLATBUFFERS_PATH="google/flatbuffers" -FLATBUFFERS_TAG=v24.3.25 +FLATBUFFERS_TAG=v25.2.10 +# Updates a git subtree dependency by pulling/adding the specified tag from GitHub function update_subtree () { name=$(echo "$1" | tr '[:lower:]' '[:upper:]') path=$(tmpvar=${name}_PATH && echo ${!tmpvar}) @@ -59,3 +60,22 @@ function update_subtree () { for dep in osmium sol rapidjson microtar protozero vtzero fmt flatbuffers; do update_subtree $dep done + +## Update npm package.json to match FLATBUFFERS_TAG +echo "Updating package.json flatbuffers version to match ${FLATBUFFERS_TAG}..." +FLATBUFFERS_VERSION=${FLATBUFFERS_TAG#v} # Remove 'v' prefix +npm install flatbuffers@${FLATBUFFERS_VERSION} + +## Regenerate FlatBuffers bindings after update +echo "Regenerating FlatBuffers TypeScript bindings..." +flatc --ts --gen-name-strings -o features/support/ include/engine/api/flatbuffers/fbresult.fbs + +echo "Regenerating FlatBuffers C++ headers..." +for schema in include/engine/api/flatbuffers/*.fbs; do + flatc --cpp -o generated/include/engine/api/flatbuffers/ "$schema" +done + +# Note: fbresult_generated.js is a manual compatibility wrapper that maps +# the new TypeScript module structure to the old JavaScript namespace structure +# expected by the test files. This wrapper should be updated manually if +# new types are added to the .fbs schema files. diff --git a/third_party/flatbuffers/.bazelci/presubmit.yml b/third_party/flatbuffers/.bazelci/presubmit.yml index bcab65430d6..aa88684f153 100644 --- a/third_party/flatbuffers/.bazelci/presubmit.yml +++ b/third_party/flatbuffers/.bazelci/presubmit.yml @@ -1,38 +1,60 @@ --- buildifier: latest -bazel: 6.4.0 -platforms: - ubuntu1804: +matrix: + bazel: + - 7.x + - 8.x +tasks: + verify_ubuntu2004: + platform: ubuntu2004 + bazel: ${{ bazel }} environment: CC: clang - SWIFT_VERSION: "5.5.3" + SWIFT_VERSION: "5.9" SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" PATH: "$PATH:$SWIFT_HOME/usr/bin" shell_commands: - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" - "mkdir $SWIFT_HOME" - - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu1804/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu18.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" + - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" build_targets: - "//..." test_targets: - "//..." - ubuntu2004: + verify_ubuntu2204: + platform: ubuntu2204 + bazel: ${{ bazel }} environment: CC: clang - SWIFT_VERSION: "5.5.3" + SWIFT_VERSION: "5.9" SWIFT_HOME: "$HOME/swift-$SWIFT_VERSION" PATH: "$PATH:$SWIFT_HOME/usr/bin" shell_commands: - "echo --- Downloading and extracting Swift $SWIFT_VERSION to $SWIFT_HOME" - "mkdir $SWIFT_HOME" - - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2004/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu20.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" + - "curl https://download.swift.org/swift-${SWIFT_VERSION}-release/ubuntu2204/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-ubuntu22.04.tar.gz | tar xvz --strip-components=1 -C $SWIFT_HOME" build_targets: - "//..." test_targets: - "//..." - macos: - xcode_version: "14.2" + test_module_cpp: + platform: ubuntu2204 + bazel: ${{ bazel }} + working_directory: tests/bazel_repository_test_dir build_targets: - "//..." + test_module_ts: + platform: ubuntu2204 + bazel: ${{ bazel }} + working_directory: tests/ts/bazel_repository_test_dir test_targets: - "//..." + verify_macos: + platform: macos + bazel: ${{ bazel }} + xcode_version: "15.2" + build_targets: + - "//:flatbuffers" + - "//:flatc" + test_targets: + - "//tests:flatbuffers_test" diff --git a/third_party/flatbuffers/.bazelignore b/third_party/flatbuffers/.bazelignore index 3c3629e647f..874adf91565 100644 --- a/third_party/flatbuffers/.bazelignore +++ b/third_party/flatbuffers/.bazelignore @@ -1 +1,5 @@ -node_modules +ts/node_modules + +# Test workspaces +tests/bazel_repository_test_dir +tests/ts/bazel_repository_test_dir diff --git a/third_party/flatbuffers/.bazelrc b/third_party/flatbuffers/.bazelrc index f9f47a74237..a02667e1821 100644 --- a/third_party/flatbuffers/.bazelrc +++ b/third_party/flatbuffers/.bazelrc @@ -1,4 +1,18 @@ # We cannot use "common" here because the "version" command doesn't support # --deleted_packages. We need to specify it for both build and query instead. -build --deleted_packages=tests/ts/bazel_repository_test_dir -query --deleted_packages=tests/ts/bazel_repository_test_dir +build --deleted_packages=tests/bazel_repository_test_dir,tests/ts/bazel_repository_test_dir +query --deleted_packages=tests/bazel_repository_test_dir,tests/ts/bazel_repository_test_dir +# Point tools such as coursier (used in rules_jvm_external) to Bazel's internal JDK +# suggested in https://github.com/bazelbuild/rules_jvm_external/issues/445 +common --repo_env=JAVA_HOME=../bazel_tools/jdk +common --action_env=JAVA_HOME=../bazel_tools/jdk +# Workaround "Error: need --enable_runfiles on Windows for to support rules_js" +common:windows --enable_runfiles +# Swift is not required on Windows +common:windows --deleted_packages=swift +# Ignore warnings in external dependencies +build --per_file_copt=external/.*@-Wno-everything --host_per_file_copt=external/.*@-Wno-everything +# Honor the setting of `skipLibCheck` in the tsconfig.json file. +common --@aspect_rules_ts//ts:skipLibCheck=honor_tsconfig +# Use "tsc" as the transpiler when ts_project has no `transpiler` set. +common --@aspect_rules_ts//ts:default_to_tsc_transpiler diff --git a/third_party/flatbuffers/.github/ISSUE_TEMPLATE.md b/third_party/flatbuffers/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000000..a053fe4406a --- /dev/null +++ b/third_party/flatbuffers/.github/ISSUE_TEMPLATE.md @@ -0,0 +1,12 @@ +Thank you for submitting an issue! + +Please make sure you include the names of the affected language(s), compiler version(s), operating system version(s), and FlatBuffers version(s) in your issue title. + +This helps us get the correct maintainers to look at your issue. Here are examples of good titles: + +- Crash when accessing FlatBuffer [C++, gcc 4.8, OS X, master] +- Flatc converts a protobuf 'bytes' field to 'string' in fbs schema file [all languages, FlatBuffers 1.4] + +Include other details as appropriate. + +Thanks! diff --git a/third_party/flatbuffers/.github/ISSUE_TEMPLATE/404-doc.md b/third_party/flatbuffers/.github/ISSUE_TEMPLATE/404-doc.md new file mode 100644 index 00000000000..c394d384541 --- /dev/null +++ b/third_party/flatbuffers/.github/ISSUE_TEMPLATE/404-doc.md @@ -0,0 +1,11 @@ +--- +name: 404 Doc +about: To fix broken documentation links +title: "[Doc 404]" +labels: documentation +assignees: dbaileychess + +--- + +Target URL: +[Optional] Source Site: diff --git a/third_party/flatbuffers/.github/PULL_REQUEST_TEMPLATE.md b/third_party/flatbuffers/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000000..b8cc0ce1db5 --- /dev/null +++ b/third_party/flatbuffers/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,19 @@ +Thank you for submitting a PR! + +Please delete this standard text once you've created your own description. + +If you make changes to any of the code generators (`src/idl_gen*`) be sure to +[build](https://google.github.io/flatbuffers/flatbuffers_guide_building.html) your project, as it will generate code based on the changes. If necessary +the code generation script can be directly run (`scripts/generate_code.py`), +requires Python3. This allows us to better see the effect of the PR. + +If your PR includes C++ code, please adhere to the +[Google C++ Style Guide](https://google.github.io/styleguide/cppguide.html), +and don't forget we try to support older compilers (e.g. VS2010, GCC 4.6.3), +so only some C++11 support is available. + +For any C++ changes, please make sure to run `sh scripts/clang-format-git.sh` + +Include other details as appropriate. + +Thanks! diff --git a/third_party/flatbuffers/.github/labeler.yml b/third_party/flatbuffers/.github/labeler.yml new file mode 100644 index 00000000000..e3da18c1eda --- /dev/null +++ b/third_party/flatbuffers/.github/labeler.yml @@ -0,0 +1,97 @@ +# Configuration for Auto Labeler during pull request +# +# See https://github.com/actions/labeler for file format +# and https://github.com/google/flatbuffers/labels for a list of valid labels +# +# See .github/workflows/label.yml for Github Action workflow script + +c#: + - '**/*.cs' + - net/**/* + - tests/FlatBuffers.Test/**/* + - tests/FlatBuffers.Benchmarks/**/* + - src/idl_gen_csharp.cpp + +swift: + - '**/*.swift' + - swift/**/* + - tests/swift/** + - src/idl_gen_swift.cpp + +nim: + - '**/*.nim' + - nim/**/* + - src/idl_gen_nim.cpp + - src/bfbs_gen_nim.cpp + +javascript: + - '**/*.js' + - src/idl_gen_ts.cpp + +typescript: + - '**/*.ts' + - src/idl_gen_ts.cpp + - grpc/flatbuffers-js-grpc/**/*.ts + +golang: + - '**/*.go' + - src/idl_gen_go.cpp + +python: + - '**/*.py' + - src/idl_gen_python.cpp + +java: + - '**/*.java' + - src/idl_gen_java.cpp + +kotlin: + - '**/*.kt' + - src/idl_gen_kotlin.cpp + - src/idl_gen_kotlin_kmp.cpp + +lua: + - '**/*.lua' + - lua/**/* + - src/bfbs_gen_lua.cpp + +lobster: + - '**/*.lobster' + - src/idl_gen_lobster.cpp + +php: + - '**/*.php' + - src/idl_gen_php.cpp + +rust: + - '**/*.rs' + - rust/**/* + - src/idl_gen_rust.cpp + +dart: + - '**/*.dart' + - src/idl_gen_dart.cpp + +c++: + - '**/*.cc' + - '**/*.cpp' + - '**/*.h' + +json: + - '**/*.json' + - src/idl_gen_json_schema.cpp + +codegen: + - src/**/* + +documentation: + - docs/**/* + - '**/*.md' + +CI: + - '.github/**/*' + - '.bazelci/**/*' + +grpc: + - grpc/**/* + - src/idl_gen_grpc.cpp diff --git a/third_party/flatbuffers/.github/workflows/build.yml b/third_party/flatbuffers/.github/workflows/build.yml new file mode 100644 index 00000000000..2a763167b9f --- /dev/null +++ b/third_party/flatbuffers/.github/workflows/build.yml @@ -0,0 +1,628 @@ +name: CI +permissions: read-all + +on: + # For manual tests. + workflow_dispatch: + push: + tags: + - "*" # new tag version, like `0.8.4` or else + branches: + - master + pull_request: + branches: + - master + schedule: + # Run daily at 4:45 A.M. to catch dependencies that break us. + - cron: '45 4 * * *' + +jobs: + build-linux: + permissions: + contents: write + outputs: + digests-gcc: ${{ steps.hash-gcc.outputs.hashes }} + digests-clang: ${{ steps.hash-clang.outputs.hashes }} + name: Build Linux + runs-on: ubuntu-24.04 + strategy: + matrix: + cxx: [g++-13, clang++-18] + fail-fast: false + steps: + - uses: actions/checkout@v3 + - name: cmake + run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_STATIC_FLATC=ON . + - name: build + run: make -j + - name: test + run: ./flattests + - name: make flatc executable + run: | + chmod +x flatc + ./flatc --version + - name: upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: Linux flatc binary ${{ matrix.cxx }} + path: flatc + # Below if only for release. + - name: Zip file + if: startsWith(github.ref, 'refs/tags/') + run: zip Linux.flatc.binary.${{ matrix.cxx }}.zip flatc + - name: Release zip file + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + files: Linux.flatc.binary.${{ matrix.cxx }}.zip + - name: Generate SLSA subjects - clang + if: matrix.cxx == 'clang++-18' && startsWith(github.ref, 'refs/tags/') + id: hash-clang + run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT + - name: Generate SLSA subjects - gcc + if: matrix.cxx == 'g++-13' && startsWith(github.ref, 'refs/tags/') + id: hash-gcc + run: echo "hashes=$(sha256sum Linux.flatc.binary.${{ matrix.cxx }}.zip | base64 -w0)" >> $GITHUB_OUTPUT + + build-linux-no-file-tests: + name: Build Linux with -DFLATBUFFERS_NO_FILE_TESTS + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: cmake + run: CXX=clang++-18 cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON -DFLATBUFFERS_CXX_FLAGS="-DFLATBUFFERS_NO_FILE_TESTS" . + - name: build + run: make -j + - name: test + run: ./flattests + + build-linux-out-of-source: + name: Build Linux with out-of-source build location + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: make build directory + run: mkdir build + - name: cmake + working-directory: build + run: > + CXX=clang++-18 cmake .. -G "Unix Makefiles" -DFLATBUFFERS_STRICT_MODE=ON + -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_CPP_STD=17 + - name: build + working-directory: build + run: make -j + - name: test + working-directory: build + run: pwd && ./flattests + - name: test C++17 + working-directory: build + run: ./flattests_cpp17 + + build-linux-cpp-std: + name: Build Linux C++ + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + std: [11, 14, 17, 20, 23] + cxx: [g++-13, clang++-18] + exclude: + # Clang++15 10.3.0 stdlibc++ doesn't fully support std 23 + - cxx: clang++-18 + std: 23 + + steps: + - uses: actions/checkout@v3 + - name: cmake + run: > + CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" + -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON + -DFLATBUFFERS_CPP_STD=${{ matrix.std }} + -DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}} + - name: build + run: make -j + - name: test + run: ./flattests + - name: test C++17 + if: matrix.std >= 17 + run: ./flattests_cpp17 + + build-cpp-std: + name: Build Windows C++ + runs-on: windows-2019 + strategy: + matrix: + std: [11, 14, 17, 20, 23] + fail-fast: false + steps: + - uses: actions/checkout@v3 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 + - name: cmake + run: > + cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release + -DFLATBUFFERS_STRICT_MODE=ON + -DFLATBUFFERS_CPP_STD=${{ matrix.std }} + -DFLATBUFFERS_BUILD_CPP17=${{ matrix.std >= 17 && 'On' || 'Off'}} + - name: build + run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 + - name: test + run: Release\flattests.exe + - name: test C++17 + if: matrix.std >= 17 + run: Release\flattests_cpp17.exe + + build-windows: + permissions: + contents: write + outputs: + digests: ${{ steps.hash.outputs.hashes }} + name: Build Windows 2019 + runs-on: windows-2019 + steps: + - uses: actions/checkout@v3 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 + - name: cmake + run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON . + - name: build + run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 + - name: test + run: Release\flattests.exe + - name: upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: Windows flatc binary + path: Release\flatc.exe + # Below if only for release. + - name: Zip file + if: startsWith(github.ref, 'refs/tags/') + run: move Release/flatc.exe . && Compress-Archive flatc.exe Windows.flatc.binary.zip + - name: Release binary + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + files: Windows.flatc.binary.zip + - name: Generate SLSA subjects + if: startsWith(github.ref, 'refs/tags/') + id: hash + shell: bash + run: echo "hashes=$(sha256sum Windows.flatc.binary.zip | base64 -w0)" >> $GITHUB_OUTPUT + + build-dotnet-windows: + name: Build .NET Windows + runs-on: windows-2022-64core + strategy: + matrix: + configuration: [ + '', + '-p:UnsafeByteBuffer=true', + # Fails two tests currently. + #'-p:EnableSpanT=true,UnsafeByteBuffer=true' + ] + steps: + - uses: actions/checkout@v3 + - name: Setup .NET Core SDK + uses: actions/setup-dotnet@v4.2.0 + with: + dotnet-version: '8.0.x' + - name: Build + run: | + cd tests\FlatBuffers.Test + dotnet new sln --force --name FlatBuffers.Test + dotnet sln FlatBuffers.Test.sln add FlatBuffers.Test.csproj + dotnet build -c Release ${{matrix.configuration}} FlatBuffers.Test.sln + - name: Run net6.0 + run: | + cd tests\FlatBuffers.Test\bin\Release\net6.0 + dir + .\FlatBuffers.Test.exe + - name: Run net8.0 + run: | + cd tests\FlatBuffers.Test\bin\Release\net8.0 + .\FlatBuffers.Test.exe + + build-mac-intel: + permissions: + contents: write + outputs: + digests: ${{ steps.hash.outputs.hashes }} + name: Build Mac (for Intel) + runs-on: macos-latest-large + steps: + - uses: actions/checkout@v3 + - name: cmake + run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . + - name: build + run: xcodebuild -toolchain clang -configuration Release -target flattests + - name: check that the binary is x86_64 + run: | + info=$(file Release/flatc) + echo $info + echo $info | grep "Mach-O 64-bit executable x86_64" + - name: test + run: Release/flattests + - name: make flatc executable + run: | + chmod +x Release/flatc + Release/flatc --version + - name: upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: Mac flatc binary Intel + path: Release/flatc + # Below if only for release. + - name: Zip file + if: startsWith(github.ref, 'refs/tags/') + run: mv Release/flatc . && zip MacIntel.flatc.binary.zip flatc + - name: Release binary + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + files: MacIntel.flatc.binary.zip + - name: Generate SLSA subjects + if: startsWith(github.ref, 'refs/tags/') + id: hash + run: echo "hashes=$(shasum -a 256 MacIntel.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT + + build-mac-universal: + permissions: + contents: write + outputs: + digests: ${{ steps.hash.outputs.hashes }} + name: Build Mac (universal build) + runs-on: macos-latest + steps: + - uses: actions/checkout@v3 + - name: cmake + run: cmake -G "Xcode" -DCMAKE_OSX_ARCHITECTURES="arm64;x86_64" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . + - name: build + run: xcodebuild -toolchain clang -configuration Release -target flattests + - name: check that the binary is "universal" + run: | + info=$(file Release/flatc) + echo $info + echo $info | grep "Mach-O universal binary with 2 architectures" + - name: test + run: Release/flattests + - name: make flatc executable + run: | + chmod +x Release/flatc + Release/flatc --version + - name: upload build artifacts + uses: actions/upload-artifact@v4 + with: + name: Mac flatc binary Universal + path: Release/flatc + # Below if only for release. + - name: Zip file + if: startsWith(github.ref, 'refs/tags/') + run: mv Release/flatc . && zip Mac.flatc.binary.zip flatc + - name: Release binary + uses: softprops/action-gh-release@v1 + if: startsWith(github.ref, 'refs/tags/') + with: + files: Mac.flatc.binary.zip + - name: Generate SLSA subjects + if: startsWith(github.ref, 'refs/tags/') + id: hash + run: echo "hashes=$(shasum -a 256 Mac.flatc.binary.zip | base64)" >> $GITHUB_OUTPUT + + build-android: + name: Build Android (on Linux) + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: set up Java + uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '11' + - name: set up flatc + run: | + cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . + make -j + echo "${PWD}" >> $GITHUB_PATH + - name: build + working-directory: android + run: gradle clean build + + build-generator: + name: Check Generated Code + runs-on: ubuntu-24.04 + strategy: + matrix: + cxx: [g++-13, clang++-18] + steps: + - uses: actions/checkout@v3 + - name: cmake + run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_BUILD_TESTS=OFF -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: Generate + run: scripts/check_generate_code.py + - name: Generate gRPC + run: scripts/check-grpc-generated-code.py + + build-generator-windows: + name: Check Generated Code on Windows + runs-on: windows-2019 + steps: + - uses: actions/checkout@v3 + - name: Add msbuild to PATH + uses: microsoft/setup-msbuild@v1.1 + - name: cmake + run: cmake -G "Visual Studio 16 2019" -A x64 -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_CPP17=ON -DFLATBUFFERS_STRICT_MODE=ON . + - name: build + run: msbuild.exe FlatBuffers.sln /p:Configuration=Release /p:Platform=x64 + - name: Generate + run: python3 scripts/check_generate_code.py --flatc Release\flatc.exe + - name: Generate gRPC + run: python3 scripts/check-grpc-generated-code.py --flatc Release\flatc.exe + + build-benchmarks: + name: Build Benchmarks (on Linux) + runs-on: ubuntu-24.04 + strategy: + matrix: + cxx: [g++-13] + steps: + - uses: actions/checkout@v3 + - name: cmake + run: CXX=${{ matrix.cxx }} cmake -G "Unix Makefiles" -DFLATBUFFERS_CXX_FLAGS="-Wno-unused-parameter -fno-aligned-new" -DFLATBUFFERS_BUILD_BENCHMARKS=ON -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: Run benchmarks + run: ./flatbenchmark --benchmark_repetitions=5 --benchmark_display_aggregates_only=true --benchmark_out_format=console --benchmark_out=benchmarks/results_${{matrix.cxx}} + - name: Upload benchmarks results + uses: actions/upload-artifact@v4 + with: + name: Linux flatbenchmark results ${{matrix.cxx}} + path: benchmarks/results_${{matrix.cxx}} + + build-java: + name: Build Java + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: test + working-directory: java + run: mvn test + + build-kotlin-macos: + name: Build Kotlin MacOS + runs-on: macos-13 + steps: + - name: Checkout + uses: actions/checkout@v3 + # Force Xcode 14.3 since Xcode 15 doesnt support older versions of + # kotlin. For Xcode 15, kotlin should be bumpped to 1.9.10 + # https://stackoverflow.com/a/77150623 + # For now, run with macos-13 which has this 14.3 installed: + # https://github.com/actions/runner-images/blob/main/images/macos/macos-13-Readme.md#xcode + - name: Set up Xcode version + run: sudo xcode-select -s /Applications/Xcode_14.3.app/Contents/Developer + - uses: gradle/wrapper-validation-action@v1.0.5 + - uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '11' + - name: Build flatc + run: | + cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . + make -j + echo "${PWD}" >> $GITHUB_PATH + - name: Build + working-directory: kotlin + run: ./gradlew clean iosSimulatorArm64Test macosX64Test macosArm64Test + + build-kotlin-linux: + name: Build Kotlin Linux + runs-on: ubuntu-24.04 + steps: + - name: Checkout + uses: actions/checkout@v3 + - uses: actions/setup-java@v3 + with: + distribution: 'temurin' + java-version: '11' + - uses: gradle/wrapper-validation-action@v1.0.5 + - name: Build flatc + run: | + cmake -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . + make -j + echo "${PWD}" >> $GITHUB_PATH + - name: Build + working-directory: kotlin + # we are using docker's version of gradle + # so no need for wrapper validation or user + # gradlew + run: gradle jvmMainClasses jvmTest jsTest jsBrowserTest + + build-rust-linux: + name: Build Rust Linux + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: test + working-directory: tests + run: bash RustTest.sh + + build-rust-windows: + name: Build Rust Windows + runs-on: windows-2022-64core + steps: + - uses: actions/checkout@v3 + - name: test + working-directory: tests + run: ./RustTest.bat + + build-python: + name: Build Python + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: flatc + # FIXME: make test script not rely on flatc + run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: test + working-directory: tests + run: bash PythonTest.sh + + build-go: + name: Build Go + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: flatc + # FIXME: make test script not rely on flatc + run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: test + working-directory: tests + run: bash GoTest.sh + + build-php: + name: Build PHP + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: flatc + # FIXME: make test script not rely on flatc + run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: test + working-directory: tests + run: | + php phpTest.php + sh phpUnionVectorTest.sh + + build-swift: + name: Build Swift + strategy: + matrix: + swift: ["5.9", "5.10", "6.0"] + # Only 22.04 has swift at the moment https://github.com/actions/runner-images/blob/main/images/ubuntu/Ubuntu2204-Readme.md?plain=1#L30 + runs-on: ubuntu-22.04 + steps: + - uses: actions/checkout@v3 + - uses: swift-actions/setup-swift@v2 + with: + swift-version: ${{ matrix.swift }} + - name: Get swift version + run: swift --version + - name: test + working-directory: tests/swift/tests + run: | + swift build --build-tests + swift test + + build-swift-wasm: + name: Build Swift Wasm + runs-on: ubuntu-24.04 + container: + image: ghcr.io/swiftwasm/carton:0.20.1 + steps: + - uses: actions/checkout@v3 + - uses: bytecodealliance/actions/wasmtime/setup@v1 + - uses: swiftwasm/setup-swiftwasm@v1 + with: + swift-version: "wasm-6.0.2-RELEASE" + - name: Test + working-directory: tests/swift/Wasm.tests + run: swift run carton test + + build-ts: + name: Build TS + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: flatc + # FIXME: make test script not rely on flatc + run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j + - name: deps + run: yarn + - name: compile + run: yarn compile + - name: test + working-directory: tests/ts + run: | + yarn global add esbuild + python3 TypeScriptTest.py + + build-dart: + name: Build Dart + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - uses: dart-lang/setup-dart@v1 + with: + sdk: stable + - name: flatc + # FIXME: make test script not rely on flatc + run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF -DFLATBUFFERS_STRICT_MODE=ON . && make -j + - name: test + working-directory: tests + run: bash DartTest.sh + + build-nim: + name: Build Nim + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: flatc + # FIXME: make test script not rely on flatc + run: cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release -DFLATBUFFERS_BUILD_TESTS=OFF -DFLATBUFFERS_INSTALL=OFF -DFLATBUFFERS_BUILD_FLATLIB=OFF -DFLATBUFFERS_BUILD_FLATHASH=OFF . && make -j + - uses: jiro4989/setup-nim-action@v1 + - name: install library + working-directory: nim + run: nimble -y develop && nimble install + - name: test + working-directory: tests/nim + run: python3 testnim.py + + bazel: + name: Bazel + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v3 + - name: bazel build + run: > + bazel build + //:flatc + //:flatbuffers + - name: bazel test + run: > + bazel test + //tests:flatbuffers_test + + release-digests: + if: startsWith(github.ref, 'refs/tags/') + needs: [build-linux, build-windows, build-mac-intel, build-mac-universal] + outputs: + digests: ${{ steps.hash.outputs.digests }} + runs-on: ubuntu-24.04 + steps: + - name: Merge results + id: hash + env: + LINUXGCC_DIGESTS: "${{ needs.build-linux.outputs.digests-gcc }}" + LINUXCLANG_DIGESTS: "${{ needs.build-linux.outputs.digests-clang }}" + MAC_DIGESTS: "${{ needs.build-mac-universal.outputs.digests }}" + MACINTEL_DIGESTS: "${{ needs.build-mac-intel.outputs.digests }}" + WINDOWS_DIGESTS: "${{ needs.build-windows.outputs.digests }}" + run: | + set -euo pipefail + echo "$LINUXGCC_DIGESTS" | base64 -d > checksums.txt + echo "$LINUXCLANG_DIGESTS" | base64 -d >> checksums.txt + echo "$MAC_DIGESTS" | base64 -d >> checksums.txt + echo "$MACINTEL_DIGESTS" | base64 -d >> checksums.txt + echo "$WINDOWS_DIGESTS" | base64 -d >> checksums.txt + echo "digests=$(cat checksums.txt | base64 -w0)" >> $GITHUB_OUTPUT + + provenance: + if: startsWith(github.ref, 'refs/tags/') + needs: [release-digests] + permissions: + actions: read # To read the workflow path. + id-token: write # To sign the provenance. + contents: write # To add assets to a release. + uses: slsa-framework/slsa-github-generator/.github/workflows/generator_generic_slsa3.yml@v1.2.1 + with: + base64-subjects: "${{ needs.release-digests.outputs.digests }}" + upload-assets: true # Optional: Upload to a new release + compile-generator: true # Workaround for https://github.com/slsa-framework/slsa-github-generator/issues/1163 diff --git a/third_party/flatbuffers/.github/workflows/docs.yml b/third_party/flatbuffers/.github/workflows/docs.yml new file mode 100644 index 00000000000..cac8561828b --- /dev/null +++ b/third_party/flatbuffers/.github/workflows/docs.yml @@ -0,0 +1,36 @@ +name: docs +on: + # For manual pushes. + workflow_dispatch: + + # Pushes to main that touch the documentation directory. + push: + branches: + - master + paths: + - 'docs/**' + +permissions: + contents: write +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + - name: Configure Git Credentials + run: | + git config user.name github-actions[bot] + git config user.email 41898282+github-actions[bot]@users.noreply.github.com + - uses: actions/setup-python@v5 + with: + python-version: 3.x + - run: echo "cache_id=$(date --utc '+%V')" >> $GITHUB_ENV + - uses: actions/cache@v4 + with: + key: mkdocs-material-${{ env.cache_id }} + path: .cache + restore-keys: | + mkdocs-material- + - run: pip install mkdocs-material + - run: pip install mkdocs-redirects + - run: mkdocs gh-deploy --force -f docs/mkdocs.yml diff --git a/third_party/flatbuffers/.github/workflows/label.yml b/third_party/flatbuffers/.github/workflows/label.yml new file mode 100644 index 00000000000..8749a9f5d6f --- /dev/null +++ b/third_party/flatbuffers/.github/workflows/label.yml @@ -0,0 +1,24 @@ +# This workflow will triage pull requests and apply a label based on the +# paths that are modified in the pull request. +# +# To use this workflow, you will need to set up a .github/labeler.yml +# file with configuration. For more information, see: +# https://github.com/actions/labeler + +name: Labeler +permissions: read-all + +on: [pull_request_target] + +jobs: + label: + permissions: + contents: read + pull-requests: write + + runs-on: ubuntu-latest + + steps: + - uses: actions/labeler@ee18d5d34efd9b4f7dafdb0e363cb688eb438044 # 4.1.0 + with: + repo-token: "${{ secrets.GITHUB_TOKEN }}" diff --git a/third_party/flatbuffers/.github/workflows/main.yml b/third_party/flatbuffers/.github/workflows/main.yml new file mode 100644 index 00000000000..9a900953924 --- /dev/null +++ b/third_party/flatbuffers/.github/workflows/main.yml @@ -0,0 +1,34 @@ +name: OSS-Fuzz +permissions: read-all + +on: + pull_request: + branches: + - master + paths: + - include/** + - src/** + - tests/**.cpp + - tests/**.h +jobs: + Fuzzing: + runs-on: ubuntu-latest + steps: + - name: Build Fuzzers + id: build + uses: google/oss-fuzz/infra/cifuzz/actions/build_fuzzers@master + with: + oss-fuzz-project-name: 'flatbuffers' + language: c++ + - name: Run Fuzzers + uses: google/oss-fuzz/infra/cifuzz/actions/run_fuzzers@master + with: + oss-fuzz-project-name: 'flatbuffers' + language: c++ + fuzz-seconds: 60 + - name: Upload Crash + uses: actions/upload-artifact@v4 + if: failure() && steps.build.outcome == 'success' + with: + name: artifacts + path: ./out/artifacts diff --git a/third_party/flatbuffers/.github/workflows/release.yml b/third_party/flatbuffers/.github/workflows/release.yml new file mode 100644 index 00000000000..b39b04c5ffa --- /dev/null +++ b/third_party/flatbuffers/.github/workflows/release.yml @@ -0,0 +1,152 @@ +name: Release +permissions: read-all + +on: + # For manual tests. + workflow_dispatch: + release: + types: [published] + +jobs: + publish-npm: + name: Publish NPM + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-node@v3 + with: + node-version: '20.x' + registry-url: 'https://registry.npmjs.org' + + - run: npm publish + env: + NODE_AUTH_TOKEN: ${{ secrets.NPM_TOKEN }} + + publish-pypi: + name: Publish PyPi + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./python + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-python@v4 + with: + python-version: '3.10' + + - name: Install Dependencies + run: | + python3 -m pip install --upgrade pip + python3 -m pip install setuptools wheel twine + + - name: Build + run: | + python3 setup.py sdist bdist_wheel + + - name: Upload to PyPi + run: | + python3 -m twine upload dist/* + env: + TWINE_USERNAME: __token__ + TWINE_PASSWORD: ${{ secrets.TWINE_TOKEN }} + + publish-nuget: + name: Publish NuGet + runs-on: windows-latest + defaults: + run: + working-directory: ./net/flatbuffers + steps: + - uses: actions/checkout@v3 + - uses: actions/setup-dotnet@v3 + with: + dotnet-version: '8.0.x' + - name: Build + run: | + dotnet build Google.FlatBuffers.csproj -c Release + + - name: Pack + run: | + dotnet pack Google.FlatBuffers.csproj -c Release + + - name: Upload to NuGet + run: | + dotnet nuget push .\bin\Release\Google.FlatBuffers.*.nupkg -k ${{ secrets.NUGET_API_KEY }} -s https://api.nuget.org/v3/index.json + + publish-maven: + name: Publish Maven + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./java + steps: + - uses: actions/checkout@v3 + + - name: Set up Maven Central Repository + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'adopt' + cache: 'maven' + server-id: ossrh + server-username: OSSRH_USERNAME + server-password: OSSRH_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var + + - name: Publish Maven + run: mvn --batch-mode clean deploy + env: + OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + publish-maven-kotlin: + name: Publish Maven - Kotlin + runs-on: ubuntu-latest + defaults: + run: + working-directory: ./kotlin + steps: + - uses: actions/checkout@v3 + - name: Set up Maven Central Repository + uses: actions/setup-java@v3 + with: + java-version: '11' + distribution: 'adopt' + cache: 'maven' + server-id: ossrh + server-username: OSSRH_USERNAME + server-password: OSSRH_PASSWORD + gpg-private-key: ${{ secrets.MAVEN_GPG_PRIVATE_KEY }} + gpg-passphrase: MAVEN_GPG_PASSPHRASE # this needs to be an env var + + - name: Publish Kotlin Library on Maven + run: ./gradlew publishAllPublicationsToSonatypeRepository + env: + OSSRH_USERNAME: ${{ secrets.OSSRH_USER_V2 }} + OSSRH_PASSWORD: ${{ secrets.OSSRH_TOKEN_V2 }} + MAVEN_GPG_PASSPHRASE: ${{ secrets.MAVEN_GPG_PASSPHRASE }} + + + publish-crates: + name: Publish crates.io + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v3 + - uses: actions-rs/toolchain@v1 + with: + toolchain: stable + override: true + + - name: Publish Flatbuffers + uses: katyo/publish-crates@v2 + with: + path: ./rust/flatbuffers + registry-token: ${{ secrets.CARGO_TOKEN }} + + - name: Publish Flexbuffers + uses: katyo/publish-crates@v2 + with: + path: ./rust/flexbuffers + registry-token: ${{ secrets.CARGO_TOKEN }} diff --git a/third_party/flatbuffers/.github/workflows/stale.yml b/third_party/flatbuffers/.github/workflows/stale.yml new file mode 100644 index 00000000000..6f9bac59654 --- /dev/null +++ b/third_party/flatbuffers/.github/workflows/stale.yml @@ -0,0 +1,37 @@ +name: Mark stale issues and pull requests +permissions: + issues: write + pull-requests: write + +on: + # For manual tests. + workflow_dispatch: + schedule: + - cron: "30 20 * * *" + +jobs: + stale: + + runs-on: ubuntu-latest + + steps: + - uses: actions/stale@v7.0.0 + with: + repo-token: ${{ secrets.GITHUB_TOKEN }} + operations-per-run: 500 + exempt-all-milestones: true + remove-stale-when-updated: true + + stale-issue-message: 'This issue is stale because it has been open 6 months with no activity. Please comment or label `not-stale`, or this will be closed in 14 days.' + close-issue-message: 'This issue was automatically closed due to no activity for 6 months plus the 14 day notice period.' + days-before-issue-stale: 182 # 6 months + days-before-issue-close: 14 # 2 weeks + exempt-issue-labels: not-stale + + stale-pr-message: 'This pull request is stale because it has been open 6 months with no activity. Please comment or label `not-stale`, or this will be closed in 14 days.' + close-pr-message: 'This pull request was automatically closed due to no activity for 6 months plus the 14 day notice period.' + days-before-pr-stale: 182 # 6 months + days-before-pr-close: 14 # 2 week + exempt-pr-labels: not-stale + exempt-draft-pr: false + diff --git a/third_party/flatbuffers/.gitignore b/third_party/flatbuffers/.gitignore index 828ca1d618e..0296f8fac36 100644 --- a/third_party/flatbuffers/.gitignore +++ b/third_party/flatbuffers/.gitignore @@ -153,3 +153,7 @@ cmake-build-debug/ _deps/ **/.gradle/** kotlin/**/generated +MODULE.bazel.lock + +# Ignore the generated docs +docs/site \ No newline at end of file diff --git a/third_party/flatbuffers/BUILD.bazel b/third_party/flatbuffers/BUILD.bazel index b4f015a0e29..20a4fd60a4d 100644 --- a/third_party/flatbuffers/BUILD.bazel +++ b/third_party/flatbuffers/BUILD.bazel @@ -1,5 +1,3 @@ -load("@aspect_rules_js//npm:defs.bzl", "npm_link_package") -load("@npm//:defs.bzl", "npm_link_all_packages") load("@rules_cc//cc:defs.bzl", "cc_binary", "cc_library") licenses(["notice"]) @@ -8,13 +6,6 @@ package( default_visibility = ["//visibility:public"], ) -npm_link_all_packages(name = "node_modules") - -npm_link_package( - name = "node_modules/flatbuffers", - src = "//ts:flatbuffers", -) - exports_files([ "LICENSE", "tsconfig.json", @@ -37,11 +28,16 @@ config_setting( filegroup( name = "distribution", srcs = [ + ".bazelignore", + ".npmrc", "BUILD.bazel", - "WORKSPACE", + "MODULE.bazel", "build_defs.bzl", + "package.json", + "pnpm-lock.yaml", "typescript.bzl", "//grpc/src/compiler:distribution", + "//include/codegen:distribution", "//reflection:distribution", "//src:distribution", "//ts:distribution", @@ -125,15 +121,7 @@ filegroup( # Library used by flatbuffer_cc_library rules. cc_library( name = "runtime_cc", - hdrs = [ - "include/flatbuffers/base.h", - "include/flatbuffers/flatbuffers.h", - "include/flatbuffers/flexbuffers.h", - "include/flatbuffers/stl_emulation.h", - "include/flatbuffers/util.h", - "include/flatbuffers/vector.h", - "include/flatbuffers/verifier.h", - ], + hdrs = ["//:public_headers"], linkstatic = 1, strip_include_prefix = "/include", ) diff --git a/third_party/flatbuffers/CHANGELOG.md b/third_party/flatbuffers/CHANGELOG.md index 2b0380df6c5..bb713fd632e 100644 --- a/third_party/flatbuffers/CHANGELOG.md +++ b/third_party/flatbuffers/CHANGELOG.md @@ -4,6 +4,22 @@ All major or breaking changes will be documented in this file, as well as any new features that should be highlighted. Minor fixes or improvements are not necessarily listed. +## [25.2.10] (February 10 2025)(https://github.com/google/flatbuffers/releases/tag/v25.2.10) + +* Removed the old documentation pages. The new one is live at https://flatbuffers.dev +* Swift version 6.0 support (#8414) + +## [25.1.24] (January 24 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.24) + +* Mostly related to bazel build support. +* Min bazel supported is now 7 or higher, as WORKSPACE files are removed (#8509) +* Minor C++ codegen fix removing extra semicolon (#8488) + +## [25.1.21] (January 21 2025)(https://github.com/google/flatbuffers/releases/tag/v25.1.21) + +* Rust Full Reflection (#8102) +* Mostly documentation updates hosted at https://flatbuffers.dev + ## [24.3.25] (March 25 2024)(https://github.com/google/flatbuffers/releases/tag/v24.3.25) * Fixed license metadata parsing (#8253) diff --git a/third_party/flatbuffers/CMake/Version.cmake b/third_party/flatbuffers/CMake/Version.cmake index df18fe47a08..fe432980fef 100644 --- a/third_party/flatbuffers/CMake/Version.cmake +++ b/third_party/flatbuffers/CMake/Version.cmake @@ -1,6 +1,6 @@ -set(VERSION_MAJOR 24) -set(VERSION_MINOR 3) -set(VERSION_PATCH 25) +set(VERSION_MAJOR 25) +set(VERSION_MINOR 2) +set(VERSION_PATCH 10) set(VERSION_COMMIT 0) if(EXISTS "${CMAKE_CURRENT_SOURCE_DIR}/.git") diff --git a/third_party/flatbuffers/CMakeLists.txt b/third_party/flatbuffers/CMakeLists.txt index c03688533a7..e7038f89d73 100644 --- a/third_party/flatbuffers/CMakeLists.txt +++ b/third_party/flatbuffers/CMakeLists.txt @@ -183,6 +183,10 @@ set(FlatBuffers_Compiler_SRCS src/bfbs_gen_lua.h src/bfbs_gen_nim.h src/bfbs_namer.h + include/codegen/idl_namer.h + include/codegen/namer.h + include/codegen/python.h + include/codegen/python.cc include/flatbuffers/code_generators.h src/binary_annotator.h src/binary_annotator.cpp diff --git a/third_party/flatbuffers/FlatBuffers.podspec b/third_party/flatbuffers/FlatBuffers.podspec index 2aa69e2a027..61c318fd5b9 100644 --- a/third_party/flatbuffers/FlatBuffers.podspec +++ b/third_party/flatbuffers/FlatBuffers.podspec @@ -1,6 +1,6 @@ Pod::Spec.new do |s| s.name = 'FlatBuffers' - s.version = '24.3.25' + s.version = '25.2.10' s.summary = 'FlatBuffers: Memory Efficient Serialization Library' s.description = "FlatBuffers is a cross platform serialization library architected for @@ -10,12 +10,15 @@ Pod::Spec.new do |s| s.homepage = 'https://github.com/google/flatbuffers' s.license = { :type => 'Apache2.0', :file => 'LICENSE' } - s.author = { 'mustii' => 'mustii@mmk.one' } - s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => s.version.to_s, :submodules => true } + s.author = { 'mustii' => 'me@mustiikhalil.se' } + s.source = { :git => 'https://github.com/google/flatbuffers.git', :tag => "v" + s.version.to_s, :submodules => true } s.ios.deployment_target = '11.0' s.osx.deployment_target = '10.14' s.swift_version = '5.0' s.source_files = 'swift/Sources/Flatbuffers/*.swift' + s.pod_target_xcconfig = { + 'BUILD_LIBRARY_FOR_DISTRIBUTION' => 'YES' + } end diff --git a/third_party/flatbuffers/MODULE.bazel b/third_party/flatbuffers/MODULE.bazel new file mode 100644 index 00000000000..d0f0f5b2773 --- /dev/null +++ b/third_party/flatbuffers/MODULE.bazel @@ -0,0 +1,77 @@ +module( + name = "flatbuffers", + version = "25.2.10", + compatibility_level = 1, + repo_name = "com_github_google_flatbuffers", +) + +bazel_dep( + name = "aspect_bazel_lib", + version = "2.11.0", +) +bazel_dep( + name = "aspect_rules_esbuild", + version = "0.21.0", +) +bazel_dep( + name = "aspect_rules_js", + version = "2.1.3", +) +bazel_dep( + name = "aspect_rules_ts", + version = "3.4.0", +) +bazel_dep( + name = "grpc", + version = "1.70.1", + repo_name = "com_github_grpc_grpc", +) +bazel_dep( + name = "platforms", + version = "0.0.10", +) +bazel_dep( + name = "rules_cc", + version = "0.0.16", +) +bazel_dep( + name = "rules_go", + version = "0.50.1", + repo_name = "io_bazel_rules_go", +) +bazel_dep( + name = "rules_nodejs", + version = "6.3.3", +) +bazel_dep( + name = "rules_shell", + version = "0.3.0", +) +bazel_dep( + name = "rules_swift", + version = "2.1.1", + repo_name = "build_bazel_rules_swift", +) +bazel_dep( + name = "bazel_skylib", + version = "1.7.1", +) + +npm = use_extension("@aspect_rules_js//npm:extensions.bzl", "npm") +npm.npm_translate_lock( + name = "flatbuffers_npm", + npmrc = "//:.npmrc", + pnpm_lock = "//ts:pnpm-lock.yaml", + # Override the Bazel package where pnpm-lock.yaml is located and link + # to the specified package instead. + root_package = "ts", + verify_node_modules_ignored = "//:.bazelignore", +) +use_repo(npm, "flatbuffers_npm") + +node = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node") +use_repo(node, "nodejs_linux_amd64") + +rules_ts_ext = use_extension("@aspect_rules_ts//ts:extensions.bzl", "ext") +rules_ts_ext.deps() +use_repo(rules_ts_ext, "npm_typescript") diff --git a/third_party/flatbuffers/Package.swift b/third_party/flatbuffers/Package.swift index 0fc26da7601..ad6f0e866c2 100644 --- a/third_party/flatbuffers/Package.swift +++ b/third_party/flatbuffers/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.6 +// swift-tools-version:5.9 /* * Copyright 2020 Google Inc. All rights reserved. * diff --git a/third_party/flatbuffers/README.md b/third_party/flatbuffers/README.md index 47d506720e1..7b64a427d08 100644 --- a/third_party/flatbuffers/README.md +++ b/third_party/flatbuffers/README.md @@ -4,8 +4,6 @@ ![Build status](https://github.com/google/flatbuffers/actions/workflows/build.yml/badge.svg?branch=master) [![BuildKite status](https://badge.buildkite.com/7979d93bc6279aa539971f271253c65d5e8fe2fe43c90bbb25.svg)](https://buildkite.com/bazel/flatbuffers) [![Fuzzing Status](https://oss-fuzz-build-logs.storage.googleapis.com/badges/flatbuffers.svg)](https://bugs.chromium.org/p/oss-fuzz/issues/list?sort=-opened&can=1&q=proj:flatbuffers) -[![OpenSSF Scorecard](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers/badge)](https://api.securityscorecards.dev/projects/github.com/google/flatbuffers) -[![Join the chat at https://gitter.im/google/flatbuffers](https://badges.gitter.im/google/flatbuffers.svg)](https://gitter.im/google/flatbuffers?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge) [![Discord Chat](https://img.shields.io/discord/656202785926152206.svg)](https:///discord.gg/6qgKs3R) [![Twitter Follow](https://img.shields.io/twitter/follow/wvo.svg?style=social)](https://twitter.com/wvo) [![Twitter Follow](https://img.shields.io/twitter/follow/dbaileychess.svg?style=social)](https://twitter.com/dbaileychess) @@ -18,7 +16,7 @@ maximum memory efficiency. It allows you to directly access serialized data with 1. Build the compiler for flatbuffers (`flatc`) - Use `cmake` to create the build files for your platform and then perform the compliation (Linux example). + Use `cmake` to create the build files for your platform and then perform the compilation (Linux example). ``` cmake -G "Unix Makefiles" diff --git a/third_party/flatbuffers/WORKSPACE b/third_party/flatbuffers/WORKSPACE deleted file mode 100644 index e56d4ce364b..00000000000 --- a/third_party/flatbuffers/WORKSPACE +++ /dev/null @@ -1,169 +0,0 @@ -workspace(name = "com_github_google_flatbuffers") - -load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive", "http_file") - -http_archive( - name = "platforms", - sha256 = "3a561c99e7bdbe9173aa653fd579fe849f1d8d67395780ab4770b1f381431d51", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz", - "https://github.com/bazelbuild/platforms/releases/download/0.0.7/platforms-0.0.7.tar.gz", - ], -) - -http_archive( - name = "build_bazel_rules_apple", - sha256 = "34c41bfb59cdaea29ac2df5a2fa79e5add609c71bb303b2ebb10985f93fa20e7", - url = "https://github.com/bazelbuild/rules_apple/releases/download/3.1.1/rules_apple.3.1.1.tar.gz", -) - -load( - "@build_bazel_rules_apple//apple:repositories.bzl", - "apple_rules_dependencies", -) - -apple_rules_dependencies() - -http_archive( - name = "build_bazel_rules_swift", - sha256 = "a2fd565e527f83fb3f9eb07eb9737240e668c9242d3bc318712efa54a7deda97", - url = "https://github.com/bazelbuild/rules_swift/releases/download/0.27.0/rules_swift.0.27.0.tar.gz", -) - -load( - "@build_bazel_rules_swift//swift:repositories.bzl", - "swift_rules_dependencies", -) - -swift_rules_dependencies() - -load( - "@build_bazel_rules_swift//swift:extras.bzl", - "swift_rules_extra_dependencies", -) - -swift_rules_extra_dependencies() - -http_archive( - name = "io_bazel_rules_go", - sha256 = "278b7ff5a826f3dc10f04feaf0b70d48b68748ccd512d7f98bf442077f043fe3", - urls = [ - "https://mirror.bazel.build/github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip", - "https://github.com/bazelbuild/rules_go/releases/download/v0.41.0/rules_go-v0.41.0.zip", - ], -) - -load("@io_bazel_rules_go//go:deps.bzl", "go_rules_dependencies") - -go_rules_dependencies() - -##### Protobuf -_PROTOBUF_VERSION = "3.15.2" - -http_archive( - name = "com_google_protobuf", - strip_prefix = "protobuf-" + _PROTOBUF_VERSION, - urls = [ - "https://github.com/protocolbuffers/protobuf/archive/v" + _PROTOBUF_VERSION + ".tar.gz", - ], -) - -##### GRPC -_GRPC_VERSION = "1.49.0" # https://github.com/grpc/grpc/releases/tag/v1.48.0 - -http_archive( - name = "com_github_grpc_grpc", - patch_args = ["-p1"], - patches = ["//grpc:build_grpc_with_cxx14.patch"], - sha256 = "15715e1847cc9e42014f02c727dbcb48e39dbdb90f79ad3d66fe4361709ff935", - strip_prefix = "grpc-" + _GRPC_VERSION, - urls = ["https://github.com/grpc/grpc/archive/refs/tags/v" + _GRPC_VERSION + ".tar.gz"], -) - -load("@com_github_grpc_grpc//bazel:grpc_deps.bzl", "grpc_deps") - -grpc_deps() - -load("@com_github_grpc_grpc//bazel:grpc_extra_deps.bzl", "grpc_extra_deps") - -grpc_extra_deps() - -# rules_go from https://github.com/bazelbuild/rules_go/releases/tag/v0.34.0 - -http_archive( - name = "aspect_rules_js", - sha256 = "76a04ef2120ee00231d85d1ff012ede23963733339ad8db81f590791a031f643", - strip_prefix = "rules_js-1.34.1", - url = "https://github.com/aspect-build/rules_js/releases/download/v1.34.1/rules_js-v1.34.1.tar.gz", -) - -load("@aspect_rules_js//js:repositories.bzl", "rules_js_dependencies") - -rules_js_dependencies() - -load("@aspect_rules_js//npm:npm_import.bzl", "npm_translate_lock", "pnpm_repository") - -pnpm_repository(name = "pnpm") - -http_archive( - name = "aspect_rules_ts", - sha256 = "4c3f34fff9f96ffc9c26635d8235a32a23a6797324486c7d23c1dfa477e8b451", - strip_prefix = "rules_ts-1.4.5", - url = "https://github.com/aspect-build/rules_ts/releases/download/v1.4.5/rules_ts-v1.4.5.tar.gz", -) - -load("@aspect_rules_ts//ts:repositories.bzl", "rules_ts_dependencies") - -rules_ts_dependencies( - # Since rules_ts doesn't always have the newest integrity hashes, we - # compute it manually here. - # $ curl --silent https://registry.npmjs.org/typescript/5.3.3 | jq ._integrity - ts_integrity = "sha512-pXWcraxM0uxAS+tN0AG/BF2TyqmHO014Z070UsJ+pFvYuRSq8KH8DmWpnbXe0pEPDHXZV3FcAbJkijJ5oNEnWw==", - ts_version_from = "//:package.json", -) - -load("@rules_nodejs//nodejs:repositories.bzl", "DEFAULT_NODE_VERSION", "nodejs_register_toolchains") - -nodejs_register_toolchains( - name = "nodejs", - node_version = DEFAULT_NODE_VERSION, -) - -npm_translate_lock( - name = "npm", - npmrc = "//:.npmrc", - pnpm_lock = "//:pnpm-lock.yaml", - # Set this to True when the lock file needs to be updated, commit the - # changes, then set to False again. - update_pnpm_lock = False, - verify_node_modules_ignored = "//:.bazelignore", -) - -load("@npm//:repositories.bzl", "npm_repositories") - -npm_repositories() - -http_archive( - name = "aspect_rules_esbuild", - sha256 = "098e38e5ee868c14a6484ba263b79e57d48afacfc361ba30137c757a9c4716d6", - strip_prefix = "rules_esbuild-0.15.0", - url = "https://github.com/aspect-build/rules_esbuild/releases/download/v0.15.0/rules_esbuild-v0.15.0.tar.gz", -) - -# Register a toolchain containing esbuild npm package and native bindings -load("@aspect_rules_esbuild//esbuild:repositories.bzl", "LATEST_ESBUILD_VERSION", "esbuild_register_toolchains") - -esbuild_register_toolchains( - name = "esbuild", - esbuild_version = LATEST_ESBUILD_VERSION, -) - -http_file( - name = "bazel_linux_x86_64", - downloaded_file_path = "bazel", - executable = True, - sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458", - urls = [ - "https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64", - ], -) diff --git a/third_party/flatbuffers/android/.project b/third_party/flatbuffers/android/.project new file mode 100644 index 00000000000..17f0659d4a1 --- /dev/null +++ b/third_party/flatbuffers/android/.project @@ -0,0 +1,22 @@ + + + FlatBufferTest + + + + + + + + + + 1672434305228 + + 30 + + org.eclipse.core.resources.regexFilterMatcher + node_modules|\.git|__CREATED_BY_JAVA_LANGUAGE_SERVER__ + + + + diff --git a/third_party/flatbuffers/android/AndroidManifest.xml b/third_party/flatbuffers/android/AndroidManifest.xml new file mode 100644 index 00000000000..a6c97492b17 --- /dev/null +++ b/third_party/flatbuffers/android/AndroidManifest.xml @@ -0,0 +1,31 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/flatbuffers/android/app/.gitignore b/third_party/flatbuffers/android/app/.gitignore new file mode 100644 index 00000000000..796b96d1c40 --- /dev/null +++ b/third_party/flatbuffers/android/app/.gitignore @@ -0,0 +1 @@ +/build diff --git a/third_party/flatbuffers/android/app/build.gradle b/third_party/flatbuffers/android/app/build.gradle new file mode 100644 index 00000000000..99417830993 --- /dev/null +++ b/third_party/flatbuffers/android/app/build.gradle @@ -0,0 +1,125 @@ +apply plugin: 'com.android.application' +apply plugin: 'kotlin-android' + +android { + compileSdk 33 + + defaultConfig { + applicationId "com.flatbuffers.app" + minSdkVersion 26 + targetSdkVersion 33 + versionCode 1 + versionName "1.0" + + compileOptions { + sourceCompatibility JavaVersion.VERSION_1_8 + targetCompatibility JavaVersion.VERSION_1_8 + } + + sourceSets { + main { + java { + srcDir '../../java/src/main/java/' + } + } + } + + ndk { + abiFilters 'arm64-v8a', 'armeabi-v7a' + } + + testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner" + externalNativeBuild { + cmake { + arguments "-DFLATBUFFERS_SRC=${rootProject.projectDir}/.." + } + } + } + + buildTypes { + release { + minifyEnabled false + proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro' + } + } + + externalNativeBuild { + cmake { + path "src/main/cpp/CMakeLists.txt" + } + } + + task generateFbsCpp(type: Exec) { + def inputDir = file("$projectDir/src/main/fbs") + def outputCppDir = file("$projectDir/src/main/cpp/generated/") + def fbsFiles = layout.files { file(inputDir).listFiles() }.filter { File f -> f.name.endsWith(".fbs") }.toList() + ignoreExitValue(true) + + standardOutput = new ByteArrayOutputStream() + errorOutput = new ByteArrayOutputStream() + def commandLineArgs = ['flatc', '-o', outputCppDir, '--cpp'] + fbsFiles.forEach{ + commandLineArgs.add(it.path) + } + + commandLine commandLineArgs + + doFirst { + delete "$outputCppDir/" + mkdir "$outputCppDir/" + } + + doLast { + if (executionResult.get().exitValue != 0) { + throw new GradleException("flatc failed with: ${executionResult.get().toString()}") + } + } + } + + task generateFbsKotlin(type: Exec) { + def inputDir = file("$projectDir/src/main/fbs") + def outputKotlinDir = file("$projectDir/src/main/java/generated/") + def fbsFiles = layout.files { file(inputDir).listFiles() }.filter { File f -> f.name.endsWith(".fbs") }.toList() + ignoreExitValue(true) + + standardOutput = new ByteArrayOutputStream() + errorOutput = new ByteArrayOutputStream() + + setErrorOutput(errorOutput) + setStandardOutput(standardOutput) + + def commandLineArgs = ['flatc', '-o', outputKotlinDir, '--kotlin'] + fbsFiles.forEach{ + commandLineArgs.add(it.path) + } + commandLine commandLineArgs + + doFirst { + delete "$outputKotlinDir/" + mkdir "$outputKotlinDir/" + } + doLast { + if (executionResult.get().exitValue != 0) { + throw new GradleException("flatc failed with: ${executionResult.get().toString()}") + } + } + } + + afterEvaluate { + tasks.named("preBuild") { + dependsOn(generateFbsKotlin) + dependsOn(generateFbsCpp) + } + } + namespace 'com.flatbuffers.app' +} + +dependencies { + implementation fileTree(dir: "libs", include: ["*.jar"]) + implementation "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" + implementation 'androidx.appcompat:appcompat:1.6.1' + + // If you using java runtime you can add its dependency as the example below + // implementation 'com.google.flatbuffers:flatbuffers-java:$latest_version' + +} diff --git a/third_party/flatbuffers/android/app/proguard-rules.pro b/third_party/flatbuffers/android/app/proguard-rules.pro new file mode 100644 index 00000000000..f1b424510da --- /dev/null +++ b/third_party/flatbuffers/android/app/proguard-rules.pro @@ -0,0 +1,21 @@ +# Add project specific ProGuard rules here. +# You can control the set of applied configuration files using the +# proguardFiles setting in build.gradle. +# +# For more details, see +# http://developer.android.com/guide/developing/tools/proguard.html + +# If your project uses WebView with JS, uncomment the following +# and specify the fully qualified class name to the JavaScript interface +# class: +#-keepclassmembers class fqcn.of.javascript.interface.for.webview { +# public *; +#} + +# Uncomment this to preserve the line number information for +# debugging stack traces. +#-keepattributes SourceFile,LineNumberTable + +# If you keep the line number information, uncomment this to +# hide the original source file name. +#-renamesourcefileattribute SourceFile diff --git a/third_party/flatbuffers/android/app/src/main/AndroidManifest.xml b/third_party/flatbuffers/android/app/src/main/AndroidManifest.xml new file mode 100644 index 00000000000..53caca65bcf --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/AndroidManifest.xml @@ -0,0 +1,21 @@ + + + + + + + + + + + + + + diff --git a/third_party/flatbuffers/android/app/src/main/cpp/CMakeLists.txt b/third_party/flatbuffers/android/app/src/main/cpp/CMakeLists.txt new file mode 100644 index 00000000000..abb8250bda0 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/cpp/CMakeLists.txt @@ -0,0 +1,53 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.4.1) + +# Creates and names a library, sets it as either STATIC +# or SHARED, and provides the relative paths to its source code. +# You can define multiple libraries, and CMake builds them for you. +# Gradle automatically packages shared libraries with your APK. + +include_directories(${FLATBUFFERS_SRC}/include) + +add_subdirectory(flatbuffers) + +FILE(GLOB Generated_SRCS generated/*.h) + +add_library( # Sets the name of the library. + native-lib + + # Sets the library as a shared library. + SHARED + + # Provides a relative path to your source file(s). + animals.cpp + ${Generated_SRCS} + +) + +# Searches for a specified prebuilt library and stores the path as a +# variable. Because CMake includes system libraries in the search path by +# default, you only need to specify the name of the public NDK library +# you want to add. CMake verifies that the library exists before +# completing its build. + +find_library( # Sets the name of the path variable. + log-lib + + # Specifies the name of the NDK library that + # you want CMake to locate. + log ) + +# Specifies libraries CMake should link to your target library. You +# can link multiple libraries, such as libraries you define in this +# build script, prebuilt third-party libraries, or system libraries. + +target_link_libraries( # Specifies the target library. + native-lib + flatbuffers + # Links the target library to the log library + # included in the NDK. + ${log-lib} ) diff --git a/third_party/flatbuffers/android/app/src/main/cpp/animals.cpp b/third_party/flatbuffers/android/app/src/main/cpp/animals.cpp new file mode 100644 index 00000000000..bf87b875c63 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/cpp/animals.cpp @@ -0,0 +1,39 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include +#include "generated/animal_generated.h" + +using namespace com::fbs::app; +using namespace flatbuffers; + +extern "C" JNIEXPORT jbyteArray JNICALL Java_com_flatbuffers_app_MainActivity_createAnimalFromJNI( + JNIEnv* env, + jobject /* this */) { + // create a new animal flatbuffers + auto fb = FlatBufferBuilder(1024); + auto tiger = CreateAnimalDirect(fb, "Tiger", "Roar", 300); + fb.Finish(tiger); + + // copies it to a Java byte array. + auto buf = reinterpret_cast(fb.GetBufferPointer()); + int size = fb.GetSize(); + auto ret = env->NewByteArray(size); + env->SetByteArrayRegion (ret, 0, fb.GetSize(), buf); + return ret; +} diff --git a/third_party/flatbuffers/android/app/src/main/cpp/flatbuffers/CMakeLists.txt b/third_party/flatbuffers/android/app/src/main/cpp/flatbuffers/CMakeLists.txt new file mode 100644 index 00000000000..144523ee85a --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/cpp/flatbuffers/CMakeLists.txt @@ -0,0 +1,56 @@ +# For more information about using CMake with Android Studio, read the +# documentation: https://d.android.com/studio/projects/add-native-code.html + +# Sets the minimum version of CMake required to build the native library. + +cmake_minimum_required(VERSION 3.4.1) + +include_directories(${FLATBUFFERS_SRC}/include) + +set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=gnu++11 -fexceptions -Wall -DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE") + +# Certain platforms such as ARM do not use signed chars by default +# which causes issues with certain bounds checks. +set(CMAKE_CXX_FLAGS + "${CMAKE_CXX_FLAGS} -fsigned-char") + +set(FlatBuffers_Library_SRCS + ${FLATBUFFERS_SRC}/include/flatbuffers/allocator.h + ${FLATBUFFERS_SRC}/include/flatbuffers/array.h + ${FLATBUFFERS_SRC}/include/flatbuffers/base.h + ${FLATBUFFERS_SRC}/include/flatbuffers/buffer.h + ${FLATBUFFERS_SRC}/include/flatbuffers/buffer_ref.h + ${FLATBUFFERS_SRC}/include/flatbuffers/default_allocator.h + ${FLATBUFFERS_SRC}/include/flatbuffers/detached_buffer.h + ${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffer_builder.h + ${FLATBUFFERS_SRC}/include/flatbuffers/flatbuffers.h + ${FLATBUFFERS_SRC}/include/flatbuffers/flexbuffers.h + ${FLATBUFFERS_SRC}/include/flatbuffers/flex_flat_util.h + ${FLATBUFFERS_SRC}/include/flatbuffers/hash.h + ${FLATBUFFERS_SRC}/include/flatbuffers/idl.h + ${FLATBUFFERS_SRC}/include/flatbuffers/minireflect.h + ${FLATBUFFERS_SRC}/include/flatbuffers/reflection.h + ${FLATBUFFERS_SRC}/include/flatbuffers/reflection_generated.h + ${FLATBUFFERS_SRC}/include/flatbuffers/registry.h + ${FLATBUFFERS_SRC}/include/flatbuffers/stl_emulation.h + ${FLATBUFFERS_SRC}/include/flatbuffers/string.h + ${FLATBUFFERS_SRC}/include/flatbuffers/struct.h + ${FLATBUFFERS_SRC}/include/flatbuffers/table.h + ${FLATBUFFERS_SRC}/include/flatbuffers/util.h + ${FLATBUFFERS_SRC}/include/flatbuffers/vector.h + ${FLATBUFFERS_SRC}/include/flatbuffers/vector_downward.h + ${FLATBUFFERS_SRC}/include/flatbuffers/verifier.h + ${FLATBUFFERS_SRC}/src/idl_parser.cpp + ${FLATBUFFERS_SRC}/src/idl_gen_text.cpp + ${FLATBUFFERS_SRC}/src/reflection.cpp + ${FLATBUFFERS_SRC}/src/util.cpp + ${FLATBUFFERS_SRC}/src/idl_gen_fbs.cpp + ${FLATBUFFERS_SRC}/src/code_generators.cpp + ) + +add_library( # Sets the name of the library. + flatbuffers + + ${FlatBuffers_Library_SRCS} + ${Generated_SRCS} +) diff --git a/third_party/flatbuffers/android/app/src/main/cpp/generated/animal_generated.h b/third_party/flatbuffers/android/app/src/main/cpp/generated/animal_generated.h new file mode 100644 index 00000000000..21d92f82f6c --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/cpp/generated/animal_generated.h @@ -0,0 +1,134 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_ +#define FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 12 && + FLATBUFFERS_VERSION_REVISION == 23, + "Non-compatible flatbuffers version included"); + +namespace com { +namespace fbs { +namespace app { + +struct Animal; +struct AnimalBuilder; + +struct Animal FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef AnimalBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NAME = 4, + VT_SOUND = 6, + VT_WEIGHT = 8 + }; + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + const ::flatbuffers::String *sound() const { + return GetPointer(VT_SOUND); + } + uint16_t weight() const { + return GetField(VT_WEIGHT, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_SOUND) && + verifier.VerifyString(sound()) && + VerifyField(verifier, VT_WEIGHT, 2) && + verifier.EndTable(); + } +}; + +struct AnimalBuilder { + typedef Animal Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Animal::VT_NAME, name); + } + void add_sound(::flatbuffers::Offset<::flatbuffers::String> sound) { + fbb_.AddOffset(Animal::VT_SOUND, sound); + } + void add_weight(uint16_t weight) { + fbb_.AddElement(Animal::VT_WEIGHT, weight, 0); + } + explicit AnimalBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateAnimal( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::String> sound = 0, + uint16_t weight = 0) { + AnimalBuilder builder_(_fbb); + builder_.add_sound(sound); + builder_.add_name(name); + builder_.add_weight(weight); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateAnimalDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *name = nullptr, + const char *sound = nullptr, + uint16_t weight = 0) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto sound__ = sound ? _fbb.CreateString(sound) : 0; + return com::fbs::app::CreateAnimal( + _fbb, + name__, + sound__, + weight); +} + +inline const com::fbs::app::Animal *GetAnimal(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const com::fbs::app::Animal *GetSizePrefixedAnimal(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline bool VerifyAnimalBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedAnimalBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishAnimalBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedAnimalBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +} // namespace app +} // namespace fbs +} // namespace com + +#endif // FLATBUFFERS_GENERATED_ANIMAL_COM_FBS_APP_H_ diff --git a/third_party/flatbuffers/android/app/src/main/fbs/animal.fbs b/third_party/flatbuffers/android/app/src/main/fbs/animal.fbs new file mode 100644 index 00000000000..479e22b2940 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/fbs/animal.fbs @@ -0,0 +1,23 @@ +// Copyright 2015 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +namespace com.fbs.app; + +table Animal { + name:string; + sound:string; + weight: uint16; +} + +root_type Animal; diff --git a/third_party/flatbuffers/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt b/third_party/flatbuffers/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt new file mode 100644 index 00000000000..cdc35730e3e --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/java/com/flatbuffers/app/MainActivity.kt @@ -0,0 +1,51 @@ +package com.flatbuffers.app + +import android.annotation.SuppressLint +import androidx.appcompat.app.AppCompatActivity +import android.os.Bundle +import android.widget.TextView +import com.fbs.app.Animal +import com.google.flatbuffers.FlatBufferBuilder +import java.nio.ByteBuffer + +@ExperimentalUnsignedTypes +class MainActivity : AppCompatActivity() { + + @SuppressLint("SetTextI18n") + override fun onCreate(savedInstanceState: Bundle?) { + super.onCreate(savedInstanceState) + setContentView(R.layout.activity_main) + + val tiger = Animal.getRootAsAnimal(ByteBuffer.wrap(createAnimalFromJNI())) + findViewById(R.id.tv_animal_one).text = animalInfo(tiger) + + findViewById(R.id.tv_animal_two).text = animalInfo(createAnimalFromKotlin()) + } + + // This function is a sample of communicating FlatBuffers between JNI (native C++) and Java. + // Implementation can be found on animals.cpp file. + private external fun createAnimalFromJNI(): ByteArray + + // Create a "Cow" Animal flatbuffers from Kotlin + private fun createAnimalFromKotlin():Animal { + val fb = FlatBufferBuilder(100) + val cowOffset = Animal.createAnimal( + builder = fb, + nameOffset = fb.createString("Cow"), + soundOffset = fb.createString("Moo"), + weight = 720u + ) + fb.finish(cowOffset) + return Animal.getRootAsAnimal(fb.dataBuffer()) + } + + private fun animalInfo(animal: Animal): String = + "The ${animal.name} sound is ${animal.sound} and it weights ${animal.weight}kg." + + companion object { + // Used to load the 'native-lib' library on application startup. + init { + System.loadLibrary("native-lib") + } + } +} diff --git a/third_party/flatbuffers/android/app/src/main/java/generated/com/fbs/app/Animal.kt b/third_party/flatbuffers/android/app/src/main/java/generated/com/fbs/app/Animal.kt new file mode 100644 index 00000000000..ffa8e0a571e --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/java/generated/com/fbs/app/Animal.kt @@ -0,0 +1,84 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.fbs.app + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +@kotlin.ExperimentalUnsignedTypes +class Animal : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Animal { + __init(_i, _bb) + return this + } + val name : String? + get() { + val o = __offset(4) + return if (o != 0) { + __string(o + bb_pos) + } else { + null + } + } + val nameAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1) + fun nameInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1) + val sound : String? + get() { + val o = __offset(6) + return if (o != 0) { + __string(o + bb_pos) + } else { + null + } + } + val soundAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(6, 1) + fun soundInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 6, 1) + val weight : UShort + get() { + val o = __offset(8) + return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsAnimal(_bb: ByteBuffer): Animal = getRootAsAnimal(_bb, Animal()) + fun getRootAsAnimal(_bb: ByteBuffer, obj: Animal): Animal { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createAnimal(builder: FlatBufferBuilder, nameOffset: Int, soundOffset: Int, weight: UShort) : Int { + builder.startTable(3) + addSound(builder, soundOffset) + addName(builder, nameOffset) + addWeight(builder, weight) + return endAnimal(builder) + } + fun startAnimal(builder: FlatBufferBuilder) = builder.startTable(3) + fun addName(builder: FlatBufferBuilder, name: Int) = builder.addOffset(0, name, 0) + fun addSound(builder: FlatBufferBuilder, sound: Int) = builder.addOffset(1, sound, 0) + fun addWeight(builder: FlatBufferBuilder, weight: UShort) = builder.addShort(2, weight.toShort(), 0) + fun endAnimal(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun finishAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset) + fun finishSizePrefixedAnimalBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset) + } +} diff --git a/third_party/flatbuffers/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml b/third_party/flatbuffers/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml new file mode 100644 index 00000000000..7706ab9e6d4 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/drawable-v24/ic_launcher_foreground.xml @@ -0,0 +1,30 @@ + + + + + + + + + + + diff --git a/third_party/flatbuffers/android/app/src/main/res/drawable/ic_launcher_background.xml b/third_party/flatbuffers/android/app/src/main/res/drawable/ic_launcher_background.xml new file mode 100644 index 00000000000..07d5da9cbf1 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/drawable/ic_launcher_background.xml @@ -0,0 +1,170 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/third_party/flatbuffers/android/app/src/main/res/layout/activity_main.xml b/third_party/flatbuffers/android/app/src/main/res/layout/activity_main.xml new file mode 100644 index 00000000000..d339c224064 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/layout/activity_main.xml @@ -0,0 +1,23 @@ + + + + + + + + diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml b/third_party/flatbuffers/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml new file mode 100644 index 00000000000..6b78462d615 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml b/third_party/flatbuffers/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml new file mode 100644 index 00000000000..6b78462d615 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/mipmap-anydpi-v26/ic_launcher_round.xml @@ -0,0 +1,5 @@ + + + + + diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-hdpi/ic_launcher.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-hdpi/ic_launcher.png new file mode 100644 index 00000000000..a571e60098c Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-hdpi/ic_launcher.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png new file mode 100644 index 00000000000..61da551c559 Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-hdpi/ic_launcher_round.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-mdpi/ic_launcher.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-mdpi/ic_launcher.png new file mode 100644 index 00000000000..c41dd285319 Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-mdpi/ic_launcher.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png new file mode 100644 index 00000000000..db5080a7527 Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-mdpi/ic_launcher_round.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png new file mode 100644 index 00000000000..6dba46dab19 Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-xhdpi/ic_launcher.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png new file mode 100644 index 00000000000..da31a871c8d Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-xhdpi/ic_launcher_round.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png new file mode 100644 index 00000000000..15ac681720f Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxhdpi/ic_launcher.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png new file mode 100644 index 00000000000..b216f2d313c Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxhdpi/ic_launcher_round.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png new file mode 100644 index 00000000000..f25a4197447 Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png new file mode 100644 index 00000000000..e96783ccce8 Binary files /dev/null and b/third_party/flatbuffers/android/app/src/main/res/mipmap-xxxhdpi/ic_launcher_round.png differ diff --git a/third_party/flatbuffers/android/app/src/main/res/values/colors.xml b/third_party/flatbuffers/android/app/src/main/res/values/colors.xml new file mode 100644 index 00000000000..030098fe0f7 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/values/colors.xml @@ -0,0 +1,6 @@ + + + #6200EE + #3700B3 + #03DAC5 + diff --git a/third_party/flatbuffers/android/app/src/main/res/values/strings.xml b/third_party/flatbuffers/android/app/src/main/res/values/strings.xml new file mode 100644 index 00000000000..71d53e98a2c --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/values/strings.xml @@ -0,0 +1,3 @@ + + FlatbuffersTestApp + diff --git a/third_party/flatbuffers/android/app/src/main/res/values/styles.xml b/third_party/flatbuffers/android/app/src/main/res/values/styles.xml new file mode 100644 index 00000000000..391ec9ae3b7 --- /dev/null +++ b/third_party/flatbuffers/android/app/src/main/res/values/styles.xml @@ -0,0 +1,10 @@ + + + + + diff --git a/third_party/flatbuffers/android/build.gradle b/third_party/flatbuffers/android/build.gradle new file mode 100644 index 00000000000..7e9cdec5196 --- /dev/null +++ b/third_party/flatbuffers/android/build.gradle @@ -0,0 +1,35 @@ +// Top-level build file where you can add configuration options common to all sub-projects/modules. +buildscript { + ext.kotlin_version = "1.7.21" + repositories { + google() + mavenCentral() + } + dependencies { + classpath 'com.android.tools.build:gradle:7.4.1' + classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" + + // NOTE: Do not place your application dependencies here; they belong + // in the individual module build.gradle files + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +tasks.withType(org.jetbrains.kotlin.gradle.tasks.KotlinCompile).all { + sourceCompatibility = JavaVersion.VERSION_1_8 + targetCompatibility = JavaVersion.VERSION_1_8 + + compileKotlin { + dependsOn flatbuffer + } +} + +task clean(type: Delete) { + delete rootProject.buildDir +} diff --git a/third_party/flatbuffers/android/gradle.properties b/third_party/flatbuffers/android/gradle.properties new file mode 100644 index 00000000000..bf3068ddd74 --- /dev/null +++ b/third_party/flatbuffers/android/gradle.properties @@ -0,0 +1,23 @@ +# Project-wide Gradle settings. +# IDE (e.g. Android Studio) users: +# Gradle settings configured through the IDE *will override* +# any settings specified in this file. +# For more details on how to configure your build environment visit +# http://www.gradle.org/docs/current/userguide/build_environment.html +# Specifies the JVM arguments used for the daemon process. +# The setting is particularly useful for tweaking memory settings. +org.gradle.jvmargs=-Xmx2048m +# When configured, Gradle will run in incubating parallel mode. +# This option should only be used with decoupled projects. More details, visit +# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects +# org.gradle.parallel=true +# AndroidX package structure to make it clearer which packages are bundled with the +# Android operating system, and which are packaged with your app"s APK +# https://developer.android.com/topic/libraries/support-library/androidx-rn +android.useAndroidX=true +# Automatically convert third-party libraries to use AndroidX +android.enableJetifier=true +# Kotlin code style for this project: "official" or "obsolete": +kotlin.code.style=official +# Use parallel builds +org.gradle.parallel=true \ No newline at end of file diff --git a/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.jar b/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..41d9927a4d4 Binary files /dev/null and b/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.jar differ diff --git a/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.properties b/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..f72df95a7e8 --- /dev/null +++ b/third_party/flatbuffers/android/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/third_party/flatbuffers/android/gradlew b/third_party/flatbuffers/android/gradlew new file mode 100755 index 00000000000..cccdd3d517f --- /dev/null +++ b/third_party/flatbuffers/android/gradlew @@ -0,0 +1,172 @@ +#!/usr/bin/env sh + +############################################################################## +## +## Gradle start up script for UN*X +## +############################################################################## + +# Attempt to set APP_HOME +# Resolve links: $0 may be a link +PRG="$0" +# Need this for relative symlinks. +while [ -h "$PRG" ] ; do + ls=`ls -ld "$PRG"` + link=`expr "$ls" : '.*-> \(.*\)$'` + if expr "$link" : '/.*' > /dev/null; then + PRG="$link" + else + PRG=`dirname "$PRG"`"/$link" + fi +done +SAVED="`pwd`" +cd "`dirname \"$PRG\"`/" >/dev/null +APP_HOME="`pwd -P`" +cd "$SAVED" >/dev/null + +APP_NAME="Gradle" +APP_BASE_NAME=`basename "$0"` + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS="" + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD="maximum" + +warn () { + echo "$*" +} + +die () { + echo + echo "$*" + echo + exit 1 +} + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "`uname`" in + CYGWIN* ) + cygwin=true + ;; + Darwin* ) + darwin=true + ;; + MINGW* ) + msys=true + ;; + NONSTOP* ) + nonstop=true + ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD="$JAVA_HOME/jre/sh/java" + else + JAVACMD="$JAVA_HOME/bin/java" + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD="java" + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if [ "$cygwin" = "false" -a "$darwin" = "false" -a "$nonstop" = "false" ] ; then + MAX_FD_LIMIT=`ulimit -H -n` + if [ $? -eq 0 ] ; then + if [ "$MAX_FD" = "maximum" -o "$MAX_FD" = "max" ] ; then + MAX_FD="$MAX_FD_LIMIT" + fi + ulimit -n $MAX_FD + if [ $? -ne 0 ] ; then + warn "Could not set maximum file descriptor limit: $MAX_FD" + fi + else + warn "Could not query maximum file descriptor limit: $MAX_FD_LIMIT" + fi +fi + +# For Darwin, add options to specify how the application appears in the dock +if $darwin; then + GRADLE_OPTS="$GRADLE_OPTS \"-Xdock:name=$APP_NAME\" \"-Xdock:icon=$APP_HOME/media/gradle.icns\"" +fi + +# For Cygwin, switch paths to Windows format before running java +if $cygwin ; then + APP_HOME=`cygpath --path --mixed "$APP_HOME"` + CLASSPATH=`cygpath --path --mixed "$CLASSPATH"` + JAVACMD=`cygpath --unix "$JAVACMD"` + + # We build the pattern for arguments to be converted via cygpath + ROOTDIRSRAW=`find -L / -maxdepth 1 -mindepth 1 -type d 2>/dev/null` + SEP="" + for dir in $ROOTDIRSRAW ; do + ROOTDIRS="$ROOTDIRS$SEP$dir" + SEP="|" + done + OURCYGPATTERN="(^($ROOTDIRS))" + # Add a user-defined pattern to the cygpath arguments + if [ "$GRADLE_CYGPATTERN" != "" ] ; then + OURCYGPATTERN="$OURCYGPATTERN|($GRADLE_CYGPATTERN)" + fi + # Now convert the arguments - kludge to limit ourselves to /bin/sh + i=0 + for arg in "$@" ; do + CHECK=`echo "$arg"|egrep -c "$OURCYGPATTERN" -` + CHECK2=`echo "$arg"|egrep -c "^-"` ### Determine if an option + + if [ $CHECK -ne 0 ] && [ $CHECK2 -eq 0 ] ; then ### Added a condition + eval `echo args$i`=`cygpath --path --ignore --mixed "$arg"` + else + eval `echo args$i`="\"$arg\"" + fi + i=$((i+1)) + done + case $i in + (0) set -- ;; + (1) set -- "$args0" ;; + (2) set -- "$args0" "$args1" ;; + (3) set -- "$args0" "$args1" "$args2" ;; + (4) set -- "$args0" "$args1" "$args2" "$args3" ;; + (5) set -- "$args0" "$args1" "$args2" "$args3" "$args4" ;; + (6) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" ;; + (7) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" ;; + (8) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" ;; + (9) set -- "$args0" "$args1" "$args2" "$args3" "$args4" "$args5" "$args6" "$args7" "$args8" ;; + esac +fi + +# Escape application args +save () { + for i do printf %s\\n "$i" | sed "s/'/'\\\\''/g;1s/^/'/;\$s/\$/' \\\\/" ; done + echo " " +} +APP_ARGS=$(save "$@") + +# Collect all arguments for the java command, following the shell quoting and substitution rules +eval set -- $DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS "\"-Dorg.gradle.appname=$APP_BASE_NAME\"" -classpath "\"$CLASSPATH\"" org.gradle.wrapper.GradleWrapperMain "$APP_ARGS" + +# by default we should be in the correct project dir, but when run from Finder on Mac, the cwd is wrong +if [ "$(uname)" = "Darwin" ] && [ "$HOME" = "$PWD" ]; then + cd "$(dirname "$0")" +fi + +exec "$JAVACMD" "$@" diff --git a/third_party/flatbuffers/android/gradlew.bat b/third_party/flatbuffers/android/gradlew.bat new file mode 100644 index 00000000000..f9553162f12 --- /dev/null +++ b/third_party/flatbuffers/android/gradlew.bat @@ -0,0 +1,84 @@ +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS= + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto init + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto init + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:init +@rem Get command-line arguments, handling Windows variants + +if not "%OS%" == "Windows_NT" goto win9xME_args + +:win9xME_args +@rem Slurp the command line arguments. +set CMD_LINE_ARGS= +set _SKIP=2 + +:win9xME_args_slurp +if "x%~1" == "x" goto execute + +set CMD_LINE_ARGS=%* + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %CMD_LINE_ARGS% + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/third_party/flatbuffers/android/settings.gradle b/third_party/flatbuffers/android/settings.gradle new file mode 100644 index 00000000000..c4c0afbc97d --- /dev/null +++ b/third_party/flatbuffers/android/settings.gradle @@ -0,0 +1,2 @@ +include ':app' +rootProject.name = "FlatbuffersTest" diff --git a/third_party/flatbuffers/bazel/BUILD.bazel b/third_party/flatbuffers/bazel/BUILD.bazel new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/benchmarks/CMakeLists.txt b/third_party/flatbuffers/benchmarks/CMakeLists.txt new file mode 100644 index 00000000000..18f6ef9fd4e --- /dev/null +++ b/third_party/flatbuffers/benchmarks/CMakeLists.txt @@ -0,0 +1,88 @@ +# Setup for running Google Benchmarks (https://github.com/google/benchmark) on +# flatbuffers. This requires both that benchmark library and its dependency gtest +# to build. Instead of including them here or doing a submodule, this uses +# FetchContent (https://cmake.org/cmake/help/latest/module/FetchContent.html) to +# grab the dependencies at config time. This requires CMake 3.14 or higher. + +cmake_minimum_required(VERSION 3.14) +include(FetchContent) + +# No particular reason for the specific GIT_TAGs for the following repos, they +# were just the latest releases when this was added. +FetchContent_Declare( + googletest + GIT_REPOSITORY https://github.com/google/googletest.git + GIT_TAG e2239ee6043f73722e7aa812a459f54a28552929 # release-1.11.0 +) +FetchContent_Declare( + googlebenchmark + GIT_REPOSITORY https://github.com/google/benchmark.git + GIT_TAG 0d98dba29d66e93259db7daa53a9327df767a415 # v1.6.1 +) + +# For Windows: Prevent overriding the parent project's compiler/linker +# settings. +set(gtest_force_shared_crt ON CACHE BOOL "" FORCE) +FetchContent_MakeAvailable( + googletest + googlebenchmark +) + +set(CPP_BENCH_DIR ${CMAKE_CURRENT_SOURCE_DIR}/cpp) +set(CPP_FB_BENCH_DIR ${CPP_BENCH_DIR}/flatbuffers) +set(CPP_RAW_BENCH_DIR ${CPP_BENCH_DIR}/raw) +set(CPP_BENCH_FBS ${CPP_FB_BENCH_DIR}/bench.fbs) +set(CPP_BENCH_FB_GEN ${CPP_FB_BENCH_DIR}/bench_generated.h) + +set(FlatBenchmark_SRCS + ${CPP_BENCH_DIR}/benchmark_main.cpp + ${CPP_FB_BENCH_DIR}/fb_bench.cpp + ${CPP_RAW_BENCH_DIR}/raw_bench.cpp + ${CPP_BENCH_FB_GEN} +) + +# Generate the flatbuffers benchmark code from the flatbuffers schema using +# flatc itself, thus it depends on flatc. This also depends on the C++ runtime +# flatbuffers and the schema file itself, so it should auto-generated at the +# correct times. +add_custom_command( + OUTPUT ${CPP_BENCH_FB_GEN} + COMMAND + "${FLATBUFFERS_FLATC_EXECUTABLE}" + --cpp + -o ${CPP_FB_BENCH_DIR} + ${CPP_BENCH_FBS} + DEPENDS + flatc + flatbuffers + ${CPP_BENCH_FBS} + COMMENT "Run Flatbuffers Benchmark Codegen: ${CPP_BENCH_FB_GEN}" + VERBATIM) + +# The main flatbuffers benchmark executable +add_executable(flatbenchmark ${FlatBenchmark_SRCS}) + +# Benchmark requires C++11 +target_compile_features(flatbenchmark PRIVATE + cxx_std_11 # requires cmake 3.8 +) + +target_compile_options(flatbenchmark + PRIVATE + -fno-aligned-new + -Wno-deprecated-declarations +) + +# Set the output directory to the root binary directory +set_target_properties(flatbenchmark + PROPERTIES RUNTIME_OUTPUT_DIRECTORY + "${CMAKE_BINARY_DIR}" +) + +# The includes of the benchmark files are fully qualified from flatbuffers root. +target_include_directories(flatbenchmark PUBLIC ${CMAKE_SOURCE_DIR}) + +target_link_libraries(flatbenchmark PRIVATE + benchmark::benchmark_main # _main to use their entry point + gtest # Link to gtest so we can also assert in the benchmarks +) \ No newline at end of file diff --git a/third_party/flatbuffers/benchmarks/cpp/bench.h b/third_party/flatbuffers/benchmarks/cpp/bench.h new file mode 100644 index 00000000000..ad4baebf51c --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/bench.h @@ -0,0 +1,19 @@ +#ifndef BENCHMARKS_CPP_BENCH_H_ +#define BENCHMARKS_CPP_BENCH_H_ + +#include + +struct Bench { + virtual ~Bench() {} + + inline void Add(int64_t value) { sum += value; } + + virtual uint8_t *Encode(void *buf, int64_t &len) = 0; + virtual void *Decode(void *buf, int64_t len) = 0; + virtual int64_t Use(void *decoded) = 0; + virtual void Dealloc(void *decoded) = 0; + + int64_t sum = 0; +}; + +#endif // BENCHMARKS_CPP_BENCH_H_ \ No newline at end of file diff --git a/third_party/flatbuffers/benchmarks/cpp/benchmark_main.cpp b/third_party/flatbuffers/benchmarks/cpp/benchmark_main.cpp new file mode 100644 index 00000000000..63807a5dd53 --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/benchmark_main.cpp @@ -0,0 +1,96 @@ +#include +#include + +#include "benchmarks/cpp/bench.h" +#include "benchmarks/cpp/flatbuffers/fb_bench.h" +#include "benchmarks/cpp/raw/raw_bench.h" + +static inline void Encode(benchmark::State &state, + std::unique_ptr &bench, uint8_t *buffer) { + int64_t length; + for (auto _ : state) { + bench->Encode(buffer, length); + benchmark::DoNotOptimize(length); + } +} + +static inline void Decode(benchmark::State &state, + std::unique_ptr &bench, uint8_t *buffer) { + int64_t length; + uint8_t *encoded = bench->Encode(buffer, length); + + for (auto _ : state) { + void *decoded = bench->Decode(encoded, length); + benchmark::DoNotOptimize(decoded); + } +} + +static inline void Use(benchmark::State &state, std::unique_ptr &bench, + uint8_t *buffer, int64_t check_sum) { + int64_t length; + uint8_t *encoded = bench->Encode(buffer, length); + void *decoded = bench->Decode(encoded, length); + + int64_t sum = 0; + + for (auto _ : state) { sum = bench->Use(decoded); } + + EXPECT_EQ(sum, check_sum); +} + +static void BM_Flatbuffers_Encode(benchmark::State &state) { + const int64_t kBufferLength = 1024; + uint8_t buffer[kBufferLength]; + + StaticAllocator allocator(&buffer[0]); + std::unique_ptr bench = NewFlatBuffersBench(kBufferLength, &allocator); + Encode(state, bench, buffer); +} +BENCHMARK(BM_Flatbuffers_Encode); + +static void BM_Flatbuffers_Decode(benchmark::State &state) { + const int64_t kBufferLength = 1024; + uint8_t buffer[kBufferLength]; + + StaticAllocator allocator(&buffer[0]); + std::unique_ptr bench = NewFlatBuffersBench(kBufferLength, &allocator); + Decode(state, bench, buffer); +} +BENCHMARK(BM_Flatbuffers_Decode); + +static void BM_Flatbuffers_Use(benchmark::State &state) { + const int64_t kBufferLength = 1024; + uint8_t buffer[kBufferLength]; + + StaticAllocator allocator(&buffer[0]); + std::unique_ptr bench = NewFlatBuffersBench(kBufferLength, &allocator); + Use(state, bench, buffer, 218812692406581874); +} +BENCHMARK(BM_Flatbuffers_Use); + +static void BM_Raw_Encode(benchmark::State &state) { + const int64_t kBufferLength = 1024; + uint8_t buffer[kBufferLength]; + + std::unique_ptr bench = NewRawBench(); + Encode(state, bench, buffer); +} +BENCHMARK(BM_Raw_Encode); + +static void BM_Raw_Decode(benchmark::State &state) { + const int64_t kBufferLength = 1024; + uint8_t buffer[kBufferLength]; + + std::unique_ptr bench = NewRawBench(); + Decode(state, bench, buffer); +} +BENCHMARK(BM_Raw_Decode); + +static void BM_Raw_Use(benchmark::State &state) { + const int64_t kBufferLength = 1024; + uint8_t buffer[kBufferLength]; + + std::unique_ptr bench = NewRawBench(); + Use(state, bench, buffer, 218812692406581874); +} +BENCHMARK(BM_Raw_Use); diff --git a/third_party/flatbuffers/benchmarks/cpp/flatbuffers/bench.fbs b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/bench.fbs new file mode 100644 index 00000000000..8e5f3ff7e1c --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/bench.fbs @@ -0,0 +1,52 @@ +// Copyright 2021 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + + +// trying to represent a typical mix of datatypes: +// 1 array of 3 elements, each element: 1 string, 3 nested objects, 9 scalars +// root element has the array, additional string and an enum + +namespace benchmarks_flatbuffers; + +enum Enum : short { Apples, Pears, Bananas} + +struct Foo { + id:ulong; + count:short; + prefix:byte; + length:uint; +} + +struct Bar { + parent:Foo; + time:int; + ratio:float; + size:ushort; +} + +table FooBar { + sibling:Bar; + name:string; + rating:double; + postfix:ubyte; +} + +table FooBarContainer { + list:[FooBar]; // 3 copies of the above + initialized:bool; + fruit:Enum; + location:string; +} + +root_type FooBarContainer; diff --git a/third_party/flatbuffers/benchmarks/cpp/flatbuffers/bench_generated.h b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/bench_generated.h new file mode 100644 index 00000000000..f5f04bd97d0 --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/bench_generated.h @@ -0,0 +1,354 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_ +#define FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && + FLATBUFFERS_VERSION_MINOR == 12 && + FLATBUFFERS_VERSION_REVISION == 23, + "Non-compatible flatbuffers version included"); + +namespace benchmarks_flatbuffers { + +struct Foo; + +struct Bar; + +struct FooBar; +struct FooBarBuilder; + +struct FooBarContainer; +struct FooBarContainerBuilder; + +enum Enum : int16_t { + Enum_Apples = 0, + Enum_Pears = 1, + Enum_Bananas = 2, + Enum_MIN = Enum_Apples, + Enum_MAX = Enum_Bananas +}; + +inline const Enum (&EnumValuesEnum())[3] { + static const Enum values[] = { + Enum_Apples, + Enum_Pears, + Enum_Bananas + }; + return values; +} + +inline const char * const *EnumNamesEnum() { + static const char * const names[4] = { + "Apples", + "Pears", + "Bananas", + nullptr + }; + return names; +} + +inline const char *EnumNameEnum(Enum e) { + if (flatbuffers::IsOutRange(e, Enum_Apples, Enum_Bananas)) return ""; + const size_t index = static_cast(e); + return EnumNamesEnum()[index]; +} + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Foo FLATBUFFERS_FINAL_CLASS { + private: + uint64_t id_; + int16_t count_; + int8_t prefix_; + int8_t padding0__; + uint32_t length_; + + public: + Foo() + : id_(0), + count_(0), + prefix_(0), + padding0__(0), + length_(0) { + (void)padding0__; + } + Foo(uint64_t _id, int16_t _count, int8_t _prefix, uint32_t _length) + : id_(flatbuffers::EndianScalar(_id)), + count_(flatbuffers::EndianScalar(_count)), + prefix_(flatbuffers::EndianScalar(_prefix)), + padding0__(0), + length_(flatbuffers::EndianScalar(_length)) { + (void)padding0__; + } + uint64_t id() const { + return flatbuffers::EndianScalar(id_); + } + int16_t count() const { + return flatbuffers::EndianScalar(count_); + } + int8_t prefix() const { + return flatbuffers::EndianScalar(prefix_); + } + uint32_t length() const { + return flatbuffers::EndianScalar(length_); + } +}; +FLATBUFFERS_STRUCT_END(Foo, 16); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Bar FLATBUFFERS_FINAL_CLASS { + private: + benchmarks_flatbuffers::Foo parent_; + int32_t time_; + float ratio_; + uint16_t size_; + int16_t padding0__; int32_t padding1__; + + public: + Bar() + : parent_(), + time_(0), + ratio_(0), + size_(0), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Bar(const benchmarks_flatbuffers::Foo &_parent, int32_t _time, float _ratio, uint16_t _size) + : parent_(_parent), + time_(flatbuffers::EndianScalar(_time)), + ratio_(flatbuffers::EndianScalar(_ratio)), + size_(flatbuffers::EndianScalar(_size)), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + const benchmarks_flatbuffers::Foo &parent() const { + return parent_; + } + int32_t time() const { + return flatbuffers::EndianScalar(time_); + } + float ratio() const { + return flatbuffers::EndianScalar(ratio_); + } + uint16_t size() const { + return flatbuffers::EndianScalar(size_); + } +}; +FLATBUFFERS_STRUCT_END(Bar, 32); + +struct FooBar FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { + typedef FooBarBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_SIBLING = 4, + VT_NAME = 6, + VT_RATING = 8, + VT_POSTFIX = 10 + }; + const benchmarks_flatbuffers::Bar *sibling() const { + return GetStruct(VT_SIBLING); + } + const flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + double rating() const { + return GetField(VT_RATING, 0.0); + } + uint8_t postfix() const { + return GetField(VT_POSTFIX, 0); + } + bool Verify(flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_SIBLING, 8) && + VerifyOffset(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyField(verifier, VT_RATING, 8) && + VerifyField(verifier, VT_POSTFIX, 1) && + verifier.EndTable(); + } +}; + +struct FooBarBuilder { + typedef FooBar Table; + flatbuffers::FlatBufferBuilder &fbb_; + flatbuffers::uoffset_t start_; + void add_sibling(const benchmarks_flatbuffers::Bar *sibling) { + fbb_.AddStruct(FooBar::VT_SIBLING, sibling); + } + void add_name(flatbuffers::Offset name) { + fbb_.AddOffset(FooBar::VT_NAME, name); + } + void add_rating(double rating) { + fbb_.AddElement(FooBar::VT_RATING, rating, 0.0); + } + void add_postfix(uint8_t postfix) { + fbb_.AddElement(FooBar::VT_POSTFIX, postfix, 0); + } + explicit FooBarBuilder(flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = flatbuffers::Offset(end); + return o; + } +}; + +inline flatbuffers::Offset CreateFooBar( + flatbuffers::FlatBufferBuilder &_fbb, + const benchmarks_flatbuffers::Bar *sibling = nullptr, + flatbuffers::Offset name = 0, + double rating = 0.0, + uint8_t postfix = 0) { + FooBarBuilder builder_(_fbb); + builder_.add_rating(rating); + builder_.add_name(name); + builder_.add_sibling(sibling); + builder_.add_postfix(postfix); + return builder_.Finish(); +} + +inline flatbuffers::Offset CreateFooBarDirect( + flatbuffers::FlatBufferBuilder &_fbb, + const benchmarks_flatbuffers::Bar *sibling = nullptr, + const char *name = nullptr, + double rating = 0.0, + uint8_t postfix = 0) { + auto name__ = name ? _fbb.CreateString(name) : 0; + return benchmarks_flatbuffers::CreateFooBar( + _fbb, + sibling, + name__, + rating, + postfix); +} + +struct FooBarContainer FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { + typedef FooBarContainerBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_LIST = 4, + VT_INITIALIZED = 6, + VT_FRUIT = 8, + VT_LOCATION = 10 + }; + const flatbuffers::Vector> *list() const { + return GetPointer> *>(VT_LIST); + } + bool initialized() const { + return GetField(VT_INITIALIZED, 0) != 0; + } + benchmarks_flatbuffers::Enum fruit() const { + return static_cast(GetField(VT_FRUIT, 0)); + } + const flatbuffers::String *location() const { + return GetPointer(VT_LOCATION); + } + bool Verify(flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_LIST) && + verifier.VerifyVector(list()) && + verifier.VerifyVectorOfTables(list()) && + VerifyField(verifier, VT_INITIALIZED, 1) && + VerifyField(verifier, VT_FRUIT, 2) && + VerifyOffset(verifier, VT_LOCATION) && + verifier.VerifyString(location()) && + verifier.EndTable(); + } +}; + +struct FooBarContainerBuilder { + typedef FooBarContainer Table; + flatbuffers::FlatBufferBuilder &fbb_; + flatbuffers::uoffset_t start_; + void add_list(flatbuffers::Offset>> list) { + fbb_.AddOffset(FooBarContainer::VT_LIST, list); + } + void add_initialized(bool initialized) { + fbb_.AddElement(FooBarContainer::VT_INITIALIZED, static_cast(initialized), 0); + } + void add_fruit(benchmarks_flatbuffers::Enum fruit) { + fbb_.AddElement(FooBarContainer::VT_FRUIT, static_cast(fruit), 0); + } + void add_location(flatbuffers::Offset location) { + fbb_.AddOffset(FooBarContainer::VT_LOCATION, location); + } + explicit FooBarContainerBuilder(flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = flatbuffers::Offset(end); + return o; + } +}; + +inline flatbuffers::Offset CreateFooBarContainer( + flatbuffers::FlatBufferBuilder &_fbb, + flatbuffers::Offset>> list = 0, + bool initialized = false, + benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples, + flatbuffers::Offset location = 0) { + FooBarContainerBuilder builder_(_fbb); + builder_.add_location(location); + builder_.add_list(list); + builder_.add_fruit(fruit); + builder_.add_initialized(initialized); + return builder_.Finish(); +} + +inline flatbuffers::Offset CreateFooBarContainerDirect( + flatbuffers::FlatBufferBuilder &_fbb, + const std::vector> *list = nullptr, + bool initialized = false, + benchmarks_flatbuffers::Enum fruit = benchmarks_flatbuffers::Enum_Apples, + const char *location = nullptr) { + auto list__ = list ? _fbb.CreateVector>(*list) : 0; + auto location__ = location ? _fbb.CreateString(location) : 0; + return benchmarks_flatbuffers::CreateFooBarContainer( + _fbb, + list__, + initialized, + fruit, + location__); +} + +inline const benchmarks_flatbuffers::FooBarContainer *GetFooBarContainer(const void *buf) { + return flatbuffers::GetRoot(buf); +} + +inline const benchmarks_flatbuffers::FooBarContainer *GetSizePrefixedFooBarContainer(const void *buf) { + return flatbuffers::GetSizePrefixedRoot(buf); +} + +inline bool VerifyFooBarContainerBuffer( + flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedFooBarContainerBuffer( + flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishFooBarContainerBuffer( + flatbuffers::FlatBufferBuilder &fbb, + flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedFooBarContainerBuffer( + flatbuffers::FlatBufferBuilder &fbb, + flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +} // namespace benchmarks_flatbuffers + +#endif // FLATBUFFERS_GENERATED_BENCH_BENCHMARKS_FLATBUFFERS_H_ diff --git a/third_party/flatbuffers/benchmarks/cpp/flatbuffers/fb_bench.cpp b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/fb_bench.cpp new file mode 100644 index 00000000000..935166745aa --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/fb_bench.cpp @@ -0,0 +1,80 @@ +#include "benchmarks/cpp/flatbuffers/fb_bench.h" + +#include +#include + +#include "benchmarks/cpp/bench.h" +#include "benchmarks/cpp/flatbuffers/bench_generated.h" +#include "flatbuffers/flatbuffers.h" + +using namespace flatbuffers; +using namespace benchmarks_flatbuffers; + +namespace { + +struct FlatBufferBench : Bench { + explicit FlatBufferBench(int64_t initial_size, Allocator *allocator) + : fbb(initial_size, allocator, false) {} + + uint8_t *Encode(void *, int64_t &len) override { + fbb.Clear(); + + const int kVectorLength = 3; + Offset vec[kVectorLength]; + + for (int i = 0; i < kVectorLength; ++i) { + Foo foo(0xABADCAFEABADCAFE + i, 10000 + i, '@' + i, 1000000 + i); + Bar bar(foo, 123456 + i, 3.14159f + i, 10000 + i); + auto name = fbb.CreateString("Hello, World!"); + auto foobar = + CreateFooBar(fbb, &bar, name, 3.1415432432445543543 + i, '!' + i); + vec[i] = foobar; + } + auto location = fbb.CreateString("http://google.com/flatbuffers/"); + auto foobarvec = fbb.CreateVector(vec, kVectorLength); + auto foobarcontainer = + CreateFooBarContainer(fbb, foobarvec, true, Enum_Bananas, location); + fbb.Finish(foobarcontainer); + + len = fbb.GetSize(); + return fbb.GetBufferPointer(); + } + + int64_t Use(void *decoded) override { + sum = 0; + auto foobarcontainer = GetFooBarContainer(decoded); + sum = 0; + Add(foobarcontainer->initialized()); + Add(foobarcontainer->location()->Length()); + Add(foobarcontainer->fruit()); + for (unsigned int i = 0; i < foobarcontainer->list()->Length(); i++) { + auto foobar = foobarcontainer->list()->Get(i); + Add(foobar->name()->Length()); + Add(foobar->postfix()); + Add(static_cast(foobar->rating())); + auto bar = foobar->sibling(); + Add(static_cast(bar->ratio())); + Add(bar->size()); + Add(bar->time()); + auto &foo = bar->parent(); + Add(foo.count()); + Add(foo.id()); + Add(foo.length()); + Add(foo.prefix()); + } + return sum; + } + + void *Decode(void *buffer, int64_t) override { return buffer; } + void Dealloc(void *) override {}; + + FlatBufferBuilder fbb; +}; + +} // namespace + +std::unique_ptr NewFlatBuffersBench(int64_t initial_size, + Allocator *allocator) { + return std::unique_ptr( + new FlatBufferBench(initial_size, allocator)); +} diff --git a/third_party/flatbuffers/benchmarks/cpp/flatbuffers/fb_bench.h b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/fb_bench.h new file mode 100644 index 00000000000..ffb5f54c1a1 --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/flatbuffers/fb_bench.h @@ -0,0 +1,23 @@ +#ifndef BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_ +#define BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_ + +#include +#include + +#include "benchmarks/cpp/bench.h" +#include "include/flatbuffers/flatbuffers.h" + +struct StaticAllocator : public flatbuffers::Allocator { + explicit StaticAllocator(uint8_t *buffer) : buffer_(buffer) {} + + uint8_t *allocate(size_t) override { return buffer_; } + + void deallocate(uint8_t *, size_t) override {} + + uint8_t *buffer_; +}; + +std::unique_ptr NewFlatBuffersBench( + int64_t initial_size = 1024, flatbuffers::Allocator *allocator = nullptr); + +#endif // BENCHMARKS_CPP_FLATBUFFERS_FB_BENCH_H_ \ No newline at end of file diff --git a/third_party/flatbuffers/benchmarks/cpp/raw/raw_bench.cpp b/third_party/flatbuffers/benchmarks/cpp/raw/raw_bench.cpp new file mode 100644 index 00000000000..c65bca7f71c --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/raw/raw_bench.cpp @@ -0,0 +1,109 @@ +#include "benchmarks/cpp/raw/raw_bench.h" + +#include +#include +#include + +#include "benchmarks/cpp/bench.h" + +namespace { +const int64_t kStringLength = 32; +const int64_t kVectorLength = 3; + +enum Enum { Apples, Pears, Bananas }; + +struct Foo { + int64_t id; + short count; + char prefix; + int length; +}; + +struct Bar { + Foo parent; + int time; + float ratio; + unsigned short size; +}; + +struct FooBar { + Bar sibling; + // We have to stick this in, otherwise strlen() will make it slower than + // FlatBuffers: + int name_len; + char name[kStringLength]; + double rating; + unsigned char postfix; +}; + +struct FooBarContainer { + FooBar list[kVectorLength]; // 3 copies of the above + bool initialized; + Enum fruit; + int location_len; + char location[kStringLength]; +}; + +struct RawBench : Bench { + uint8_t *Encode(void *buf, int64_t &len) override { + FooBarContainer *fbc = new (buf) FooBarContainer; + strcpy(fbc->location, "http://google.com/flatbuffers/"); // Unsafe eek! + fbc->location_len = (int)strlen(fbc->location); + fbc->fruit = Bananas; + fbc->initialized = true; + for (int i = 0; i < kVectorLength; i++) { + // We add + i to not make these identical copies for a more realistic + // compression test. + auto &foobar = fbc->list[i]; + foobar.rating = 3.1415432432445543543 + i; + foobar.postfix = '!' + i; + strcpy(foobar.name, "Hello, World!"); + foobar.name_len = (int)strlen(foobar.name); + auto &bar = foobar.sibling; + bar.ratio = 3.14159f + i; + bar.size = 10000 + i; + bar.time = 123456 + i; + auto &foo = bar.parent; + foo.id = 0xABADCAFEABADCAFE + i; + foo.count = 10000 + i; + foo.length = 1000000 + i; + foo.prefix = '@' + i; + } + + len = sizeof(FooBarContainer); + return reinterpret_cast(fbc); + }; + + int64_t Use(void *decoded) override { + auto foobarcontainer = reinterpret_cast(decoded); + sum = 0; + Add(foobarcontainer->initialized); + Add(foobarcontainer->location_len); + Add(foobarcontainer->fruit); + for (unsigned int i = 0; i < kVectorLength; i++) { + auto foobar = &foobarcontainer->list[i]; + Add(foobar->name_len); + Add(foobar->postfix); + Add(static_cast(foobar->rating)); + auto bar = &foobar->sibling; + Add(static_cast(bar->ratio)); + Add(bar->size); + Add(bar->time); + auto &foo = bar->parent; + Add(foo.count); + Add(foo.id); + Add(foo.length); + Add(foo.prefix); + } + return sum; + } + + void *Decode(void *buf, int64_t) override { return buf; } + void Dealloc(void *) override{}; +}; + +} // namespace + +std::unique_ptr NewRawBench() { + return std::unique_ptr(new RawBench()); +} diff --git a/third_party/flatbuffers/benchmarks/cpp/raw/raw_bench.h b/third_party/flatbuffers/benchmarks/cpp/raw/raw_bench.h new file mode 100644 index 00000000000..68bb278c26f --- /dev/null +++ b/third_party/flatbuffers/benchmarks/cpp/raw/raw_bench.h @@ -0,0 +1,10 @@ +#ifndef BENCHMARKS_CPP_RAW_RAW_BENCH_H_ +#define BENCHMARKS_CPP_RAW_RAW_BENCH_H_ + +#include + +#include "benchmarks/cpp/bench.h" + +std::unique_ptr NewRawBench(); + +#endif // BENCHMARKS_CPP_RAW_RAW_BENCH_H_ \ No newline at end of file diff --git a/third_party/flatbuffers/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift b/third_party/flatbuffers/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift new file mode 100644 index 00000000000..21eff5fac5f --- /dev/null +++ b/third_party/flatbuffers/benchmarks/swift/Benchmarks/FlatbuffersBenchmarks/FlatbuffersBenchmarks.swift @@ -0,0 +1,201 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Benchmark +import CoreFoundation +import FlatBuffers + +@usableFromInline +struct AA: NativeStruct { + public init(a: Double, b: Double) { + self.a = a + self.b = b + } + var a: Double + var b: Double +} + +let benchmarks = { + let ints: [Int] = Array(repeating: 42, count: 100) + let bytes: [UInt8] = Array(repeating: 42, count: 100) + let str10 = (0...9).map { _ -> String in "x" }.joined() + let str100 = (0...99).map { _ -> String in "x" }.joined() + let array: [AA] = [ + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + AA(a: 2.4, b: 2.4), + ] + + let metrics: [BenchmarkMetric] = [ + .cpuTotal, + .wallClock, + .mallocCountTotal, + .releaseCount, + .peakMemoryResident, + ] + let maxIterations = 1_000_000 + let maxDuration: Duration = .seconds(3) + let singleConfiguration: Benchmark.Configuration = .init( + metrics: metrics, + warmupIterations: 1, + scalingFactor: .one, + maxDuration: maxDuration, + maxIterations: maxIterations) + let kiloConfiguration: Benchmark.Configuration = .init( + metrics: metrics, + warmupIterations: 1, + scalingFactor: .kilo, + maxDuration: maxDuration, + maxIterations: maxIterations) + let megaConfiguration: Benchmark.Configuration = .init( + metrics: metrics, + warmupIterations: 1, + scalingFactor: .mega, + maxDuration: maxDuration, + maxIterations: maxIterations) + + Benchmark.defaultConfiguration = megaConfiguration + + Benchmark("Allocating 1GB", configuration: singleConfiguration) { benchmark in + for _ in benchmark.scaledIterations { + blackHole(FlatBufferBuilder(initialSize: 1_024_000_000)) + } + } + + Benchmark("Clearing 1GB", configuration: singleConfiguration) { benchmark in + var fb = FlatBufferBuilder(initialSize: 1_024_000_000) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.clear()) + } + } + + Benchmark("Strings 10") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.create(string: str10)) + } + } + + Benchmark("Strings 100") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.create(string: str100)) + } + } + + Benchmark("Vector 1 Bytes") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.createVector(bytes: bytes)) + } + } + + Benchmark("Vector 1 Ints") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + blackHole(fb.createVector(ints)) + } + } + + Benchmark("Vector 100 Ints") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for i in benchmark.scaledIterations { + blackHole(fb.createVector(ints)) + } + } + + Benchmark("Vector 100 Bytes") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for i in benchmark.scaledIterations { + blackHole(fb.createVector(bytes)) + } + } + + Benchmark("Vector 100 ContiguousBytes") { benchmark in + var fb = FlatBufferBuilder(initialSize: 1<<20) + benchmark.startMeasurement() + for i in benchmark.scaledIterations { + blackHole(fb.createVector(bytes: bytes)) + } + } + + Benchmark( + "FlatBufferBuilder Add", + configuration: kiloConfiguration) + { benchmark in + var fb = FlatBufferBuilder(initialSize: 1024 * 1024 * 32) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let off = fb.create(string: "T") + let s = fb.startTable(with: 4) + fb.add(element: 3.2, def: 0, at: 2) + fb.add(element: 4.2, def: 0, at: 4) + fb.add(element: 5.2, def: 0, at: 6) + fb.add(offset: off, at: 8) + blackHole(fb.endTable(at: s)) + } + } + + Benchmark("Structs") { benchmark in + let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024 + var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) + var offsets: [Offset] = [] + + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let vector = fb.createVector( + ofStructs: array) + let start = fb.startTable(with: 1) + fb.add(offset: vector, at: 4) + offsets.append(Offset(offset: fb.endTable(at: start))) + } + + let vector = fb.createVector(ofOffsets: offsets) + let start = fb.startTable(with: 1) + fb.add(offset: vector, at: 4) + let root = Offset(offset: fb.endTable(at: start)) + fb.finish(offset: root) + } + + Benchmark("Vector of Offsets") { benchmark in + let rawSize = ((16 * 5) * benchmark.scaledIterations.count) / 1024 + var fb = FlatBufferBuilder(initialSize: Int32(rawSize * 1600)) + benchmark.startMeasurement() + for _ in benchmark.scaledIterations { + let offsets = [ + fb.create(string: "T"), + fb.create(string: "2"), + fb.create(string: "3"), + ] + let off = fb.createVector(ofOffsets: [ + fb.createVector(ofOffsets: offsets), + fb.createVector(ofOffsets: offsets), + ]) + let s = fb.startTable(with: 2) + fb.add(offset: off, at: 2) + blackHole(fb.endTable(at: s)) + } + } +} diff --git a/third_party/flatbuffers/benchmarks/swift/Package.swift b/third_party/flatbuffers/benchmarks/swift/Package.swift new file mode 100644 index 00000000000..4067daf66ae --- /dev/null +++ b/third_party/flatbuffers/benchmarks/swift/Package.swift @@ -0,0 +1,42 @@ +// swift-tools-version:5.9 +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import PackageDescription + +let package = Package( + name: "benchmarks", + platforms: [ + .macOS(.v13), + ], + dependencies: [ + .package(path: "../.."), + .package( + url: "https://github.com/ordo-one/package-benchmark", + from: "1.27.0"), + ], + targets: [ + .executableTarget( + name: "FlatbuffersBenchmarks", + dependencies: [ + .product(name: "FlatBuffers", package: "flatbuffers"), + .product(name: "Benchmark", package: "package-benchmark"), + ], + path: "Benchmarks/FlatbuffersBenchmarks", + plugins: [ + .plugin(name: "BenchmarkPlugin", package: "package-benchmark"), + ]), + ]) diff --git a/third_party/flatbuffers/benchmarks/swift/README.md b/third_party/flatbuffers/benchmarks/swift/README.md new file mode 100644 index 00000000000..4f95872d639 --- /dev/null +++ b/third_party/flatbuffers/benchmarks/swift/README.md @@ -0,0 +1,9 @@ +# Benchmarks + +To open the benchmarks in xcode use: + +`open --env BENCHMARK_DISABLE_JEMALLOC=true Package.swift` + +or running them directly within terminal using: + +`swift package benchmark` \ No newline at end of file diff --git a/third_party/flatbuffers/build_defs.bzl b/third_party/flatbuffers/build_defs.bzl index fff235448fd..51d3ce20fed 100644 --- a/third_party/flatbuffers/build_defs.bzl +++ b/third_party/flatbuffers/build_defs.bzl @@ -7,13 +7,13 @@ Rules for building C++ flatbuffers with Bazel. load("@rules_cc//cc:defs.bzl", "cc_library") -TRUE_FLATC_PATH = "@com_github_google_flatbuffers//:flatc" +TRUE_FLATC_PATH = Label("//:flatc") DEFAULT_INCLUDE_PATHS = [ "./", "$(GENDIR)", "$(BINDIR)", - "$(execpath @com_github_google_flatbuffers//:flatc).runfiles/com_github_google_flatbuffers", + "$(execpath %s).runfiles/%s" % (TRUE_FLATC_PATH, TRUE_FLATC_PATH.repo_name), ] def default_include_paths(flatc_path): @@ -21,7 +21,7 @@ def default_include_paths(flatc_path): "./", "$(GENDIR)", "$(BINDIR)", - "$(execpath %s).runfiles/com_github_google_flatbuffers" % (flatc_path), + "$(execpath %s).runfiles/%s" % (flatc_path, flatc_path.repo_name), ] DEFAULT_FLATC_ARGS = [ @@ -47,7 +47,7 @@ def flatbuffer_library_public( compatible_with = None, restricted_to = None, target_compatible_with = None, - flatc_path = "@com_github_google_flatbuffers//:flatc", + flatc_path = None, output_to_bindir = False, tools = None, extra_env = None, @@ -87,6 +87,11 @@ def flatbuffer_library_public( optionally a Fileset([reflection_name]) with all generated reflection binaries. """ + if flatc_path == None: + flatc_path = TRUE_FLATC_PATH + else: + flatc_path = native.package_relative_label(flatc_path) + reflection_include_paths = include_paths if include_paths == None: include_paths = default_include_paths(flatc_path) @@ -131,6 +136,8 @@ def flatbuffer_library_public( reflection_genrule_cmd = " ".join([ "SRCS=($(SRCS));", "for f in $${SRCS[@]:0:%s}; do" % len(srcs), + # Move the .fbs file into the current package if it is not there already + 'if [[ $$(dirname $$f) != "{0}" ]]; then s="$$f"; f="{0}/$$(basename "$$f")"; mkdir -p "{0}"; mv "$$s" "$$f"; fi;'.format(native.package_relative_label(":invalid").package), "$(location %s)" % (TRUE_FLATC_PATH), "-b --schema", " ".join(flatc_args), @@ -141,9 +148,10 @@ def flatbuffer_library_public( "done", ]) reflection_outs = [ - (out_prefix + "%s.bfbs") % (s.replace(".fbs", "").split("/")[-1]) + (out_prefix + "%s.bfbs") % (native.package_relative_label(s).name.removesuffix(".fbs")) for s in srcs ] + native.genrule( name = "%s_srcs" % reflection_name, srcs = srcs + includes, @@ -262,8 +270,8 @@ def flatbuffer_cc_library( "-parse_headers", ], deps = [ - "@com_github_google_flatbuffers//:runtime_cc", - "@com_github_google_flatbuffers//:flatbuffers", + Label("//:runtime_cc"), + Label("//:flatbuffers"), ] + deps, includes = cc_include_paths, compatible_with = compatible_with, diff --git a/third_party/flatbuffers/dart/CHANGELOG.md b/third_party/flatbuffers/dart/CHANGELOG.md new file mode 100644 index 00000000000..9562920965c --- /dev/null +++ b/third_party/flatbuffers/dart/CHANGELOG.md @@ -0,0 +1,46 @@ +# Changelog + +## 23.5.26 + +- omit type annotationes for local variables (#7067, #7069, #7070) +- remove BSD 3-clause license (#7073) +- correctly parse lists of enums (#7157) +- align naming conventions for generated code (#7187) +- add `putBool` to fix errors when serializing structs with booleans (#7359) +- fix handling of +/-inf defaults in codegen (#7588) +- fix import issues in generated code (#7621) +- Fix incorrect storage of floats as ints in some cases (#7703) +- add final modifiers to the library implementation (#7943) + +## 2.0.5 + +- switch to null safety (#6696) +- add Object APIs (pack/unpack) (#6682, #6723, #6846) +- add custom builder buffer allocator support (#6711) +- add `Builder.size()` - finished buffer size (#6403) +- make `writeString()` argument non-nullable (#6737) +- make tables fixed size (expect the number of fields when creating) (#6735) +- make table deduplication optional (param `deduplicateTables`) (#6734) +- change `Builder.reset()` to reuse an existing buffer (#6661) +- change table building to assert() instead of exceptions (#6754) +- optimize `writeString()` for ASCII (param `asciiOptimization`) (#6736) +- change `StringReader` to make ASCII optimization optional (param `asciiOptimization`) (#6758) +- change `[byte]` and `[ubyte]` representation to `dart:typed_data` `Int8List` and `Uint8List` (#6839) +- rename `lowFinish()` to `buffer` getter (#6712) +- fix `Builder._writeString()` - always write trailing zero byte (#6390) +- fix `Builder.reset()` - clear vTables (#6386) +- make sure added padding is zeroed, same as in C++ (#6716) +- many performance improvements (#6755) + +## 1.9.2 + +- Ensure `_writeString` adds enough padding to null terminate strings. + +## 1.9.1 + +- Changed constant identifiers to be compatible with Dart 2.x +- No longer supports Dart 1.x + +## 1.9.0 + +- Initial release, supports Dart 1.x and many dev versions of Dart 2.x diff --git a/third_party/flatbuffers/dart/LICENSE b/third_party/flatbuffers/dart/LICENSE new file mode 100644 index 00000000000..c02ca2f7a13 --- /dev/null +++ b/third_party/flatbuffers/dart/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2014 Google Inc. + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/third_party/flatbuffers/dart/README.md b/third_party/flatbuffers/dart/README.md new file mode 100644 index 00000000000..a07bc258ff6 --- /dev/null +++ b/third_party/flatbuffers/dart/README.md @@ -0,0 +1,15 @@ +# FlatBuffers for Dart + +This package is used to read and write [FlatBuffers](https://google.github.io/flatbuffers/). + +Most consumers will want to use the [`flatc` - FlatBuffer compiler](https://github.com/google/flatbuffers) binary for your platform. +You can download the flatc version matching your dart package version from [GitHub releases](https://github.com/google/flatbuffers/releases). + +The FlatBuffer compiler `flatc` reads a FlatBuffers IDL schema and generates Dart code. +The generated classes can be used to read or write binary data/files that are interoperable with +other languages and platforms supported by FlatBuffers, as illustrated in the `example.dart` in the +examples folder. + +For more details and documentation, head over to the official site and read the +[Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) and how to +[use FlatBuffers in Dart](https://google.github.io/flatbuffers/flatbuffers_guide_use_dart.html). diff --git a/third_party/flatbuffers/dart/analysis_options.yaml b/third_party/flatbuffers/dart/analysis_options.yaml new file mode 100644 index 00000000000..572dd239d09 --- /dev/null +++ b/third_party/flatbuffers/dart/analysis_options.yaml @@ -0,0 +1 @@ +include: package:lints/recommended.yaml diff --git a/third_party/flatbuffers/dart/example/example.dart b/third_party/flatbuffers/dart/example/example.dart new file mode 100644 index 00000000000..d397bbb3f44 --- /dev/null +++ b/third_party/flatbuffers/dart/example/example.dart @@ -0,0 +1,153 @@ +/* + * Copyright 2018 Dan Field. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import 'package:flat_buffers/flat_buffers.dart' as fb; +import './monster_my_game.sample_generated.dart' as my_game; + +// Example how to use FlatBuffers to create and read binary buffers. + +void main() { + builderTest(); + objectBuilderTest(); +} + +void builderTest() { + final builder = fb.Builder(initialSize: 1024); + final int? weaponOneName = builder.writeString("Sword"); + final int weaponOneDamage = 3; + + final int? weaponTwoName = builder.writeString("Axe"); + final int weaponTwoDamage = 5; + + final swordBuilder = my_game.WeaponBuilder(builder) + ..begin() + ..addNameOffset(weaponOneName) + ..addDamage(weaponOneDamage); + final int sword = swordBuilder.finish(); + + final axeBuilder = my_game.WeaponBuilder(builder) + ..begin() + ..addNameOffset(weaponTwoName) + ..addDamage(weaponTwoDamage); + final int axe = axeBuilder.finish(); + + // Serialize a name for our monster, called "Orc". + final int? name = builder.writeString('Orc'); + + // Create a list representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + final inventory = builder.writeListUint8(treasure); + final weapons = builder.writeList([sword, axe]); + + // Struct builders are very easy to reuse. + final vec3Builder = my_game.Vec3Builder(builder); + + vec3Builder.finish(4.0, 5.0, 6.0); + vec3Builder.finish(1.0, 2.0, 3.0); + // Set his hit points to 300 and his mana to 150. + final int hp = 300; + final int mana = 150; + + final monster = my_game.MonsterBuilder(builder) + ..begin() + ..addNameOffset(name) + ..addInventoryOffset(inventory) + ..addWeaponsOffset(weapons) + ..addEquippedType(my_game.EquipmentTypeId.Weapon) + ..addEquippedOffset(axe) + ..addHp(hp) + ..addMana(mana) + ..addPos(vec3Builder.finish(1.0, 2.0, 3.0)) + ..addColor(my_game.Color.Red); + + final int monsteroff = monster.finish(); + builder.finish(monsteroff); + if (verify(builder.buffer)) { + print( + "The FlatBuffer was successfully created with a builder and verified!"); + } +} + +void objectBuilderTest() { + // Create the builder here so we can use it for both weapons and equipped + // the actual data will only be written to the buffer once. + var axe = my_game.WeaponObjectBuilder(name: 'Axe', damage: 5); + + var monsterBuilder = my_game.MonsterObjectBuilder( + pos: my_game.Vec3ObjectBuilder(x: 1.0, y: 2.0, z: 3.0), + mana: 150, + hp: 300, + name: 'Orc', + inventory: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], + color: my_game.Color.Red, + weapons: [my_game.WeaponObjectBuilder(name: 'Sword', damage: 3), axe], + equippedType: my_game.EquipmentTypeId.Weapon, + equipped: axe, + ); + + var buffer = monsterBuilder.toBytes(); + + // We now have a FlatBuffer we can store on disk or send over a network. + + // ** file/network code goes here :) ** + + // Instead, we're going to access it right away (as if we just received it). + if (verify(buffer)) { + print( + "The FlatBuffer was successfully created with an object builder and verified!"); + } +} + +bool verify(List buffer) { + // Get access to the root: + var monster = my_game.Monster(buffer); + + // Get and test some scalar types from the FlatBuffer. + assert(monster.hp == 80); + assert(monster.mana == 150); // default + assert(monster.name == "MyMonster"); + + // Get and test a field of the FlatBuffer's `struct`. + var pos = monster.pos!; + assert(pos.z == 3.0); + + // Get a test an element from the `inventory` FlatBuffer's `vector`. + var inv = monster.inventory!; + assert(inv.length == 10); + assert(inv[9] == 9); + + // Get and test the `weapons` FlatBuffers's `vector`. + var expectedWeaponNames = ["Sword", "Axe"]; + var expectedWeaponDamages = [3, 5]; + var weps = monster.weapons!; + for (int i = 0; i < weps.length; i++) { + assert(weps[i].name == expectedWeaponNames[i]); + assert(weps[i].damage == expectedWeaponDamages[i]); + } + + // Get and test the `Equipment` union (`equipped` field). + assert(monster.equippedType!.value == my_game.EquipmentTypeId.Weapon.value); + assert(monster.equippedType == my_game.EquipmentTypeId.Weapon); + + assert(monster.equipped is my_game.Weapon); + var equipped = monster.equipped as my_game.Weapon; + assert(equipped.name == "Axe"); + assert(equipped.damage == 5); + + print(monster); + return true; +} diff --git a/third_party/flatbuffers/dart/example/monster_my_game.sample_generated.dart b/third_party/flatbuffers/dart/example/monster_my_game.sample_generated.dart new file mode 100644 index 00000000000..ba0a81f0d57 --- /dev/null +++ b/third_party/flatbuffers/dart/example/monster_my_game.sample_generated.dart @@ -0,0 +1,423 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable + +library my_game.sample; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +class Color { + final int value; + const Color._(this.value); + + factory Color.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum Color'); + } + return result; + } + + static Color? _createOrNull(int? value) => + value == null ? null : Color.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 2; + static bool containsValue(int value) => values.containsKey(value); + + static const Color Red = Color._(0); + static const Color Green = Color._(1); + static const Color Blue = Color._(2); + static const Map values = { + 0: Red, + 1: Green, + 2: Blue}; + + static const fb.Reader reader = _ColorReader(); + + @override + String toString() { + return 'Color{value: $value}'; + } +} + +class _ColorReader extends fb.Reader { + const _ColorReader(); + + @override + int get size => 1; + + @override + Color read(fb.BufferContext bc, int offset) => + Color.fromValue(const fb.Int8Reader().read(bc, offset)); +} + +class EquipmentTypeId { + final int value; + const EquipmentTypeId._(this.value); + + factory EquipmentTypeId.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum EquipmentTypeId'); + } + return result; + } + + static EquipmentTypeId? _createOrNull(int? value) => + value == null ? null : EquipmentTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 1; + static bool containsValue(int value) => values.containsKey(value); + + static const EquipmentTypeId NONE = EquipmentTypeId._(0); + static const EquipmentTypeId Weapon = EquipmentTypeId._(1); + static const Map values = { + 0: NONE, + 1: Weapon}; + + static const fb.Reader reader = _EquipmentTypeIdReader(); + + @override + String toString() { + return 'EquipmentTypeId{value: $value}'; + } +} + +class _EquipmentTypeIdReader extends fb.Reader { + const _EquipmentTypeIdReader(); + + @override + int get size => 1; + + @override + EquipmentTypeId read(fb.BufferContext bc, int offset) => + EquipmentTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +class Vec3 { + Vec3._(this._bc, this._bcOffset); + + static const fb.Reader reader = _Vec3Reader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + double get x => const fb.Float32Reader().read(_bc, _bcOffset + 0); + double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4); + double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8); + + @override + String toString() { + return 'Vec3{x: $x, y: $y, z: $z}'; + } +} + +class _Vec3Reader extends fb.StructReader { + const _Vec3Reader(); + + @override + int get size => 12; + + @override + Vec3 createObject(fb.BufferContext bc, int offset) => + Vec3._(bc, offset); +} + +class Vec3Builder { + Vec3Builder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(double x, double y, double z) { + fbBuilder.putFloat32(z); + fbBuilder.putFloat32(y); + fbBuilder.putFloat32(x); + return fbBuilder.offset; + } + +} + +class Vec3ObjectBuilder extends fb.ObjectBuilder { + final double _x; + final double _y; + final double _z; + + Vec3ObjectBuilder({ + required double x, + required double y, + required double z, + }) + : _x = x, + _y = y, + _z = z; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putFloat32(_z); + fbBuilder.putFloat32(_y); + fbBuilder.putFloat32(_x); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Monster { + Monster._(this._bc, this._bcOffset); + factory Monster(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MonsterReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4); + int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); + int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); + String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + List? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); + Color get color => Color.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 16, 2)); + List? get weapons => const fb.ListReader(Weapon.reader).vTableGetNullable(_bc, _bcOffset, 18); + EquipmentTypeId? get equippedType => EquipmentTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 20)); + dynamic get equipped { + switch (equippedType?.value) { + case 1: return Weapon.reader.vTableGetNullable(_bc, _bcOffset, 22); + default: return null; + } + } + List? get path => const fb.ListReader(Vec3.reader).vTableGetNullable(_bc, _bcOffset, 24); + + @override + String toString() { + return 'Monster{pos: $pos, mana: $mana, hp: $hp, name: $name, inventory: $inventory, color: $color, weapons: $weapons, equippedType: $equippedType, equipped: $equipped, path: $path}'; + } +} + +class _MonsterReader extends fb.TableReader { + const _MonsterReader(); + + @override + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); +} + +class MonsterBuilder { + MonsterBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(10); + } + + int addPos(int offset) { + fbBuilder.addStruct(0, offset); + return fbBuilder.offset; + } + int addMana(int? mana) { + fbBuilder.addInt16(1, mana); + return fbBuilder.offset; + } + int addHp(int? hp) { + fbBuilder.addInt16(2, hp); + return fbBuilder.offset; + } + int addNameOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + int addInventoryOffset(int? offset) { + fbBuilder.addOffset(5, offset); + return fbBuilder.offset; + } + int addColor(Color? color) { + fbBuilder.addInt8(6, color?.value); + return fbBuilder.offset; + } + int addWeaponsOffset(int? offset) { + fbBuilder.addOffset(7, offset); + return fbBuilder.offset; + } + int addEquippedType(EquipmentTypeId? equippedType) { + fbBuilder.addUint8(8, equippedType?.value); + return fbBuilder.offset; + } + int addEquippedOffset(int? offset) { + fbBuilder.addOffset(9, offset); + return fbBuilder.offset; + } + int addPathOffset(int? offset) { + fbBuilder.addOffset(10, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MonsterObjectBuilder extends fb.ObjectBuilder { + final Vec3ObjectBuilder? _pos; + final int? _mana; + final int? _hp; + final String? _name; + final List? _inventory; + final Color? _color; + final List? _weapons; + final EquipmentTypeId? _equippedType; + final dynamic _equipped; + final List? _path; + + MonsterObjectBuilder({ + Vec3ObjectBuilder? pos, + int? mana, + int? hp, + String? name, + List? inventory, + Color? color, + List? weapons, + EquipmentTypeId? equippedType, + dynamic equipped, + List? path, + }) + : _pos = pos, + _mana = mana, + _hp = hp, + _name = name, + _inventory = inventory, + _color = color, + _weapons = weapons, + _equippedType = equippedType, + _equipped = equipped, + _path = path; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? nameOffset = _name == null ? null + : fbBuilder.writeString(_name!); + final int? inventoryOffset = _inventory == null ? null + : fbBuilder.writeListUint8(_inventory!); + final int? weaponsOffset = _weapons == null ? null + : fbBuilder.writeList(_weapons!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? equippedOffset = _equipped?.getOrCreateOffset(fbBuilder); + final int? pathOffset = _path == null ? null + : fbBuilder.writeListOfStructs(_path!); + fbBuilder.startTable(10); + if (_pos != null) { + fbBuilder.addStruct(0, _pos!.finish(fbBuilder)); + } + fbBuilder.addInt16(1, _mana); + fbBuilder.addInt16(2, _hp); + fbBuilder.addOffset(3, nameOffset); + fbBuilder.addOffset(5, inventoryOffset); + fbBuilder.addInt8(6, _color?.value); + fbBuilder.addOffset(7, weaponsOffset); + fbBuilder.addUint8(8, _equippedType?.value); + fbBuilder.addOffset(9, equippedOffset); + fbBuilder.addOffset(10, pathOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Weapon { + Weapon._(this._bc, this._bcOffset); + factory Weapon(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _WeaponReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + int get damage => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 0); + + @override + String toString() { + return 'Weapon{name: $name, damage: $damage}'; + } +} + +class _WeaponReader extends fb.TableReader { + const _WeaponReader(); + + @override + Weapon createObject(fb.BufferContext bc, int offset) => + Weapon._(bc, offset); +} + +class WeaponBuilder { + WeaponBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addNameOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + int addDamage(int? damage) { + fbBuilder.addInt16(1, damage); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class WeaponObjectBuilder extends fb.ObjectBuilder { + final String? _name; + final int? _damage; + + WeaponObjectBuilder({ + String? name, + int? damage, + }) + : _name = name, + _damage = damage; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? nameOffset = _name == null ? null + : fbBuilder.writeString(_name!); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, nameOffset); + fbBuilder.addInt16(1, _damage); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/lib/flat_buffers.dart b/third_party/flatbuffers/dart/lib/flat_buffers.dart new file mode 100644 index 00000000000..2395992ae28 --- /dev/null +++ b/third_party/flatbuffers/dart/lib/flat_buffers.dart @@ -0,0 +1,1493 @@ +import 'dart:collection'; +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +const int _sizeofUint8 = 1; +const int _sizeofUint16 = 2; +const int _sizeofUint32 = 4; +const int _sizeofUint64 = 8; +const int _sizeofInt8 = 1; +const int _sizeofInt16 = 2; +const int _sizeofInt32 = 4; +const int _sizeofInt64 = 8; +const int _sizeofFloat32 = 4; +const int _sizeofFloat64 = 8; + +/// Callback used to invoke a struct builder's finish method. +/// +/// This callback is used by other struct's `finish` methods to write the nested +/// struct's fields inline. +typedef StructBuilder = void Function(); + +/// Buffer with data and some context about it. +class BufferContext { + final ByteData _buffer; + + ByteData get buffer => _buffer; + + /// Create from a FlatBuffer represented by a list of bytes (uint8). + factory BufferContext.fromBytes(List byteList) => + BufferContext(byteList is Uint8List + ? byteList.buffer.asByteData(byteList.offsetInBytes) + : ByteData.view(Uint8List.fromList(byteList).buffer)); + + /// Create from a FlatBuffer represented by ByteData. + BufferContext(this._buffer); + + @pragma('vm:prefer-inline') + int derefObject(int offset) => offset + _getUint32(offset); + + @pragma('vm:prefer-inline') + Uint8List _asUint8List(int offset, int length) => + _buffer.buffer.asUint8List(_buffer.offsetInBytes + offset, length); + + @pragma('vm:prefer-inline') + double _getFloat64(int offset) => _buffer.getFloat64(offset, Endian.little); + + @pragma('vm:prefer-inline') + double _getFloat32(int offset) => _buffer.getFloat32(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getInt64(int offset) => _buffer.getInt64(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getInt32(int offset) => _buffer.getInt32(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getInt16(int offset) => _buffer.getInt16(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getInt8(int offset) => _buffer.getInt8(offset); + + @pragma('vm:prefer-inline') + int _getUint64(int offset) => _buffer.getUint64(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getUint32(int offset) => _buffer.getUint32(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getUint16(int offset) => _buffer.getUint16(offset, Endian.little); + + @pragma('vm:prefer-inline') + int _getUint8(int offset) => _buffer.getUint8(offset); +} + +/// Interface implemented by the "object-api" classes (ending with "T"). +abstract class Packable { + /// Serialize the object using the given builder, returning the offset. + int pack(Builder fbBuilder); +} + +/// Class implemented by typed builders generated by flatc. +abstract class ObjectBuilder { + int? _firstOffset; + + /// Can be used to write the data represented by this builder to the [Builder] + /// and reuse the offset created in multiple tables. + /// + /// Note that this method assumes you call it using the same [Builder] instance + /// every time. The returned offset is only good for the [Builder] used in the + /// first call to this method. + int getOrCreateOffset(Builder fbBuilder) { + _firstOffset ??= finish(fbBuilder); + return _firstOffset!; + } + + /// Writes the data in this helper to the [Builder]. + int finish(Builder fbBuilder); + + /// Convenience method that will create a new [Builder], [finish]es the data, + /// and returns the buffer as a [Uint8List] of bytes. + Uint8List toBytes(); +} + +/// Class that helps building flat buffers. +class Builder { + bool _finished = false; + + final int initialSize; + + /// The list of existing VTable(s). + final List _vTables; + + final bool deduplicateTables; + + ByteData _buf; + + final Allocator _allocator; + + /// The maximum alignment that has been seen so far. If [_buf] has to be + /// reallocated in the future (to insert room at its start for more bytes) the + /// reallocation will need to be a multiple of this many bytes. + int _maxAlign = 1; + + /// The number of bytes that have been written to the buffer so far. The + /// most recently written byte is this many bytes from the end of [_buf]. + int _tail = 0; + + /// The location of the end of the current table, measured in bytes from the + /// end of [_buf]. + int _currentTableEndTail = 0; + + _VTable? _currentVTable; + + /// Map containing all strings that have been written so far. This allows us + /// to avoid duplicating strings. + /// + /// Allocated only if `internStrings` is set to true on the constructor. + Map? _strings; + + /// Creates a new FlatBuffers Builder. + /// + /// `initialSize` is the initial array size in bytes. The [Builder] will + /// automatically grow the array if/as needed. `internStrings`, if set to + /// true, will cause [writeString] to pool strings in the buffer so that + /// identical strings will always use the same offset in tables. + Builder({ + this.initialSize = 1024, + bool internStrings = false, + Allocator allocator = const DefaultAllocator(), + this.deduplicateTables = true, + }) : _allocator = allocator, + _buf = allocator.allocate(initialSize), + _vTables = deduplicateTables ? [] : const [] { + if (internStrings) { + _strings = {}; + } + } + + /// Calculate the finished buffer size (aligned). + @pragma('vm:prefer-inline') + int size() => _tail + ((-_tail) & (_maxAlign - 1)); + + /// Add the [field] with the given boolean [value]. The field is not added if + /// the [value] is equal to [def]. Booleans are stored as 8-bit fields with + /// `0` for `false` and `1` for `true`. + void addBool(int field, bool? value, [bool? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofUint8, 1); + _trackField(field); + _buf.setInt8(_buf.lengthInBytes - _tail, value ? 1 : 0); + } + } + + /// Add the [field] with the given 32-bit signed integer [value]. The field is + /// not added if the [value] is equal to [def]. + void addInt32(int field, int? value, [int? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofInt32, 1); + _trackField(field); + _setInt32AtTail(_tail, value); + } + } + + /// Add the [field] with the given 32-bit signed integer [value]. The field is + /// not added if the [value] is equal to [def]. + void addInt16(int field, int? value, [int? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofInt16, 1); + _trackField(field); + _setInt16AtTail(_tail, value); + } + } + + /// Add the [field] with the given 8-bit signed integer [value]. The field is + /// not added if the [value] is equal to [def]. + void addInt8(int field, int? value, [int? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofInt8, 1); + _trackField(field); + _setInt8AtTail(_tail, value); + } + } + + void addStruct(int field, int offset) { + assert(_inVTable); + _trackField(field); + _currentVTable!.addField(field, offset); + } + + /// Add the [field] referencing an object with the given [offset]. + void addOffset(int field, int? offset) { + assert(_inVTable); + if (offset != null) { + _prepare(_sizeofUint32, 1); + _trackField(field); + _setUint32AtTail(_tail, _tail - offset); + } + } + + /// Add the [field] with the given 32-bit unsigned integer [value]. The field + /// is not added if the [value] is equal to [def]. + void addUint32(int field, int? value, [int? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofUint32, 1); + _trackField(field); + _setUint32AtTail(_tail, value); + } + } + + /// Add the [field] with the given 32-bit unsigned integer [value]. The field + /// is not added if the [value] is equal to [def]. + void addUint16(int field, int? value, [int? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofUint16, 1); + _trackField(field); + _setUint16AtTail(_tail, value); + } + } + + /// Add the [field] with the given 8-bit unsigned integer [value]. The field + /// is not added if the [value] is equal to [def]. + void addUint8(int field, int? value, [int? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofUint8, 1); + _trackField(field); + _setUint8AtTail(_tail, value); + } + } + + /// Add the [field] with the given 32-bit float [value]. The field + /// is not added if the [value] is equal to [def]. + void addFloat32(int field, double? value, [double? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofFloat32, 1); + _trackField(field); + _setFloat32AtTail(_tail, value); + } + } + + /// Add the [field] with the given 64-bit double [value]. The field + /// is not added if the [value] is equal to [def]. + void addFloat64(int field, double? value, [double? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofFloat64, 1); + _trackField(field); + _setFloat64AtTail(_tail, value); + } + } + + /// Add the [field] with the given 64-bit unsigned integer [value]. The field + /// is not added if the [value] is equal to [def]. + void addUint64(int field, int? value, [double? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofUint64, 1); + _trackField(field); + _setUint64AtTail(_tail, value); + } + } + + /// Add the [field] with the given 64-bit unsigned integer [value]. The field + /// is not added if the [value] is equal to [def]. + void addInt64(int field, int? value, [double? def]) { + assert(_inVTable); + if (value != null && value != def) { + _prepare(_sizeofInt64, 1); + _trackField(field); + _setInt64AtTail(_tail, value); + } + } + + /// End the current table and return its offset. + int endTable() { + assert(_inVTable); + // Prepare for writing the VTable. + _prepare(_sizeofInt32, 1); + final tableTail = _tail; + // Prepare the size of the current table. + final currentVTable = _currentVTable!; + currentVTable.tableSize = tableTail - _currentTableEndTail; + // Prepare the VTable to use for the current table. + int? vTableTail; + { + currentVTable.computeFieldOffsets(tableTail); + + // Try to find an existing compatible VTable. + if (deduplicateTables) { + // Search backward - more likely to have recently used one + for (var i = _vTables.length - 1; i >= 0; i--) { + final vt2Offset = _vTables[i]; + final vt2Start = _buf.lengthInBytes - vt2Offset; + final vt2Size = _buf.getUint16(vt2Start, Endian.little); + + if (currentVTable._vTableSize == vt2Size && + currentVTable._offsetsMatch(vt2Start, _buf)) { + vTableTail = vt2Offset; + break; + } + } + } + + // Write a new VTable. + if (vTableTail == null) { + _prepare(_sizeofUint16, _currentVTable!.numOfUint16); + vTableTail = _tail; + currentVTable.tail = vTableTail; + currentVTable.output(_buf, _buf.lengthInBytes - _tail); + if (deduplicateTables) _vTables.add(currentVTable.tail); + } + } + // Set the VTable offset. + _setInt32AtTail(tableTail, vTableTail - tableTail); + // Done with this table. + _currentVTable = null; + return tableTail; + } + + /// Returns the finished buffer. You must call [finish] before accessing this. + @pragma('vm:prefer-inline') + Uint8List get buffer { + assert(_finished); + final finishedSize = size(); + return _buf.buffer + .asUint8List(_buf.lengthInBytes - finishedSize, finishedSize); + } + + /// Finish off the creation of the buffer. The given [offset] is used as the + /// root object offset, and usually references directly or indirectly every + /// written object. If [fileIdentifier] is specified (and not `null`), it is + /// interpreted as a 4-byte Latin-1 encoded string that should be placed at + /// bytes 4-7 of the file. + void finish(int offset, [String? fileIdentifier]) { + final sizeBeforePadding = size(); + final requiredBytes = _sizeofUint32 * (fileIdentifier == null ? 1 : 2); + _prepare(max(requiredBytes, _maxAlign), 1); + final finishedSize = size(); + _setUint32AtTail(finishedSize, finishedSize - offset); + if (fileIdentifier != null) { + for (var i = 0; i < 4; i++) { + _setUint8AtTail( + finishedSize - _sizeofUint32 - i, fileIdentifier.codeUnitAt(i)); + } + } + + // zero out the added padding + for (var i = sizeBeforePadding + 1; + i <= finishedSize - requiredBytes; + i++) { + _setUint8AtTail(i, 0); + } + _finished = true; + } + + /// Writes a Float64 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putFloat64(double value) { + _prepare(_sizeofFloat64, 1); + _setFloat64AtTail(_tail, value); + } + + /// Writes a Float32 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putFloat32(double value) { + _prepare(_sizeofFloat32, 1); + _setFloat32AtTail(_tail, value); + } + + /// Writes a bool to the tail of the buffer after preparing space for it. + /// Bools are represented as a Uint8, with the value set to '1' for true, and '0' for false + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putBool(bool value) { + _prepare(_sizeofUint8, 1); + _buf.setInt8(_buf.lengthInBytes - _tail, value ? 1 : 0); + } + + /// Writes a Int64 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putInt64(int value) { + _prepare(_sizeofInt64, 1); + _setInt64AtTail(_tail, value); + } + + /// Writes a Uint32 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putInt32(int value) { + _prepare(_sizeofInt32, 1); + _setInt32AtTail(_tail, value); + } + + /// Writes a Uint16 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putInt16(int value) { + _prepare(_sizeofInt16, 1); + _setInt16AtTail(_tail, value); + } + + /// Writes a Uint8 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putInt8(int value) { + _prepare(_sizeofInt8, 1); + _buf.setInt8(_buf.lengthInBytes - _tail, value); + } + + /// Writes a Uint64 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putUint64(int value) { + _prepare(_sizeofUint64, 1); + _setUint64AtTail(_tail, value); + } + + /// Writes a Uint32 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putUint32(int value) { + _prepare(_sizeofUint32, 1); + _setUint32AtTail(_tail, value); + } + + /// Writes a Uint16 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putUint16(int value) { + _prepare(_sizeofUint16, 1); + _setUint16AtTail(_tail, value); + } + + /// Writes a Uint8 to the tail of the buffer after preparing space for it. + /// + /// Updates the [offset] pointer. This method is intended for use when writing structs to the buffer. + void putUint8(int value) { + _prepare(_sizeofUint8, 1); + _buf.setUint8(_buf.lengthInBytes - _tail, value); + } + + /// Reset the builder and make it ready for filling a new buffer. + void reset() { + _finished = false; + _maxAlign = 1; + _tail = 0; + _currentVTable = null; + if (deduplicateTables) _vTables.clear(); + if (_strings != null) { + _strings = {}; + } + } + + /// Start a new table. Must be finished with [endTable] invocation. + void startTable(int numFields) { + assert(!_inVTable); // Inline tables are not supported. + _currentVTable = _VTable(numFields); + _currentTableEndTail = _tail; + } + + /// Finish a Struct vector. Most callers should preferto use [writeListOfStructs]. + /// + /// Most callers should prefer [writeListOfStructs]. + int endStructVector(int count) { + putUint32(count); + return _tail; + } + + /// Writes a list of Structs to the buffer, returning the offset + int writeListOfStructs(List structBuilders) { + assert(!_inVTable); + for (var i = structBuilders.length - 1; i >= 0; i--) { + structBuilders[i].finish(this); + } + return endStructVector(structBuilders.length); + } + + /// Write the given list of [values]. + int writeList(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1 + values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setUint32AtTail(tail, tail - value); + tail -= _sizeofUint32; + } + return result; + } + + /// Write the given list of 64-bit float [values]. + int writeListFloat64(List values) { + assert(!_inVTable); + _prepare(_sizeofFloat64, values.length, additionalBytes: _sizeofUint32); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setFloat64AtTail(tail, value); + tail -= _sizeofFloat64; + } + return result; + } + + /// Write the given list of 32-bit float [values]. + int writeListFloat32(List values) { + assert(!_inVTable); + _prepare(_sizeofFloat32, 1 + values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setFloat32AtTail(tail, value); + tail -= _sizeofFloat32; + } + return result; + } + + /// Write the given list of signed 64-bit integer [values]. + int writeListInt64(List values) { + assert(!_inVTable); + _prepare(_sizeofInt64, values.length, additionalBytes: _sizeofUint32); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setInt64AtTail(tail, value); + tail -= _sizeofInt64; + } + return result; + } + + /// Write the given list of signed 64-bit integer [values]. + int writeListUint64(List values) { + assert(!_inVTable); + _prepare(_sizeofUint64, values.length, additionalBytes: _sizeofUint32); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setUint64AtTail(tail, value); + tail -= _sizeofUint64; + } + return result; + } + + /// Write the given list of signed 32-bit integer [values]. + int writeListInt32(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1 + values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setInt32AtTail(tail, value); + tail -= _sizeofInt32; + } + return result; + } + + /// Write the given list of unsigned 32-bit integer [values]. + int writeListUint32(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1 + values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setUint32AtTail(tail, value); + tail -= _sizeofUint32; + } + return result; + } + + /// Write the given list of signed 16-bit integer [values]. + int writeListInt16(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setInt16AtTail(tail, value); + tail -= _sizeofInt16; + } + return result; + } + + /// Write the given list of unsigned 16-bit integer [values]. + int writeListUint16(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1, additionalBytes: 2 * values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setUint16AtTail(tail, value); + tail -= _sizeofUint16; + } + return result; + } + + /// Write the given list of bools as unsigend 8-bit integer [values]. + int writeListBool(List values) { + return writeListUint8(values.map((b) => b ? 1 : 0).toList()); + } + + /// Write the given list of signed 8-bit integer [values]. + int writeListInt8(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1, additionalBytes: values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setInt8AtTail(tail, value); + tail -= _sizeofUint8; + } + return result; + } + + /// Write the given list of unsigned 8-bit integer [values]. + int writeListUint8(List values) { + assert(!_inVTable); + _prepare(_sizeofUint32, 1, additionalBytes: values.length); + final result = _tail; + var tail = _tail; + _setUint32AtTail(tail, values.length); + tail -= _sizeofUint32; + for (final value in values) { + _setUint8AtTail(tail, value); + tail -= _sizeofUint8; + } + return result; + } + + /// Write the given string [value] and return its offset. + /// + /// Dart strings are UTF-16 but must be stored as UTF-8 in FlatBuffers. + /// If the given string consists only of ASCII characters, you can indicate + /// enable [asciiOptimization]. In this mode, [writeString()] first tries to + /// copy the ASCII string directly to the output buffer and if that fails + /// (because there are no-ASCII characters in the string) it falls back and to + /// the default UTF-16 -> UTF-8 conversion (with slight performance penalty). + int writeString(String value, {bool asciiOptimization = false}) { + assert(!_inVTable); + if (_strings != null) { + return _strings! + .putIfAbsent(value, () => _writeString(value, asciiOptimization)); + } else { + return _writeString(value, asciiOptimization); + } + } + + int _writeString(String value, bool asciiOptimization) { + if (asciiOptimization) { + // [utf8.encode()] is slow (up to at least Dart SDK 2.13). If the given + // string is ASCII we can just write it directly, without any conversion. + final originalTail = _tail; + if (_tryWriteASCIIString(value)) return _tail; + // if non-ASCII: reset the output buffer position for [_writeUTFString()] + _tail = originalTail; + } + _writeUTFString(value); + return _tail; + } + + // Try to write the string as ASCII, return false if there's a non-ascii char. + @pragma('vm:prefer-inline') + bool _tryWriteASCIIString(String value) { + _prepare(4, 1, additionalBytes: value.length + 1); + final length = value.length; + var offset = _buf.lengthInBytes - _tail + 4; + for (var i = 0; i < length; i++) { + // utf16 code unit, e.g. for '†' it's [0x20 0x20], which is 8224 decimal. + // ASCII characters go from 0x00 to 0x7F (which is 0 to 127 decimal). + final char = value.codeUnitAt(i); + if ((char & ~0x7F) != 0) { + return false; + } + _buf.setUint8(offset++, char); + } + _buf.setUint8(offset, 0); // trailing zero + _setUint32AtTail(_tail, value.length); + return true; + } + + @pragma('vm:prefer-inline') + void _writeUTFString(String value) { + final bytes = utf8.encode(value) as Uint8List; + final length = bytes.length; + _prepare(4, 1, additionalBytes: length + 1); + _setUint32AtTail(_tail, length); + var offset = _buf.lengthInBytes - _tail + 4; + for (var i = 0; i < length; i++) { + _buf.setUint8(offset++, bytes[i]); + } + _buf.setUint8(offset, 0); // trailing zero + } + + /// Used to assert whether a "Table" is currently being built. + /// + /// If you hit `assert(!_inVTable())`, you're trying to add table fields + /// without starting a table with [Builder.startTable()]. + /// + /// If you hit `assert(_inVTable())`, you're trying to construct a + /// Table/Vector/String during the construction of its parent table, + /// between the MyTableBuilder and [Builder.endTable()]. + /// Move the creation of these sub-objects to before the MyTableBuilder to + /// not get this assert. + @pragma('vm:prefer-inline') + bool get _inVTable => _currentVTable != null; + + /// The number of bytes that have been written to the buffer so far. The + /// most recently written byte is this many bytes from the end of the buffer. + @pragma('vm:prefer-inline') + int get offset => _tail; + + /// Zero-pads the buffer, which may be required for some struct layouts. + @pragma('vm:prefer-inline') + void pad(int howManyBytes) { + for (var i = 0; i < howManyBytes; i++) { + putUint8(0); + } + } + + /// Prepare for writing the given `count` of scalars of the given `size`. + /// Additionally allocate the specified `additionalBytes`. Update the current + /// tail pointer to point at the allocated space. + @pragma('vm:prefer-inline') + void _prepare(int size, int count, {int additionalBytes = 0}) { + assert(!_finished); + // Update the alignment. + if (_maxAlign < size) { + _maxAlign = size; + } + // Prepare amount of required space. + final dataSize = size * count + additionalBytes; + final alignDelta = (-(_tail + dataSize)) & (size - 1); + final bufSize = alignDelta + dataSize; + // Ensure that we have the required amount of space. + { + final oldCapacity = _buf.lengthInBytes; + if (_tail + bufSize > oldCapacity) { + final desiredNewCapacity = (oldCapacity + bufSize) * 2; + var deltaCapacity = desiredNewCapacity - oldCapacity; + deltaCapacity += (-deltaCapacity) & (_maxAlign - 1); + final newCapacity = oldCapacity + deltaCapacity; + _buf = _allocator.resize(_buf, newCapacity, _tail, 0); + } + } + + // zero out the added padding + for (var i = _tail + 1; i <= _tail + alignDelta; i++) { + _setUint8AtTail(i, 0); + } + + // Update the tail pointer. + _tail += bufSize; + } + + /// Record the offset of the given [field]. + @pragma('vm:prefer-inline') + void _trackField(int field) => _currentVTable!.addField(field, _tail); + + @pragma('vm:prefer-inline') + void _setFloat64AtTail(int tail, double x) => + _buf.setFloat64(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setFloat32AtTail(int tail, double x) => + _buf.setFloat32(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setUint64AtTail(int tail, int x) => + _buf.setUint64(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setInt64AtTail(int tail, int x) => + _buf.setInt64(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setInt32AtTail(int tail, int x) => + _buf.setInt32(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setUint32AtTail(int tail, int x) => + _buf.setUint32(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setInt16AtTail(int tail, int x) => + _buf.setInt16(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setUint16AtTail(int tail, int x) => + _buf.setUint16(_buf.lengthInBytes - tail, x, Endian.little); + + @pragma('vm:prefer-inline') + void _setInt8AtTail(int tail, int x) => + _buf.setInt8(_buf.lengthInBytes - tail, x); + + @pragma('vm:prefer-inline') + void _setUint8AtTail(int tail, int x) => + _buf.setUint8(_buf.lengthInBytes - tail, x); +} + +/// Reader of lists of boolean values. +/// +/// The returned unmodifiable lists lazily read values on access. +class BoolListReader extends Reader> { + const BoolListReader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) => + _FbBoolList(bc, bc.derefObject(offset)); +} + +/// The reader of booleans. +class BoolReader extends Reader { + const BoolReader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint8; + + @override + @pragma('vm:prefer-inline') + bool read(BufferContext bc, int offset) => bc._getInt8(offset) != 0; +} + +/// The reader of lists of 64-bit float values. +/// +/// The returned unmodifiable lists lazily read values on access. +class Float64ListReader extends Reader> { + const Float64ListReader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofFloat64; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) => + _FbFloat64List(bc, bc.derefObject(offset)); +} + +class Float32ListReader extends Reader> { + const Float32ListReader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofFloat32; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) => + _FbFloat32List(bc, bc.derefObject(offset)); +} + +class Float64Reader extends Reader { + const Float64Reader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofFloat64; + + @override + @pragma('vm:prefer-inline') + double read(BufferContext bc, int offset) => bc._getFloat64(offset); +} + +class Float32Reader extends Reader { + const Float32Reader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofFloat32; + + @override + @pragma('vm:prefer-inline') + double read(BufferContext bc, int offset) => bc._getFloat32(offset); +} + +class Int64Reader extends Reader { + const Int64Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofInt64; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getInt64(offset); +} + +/// The reader of signed 32-bit integers. +class Int32Reader extends Reader { + const Int32Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofInt32; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getInt32(offset); +} + +/// The reader of signed 32-bit integers. +class Int16Reader extends Reader { + const Int16Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofInt16; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getInt16(offset); +} + +/// The reader of 8-bit signed integers. +class Int8Reader extends Reader { + const Int8Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofInt8; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getInt8(offset); +} + +/// The reader of lists of objects. Lazy by default - see [lazy]. +class ListReader extends Reader> { + final Reader _elementReader; + + /// Enables lazy reading of the list + /// + /// If true, the returned unmodifiable list lazily reads objects on access. + /// Therefore, the underlying buffer must not change while accessing the list. + /// + /// If false, reads the whole list immediately on access. + final bool lazy; + + const ListReader(this._elementReader, {this.lazy = true}); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + List read(BufferContext bc, int offset) { + final listOffset = bc.derefObject(offset); + return lazy + ? _FbGenericList(_elementReader, bc, listOffset) + : List.generate( + bc.buffer.getUint32(listOffset, Endian.little), + (int index) => _elementReader.read( + bc, listOffset + size + _elementReader.size * index), + growable: true); + } +} + +/// Object that can read a value at a [BufferContext]. +abstract class Reader { + const Reader(); + + /// The size of the value in bytes. + int get size; + + /// Read the value at the given [offset] in [bc]. + T read(BufferContext bc, int offset); + + /// Read the value of the given [field] in the given [object]. + @pragma('vm:prefer-inline') + T vTableGet(BufferContext object, int offset, int field, T defaultValue) { + final fieldOffset = _vTableFieldOffset(object, offset, field); + return fieldOffset == 0 ? defaultValue : read(object, offset + fieldOffset); + } + + /// Read the value of the given [field] in the given [object]. + @pragma('vm:prefer-inline') + T? vTableGetNullable(BufferContext object, int offset, int field) { + final fieldOffset = _vTableFieldOffset(object, offset, field); + return fieldOffset == 0 ? null : read(object, offset + fieldOffset); + } + + @pragma('vm:prefer-inline') + int _vTableFieldOffset(BufferContext object, int offset, int field) { + final vTableSOffset = object._getInt32(offset); + final vTableOffset = offset - vTableSOffset; + final vTableSize = object._getUint16(vTableOffset); + if (field >= vTableSize) return 0; + return object._getUint16(vTableOffset + field); + } +} + +/// The reader of string values. +class StringReader extends Reader { + final bool asciiOptimization; + + const StringReader({this.asciiOptimization = false}) : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + String read(BufferContext bc, int offset) { + final strOffset = bc.derefObject(offset); + final length = bc._getUint32(strOffset); + final bytes = bc._asUint8List(strOffset + _sizeofUint32, length); + if (asciiOptimization && _isLatin(bytes)) { + return String.fromCharCodes(bytes); + } + return utf8.decode(bytes); + } + + @pragma('vm:prefer-inline') + static bool _isLatin(Uint8List bytes) { + final length = bytes.length; + for (var i = 0; i < length; i++) { + if (bytes[i] > 127) { + return false; + } + } + return true; + } +} + +/// An abstract reader for structs. +abstract class StructReader extends Reader { + const StructReader(); + + /// Return the object at `offset`. + T createObject(BufferContext bc, int offset); + + @override + T read(BufferContext bc, int offset) { + return createObject(bc, offset); + } +} + +/// An abstract reader for tables. +abstract class TableReader extends Reader { + const TableReader(); + + @override + @pragma('vm:prefer-inline') + int get size => 4; + + /// Return the object at [offset]. + T createObject(BufferContext bc, int offset); + + @override + T read(BufferContext bc, int offset) { + final objectOffset = bc.derefObject(offset); + return createObject(bc, objectOffset); + } +} + +/// Reader of lists of unsigned 32-bit integer values. +/// +/// The returned unmodifiable lists lazily read values on access. +class Uint32ListReader extends Reader> { + const Uint32ListReader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) => + _FbUint32List(bc, bc.derefObject(offset)); +} + +/// The reader of unsigned 64-bit integers. +/// +/// WARNING: May have compatibility issues with JavaScript +class Uint64Reader extends Reader { + const Uint64Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint64; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getUint64(offset); +} + +/// The reader of unsigned 32-bit integers. +class Uint32Reader extends Reader { + const Uint32Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getUint32(offset); +} + +/// Reader of lists of unsigned 32-bit integer values. +/// +/// The returned unmodifiable lists lazily read values on access. +class Uint16ListReader extends Reader> { + const Uint16ListReader(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) => + _FbUint16List(bc, bc.derefObject(offset)); +} + +/// The reader of unsigned 32-bit integers. +class Uint16Reader extends Reader { + const Uint16Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint16; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getUint16(offset); +} + +/// Reader of unmodifiable binary data (a list of unsigned 8-bit integers). +class Uint8ListReader extends Reader> { + /// Enables lazy reading of the list + /// + /// If true, the returned unmodifiable list lazily reads bytes on access. + /// Therefore, the underlying buffer must not change while accessing the list. + /// + /// If false, reads the whole list immediately as an Uint8List. + final bool lazy; + + const Uint8ListReader({this.lazy = true}); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) { + final listOffset = bc.derefObject(offset); + if (lazy) return _FbUint8List(bc, listOffset); + + final length = bc._getUint32(listOffset); + final result = Uint8List(length); + var pos = listOffset + _sizeofUint32; + for (var i = 0; i < length; i++, pos++) { + result[i] = bc._getUint8(pos); + } + return result; + } +} + +/// The reader of unsigned 8-bit integers. +class Uint8Reader extends Reader { + const Uint8Reader() : super(); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint8; + + @override + @pragma('vm:prefer-inline') + int read(BufferContext bc, int offset) => bc._getUint8(offset); +} + +/// Reader of unmodifiable binary data (a list of signed 8-bit integers). +class Int8ListReader extends Reader> { + /// Enables lazy reading of the list + /// + /// If true, the returned unmodifiable list lazily reads bytes on access. + /// Therefore, the underlying buffer must not change while accessing the list. + /// + /// If false, reads the whole list immediately as an Uint8List. + final bool lazy; + + const Int8ListReader({this.lazy = true}); + + @override + @pragma('vm:prefer-inline') + int get size => _sizeofUint32; + + @override + @pragma('vm:prefer-inline') + List read(BufferContext bc, int offset) { + final listOffset = bc.derefObject(offset); + if (lazy) return _FbUint8List(bc, listOffset); + + final length = bc._getUint32(listOffset); + final result = Int8List(length); + var pos = listOffset + _sizeofUint32; + for (var i = 0; i < length; i++, pos++) { + result[i] = bc._getInt8(pos); + } + return result; + } +} + +/// The list backed by 64-bit values - Uint64 length and Float64. +class _FbFloat64List extends _FbList { + _FbFloat64List(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + double operator [](int i) => bc._getFloat64(offset + 4 + 8 * i); +} + +/// The list backed by 32-bit values - Float32. +class _FbFloat32List extends _FbList { + _FbFloat32List(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + double operator [](int i) => bc._getFloat32(offset + 4 + 4 * i); +} + +/// List backed by a generic object which may have any size. +class _FbGenericList extends _FbList { + final Reader elementReader; + + List? _items; + + _FbGenericList(this.elementReader, BufferContext bp, int offset) + : super(bp, offset); + + @override + @pragma('vm:prefer-inline') + E operator [](int i) { + _items ??= List.filled(length, null); + var item = _items![i]; + if (item == null) { + item = elementReader.read(bc, offset + 4 + elementReader.size * i); + _items![i] = item; + } + return item!; + } +} + +/// The base class for immutable lists read from flat buffers. +abstract class _FbList extends Object with ListMixin implements List { + final BufferContext bc; + final int offset; + int? _length; + + _FbList(this.bc, this.offset); + + @override + @pragma('vm:prefer-inline') + int get length => _length ??= bc._getUint32(offset); + + @override + set length(int i) => throw StateError('Attempt to modify immutable list'); + + @override + void operator []=(int i, E e) => + throw StateError('Attempt to modify immutable list'); +} + +/// List backed by 32-bit unsigned integers. +class _FbUint32List extends _FbList { + _FbUint32List(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + int operator [](int i) => bc._getUint32(offset + 4 + 4 * i); +} + +/// List backed by 16-bit unsigned integers. +class _FbUint16List extends _FbList { + _FbUint16List(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + int operator [](int i) => bc._getUint16(offset + 4 + 2 * i); +} + +/// List backed by 8-bit unsigned integers. +class _FbUint8List extends _FbList { + _FbUint8List(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + int operator [](int i) => bc._getUint8(offset + 4 + i); +} + +/// List backed by 8-bit signed integers. +class _FbInt8List extends _FbList { + _FbInt8List(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + int operator [](int i) => bc._getInt8(offset + 4 + i); +} + +/// List backed by 8-bit unsigned integers. +class _FbBoolList extends _FbList { + _FbBoolList(BufferContext bc, int offset) : super(bc, offset); + + @override + @pragma('vm:prefer-inline') + bool operator [](int i) => bc._getUint8(offset + 4 + i) == 1 ? true : false; +} + +/// Class that describes the structure of a table. +class _VTable { + static const int _metadataLength = 4; + + final int numFields; + + // Note: fieldOffsets start as "tail offsets" and are then transformed by + // [computeFieldOffsets()] to actual offsets when a table is finished. + final Uint32List fieldOffsets; + bool offsetsComputed = false; + + _VTable(this.numFields) : fieldOffsets = Uint32List(numFields); + + /// The size of the table that uses this VTable. + int tableSize = 0; + + /// The tail of this VTable. It is used to share the same VTable between + /// multiple tables of identical structure. + int tail = 0; + + int get _vTableSize => numOfUint16 * _sizeofUint16; + + int get numOfUint16 => 1 + 1 + numFields; + + @pragma('vm:prefer-inline') + void addField(int field, int offset) { + assert(!offsetsComputed); + assert(offset > 0); // it's impossible for field to start at the buffer end + assert(offset <= 4294967295); // uint32 max + fieldOffsets[field] = offset; + } + + @pragma('vm:prefer-inline') + bool _offsetsMatch(int vt2Start, ByteData buf) { + assert(offsetsComputed); + for (var i = 0; i < numFields; i++) { + if (fieldOffsets[i] != + buf.getUint16(vt2Start + _metadataLength + (2 * i), Endian.little)) { + return false; + } + } + return true; + } + + /// Fill the [fieldOffsets] field. + @pragma('vm:prefer-inline') + void computeFieldOffsets(int tableTail) { + assert(!offsetsComputed); + offsetsComputed = true; + for (var i = 0; i < numFields; i++) { + if (fieldOffsets[i] != 0) { + fieldOffsets[i] = tableTail - fieldOffsets[i]; + } + } + } + + /// Outputs this VTable to [buf], which is is expected to be aligned to 16-bit + /// and have at least [numOfUint16] 16-bit words available. + @pragma('vm:prefer-inline') + void output(ByteData buf, int bufOffset) { + assert(offsetsComputed); + // VTable size. + buf.setUint16(bufOffset, numOfUint16 * 2, Endian.little); + bufOffset += 2; + // Table size. + buf.setUint16(bufOffset, tableSize, Endian.little); + bufOffset += 2; + // Field offsets. + for (var i = 0; i < numFields; i++) { + buf.setUint16(bufOffset, fieldOffsets[i], Endian.little); + bufOffset += 2; + } + } +} + +/// The interface that [Builder] uses to allocate buffers for encoding. +abstract class Allocator { + const Allocator(); + + /// Allocate a [ByteData] buffer of a given size. + ByteData allocate(int size); + + /// Free the given [ByteData] buffer previously allocated by [allocate]. + void deallocate(ByteData data); + + /// Reallocate [newSize] bytes of memory, replacing the old [oldData]. This + /// grows downwards, and is intended specifically for use with [Builder]. + /// Params [inUseBack] and [inUseFront] indicate how much of [oldData] is + /// actually in use at each end, and needs to be copied. + ByteData resize( + ByteData oldData, int newSize, int inUseBack, int inUseFront) { + final newData = allocate(newSize); + _copyDownward(oldData, newData, inUseBack, inUseFront); + deallocate(oldData); + return newData; + } + + /// Called by [resize] to copy memory from [oldData] to [newData]. Only + /// memory of size [inUseFront] and [inUseBack] will be copied from the front + /// and back of the old memory allocation. + void _copyDownward( + ByteData oldData, ByteData newData, int inUseBack, int inUseFront) { + if (inUseBack != 0) { + newData.buffer.asUint8List().setAll( + newData.lengthInBytes - inUseBack, + oldData.buffer.asUint8List().getRange( + oldData.lengthInBytes - inUseBack, oldData.lengthInBytes)); + } + if (inUseFront != 0) { + newData.buffer + .asUint8List() + .setAll(0, oldData.buffer.asUint8List().getRange(0, inUseFront)); + } + } +} + +class DefaultAllocator extends Allocator { + const DefaultAllocator(); + + @override + ByteData allocate(int size) => ByteData(size); + + @override + void deallocate(ByteData data) { + // nothing to do, it's garbage-collected + } +} diff --git a/third_party/flatbuffers/dart/lib/flex_buffers.dart b/third_party/flatbuffers/dart/lib/flex_buffers.dart new file mode 100644 index 00000000000..824affffcc5 --- /dev/null +++ b/third_party/flatbuffers/dart/lib/flex_buffers.dart @@ -0,0 +1,2 @@ +export 'src/builder.dart'; +export 'src/reference.dart'; diff --git a/third_party/flatbuffers/dart/lib/src/builder.dart b/third_party/flatbuffers/dart/lib/src/builder.dart new file mode 100644 index 00000000000..82681e7ec69 --- /dev/null +++ b/third_party/flatbuffers/dart/lib/src/builder.dart @@ -0,0 +1,676 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'types.dart'; + +/// The main builder class for creation of a FlexBuffer. +class Builder { + final ByteData _buffer; + List<_StackValue> _stack = []; + List<_StackPointer> _stackPointers = []; + int _offset = 0; + bool _finished = false; + final Map _stringCache = {}; + final Map _keyCache = {}; + final Map<_KeysHash, _StackValue> _keyVectorCache = {}; + final Map _indirectIntCache = {}; + final Map _indirectDoubleCache = {}; + + /// Instantiate the builder if you intent to gradually build up the buffer by calling + /// add... methods and calling [finish] to receive the resulting byte array. + /// + /// The default size of internal buffer is set to 2048. Provide a different value in order to avoid buffer copies. + Builder({int size = 2048}) : _buffer = ByteData(size); + + /// Use this method in order to turn an object into a FlexBuffer directly. + /// + /// Use the manual instantiation of the [Builder] and gradual addition of values, if performance is more important than convenience. + static ByteBuffer buildFromObject(Object? value) { + final builder = Builder(); + builder._add(value); + final buffer = builder.finish(); + final byteData = ByteData(buffer.lengthInBytes); + byteData.buffer.asUint8List().setAll(0, buffer); + return byteData.buffer; + } + + void _add(Object? value) { + if (value == null) { + addNull(); + } else if (value is bool) { + addBool(value); + } else if (value is int) { + addInt(value); + } else if (value is double) { + addDouble(value); + } else if (value is ByteBuffer) { + addBlob(value); + } else if (value is String) { + addString(value); + } else if (value is List) { + startVector(); + for (var i = 0; i < value.length; i++) { + _add(value[i]); + } + end(); + } else if (value is Map) { + startMap(); + value.forEach((key, value) { + addKey(key); + _add(value); + }); + end(); + } else { + throw UnsupportedError('Value of unexpected type: $value'); + } + } + + /// Use this method if you want to store a null value. + /// + /// Specifically useful when building up a vector where values can be null. + void addNull() { + _integrityCheckOnValueAddition(); + _stack.add(_StackValue.withNull()); + } + + /// Adds a string value. + void addInt(int value) { + _integrityCheckOnValueAddition(); + _stack.add(_StackValue.withInt(value)); + } + + /// Adds a bool value. + void addBool(bool value) { + _integrityCheckOnValueAddition(); + _stack.add(_StackValue.withBool(value)); + } + + /// Adds a double value. + void addDouble(double value) { + _integrityCheckOnValueAddition(); + _stack.add(_StackValue.withDouble(value)); + } + + /// Adds a string value. + void addString(String value) { + _integrityCheckOnValueAddition(); + if (_stringCache.containsKey(value)) { + _stack.add(_stringCache[value]!); + return; + } + final utf8String = utf8.encode(value); + final length = utf8String.length; + final bitWidth = BitWidthUtil.uwidth(length); + final byteWidth = _align(bitWidth); + _writeUInt(length, byteWidth); + final stringOffset = _offset; + final newOffset = _newOffset(length + 1); + _pushBuffer(utf8String); + _offset = newOffset; + final stackValue = + _StackValue.withOffset(stringOffset, ValueType.String, bitWidth); + _stack.add(stackValue); + _stringCache[value] = stackValue; + } + + /// This methods adds a key to a map and should be followed by an add... value call. + /// + /// It also implies that you call this method only after you called [startMap]. + void addKey(String value) { + _integrityCheckOnKeyAddition(); + if (_keyCache.containsKey(value)) { + _stack.add(_keyCache[value]!); + return; + } + final utf8String = utf8.encode(value); + final length = utf8String.length; + final keyOffset = _offset; + final newOffset = _newOffset(length + 1); + _pushBuffer(utf8String); + _offset = newOffset; + final stackValue = + _StackValue.withOffset(keyOffset, ValueType.Key, BitWidth.width8); + _stack.add(stackValue); + _keyCache[value] = stackValue; + } + + /// Adds a byte array. + /// + /// This method can be used to store any generic BLOB. + void addBlob(ByteBuffer value) { + _integrityCheckOnValueAddition(); + final length = value.lengthInBytes; + final bitWidth = BitWidthUtil.uwidth(length); + final byteWidth = _align(bitWidth); + _writeUInt(length, byteWidth); + final blobOffset = _offset; + final newOffset = _newOffset(length); + _pushBuffer(value.asUint8List()); + _offset = newOffset; + final stackValue = + _StackValue.withOffset(blobOffset, ValueType.Blob, bitWidth); + _stack.add(stackValue); + } + + /// Stores int value indirectly in the buffer. + /// + /// Adding large integer values indirectly might be beneficial if those values suppose to be store in a vector together with small integer values. + /// This is due to the fact that FlexBuffers will add padding to small integer values, if they are stored together with large integer values. + /// When we add integer indirectly the vector of ints will contain not the value itself, but only the relative offset to the value. + /// By setting the [cache] parameter to true, you make sure that the builder tracks added int value and performs deduplication. + void addIntIndirectly(int value, {bool cache = false}) { + _integrityCheckOnValueAddition(); + if (_indirectIntCache.containsKey(value)) { + _stack.add(_indirectIntCache[value]!); + return; + } + final stackValue = _StackValue.withInt(value); + final byteWidth = _align(stackValue.width); + final newOffset = _newOffset(byteWidth); + final valueOffset = _offset; + _pushBuffer(stackValue.asU8List(stackValue.width)); + final stackOffset = _StackValue.withOffset( + valueOffset, ValueType.IndirectInt, stackValue.width); + _stack.add(stackOffset); + _offset = newOffset; + if (cache) { + _indirectIntCache[value] = stackOffset; + } + } + + /// Stores double value indirectly in the buffer. + /// + /// Double are stored as 8 or 4 byte values in FlexBuffers. If they are stored in a mixed vector, values which are smaller than 4 / 8 bytes will be padded. + /// When we add double indirectly, the vector will contain not the value itself, but only the relative offset to the value. Which could occupy only 1 or 2 bytes, reducing the odds for unnecessary padding. + /// By setting the [cache] parameter to true, you make sure that the builder tracks already added double value and performs deduplication. + void addDoubleIndirectly(double value, {bool cache = false}) { + _integrityCheckOnValueAddition(); + if (cache && _indirectDoubleCache.containsKey(value)) { + _stack.add(_indirectDoubleCache[value]!); + return; + } + final stackValue = _StackValue.withDouble(value); + final byteWidth = _align(stackValue.width); + final newOffset = _newOffset(byteWidth); + final valueOffset = _offset; + _pushBuffer(stackValue.asU8List(stackValue.width)); + final stackOffset = _StackValue.withOffset( + valueOffset, ValueType.IndirectFloat, stackValue.width); + _stack.add(stackOffset); + _offset = newOffset; + if (cache) { + _indirectDoubleCache[value] = stackOffset; + } + } + + /// This method starts a vector definition and needs to be followed by 0 to n add... value calls. + /// + /// The vector definition needs to be finished with an [end] call. + /// It is also possible to add nested vector or map by calling [startVector] / [startMap]. + void startVector() { + _integrityCheckOnValueAddition(); + _stackPointers.add(_StackPointer(_stack.length, true)); + } + + /// This method starts a map definition. + /// + /// This method call needs to be followed by 0 to n [addKey] + add... value calls. + /// The map definition needs to be finished with an [end] call. + /// It is also possible to add nested vector or map by calling [startVector] / [startMap] after calling [addKey]. + void startMap() { + _integrityCheckOnValueAddition(); + _stackPointers.add(_StackPointer(_stack.length, false)); + } + + /// Marks that the addition of values to the last vector, or map have ended. + void end() { + final pointer = _stackPointers.removeLast(); + if (pointer.isVector) { + _endVector(pointer); + } else { + _sortKeysAndEndMap(pointer); + } + } + + /// Finish building the FlatBuffer and return array of bytes. + /// + /// Can be called multiple times, to get the array of bytes. + /// After the first call, adding values, or starting vectors / maps will result in an exception. + Uint8List finish() { + if (_finished == false) { + _finish(); + } + return _buffer.buffer.asUint8List(0, _offset); + } + + /// Builds a FlatBuffer with current state without finishing the builder. + /// + /// Creates an internal temporary copy of current builder and finishes the copy. + /// Use this method, when the state of a long lasting builder need to be persisted periodically. + ByteBuffer snapshot() { + final tmp = Builder(size: _offset + 200); + tmp._offset = _offset; + tmp._stack = List.from(_stack); + tmp._stackPointers = List.from(_stackPointers); + tmp._buffer.buffer + .asUint8List() + .setAll(0, _buffer.buffer.asUint8List(0, _offset)); + for (var i = 0; i < tmp._stackPointers.length; i++) { + tmp.end(); + } + final buffer = tmp.finish(); + final bd = ByteData(buffer.lengthInBytes); + bd.buffer.asUint8List().setAll(0, buffer); + return bd.buffer; + } + + void _integrityCheckOnValueAddition() { + if (_finished) { + throw StateError('Adding values after finish is prohibited'); + } + if (_stackPointers.isNotEmpty && _stackPointers.last.isVector == false) { + if (_stack.last.type != ValueType.Key) { + throw StateError( + 'Adding value to a map before adding a key is prohibited'); + } + } + } + + void _integrityCheckOnKeyAddition() { + if (_finished) { + throw StateError('Adding values after finish is prohibited'); + } + if (_stackPointers.isEmpty || _stackPointers.last.isVector) { + throw StateError('Adding key before staring a map is prohibited'); + } + } + + void _finish() { + if (_stack.length != 1) { + throw StateError( + 'Stack has to be exactly 1, but is ${_stack.length}. You have to end all started vectors and maps, before calling [finish]'); + } + final value = _stack[0]; + final byteWidth = _align(value.elementWidth(_offset, 0)); + _writeStackValue(value, byteWidth); + _writeUInt(value.storedPackedType(), 1); + _writeUInt(byteWidth, 1); + _finished = true; + } + + _StackValue _createVector(int start, int vecLength, int step, + [_StackValue? keys]) { + var bitWidth = BitWidthUtil.uwidth(vecLength); + var prefixElements = 1; + if (keys != null) { + var elemWidth = keys.elementWidth(_offset, 0); + if (elemWidth.index > bitWidth.index) { + bitWidth = elemWidth; + } + prefixElements += 2; + } + var vectorType = ValueType.Key; + var typed = keys == null; + for (var i = start; i < _stack.length; i += step) { + final elemWidth = _stack[i].elementWidth(_offset, i + prefixElements); + if (elemWidth.index > bitWidth.index) { + bitWidth = elemWidth; + } + if (i == start) { + vectorType = _stack[i].type; + typed &= ValueTypeUtils.isTypedVectorElement(vectorType); + } else { + if (vectorType != _stack[i].type) { + typed = false; + } + } + } + final byteWidth = _align(bitWidth); + final fix = typed & ValueTypeUtils.isNumber(vectorType) && + vecLength >= 2 && + vecLength <= 4; + if (keys != null) { + _writeStackValue(keys, byteWidth); + _writeUInt(1 << keys.width.index, byteWidth); + } + if (fix == false) { + _writeUInt(vecLength, byteWidth); + } + final vecOffset = _offset; + for (var i = start; i < _stack.length; i += step) { + _writeStackValue(_stack[i], byteWidth); + } + if (typed == false) { + for (var i = start; i < _stack.length; i += step) { + _writeUInt(_stack[i].storedPackedType(), 1); + } + } + if (keys != null) { + return _StackValue.withOffset(vecOffset, ValueType.Map, bitWidth); + } + if (typed) { + final vType = + ValueTypeUtils.toTypedVector(vectorType, fix ? vecLength : 0); + return _StackValue.withOffset(vecOffset, vType, bitWidth); + } + return _StackValue.withOffset(vecOffset, ValueType.Vector, bitWidth); + } + + void _endVector(_StackPointer pointer) { + final vecLength = _stack.length - pointer.stackPosition; + final vec = _createVector(pointer.stackPosition, vecLength, 1); + _stack.removeRange(pointer.stackPosition, _stack.length); + _stack.add(vec); + } + + void _sortKeysAndEndMap(_StackPointer pointer) { + if (((_stack.length - pointer.stackPosition) & 1) == 1) { + throw StateError( + 'The stack needs to hold key value pairs (even number of elements). Check if you combined [addKey] with add... method calls properly.'); + } + + var sorted = true; + for (var i = pointer.stackPosition; i < _stack.length - 2; i += 2) { + if (_shouldFlip(_stack[i], _stack[i + 2])) { + sorted = false; + break; + } + } + + if (sorted == false) { + for (var i = pointer.stackPosition; i < _stack.length; i += 2) { + var flipIndex = i; + for (var j = i + 2; j < _stack.length; j += 2) { + if (_shouldFlip(_stack[flipIndex], _stack[j])) { + flipIndex = j; + } + } + if (flipIndex != i) { + var k = _stack[flipIndex]; + var v = _stack[flipIndex + 1]; + _stack[flipIndex] = _stack[i]; + _stack[flipIndex + 1] = _stack[i + 1]; + _stack[i] = k; + _stack[i + 1] = v; + } + } + } + _endMap(pointer); + } + + void _endMap(_StackPointer pointer) { + final vecLength = (_stack.length - pointer.stackPosition) >> 1; + final offsets = []; + for (var i = pointer.stackPosition; i < _stack.length; i += 2) { + offsets.add(_stack[i].offset!); + } + final keysHash = _KeysHash(offsets); + _StackValue? keysStackValue; + if (_keyVectorCache.containsKey(keysHash)) { + keysStackValue = _keyVectorCache[keysHash]; + } else { + keysStackValue = _createVector(pointer.stackPosition, vecLength, 2); + _keyVectorCache[keysHash] = keysStackValue; + } + final vec = + _createVector(pointer.stackPosition + 1, vecLength, 2, keysStackValue); + _stack.removeRange(pointer.stackPosition, _stack.length); + _stack.add(vec); + } + + bool _shouldFlip(_StackValue v1, _StackValue v2) { + if (v1.type != ValueType.Key || v2.type != ValueType.Key) { + throw StateError( + 'Stack values are not keys $v1 | $v2. Check if you combined [addKey] with add... method calls properly.'); + } + + late int c1, c2; + var index = 0; + do { + c1 = _buffer.getUint8(v1.offset! + index); + c2 = _buffer.getUint8(v2.offset! + index); + if (c2 < c1) return true; + if (c1 < c2) return false; + index += 1; + } while (c1 != 0 && c2 != 0); + return false; + } + + int _align(BitWidth width) { + final byteWidth = BitWidthUtil.toByteWidth(width); + _offset += BitWidthUtil.paddingSize(_offset, byteWidth); + return byteWidth; + } + + void _writeStackValue(_StackValue value, int byteWidth) { + final newOffset = _newOffset(byteWidth); + if (value.isOffset) { + final relativeOffset = _offset - value.offset!; + if (byteWidth == 8 || relativeOffset < (1 << (byteWidth * 8))) { + _writeUInt(relativeOffset, byteWidth); + } else { + throw StateError( + 'Unexpected size $byteWidth. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new'); + } + } else { + _pushBuffer(value.asU8List(BitWidthUtil.fromByteWidth(byteWidth))); + } + _offset = newOffset; + } + + void _writeUInt(int value, int byteWidth) { + final newOffset = _newOffset(byteWidth); + _pushUInt(value, BitWidthUtil.fromByteWidth(byteWidth)); + _offset = newOffset; + } + + int _newOffset(int newValueSize) { + final newOffset = _offset + newValueSize; + var size = _buffer.lengthInBytes; + final prevSize = size; + while (size < newOffset) { + size <<= 1; + } + if (prevSize < size) { + final newBuf = ByteData(size); + newBuf.buffer.asUint8List().setAll(0, _buffer.buffer.asUint8List()); + } + return newOffset; + } + + void _pushInt(int value, BitWidth width) { + switch (width) { + case BitWidth.width8: + _buffer.setInt8(_offset, value); + break; + case BitWidth.width16: + _buffer.setInt16(_offset, value, Endian.little); + break; + case BitWidth.width32: + _buffer.setInt32(_offset, value, Endian.little); + break; + case BitWidth.width64: + _buffer.setInt64(_offset, value, Endian.little); + break; + } + } + + void _pushUInt(int value, BitWidth width) { + switch (width) { + case BitWidth.width8: + _buffer.setUint8(_offset, value); + break; + case BitWidth.width16: + _buffer.setUint16(_offset, value, Endian.little); + break; + case BitWidth.width32: + _buffer.setUint32(_offset, value, Endian.little); + break; + case BitWidth.width64: + _buffer.setUint64(_offset, value, Endian.little); + break; + } + } + + void _pushBuffer(List value) { + _buffer.buffer.asUint8List().setAll(_offset, value); + } +} + +class _StackValue { + late Object _value; + int? _offset; + final ValueType _type; + final BitWidth _width; + + _StackValue.withNull() + : _type = ValueType.Null, + _width = BitWidth.width8; + + _StackValue.withInt(int value) + : _type = ValueType.Int, + _width = BitWidthUtil.width(value), + _value = value; + + _StackValue.withBool(bool value) + : _type = ValueType.Bool, + _width = BitWidth.width8, + _value = value; + + _StackValue.withDouble(double value) + : _type = ValueType.Float, + _width = BitWidthUtil.width(value), + _value = value; + + _StackValue.withOffset(int value, ValueType type, BitWidth width) + : _offset = value, + _type = type, + _width = width; + + BitWidth storedWidth({BitWidth width = BitWidth.width8}) { + return ValueTypeUtils.isInline(_type) + ? BitWidthUtil.max(_width, width) + : _width; + } + + int storedPackedType({BitWidth width = BitWidth.width8}) { + return ValueTypeUtils.packedType(_type, storedWidth(width: width)); + } + + BitWidth elementWidth(int size, int index) { + if (ValueTypeUtils.isInline(_type)) return _width; + final offset = _offset!; + for (var i = 0; i < 4; i++) { + final width = 1 << i; + final bitWidth = BitWidthUtil.uwidth(size + + BitWidthUtil.paddingSize(size, width) + + index * width - + offset); + if (1 << bitWidth.index == width) { + return bitWidth; + } + } + throw StateError( + 'Element is of unknown. Size: $size at index: $index. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new'); + } + + List asU8List(BitWidth width) { + if (ValueTypeUtils.isNumber(_type)) { + if (_type == ValueType.Float) { + if (width == BitWidth.width32) { + final result = ByteData(4); + result.setFloat32(0, _value as double, Endian.little); + return result.buffer.asUint8List(); + } else { + final result = ByteData(8); + result.setFloat64(0, _value as double, Endian.little); + return result.buffer.asUint8List(); + } + } else { + switch (width) { + case BitWidth.width8: + final result = ByteData(1); + result.setInt8(0, _value as int); + return result.buffer.asUint8List(); + case BitWidth.width16: + final result = ByteData(2); + result.setInt16(0, _value as int, Endian.little); + return result.buffer.asUint8List(); + case BitWidth.width32: + final result = ByteData(4); + result.setInt32(0, _value as int, Endian.little); + return result.buffer.asUint8List(); + case BitWidth.width64: + final result = ByteData(8); + result.setInt64(0, _value as int, Endian.little); + return result.buffer.asUint8List(); + } + } + } + if (_type == ValueType.Null) { + final result = ByteData(1); + result.setInt8(0, 0); + return result.buffer.asUint8List(); + } + if (_type == ValueType.Bool) { + final result = ByteData(1); + result.setInt8(0, _value as bool ? 1 : 0); + return result.buffer.asUint8List(); + } + + throw StateError( + 'Unexpected type: $_type. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new'); + } + + ValueType get type { + return _type; + } + + BitWidth get width { + return _width; + } + + bool get isOffset { + return !ValueTypeUtils.isInline(_type); + } + + int? get offset => _offset; + + bool get isFloat32 { + return _type == ValueType.Float && _width == BitWidth.width32; + } +} + +class _StackPointer { + int stackPosition; + bool isVector; + + _StackPointer(this.stackPosition, this.isVector); +} + +class _KeysHash { + final List keys; + + const _KeysHash(this.keys); + + @override + bool operator ==(Object other) { + if (other is _KeysHash) { + if (keys.length != other.keys.length) return false; + for (var i = 0; i < keys.length; i++) { + if (keys[i] != other.keys[i]) return false; + } + return true; + } + return false; + } + + @override + int get hashCode { + var result = 17; + for (var i = 0; i < keys.length; i++) { + result = result * 23 + keys[i]; + } + return result; + } +} diff --git a/third_party/flatbuffers/dart/lib/src/reference.dart b/third_party/flatbuffers/dart/lib/src/reference.dart new file mode 100644 index 00000000000..66195c1bd4a --- /dev/null +++ b/third_party/flatbuffers/dart/lib/src/reference.dart @@ -0,0 +1,481 @@ +import 'dart:collection'; +import 'dart:convert'; +import 'dart:typed_data'; +import 'types.dart'; + +/// Main class to read a value out of a FlexBuffer. +/// +/// This class let you access values stored in the buffer in a lazy fashion. +class Reference { + final ByteData _buffer; + final int _offset; + final BitWidth _parentWidth; + final String _path; + final int _byteWidth; + final ValueType _valueType; + int? _length; + + Reference._( + this._buffer, this._offset, this._parentWidth, int packedType, this._path, + [int? byteWidth, ValueType? valueType]) + : _byteWidth = byteWidth ?? 1 << (packedType & 3), + _valueType = valueType ?? ValueTypeUtils.fromInt(packedType >> 2); + + /// Use this method to access the root value of a FlexBuffer. + static Reference fromBuffer(ByteBuffer buffer) { + final len = buffer.lengthInBytes; + if (len < 3) { + throw UnsupportedError('Buffer needs to be bigger than 3'); + } + final byteData = ByteData.view(buffer); + final byteWidth = byteData.getUint8(len - 1); + final packedType = byteData.getUint8(len - 2); + final offset = len - byteWidth - 2; + return Reference._(ByteData.view(buffer), offset, + BitWidthUtil.fromByteWidth(byteWidth), packedType, "/"); + } + + /// Returns true if the underlying value is null. + bool get isNull => _valueType == ValueType.Null; + + /// Returns true if the underlying value can be represented as [num]. + bool get isNum => + ValueTypeUtils.isNumber(_valueType) || + ValueTypeUtils.isIndirectNumber(_valueType); + + /// Returns true if the underlying value was encoded as a float (direct or indirect). + bool get isDouble => + _valueType == ValueType.Float || _valueType == ValueType.IndirectFloat; + + /// Returns true if the underlying value was encoded as an int or uint (direct or indirect). + bool get isInt => isNum && !isDouble; + + /// Returns true if the underlying value was encoded as a string or a key. + bool get isString => + _valueType == ValueType.String || _valueType == ValueType.Key; + + /// Returns true if the underlying value was encoded as a bool. + bool get isBool => _valueType == ValueType.Bool; + + /// Returns true if the underlying value was encoded as a blob. + bool get isBlob => _valueType == ValueType.Blob; + + /// Returns true if the underlying value points to a vector. + bool get isVector => ValueTypeUtils.isAVector(_valueType); + + /// Returns true if the underlying value points to a map. + bool get isMap => _valueType == ValueType.Map; + + /// If this [isBool], returns the bool value. Otherwise, returns null. + bool? get boolValue { + if (_valueType == ValueType.Bool) { + return _readInt(_offset, _parentWidth) != 0; + } + return null; + } + + /// Returns an [int], if the underlying value can be represented as an int. + /// + /// Otherwise returns [null]. + int? get intValue { + if (_valueType == ValueType.Int) { + return _readInt(_offset, _parentWidth); + } + if (_valueType == ValueType.UInt) { + return _readUInt(_offset, _parentWidth); + } + if (_valueType == ValueType.IndirectInt) { + return _readInt(_indirect, BitWidthUtil.fromByteWidth(_byteWidth)); + } + if (_valueType == ValueType.IndirectUInt) { + return _readUInt(_indirect, BitWidthUtil.fromByteWidth(_byteWidth)); + } + return null; + } + + /// Returns [double], if the underlying value [isDouble]. + /// + /// Otherwise returns [null]. + double? get doubleValue { + if (_valueType == ValueType.Float) { + return _readFloat(_offset, _parentWidth); + } + if (_valueType == ValueType.IndirectFloat) { + return _readFloat(_indirect, BitWidthUtil.fromByteWidth(_byteWidth)); + } + return null; + } + + /// Returns [num], if the underlying value is numeric, be it int uint, or float (direct or indirect). + /// + /// Otherwise returns [null]. + num? get numValue => doubleValue ?? intValue; + + /// Returns [String] value or null otherwise. + /// + /// This method performers a utf8 decoding, as FlexBuffers format stores strings in utf8 encoding. + String? get stringValue { + if (_valueType == ValueType.String || _valueType == ValueType.Key) { + return utf8.decode(_buffer.buffer.asUint8List(_indirect, length)); + } + return null; + } + + /// Returns [Uint8List] value or null otherwise. + Uint8List? get blobValue { + if (_valueType == ValueType.Blob) { + return _buffer.buffer.asUint8List(_indirect, length); + } + return null; + } + + /// Can be used with an [int] or a [String] value for key. + /// If the underlying value in FlexBuffer is a vector, then use [int] for access. + /// If the underlying value in FlexBuffer is a map, then use [String] for access. + /// Returns [Reference] value. Throws an exception when [key] is not applicable. + Reference operator [](Object key) { + if (key is int && ValueTypeUtils.isAVector(_valueType)) { + final index = key; + if (index >= length || index < 0) { + throw ArgumentError( + 'Key: [$key] is not applicable on: $_path of: $_valueType length: $length'); + } + final elementOffset = _indirect + index * _byteWidth; + int packedType = 0; + int? byteWidth; + ValueType? valueType; + if (ValueTypeUtils.isTypedVector(_valueType)) { + byteWidth = 1; + valueType = ValueTypeUtils.typedVectorElementType(_valueType); + } else if (ValueTypeUtils.isFixedTypedVector(_valueType)) { + byteWidth = 1; + valueType = ValueTypeUtils.fixedTypedVectorElementType(_valueType); + } else { + packedType = _buffer.getUint8(_indirect + length * _byteWidth + index); + } + return Reference._( + _buffer, + elementOffset, + BitWidthUtil.fromByteWidth(_byteWidth), + packedType, + "$_path[$index]", + byteWidth, + valueType); + } + if (key is String && _valueType == ValueType.Map) { + final index = _keyIndex(key); + if (index != null) { + return _valueForIndexWithKey(index, key); + } + } + throw ArgumentError( + 'Key: [$key] is not applicable on: $_path of: $_valueType'); + } + + /// Get an iterable if the underlying flexBuffer value is a vector. + /// Otherwise throws an exception. + Iterable get vectorIterable { + if (isVector == false) { + throw UnsupportedError('Value is not a vector. It is: $_valueType'); + } + return _VectorIterator(this); + } + + /// Get an iterable for keys if the underlying flexBuffer value is a map. + /// Otherwise throws an exception. + Iterable get mapKeyIterable { + if (isMap == false) { + throw UnsupportedError('Value is not a map. It is: $_valueType'); + } + return _MapKeyIterator(this); + } + + /// Get an iterable for values if the underlying flexBuffer value is a map. + /// Otherwise throws an exception. + Iterable get mapValueIterable { + if (isMap == false) { + throw UnsupportedError('Value is not a map. It is: $_valueType'); + } + return _MapValueIterator(this); + } + + /// Returns the length of the underlying FlexBuffer value. + /// If the underlying value is [null] the length is 0. + /// If the underlying value is a number, or a bool, the length is 1. + /// If the underlying value is a vector, or map, the length reflects number of elements / element pairs. + /// If the values is a string or a blob, the length reflects a number of bytes the value occupies (strings are encoded in utf8 format). + int get length { + if (_length == null) { + // needs to be checked before more generic isAVector + if (ValueTypeUtils.isFixedTypedVector(_valueType)) { + _length = ValueTypeUtils.fixedTypedVectorElementSize(_valueType); + } else if (_valueType == ValueType.Blob || + ValueTypeUtils.isAVector(_valueType) || + _valueType == ValueType.Map) { + _length = _readUInt( + _indirect - _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth)); + } else if (_valueType == ValueType.Null) { + _length = 0; + } else if (_valueType == ValueType.String) { + final indirect = _indirect; + var sizeByteWidth = _byteWidth; + var size = _readUInt(indirect - sizeByteWidth, + BitWidthUtil.fromByteWidth(sizeByteWidth)); + while (_buffer.getInt8(indirect + size) != 0) { + sizeByteWidth <<= 1; + size = _readUInt(indirect - sizeByteWidth, + BitWidthUtil.fromByteWidth(sizeByteWidth)); + } + _length = size; + } else if (_valueType == ValueType.Key) { + final indirect = _indirect; + var size = 1; + while (_buffer.getInt8(indirect + size) != 0) { + size += 1; + } + _length = size; + } else { + _length = 1; + } + } + return _length!; + } + + /// Returns a minified JSON representation of the underlying FlexBuffer value. + /// + /// This method involves materializing the entire object tree, which may be + /// expensive. It is more efficient to work with [Reference] and access only the needed data. + /// Blob values are represented as base64 encoded string. + String get json { + if (_valueType == ValueType.Bool) { + return boolValue! ? 'true' : 'false'; + } + if (_valueType == ValueType.Null) { + return 'null'; + } + if (ValueTypeUtils.isNumber(_valueType)) { + return jsonEncode(numValue); + } + if (_valueType == ValueType.String) { + return jsonEncode(stringValue); + } + if (_valueType == ValueType.Blob) { + return jsonEncode(base64Encode(blobValue!)); + } + if (ValueTypeUtils.isAVector(_valueType)) { + final result = StringBuffer(); + result.write('['); + for (var i = 0; i < length; i++) { + result.write(this[i].json); + if (i < length - 1) { + result.write(','); + } + } + result.write(']'); + return result.toString(); + } + if (_valueType == ValueType.Map) { + final result = StringBuffer(); + result.write('{'); + for (var i = 0; i < length; i++) { + result.write(jsonEncode(_keyForIndex(i))); + result.write(':'); + result.write(_valueForIndex(i).json); + if (i < length - 1) { + result.write(','); + } + } + result.write('}'); + return result.toString(); + } + throw UnsupportedError( + 'Type: $_valueType is not supported for JSON conversion'); + } + + /// Computes the indirect offset of the value. + /// + /// To optimize for the more common case of being called only once, this + /// value is not cached. Callers that need to use it more than once should + /// cache the return value in a local variable. + int get _indirect { + final step = _readUInt(_offset, _parentWidth); + return _offset - step; + } + + int _readInt(int offset, BitWidth width) { + _validateOffset(offset, width); + if (width == BitWidth.width8) { + return _buffer.getInt8(offset); + } + if (width == BitWidth.width16) { + return _buffer.getInt16(offset, Endian.little); + } + if (width == BitWidth.width32) { + return _buffer.getInt32(offset, Endian.little); + } + return _buffer.getInt64(offset, Endian.little); + } + + int _readUInt(int offset, BitWidth width) { + _validateOffset(offset, width); + if (width == BitWidth.width8) { + return _buffer.getUint8(offset); + } + if (width == BitWidth.width16) { + return _buffer.getUint16(offset, Endian.little); + } + if (width == BitWidth.width32) { + return _buffer.getUint32(offset, Endian.little); + } + return _buffer.getUint64(offset, Endian.little); + } + + double _readFloat(int offset, BitWidth width) { + _validateOffset(offset, width); + if (width.index < BitWidth.width32.index) { + throw StateError('Bad width: $width'); + } + + if (width == BitWidth.width32) { + return _buffer.getFloat32(offset, Endian.little); + } + + return _buffer.getFloat64(offset, Endian.little); + } + + void _validateOffset(int offset, BitWidth width) { + if (_offset < 0 || + _buffer.lengthInBytes <= offset + width.index || + offset & (BitWidthUtil.toByteWidth(width) - 1) != 0) { + throw StateError('Bad offset: $offset, width: $width'); + } + } + + int? _keyIndex(String key) { + final input = utf8.encode(key); + final keysVectorOffset = _indirect - _byteWidth * 3; + final indirectOffset = keysVectorOffset - + _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth)); + final byteWidth = _readUInt( + keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth)); + var low = 0; + var high = length - 1; + while (low <= high) { + final mid = (high + low) >> 1; + final dif = _diffKeys(input, mid, indirectOffset, byteWidth); + if (dif == 0) return mid; + if (dif < 0) { + high = mid - 1; + } else { + low = mid + 1; + } + } + return null; + } + + int _diffKeys(List input, int index, int indirectOffset, int byteWidth) { + final keyOffset = indirectOffset + index * byteWidth; + final keyIndirectOffset = + keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth)); + for (var i = 0; i < input.length; i++) { + final dif = input[i] - _buffer.getUint8(keyIndirectOffset + i); + if (dif != 0) { + return dif; + } + } + return (_buffer.getUint8(keyIndirectOffset + input.length) == 0) ? 0 : -1; + } + + Reference _valueForIndexWithKey(int index, String key) { + final indirect = _indirect; + final elementOffset = indirect + index * _byteWidth; + final packedType = _buffer.getUint8(indirect + length * _byteWidth + index); + return Reference._(_buffer, elementOffset, + BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/$key"); + } + + Reference _valueForIndex(int index) { + final indirect = _indirect; + final elementOffset = indirect + index * _byteWidth; + final packedType = _buffer.getUint8(indirect + length * _byteWidth + index); + return Reference._(_buffer, elementOffset, + BitWidthUtil.fromByteWidth(_byteWidth), packedType, "$_path/[$index]"); + } + + String _keyForIndex(int index) { + final keysVectorOffset = _indirect - _byteWidth * 3; + final indirectOffset = keysVectorOffset - + _readUInt(keysVectorOffset, BitWidthUtil.fromByteWidth(_byteWidth)); + final byteWidth = _readUInt( + keysVectorOffset + _byteWidth, BitWidthUtil.fromByteWidth(_byteWidth)); + final keyOffset = indirectOffset + index * byteWidth; + final keyIndirectOffset = + keyOffset - _readUInt(keyOffset, BitWidthUtil.fromByteWidth(byteWidth)); + var length = 0; + while (_buffer.getUint8(keyIndirectOffset + length) != 0) { + length += 1; + } + return utf8.decode(_buffer.buffer.asUint8List(keyIndirectOffset, length)); + } +} + +class _VectorIterator + with IterableMixin + implements Iterator { + final Reference _vector; + int index = -1; + + _VectorIterator(this._vector); + + @override + Reference get current => _vector[index]; + + @override + bool moveNext() { + index++; + return index < _vector.length; + } + + @override + Iterator get iterator => this; +} + +class _MapKeyIterator with IterableMixin implements Iterator { + final Reference _map; + int index = -1; + + _MapKeyIterator(this._map); + + @override + String get current => _map._keyForIndex(index); + + @override + bool moveNext() { + index++; + return index < _map.length; + } + + @override + Iterator get iterator => this; +} + +class _MapValueIterator + with IterableMixin + implements Iterator { + final Reference _map; + int index = -1; + + _MapValueIterator(this._map); + + @override + Reference get current => _map._valueForIndex(index); + + @override + bool moveNext() { + index++; + return index < _map.length; + } + + @override + Iterator get iterator => this; +} diff --git a/third_party/flatbuffers/dart/lib/src/types.dart b/third_party/flatbuffers/dart/lib/src/types.dart new file mode 100644 index 00000000000..b4d006072df --- /dev/null +++ b/third_party/flatbuffers/dart/lib/src/types.dart @@ -0,0 +1,190 @@ +import 'dart:typed_data'; + +/// Represents the number of bits a value occupies. +enum BitWidth { width8, width16, width32, width64 } + +class BitWidthUtil { + static int toByteWidth(BitWidth self) { + return 1 << self.index; + } + + static BitWidth width(num value) { + if (value is int) { + var v = value.toInt().abs(); + if (v >> 7 == 0) return BitWidth.width8; + if (v >> 15 == 0) return BitWidth.width16; + if (v >> 31 == 0) return BitWidth.width32; + return BitWidth.width64; + } + return value == _toF32(value as double) + ? BitWidth.width32 + : BitWidth.width64; + } + + static BitWidth uwidth(num value) { + if (value.toInt() == value) { + var v = value.toInt().abs(); + if (v >> 8 == 0) return BitWidth.width8; + if (v >> 16 == 0) return BitWidth.width16; + if (v >> 32 == 0) return BitWidth.width32; + return BitWidth.width64; + } + return value == _toF32(value as double) + ? BitWidth.width32 + : BitWidth.width64; + } + + static BitWidth fromByteWidth(int value) { + if (value == 1) { + return BitWidth.width8; + } + if (value == 2) { + return BitWidth.width16; + } + if (value == 4) { + return BitWidth.width32; + } + if (value == 8) { + return BitWidth.width64; + } + throw Exception('Unexpected value $value'); + } + + static int paddingSize(int bufSize, int scalarSize) { + return (~bufSize + 1) & (scalarSize - 1); + } + + static double _toF32(double value) { + var bdata = ByteData(4); + bdata.setFloat32(0, value); + return bdata.getFloat32(0); + } + + static BitWidth max(BitWidth self, BitWidth other) { + if (self.index < other.index) { + return other; + } + return self; + } +} + +/// Represents all internal FlexBuffer types. +enum ValueType { + Null, + Int, + UInt, + Float, + Key, + String, + IndirectInt, + IndirectUInt, + IndirectFloat, + Map, + Vector, + VectorInt, + VectorUInt, + VectorFloat, + VectorKey, + @Deprecated( + 'VectorString is deprecated due to a flaw in the binary format (https://github.com/google/flatbuffers/issues/5627)') + VectorString, + VectorInt2, + VectorUInt2, + VectorFloat2, + VectorInt3, + VectorUInt3, + VectorFloat3, + VectorInt4, + VectorUInt4, + VectorFloat4, + Blob, + Bool, + VectorBool +} + +class ValueTypeUtils { + static int toInt(ValueType self) { + if (self == ValueType.VectorBool) return 36; + return self.index; + } + + static ValueType fromInt(int value) { + if (value == 36) return ValueType.VectorBool; + return ValueType.values[value]; + } + + static bool isInline(ValueType self) { + return self == ValueType.Bool || toInt(self) <= toInt(ValueType.Float); + } + + static bool isNumber(ValueType self) { + return toInt(self) >= toInt(ValueType.Int) && + toInt(self) <= toInt(ValueType.Float); + } + + static bool isIndirectNumber(ValueType self) { + return toInt(self) >= toInt(ValueType.IndirectInt) && + toInt(self) <= toInt(ValueType.IndirectFloat); + } + + static bool isTypedVectorElement(ValueType self) { + return self == ValueType.Bool || + (toInt(self) >= toInt(ValueType.Int) && + toInt(self) <= toInt(ValueType.String)); + } + + static bool isTypedVector(ValueType self) { + return self == ValueType.VectorBool || + (toInt(self) >= toInt(ValueType.VectorInt) && + toInt(self) <= toInt(ValueType.VectorString)); + } + + static bool isFixedTypedVector(ValueType self) { + return (toInt(self) >= toInt(ValueType.VectorInt2) && + toInt(self) <= toInt(ValueType.VectorFloat4)); + } + + static bool isAVector(ValueType self) { + return (isTypedVector(self) || + isFixedTypedVector(self) || + self == ValueType.Vector); + } + + static ValueType toTypedVector(ValueType self, int length) { + if (length == 0) { + return ValueTypeUtils.fromInt( + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt)); + } + if (length == 2) { + return ValueTypeUtils.fromInt( + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt2)); + } + if (length == 3) { + return ValueTypeUtils.fromInt( + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt3)); + } + if (length == 4) { + return ValueTypeUtils.fromInt( + toInt(self) - toInt(ValueType.Int) + toInt(ValueType.VectorInt4)); + } + throw Exception('unexpected length ' + length.toString()); + } + + static ValueType typedVectorElementType(ValueType self) { + return ValueTypeUtils.fromInt( + toInt(self) - toInt(ValueType.VectorInt) + toInt(ValueType.Int)); + } + + static ValueType fixedTypedVectorElementType(ValueType self) { + return ValueTypeUtils.fromInt( + (toInt(self) - toInt(ValueType.VectorInt2)) % 3 + toInt(ValueType.Int)); + } + + static int fixedTypedVectorElementSize(ValueType self) { + return (toInt(self) - toInt(ValueType.VectorInt2)) ~/ 3 + 2; + } + + static int packedType(ValueType self, BitWidth bitWidth) { + return bitWidth.index | (toInt(self) << 2); + } +} diff --git a/third_party/flatbuffers/dart/publish.sh b/third_party/flatbuffers/dart/publish.sh new file mode 100755 index 00000000000..bda43ba01bf --- /dev/null +++ b/third_party/flatbuffers/dart/publish.sh @@ -0,0 +1,36 @@ +#!/bin/sh +# +# Copyright 2018 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# +# Note to pub consumers: this file is used to assist with publishing the +# pub package from the flatbuffers repository and is not meant for general use. +# As pub does not currently provide a way to exclude files, it is included here. +set -e + +command -v dart >/dev/null 2>&1 || { echo >&2 "Require `dart` but it's not installed. Aborting."; exit 1; } + +pushd ../tests +./DartTest.sh +popd + +pushd ../samples +./dart_sample.sh +popd + +dart pub publish + +rm example/monster.fbs +rm test/*.fbs +rm -rf test/sub diff --git a/third_party/flatbuffers/dart/pubspec.yaml b/third_party/flatbuffers/dart/pubspec.yaml new file mode 100644 index 00000000000..25e8d678d8e --- /dev/null +++ b/third_party/flatbuffers/dart/pubspec.yaml @@ -0,0 +1,14 @@ +name: flat_buffers +version: 25.2.10 +description: FlatBuffers reading and writing library for Dart. Based on original work by Konstantin Scheglov and Paul Berry of the Dart SDK team. +homepage: https://github.com/google/flatbuffers +documentation: https://google.github.io/flatbuffers/index.html + +environment: + sdk: '>=2.17.0 <4.0.0' + +dev_dependencies: + test: ^1.17.7 + test_reflective_loader: ^0.2.0 + path: ^1.8.0 + lints: ^1.0.1 diff --git a/third_party/flatbuffers/dart/test/bool_structs.fbs b/third_party/flatbuffers/dart/test/bool_structs.fbs new file mode 100644 index 00000000000..47b26b5b1bd --- /dev/null +++ b/third_party/flatbuffers/dart/test/bool_structs.fbs @@ -0,0 +1,10 @@ +// Test for #7355 +table Foo { + my_foo : foo_properties; +} + +struct foo_properties +{ + a : bool; + b : bool; +} diff --git a/third_party/flatbuffers/dart/test/bool_structs_generated.dart b/third_party/flatbuffers/dart/test/bool_structs_generated.dart new file mode 100644 index 00000000000..b123ba12f26 --- /dev/null +++ b/third_party/flatbuffers/dart/test/bool_structs_generated.dart @@ -0,0 +1,207 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +class Foo { + Foo._(this._bc, this._bcOffset); + factory Foo(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _FooReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + FooProperties? get myFoo => FooProperties.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'Foo{myFoo: ${myFoo}}'; + } + + FooT unpack() => FooT( + myFoo: myFoo?.unpack()); + + static int pack(fb.Builder fbBuilder, FooT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class FooT implements fb.Packable { + FooPropertiesT? myFoo; + + FooT({ + this.myFoo}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + if (myFoo != null) { + fbBuilder.addStruct(0, myFoo!.pack(fbBuilder)); + } + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'FooT{myFoo: ${myFoo}}'; + } +} + +class _FooReader extends fb.TableReader { + const _FooReader(); + + @override + Foo createObject(fb.BufferContext bc, int offset) => + Foo._(bc, offset); +} + +class FooBuilder { + FooBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addMyFoo(int offset) { + fbBuilder.addStruct(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class FooObjectBuilder extends fb.ObjectBuilder { + final FooPropertiesObjectBuilder? _myFoo; + + FooObjectBuilder({ + FooPropertiesObjectBuilder? myFoo, + }) + : _myFoo = myFoo; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + if (_myFoo != null) { + fbBuilder.addStruct(0, _myFoo!.finish(fbBuilder)); + } + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class FooProperties { + FooProperties._(this._bc, this._bcOffset); + + static const fb.Reader reader = _FooPropertiesReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + bool get a => const fb.BoolReader().read(_bc, _bcOffset + 0); + bool get b => const fb.BoolReader().read(_bc, _bcOffset + 1); + + @override + String toString() { + return 'FooProperties{a: ${a}, b: ${b}}'; + } + + FooPropertiesT unpack() => FooPropertiesT( + a: a, + b: b); + + static int pack(fb.Builder fbBuilder, FooPropertiesT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class FooPropertiesT implements fb.Packable { + bool a; + bool b; + + FooPropertiesT({ + required this.a, + required this.b}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putBool(b); + fbBuilder.putBool(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'FooPropertiesT{a: ${a}, b: ${b}}'; + } +} + +class _FooPropertiesReader extends fb.StructReader { + const _FooPropertiesReader(); + + @override + int get size => 2; + + @override + FooProperties createObject(fb.BufferContext bc, int offset) => + FooProperties._(bc, offset); +} + +class FooPropertiesBuilder { + FooPropertiesBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(bool a, bool b) { + fbBuilder.putBool(b); + fbBuilder.putBool(a); + return fbBuilder.offset; + } + +} + +class FooPropertiesObjectBuilder extends fb.ObjectBuilder { + final bool _a; + final bool _b; + + FooPropertiesObjectBuilder({ + required bool a, + required bool b, + }) + : _a = a, + _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putBool(_b); + fbBuilder.putBool(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/enums.fbs b/third_party/flatbuffers/dart/test/enums.fbs new file mode 100644 index 00000000000..a4272a43bc0 --- /dev/null +++ b/third_party/flatbuffers/dart/test/enums.fbs @@ -0,0 +1,10 @@ +enum OptionsEnum : uint32 +{ + A = 1, + B = 2, + C = 3 +} + +table MyTable { + options : [OptionsEnum]; +} diff --git a/third_party/flatbuffers/dart/test/enums_generated.dart b/third_party/flatbuffers/dart/test/enums_generated.dart new file mode 100644 index 00000000000..e2b8c50df7d --- /dev/null +++ b/third_party/flatbuffers/dart/test/enums_generated.dart @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +enum OptionsEnum { + A(1), + B(2), + C(3); + + final int value; + const OptionsEnum(this.value); + + factory OptionsEnum.fromValue(int value) { + switch (value) { + case 1: return OptionsEnum.A; + case 2: return OptionsEnum.B; + case 3: return OptionsEnum.C; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static OptionsEnum? _createOrNull(int? value) => + value == null ? null : OptionsEnum.fromValue(value); + + static const int minValue = 1; + static const int maxValue = 3; + static const fb.Reader reader = _OptionsEnumReader(); +} + +class _OptionsEnumReader extends fb.Reader { + const _OptionsEnumReader(); + + @override + int get size => 4; + + @override + OptionsEnum read(fb.BufferContext bc, int offset) => + OptionsEnum.fromValue(const fb.Uint32Reader().read(bc, offset)); +} + +class MyTable { + MyTable._(this._bc, this._bcOffset); + factory MyTable(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MyTableReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + List? get options => const fb.ListReader(OptionsEnum.reader).vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'MyTable{options: ${options}}'; + } + + MyTableT unpack() => MyTableT( + options: const fb.ListReader(OptionsEnum.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 4)); + + static int pack(fb.Builder fbBuilder, MyTableT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class MyTableT implements fb.Packable { + List? options; + + MyTableT({ + this.options}); + + @override + int pack(fb.Builder fbBuilder) { + final int? optionsOffset = options == null ? null + : fbBuilder.writeListUint32(options!.map((f) => f.value).toList()); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, optionsOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'MyTableT{options: ${options}}'; + } +} + +class _MyTableReader extends fb.TableReader { + const _MyTableReader(); + + @override + MyTable createObject(fb.BufferContext bc, int offset) => + MyTable._(bc, offset); +} + +class MyTableBuilder { + MyTableBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addOptionsOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MyTableObjectBuilder extends fb.ObjectBuilder { + final List? _options; + + MyTableObjectBuilder({ + List? options, + }) + : _options = options; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? optionsOffset = _options == null ? null + : fbBuilder.writeListUint32(_options!.map((f) => f.value).toList()); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, optionsOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/flat_buffers_test.dart b/third_party/flatbuffers/dart/test/flat_buffers_test.dart new file mode 100644 index 00000000000..b872cfbe814 --- /dev/null +++ b/third_party/flatbuffers/dart/test/flat_buffers_test.dart @@ -0,0 +1,943 @@ +import 'dart:typed_data'; +import 'dart:io' as io; + +import 'package:path/path.dart' as path; + +import 'package:flat_buffers/flat_buffers.dart'; +import 'package:test/test.dart'; +import 'package:test_reflective_loader/test_reflective_loader.dart'; + +import './monster_test_my_game.example_generated.dart' as example; +import './monster_test_my_game.example2_generated.dart' as example2; +import 'enums_generated.dart' as example3; +import './bool_structs_generated.dart' as example4; + +main() { + defineReflectiveSuite(() { + defineReflectiveTests(BuilderTest); + defineReflectiveTests(ObjectAPITest); + defineReflectiveTests(CheckOtherLangaugesData); + defineReflectiveTests(GeneratorTest); + defineReflectiveTests(ListOfEnumsTest); + }); +} + +int indexToField(int index) { + return (1 + 1 + index) * 2; +} + +@reflectiveTest +class CheckOtherLangaugesData { + test_cppData() async { + List data = await io.File(path.join( + path.context.current, + 'test', + 'monsterdata_test.mon', + )).readAsBytes(); + example.Monster mon = example.Monster(data); + expect(mon.hp, 80); + expect(mon.mana, 150); + expect(mon.name, 'MyMonster'); + expect(mon.pos!.x, 1.0); + expect(mon.pos!.y, 2.0); + expect(mon.pos!.z, 3.0); + expect(mon.pos!.test1, 3.0); + expect(mon.pos!.test2.value, 2.0); + expect(mon.pos!.test3.a, 5); + expect(mon.pos!.test3.b, 6); + expect(mon.testType!.value, example.AnyTypeId.Monster.value); + expect(mon.test is example.Monster, true); + final monster2 = mon.test as example.Monster; + expect(monster2.name, "Fred"); + + expect(mon.inventory!.length, 5); + expect(mon.inventory!.reduce((cur, next) => cur + next), 10); + final test4 = mon.test4!; + expect(test4.length, 2); + expect(test4[0].a + test4[0].b + test4[1].a + test4[1].b, 100); + expect(mon.testarrayofstring!.length, 2); + expect(mon.testarrayofstring![0], "test1"); + expect(mon.testarrayofstring![1], "test2"); + + // this will fail if accessing any field fails. + expect( + mon.toString(), + 'Monster{' + 'pos: Vec3{x: 1.0, y: 2.0, z: 3.0, test1: 3.0, test2: Color.Green, test3: Test{a: 5, b: 6}}, ' + 'mana: 150, hp: 80, name: MyMonster, inventory: [0, 1, 2, 3, 4], ' + 'color: Color.Blue, testType: AnyTypeId.Monster, ' + 'test: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' + 'inventory: null, color: Color.Blue, testType: null, ' + 'test: null, test4: null, testarrayofstring: null, ' + 'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, ' + 'testempty: null, testbool: false, testhashs32Fnv1: 0, ' + 'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, ' + 'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, ' + 'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, ' + 'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, ' + 'testarrayofsortedstruct: null, flex: null, test5: null, ' + 'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, ' + 'vectorOfReferrables: null, singleWeakReference: 0, ' + 'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, ' + 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' + 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' + 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' + 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' + 'nativeInline: null, ' + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, ' + 'test4: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], ' + 'testarrayofstring: [test1, test2], testarrayoftables: null, ' + 'enemy: Monster{pos: null, mana: 150, hp: 100, name: Fred, ' + 'inventory: null, color: Color.Blue, testType: null, ' + 'test: null, test4: null, testarrayofstring: null, ' + 'testarrayoftables: null, enemy: null, testnestedflatbuffer: null, ' + 'testempty: null, testbool: false, testhashs32Fnv1: 0, ' + 'testhashu32Fnv1: 0, testhashs64Fnv1: 0, testhashu64Fnv1: 0, ' + 'testhashs32Fnv1a: 0, testhashu32Fnv1a: 0, testhashs64Fnv1a: 0, ' + 'testhashu64Fnv1a: 0, testarrayofbools: null, testf: 3.14159, ' + 'testf2: 3.0, testf3: 0.0, testarrayofstring2: null, ' + 'testarrayofsortedstruct: null, flex: null, test5: null, ' + 'vectorOfLongs: null, vectorOfDoubles: null, parentNamespaceTest: null, ' + 'vectorOfReferrables: null, singleWeakReference: 0, ' + 'vectorOfWeakReferences: null, vectorOfStrongReferrables: null, ' + 'coOwningReference: 0, vectorOfCoOwningReferences: null, ' + 'nonOwningReference: 0, vectorOfNonOwningReferences: null, ' + 'anyUniqueType: null, anyUnique: null, anyAmbiguousType: null, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' + 'testrequirednestedflatbuffer: null, scalarKeySortedTables: null, ' + 'nativeInline: null, ' + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}, ' + 'testnestedflatbuffer: null, testempty: null, testbool: true, ' + 'testhashs32Fnv1: -579221183, testhashu32Fnv1: 3715746113, ' + 'testhashs64Fnv1: 7930699090847568257, ' + 'testhashu64Fnv1: 7930699090847568257, ' + 'testhashs32Fnv1a: -1904106383, testhashu32Fnv1a: 2390860913, ' + 'testhashs64Fnv1a: 4898026182817603057, ' + 'testhashu64Fnv1a: 4898026182817603057, ' + 'testarrayofbools: [true, false, true], testf: 3.14159, testf2: 3.0, ' + 'testf3: 0.0, testarrayofstring2: null, testarrayofsortedstruct: [' + 'Ability{id: 0, distance: 45}, Ability{id: 1, distance: 21}, ' + 'Ability{id: 5, distance: 12}], ' + 'flex: null, test5: [Test{a: 10, b: 20}, Test{a: 30, b: 40}], ' + 'vectorOfLongs: [1, 100, 10000, 1000000, 100000000], ' + 'vectorOfDoubles: [-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], ' + 'parentNamespaceTest: null, vectorOfReferrables: null, ' + 'singleWeakReference: 0, vectorOfWeakReferences: null, ' + 'vectorOfStrongReferrables: null, coOwningReference: 0, ' + 'vectorOfCoOwningReferences: null, nonOwningReference: 0, ' + 'vectorOfNonOwningReferences: null, ' + 'anyUniqueType: null, anyUnique: null, ' + 'anyAmbiguousType: null, ' + 'anyAmbiguous: null, vectorOfEnums: null, signedEnum: Race.None, ' + 'testrequirednestedflatbuffer: null, scalarKeySortedTables: [Stat{id: ' + 'miss, val: 0, count: 0}, Stat{id: hit, val: 10, count: 1}], ' + 'nativeInline: Test{a: 1, b: 2}, ' + 'longEnumNonEnumDefault: LongEnum._default, ' + 'longEnumNormalDefault: LongEnum.LongOne, nanDefault: NaN, ' + 'infDefault: Infinity, positiveInfDefault: Infinity, infinityDefault: ' + 'Infinity, positiveInfinityDefault: Infinity, negativeInfDefault: ' + '-Infinity, negativeInfinityDefault: -Infinity, doubleInfDefault: Infinity}'); + } +} + +/// Test a custom, fixed-memory allocator (no actual allocations performed) +class CustomAllocator extends Allocator { + final _memory = ByteData(10 * 1024); + int _used = 0; + + Uint8List buffer(int size) => _memory.buffer.asUint8List(_used - size, size); + + @override + ByteData allocate(int size) { + if (size > _memory.lengthInBytes) { + throw UnsupportedError('Trying to allocate too much'); + } + _used = size; + return ByteData.sublistView(_memory, 0, size); + } + + @override + void deallocate(ByteData _) {} +} + +@reflectiveTest +class BuilderTest { + void test_monsterBuilder([Builder? builder]) { + final fbBuilder = builder ?? Builder(); + final str = fbBuilder.writeString('MyMonster'); + + fbBuilder.writeString('test1'); + fbBuilder.writeString('test2', asciiOptimization: true); + final testArrayOfString = fbBuilder.endStructVector(2); + + final fred = fbBuilder.writeString('Fred'); + + final List treasure = [0, 1, 2, 3, 4]; + final inventory = fbBuilder.writeListUint8(treasure); + + final monBuilder = example.MonsterBuilder(fbBuilder) + ..begin() + ..addNameOffset(fred); + final mon2 = monBuilder.finish(); + + final testBuilder = example.TestBuilder(fbBuilder); + testBuilder.finish(10, 20); + testBuilder.finish(30, 40); + final test4 = fbBuilder.endStructVector(2); + + monBuilder + ..begin() + ..addPos( + example.Vec3Builder(fbBuilder).finish( + 1.0, + 2.0, + 3.0, + 3.0, + example.Color.Green, + () => testBuilder.finish(5, 6), + ), + ) + ..addHp(80) + ..addNameOffset(str) + ..addInventoryOffset(inventory) + ..addTestType(example.AnyTypeId.Monster) + ..addTestOffset(mon2) + ..addTest4Offset(test4) + ..addTestarrayofstringOffset(testArrayOfString); + final mon = monBuilder.finish(); + fbBuilder.finish(mon); + + final mon3 = example.Monster(fbBuilder.buffer); + expect(mon3.name, 'MyMonster'); + expect(mon3.pos!.test1, 3.0); + } + + void test_error_addInt32_withoutStartTable([Builder? builder]) { + builder ??= Builder(); + expect(() { + builder!.addInt32(0, 0); + }, throwsA(isA())); + } + + void test_error_addOffset_withoutStartTable() { + Builder builder = Builder(); + expect(() { + builder.addOffset(0, 0); + }, throwsA(isA())); + } + + void test_error_endTable_withoutStartTable() { + Builder builder = Builder(); + expect(() { + builder.endTable(); + }, throwsA(isA())); + } + + void test_error_startTable_duringTable() { + Builder builder = Builder(); + builder.startTable(0); + expect(() { + builder.startTable(0); + }, throwsA(isA())); + } + + void test_error_writeString_duringTable() { + Builder builder = Builder(); + builder.startTable(1); + expect(() { + builder.writeString('12345'); + }, throwsA(isA())); + } + + void test_file_identifier() { + Uint8List byteList; + { + Builder builder = Builder(initialSize: 0); + builder.startTable(0); + int offset = builder.endTable(); + builder.finish(offset, 'Az~ÿ'); + byteList = builder.buffer; + } + // Convert byteList to a ByteData so that we can read data from it. + ByteData byteData = byteList.buffer.asByteData(byteList.offsetInBytes); + // First 4 bytes are an offset to the table data. + int tableDataLoc = byteData.getUint32(0, Endian.little); + // Next 4 bytes are the file identifier. + expect(byteData.getUint8(4), 65); // 'a' + expect(byteData.getUint8(5), 122); // 'z' + expect(byteData.getUint8(6), 126); // '~' + expect(byteData.getUint8(7), 255); // 'ÿ' + // First 4 bytes of the table data are a backwards offset to the vtable. + int vTableLoc = + tableDataLoc - byteData.getInt32(tableDataLoc, Endian.little); + // First 2 bytes of the vtable are the size of the vtable in bytes, which + // should be 4. + expect(byteData.getUint16(vTableLoc, Endian.little), 4); + // Next 2 bytes are the size of the object in bytes (including the vtable + // pointer), which should be 4. + expect(byteData.getUint16(vTableLoc + 2, Endian.little), 4); + } + + void test_low() { + final allocator = CustomAllocator(); + final builder = Builder(initialSize: 0, allocator: allocator); + + builder.putUint8(1); + expect(allocator.buffer(builder.size()), [1]); + + builder.putUint32(2); + expect(allocator.buffer(builder.size()), [2, 0, 0, 0, 0, 0, 0, 1]); + + builder.putUint8(3); + expect( + allocator.buffer(builder.size()), [0, 0, 0, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + + builder.putUint8(4); + expect( + allocator.buffer(builder.size()), [0, 0, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + + builder.putUint8(5); + expect( + allocator.buffer(builder.size()), [0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + + builder.putUint32(6); + expect(allocator.buffer(builder.size()), + [6, 0, 0, 0, 0, 5, 4, 3, 2, 0, 0, 0, 0, 0, 0, 1]); + } + + void test_table_default() { + List byteList; + { + final builder = Builder(initialSize: 0, allocator: CustomAllocator()); + builder.startTable(2); + builder.addInt32(0, 10, 10); + builder.addInt32(1, 20, 10); + int offset = builder.endTable(); + builder.finish(offset); + byteList = builder.buffer; + expect(builder.size(), byteList.length); + } + // read and verify + BufferContext buffer = BufferContext.fromBytes(byteList); + int objectOffset = buffer.derefObject(0); + // was not written, so uses the new default value + expect( + const Int32Reader() + .vTableGet(buffer, objectOffset, indexToField(0), 15), + 15); + // has the written value + expect( + const Int32Reader() + .vTableGet(buffer, objectOffset, indexToField(1), 15), + 20); + } + + void test_table_format([Builder? builder]) { + Uint8List byteList; + { + builder ??= Builder(initialSize: 0); + builder.startTable(3); + builder.addInt32(0, 10); + builder.addInt32(1, 20); + builder.addInt32(2, 30); + builder.finish(builder.endTable()); + byteList = builder.buffer; + } + // Convert byteList to a ByteData so that we can read data from it. + ByteData byteData = byteList.buffer.asByteData(byteList.offsetInBytes); + // First 4 bytes are an offset to the table data. + int tableDataLoc = byteData.getUint32(0, Endian.little); + // First 4 bytes of the table data are a backwards offset to the vtable. + int vTableLoc = + tableDataLoc - byteData.getInt32(tableDataLoc, Endian.little); + // First 2 bytes of the vtable are the size of the vtable in bytes, which + // should be 10. + expect(byteData.getUint16(vTableLoc, Endian.little), 10); + // Next 2 bytes are the size of the object in bytes (including the vtable + // pointer), which should be 16. + expect(byteData.getUint16(vTableLoc + 2, Endian.little), 16); + // Remaining 6 bytes are the offsets within the object where the ints are + // located. + for (int i = 0; i < 3; i++) { + int offset = byteData.getUint16(vTableLoc + 4 + 2 * i, Endian.little); + expect( + byteData.getInt32(tableDataLoc + offset, Endian.little), 10 + 10 * i); + } + } + + void test_table_string() { + String latinString = 'test'; + String unicodeString = 'Проба пера'; + List byteList; + { + Builder builder = Builder(initialSize: 0); + int? latinStringOffset = + builder.writeString(latinString, asciiOptimization: true); + int? unicodeStringOffset = + builder.writeString(unicodeString, asciiOptimization: true); + builder.startTable(2); + builder.addOffset(0, latinStringOffset); + builder.addOffset(1, unicodeStringOffset); + int offset = builder.endTable(); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + int objectOffset = buf.derefObject(0); + expect( + const StringReader() + .vTableGetNullable(buf, objectOffset, indexToField(0)), + latinString); + expect( + const StringReader(asciiOptimization: true) + .vTableGetNullable(buf, objectOffset, indexToField(1)), + unicodeString); + } + + void test_table_types([Builder? builder]) { + List byteList; + { + builder ??= Builder(initialSize: 0); + int? stringOffset = builder.writeString('12345'); + builder.startTable(7); + builder.addBool(0, true); + builder.addInt8(1, 10); + builder.addInt32(2, 20); + builder.addOffset(3, stringOffset); + builder.addInt32(4, 40); + builder.addUint32(5, 0x9ABCDEF0); + builder.addUint8(6, 0x9A); + int offset = builder.endTable(); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + int objectOffset = buf.derefObject(0); + expect( + const BoolReader() + .vTableGetNullable(buf, objectOffset, indexToField(0)), + true); + expect( + const Int8Reader() + .vTableGetNullable(buf, objectOffset, indexToField(1)), + 10); + expect( + const Int32Reader() + .vTableGetNullable(buf, objectOffset, indexToField(2)), + 20); + expect( + const StringReader() + .vTableGetNullable(buf, objectOffset, indexToField(3)), + '12345'); + expect( + const Int32Reader() + .vTableGetNullable(buf, objectOffset, indexToField(4)), + 40); + expect( + const Uint32Reader() + .vTableGetNullable(buf, objectOffset, indexToField(5)), + 0x9ABCDEF0); + expect( + const Uint8Reader() + .vTableGetNullable(buf, objectOffset, indexToField(6)), + 0x9A); + } + + void test_writeList_of_Uint32() { + List values = [10, 100, 12345, 0x9abcdef0]; + // write + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListUint32(values); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const Uint32ListReader().read(buf, 0); + expect(items, hasLength(4)); + expect(items, orderedEquals(values)); + } + + void test_writeList_ofBool() { + void verifyListBooleans(int len, List trueBits) { + // write + List byteList; + { + Builder builder = Builder(initialSize: 0); + List values = List.filled(len, false); + for (int bit in trueBits) { + values[bit] = true; + } + int offset = builder.writeListBool(values); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const BoolListReader().read(buf, 0); + expect(items, hasLength(len)); + for (int i = 0; i < items.length; i++) { + expect(items[i], trueBits.contains(i), reason: 'bit $i of $len'); + } + } + + verifyListBooleans(0, []); + verifyListBooleans(1, []); + verifyListBooleans(1, [0]); + verifyListBooleans(31, [0, 1]); + verifyListBooleans(31, [1, 2, 24, 25, 30]); + verifyListBooleans(31, [0, 30]); + verifyListBooleans(32, [1, 2, 24, 25, 31]); + verifyListBooleans(33, [1, 2, 24, 25, 32]); + verifyListBooleans(33, [1, 2, 24, 25, 31, 32]); + verifyListBooleans(63, []); + verifyListBooleans(63, [0, 1, 2, 61, 62]); + verifyListBooleans(63, List.generate(63, (i) => i)); + verifyListBooleans(64, []); + verifyListBooleans(64, [0, 1, 2, 61, 62, 63]); + verifyListBooleans(64, [1, 2, 62]); + verifyListBooleans(64, [0, 1, 2, 63]); + verifyListBooleans(64, List.generate(64, (i) => i)); + verifyListBooleans(100, [0, 3, 30, 60, 90, 99]); + } + + void test_writeList_ofInt32() { + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListInt32([1, 2, 3, 4, 5]); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const ListReader(Int32Reader()).read(buf, 0); + expect(items, hasLength(5)); + expect(items, orderedEquals([1, 2, 3, 4, 5])); + } + + void test_writeList_ofFloat64() { + List values = [-1.234567, 3.4E+9, -5.6E-13, 7.8, 12.13]; + // write + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListFloat64(values); + builder.finish(offset); + byteList = builder.buffer; + } + + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const Float64ListReader().read(buf, 0); + + expect(items, hasLength(values.length)); + for (int i = 0; i < values.length; i++) { + expect(values[i], closeTo(items[i], .001)); + } + } + + void test_writeList_ofFloat32() { + List values = [1.0, 2.23, -3.213, 7.8, 12.13]; + // write + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListFloat32(values); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const Float32ListReader().read(buf, 0); + expect(items, hasLength(5)); + for (int i = 0; i < values.length; i++) { + expect(values[i], closeTo(items[i], .001)); + } + } + + void test_writeList_ofObjects([Builder? builder]) { + List byteList; + { + builder ??= Builder(initialSize: 0); + // write the object #1 + int object1; + { + builder.startTable(2); + builder.addInt32(0, 10); + builder.addInt32(1, 20); + object1 = builder.endTable(); + } + // write the object #1 + int object2; + { + builder.startTable(2); + builder.addInt32(0, 100); + builder.addInt32(1, 200); + object2 = builder.endTable(); + } + // write the list + int offset = builder.writeList([object1, object2]); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = + const ListReader(TestPointReader()).read(buf, 0); + expect(items, hasLength(2)); + expect(items[0].x, 10); + expect(items[0].y, 20); + expect(items[1].x, 100); + expect(items[1].y, 200); + } + + void test_writeList_ofStrings_asRoot() { + List byteList; + { + Builder builder = Builder(initialSize: 0); + int? str1 = builder.writeString('12345'); + int? str2 = builder.writeString('ABC'); + int offset = builder.writeList([str1, str2]); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const ListReader(StringReader()).read(buf, 0); + expect(items, hasLength(2)); + expect(items, contains('12345')); + expect(items, contains('ABC')); + } + + void test_writeList_ofStrings_inObject([Builder? builder]) { + List byteList; + { + builder ??= Builder(initialSize: 0); + int listOffset = builder.writeList( + [builder.writeString('12345'), builder.writeString('ABC')]); + builder.startTable(1); + builder.addOffset(0, listOffset); + int offset = builder.endTable(); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + StringListWrapperImpl reader = StringListWrapperReader().read(buf, 0); + List? items = reader.items; + expect(items, hasLength(2)); + expect(items, contains('12345')); + expect(items, contains('ABC')); + } + + void test_writeList_ofUint32() { + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListUint32([1, 2, 0x9ABCDEF0]); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const Uint32ListReader().read(buf, 0); + expect(items, hasLength(3)); + expect(items, orderedEquals([1, 2, 0x9ABCDEF0])); + } + + void test_writeList_ofUint16() { + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListUint16([1, 2, 60000]); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + List items = const Uint16ListReader().read(buf, 0); + expect(items, hasLength(3)); + expect(items, orderedEquals([1, 2, 60000])); + } + + void test_writeList_ofUint8() { + List byteList; + { + Builder builder = Builder(initialSize: 0); + int offset = builder.writeListUint8([1, 2, 3, 4, 0x9A, 0xFA]); + builder.finish(offset); + byteList = builder.buffer; + } + // read and verify + BufferContext buf = BufferContext.fromBytes(byteList); + const buffOffset = 8; // 32-bit offset to the list, + 32-bit length + for (final lazy in [true, false]) { + List items = Uint8ListReader(lazy: lazy).read(buf, 0); + expect(items, hasLength(6)); + expect(items, orderedEquals([1, 2, 3, 4, 0x9A, 0xFA])); + + // overwrite the buffer to verify the laziness + buf.buffer.setUint8(buffOffset + 1, 99); + expect(items, orderedEquals([1, lazy ? 99 : 2, 3, 4, 0x9A, 0xFA])); + + // restore the previous value for the next loop + buf.buffer.setUint8(buffOffset + 1, 2); + } + } + + void test_reset() { + // We'll run a selection of tests , reusing the builder between them. + final testCases = [ + test_monsterBuilder, + test_error_addInt32_withoutStartTable, + test_table_format, + test_table_types, + test_writeList_ofObjects, + test_writeList_ofStrings_inObject + ]; + + // Execute all test cases in all permutations of their order. + // To do that, we generate permutations of test case indexes. + final testCasesPermutations = + _permutationsOf(List.generate(testCases.length, (index) => index)); + expect(testCasesPermutations.length, _factorial(testCases.length)); + + for (var indexes in testCasesPermutations) { + // print the order so failures are reproducible + printOnFailure('Running reset() test cases in order: $indexes'); + + Builder? builder; + for (var index in indexes) { + if (builder == null) { + // Initial size small enough so at least one test case increases it. + // On the other hand, it's large enough so that some test cases don't. + builder = Builder(initialSize: 32); + } else { + builder.reset(); + } + testCases[index](builder); + } + } + } + + // Generate permutations of the given list + List> _permutationsOf(List source) { + final result = >[]; + + void permutate(List items, int startAt) { + for (var i = startAt; i < items.length; i++) { + List permutation = items.toList(growable: false); + permutation[i] = items[startAt]; + permutation[startAt] = items[i]; + + // add the current list upon reaching the end + if (startAt == items.length - 1) { + result.add(items); + } else { + permutate(permutation, startAt + 1); + } + } + } + + permutate(source, 0); + return result; + } + + // a very simple implementation of n! + int _factorial(int n) { + var result = 1; + for (var i = 2; i <= n; i++) { + result *= i; + } + return result; + } +} + +@reflectiveTest +class ObjectAPITest { + void test_tableStat() { + final object1 = example.StatT(count: 3, id: "foo", val: 4); + final fbb = Builder(); + fbb.finish(object1.pack(fbb)); + final object2 = example.Stat(fbb.buffer).unpack(); + expect(object2.count, object1.count); + expect(object2.id, object1.id); + expect(object2.val, object1.val); + expect(object2.toString(), object1.toString()); + } + + void test_tableMonster() { + final monster = example.MonsterT() + ..pos = example.Vec3T( + x: 1, + y: 2, + z: 3, + test1: 4.0, + test2: example.Color.Red, + test3: example.TestT(a: 1, b: 2)) + ..mana = 2 + ..name = 'Monstrous' + ..inventory = [24, 42] + ..color = example.Color.Green + // TODO be smarter for unions and automatically set the `type` field? + ..testType = example.AnyTypeId.MyGame_Example2_Monster + ..test = example2.MonsterT() + ..test4 = [example.TestT(a: 3, b: 4), example.TestT(a: 5, b: 6)] + ..testarrayofstring = ["foo", "bar"] + ..testarrayoftables = [example.MonsterT(name: 'Oof')] + ..enemy = example.MonsterT(name: 'Enemy') + ..testarrayofbools = [false, true, false] + ..testf = 42.24 + ..testarrayofsortedstruct = [ + example.AbilityT(id: 1, distance: 5), + example.AbilityT(id: 3, distance: 7) + ] + ..vectorOfLongs = [5, 6, 7] + ..vectorOfDoubles = [8.9, 9.0, 10.1, 11.2] + ..anyAmbiguousType = example.AnyAmbiguousAliasesTypeId.M2 + ..anyAmbiguous = null + ..vectorOfEnums = [example.Color.Blue, example.Color.Green] + ..signedEnum = example.Race.None; + + final fbBuilder = Builder(); + final offset = monster.pack(fbBuilder); + expect(offset, isNonZero); + fbBuilder.finish(offset); + final data = fbBuilder.buffer; + + // TODO currently broken because of struct builder issue, see #6688 + // final monster2 = example.Monster(data); // Monster (reader) + // expect( + // // map Monster => MonsterT, Vec3 => Vec3T, ... + // monster2.toString().replaceAllMapped( + // RegExp('([a-zA-z0-9]+){'), (match) => match.group(1) + 'T{'), + // monster.toString()); + // + // final monster3 = monster2.unpack(); // MonsterT + // expect(monster3.toString(), monster.toString()); + } + + void test_Lists() { + // Ensure unpack() reads lists eagerly by reusing the same builder and + // overwriting data. Why: because standard reader reads lists lazily... + final fbb = Builder(); + + final object1 = example.TypeAliasesT(v8: [1, 2, 3], vf64: [5, 6]); + fbb.finish(object1.pack(fbb)); + final object1Read = example.TypeAliases(fbb.buffer).unpack(); + + // overwrite the original buffer by writing to the same builder + fbb.reset(); + final object2 = example.TypeAliasesT(v8: [7, 8, 9], vf64: [10, 11]); + fbb.finish(object2.pack(fbb)); + final object2Read = example.TypeAliases(fbb.buffer).unpack(); + + // this is fine even with lazy lists: + expect(object2.toString(), object2Read.toString()); + + // this fails with lazy lists: + expect(object1.toString(), object1Read.toString()); + + // empty list must be serialized as such (were stored NULL before v2.0) + fbb.reset(); + final object3 = example.TypeAliasesT(v8: [], vf64: null); + fbb.finish(object3.pack(fbb)); + final object3Read = example.TypeAliases(fbb.buffer).unpack(); + expect(object3.toString(), object3Read.toString()); + } +} + +class StringListWrapperImpl { + final BufferContext bp; + final int offset; + + StringListWrapperImpl(this.bp, this.offset); + + List? get items => const ListReader(StringReader()) + .vTableGetNullable(bp, offset, indexToField(0)); +} + +class StringListWrapperReader extends TableReader { + const StringListWrapperReader(); + + @override + StringListWrapperImpl createObject(BufferContext object, int offset) { + return StringListWrapperImpl(object, offset); + } +} + +class TestPointImpl { + final BufferContext bp; + final int offset; + + TestPointImpl(this.bp, this.offset); + + int get x => const Int32Reader().vTableGet(bp, offset, indexToField(0), 0); + + int get y => const Int32Reader().vTableGet(bp, offset, indexToField(1), 0); +} + +class TestPointReader extends TableReader { + const TestPointReader(); + + @override + TestPointImpl createObject(BufferContext object, int offset) { + return TestPointImpl(object, offset); + } +} + +@reflectiveTest +class GeneratorTest { + void test_constantEnumValues() async { + expect(example.Color.values, same(example.Color.values)); + expect(example.Race.values, same(example.Race.values)); + expect(example.AnyTypeId.values, same(example.AnyTypeId.values)); + expect(example.AnyUniqueAliasesTypeId.values, + same(example.AnyUniqueAliasesTypeId.values)); + expect(example.AnyAmbiguousAliasesTypeId.values, + same(example.AnyAmbiguousAliasesTypeId.values)); + } +} + +// See #6869 +@reflectiveTest +class ListOfEnumsTest { + void test_listOfEnums() async { + var mytable = example3.MyTableObjectBuilder(options: [ + example3.OptionsEnum.A, + example3.OptionsEnum.B, + example3.OptionsEnum.C + ]); + var bytes = mytable.toBytes(); + var mytable_read = example3.MyTable(bytes); + expect(mytable_read.options![0].value, example3.OptionsEnum.A.value); + expect(mytable_read.options![1].value, example3.OptionsEnum.B.value); + expect(mytable_read.options![2].value, example3.OptionsEnum.C.value); + } +} + +@reflectiveTest +class BoolInStructTest { + void test_boolInStruct() async { + var mystruct = example4.FooObjectBuilder( + myFoo: example4.FooPropertiesObjectBuilder(a: true, b: false)); + var bytes = mystruct.toBytes(); + var mystruct_read = example4.Foo(bytes); + expect(mystruct_read.myFoo!.a, true); + expect(mystruct_read.myFoo!.b, false); + } +} diff --git a/third_party/flatbuffers/dart/test/flex_builder_test.dart b/third_party/flatbuffers/dart/test/flex_builder_test.dart new file mode 100644 index 00000000000..0c4a18e61d3 --- /dev/null +++ b/third_party/flatbuffers/dart/test/flex_builder_test.dart @@ -0,0 +1,597 @@ +import 'dart:typed_data'; + +import 'package:flat_buffers/flex_buffers.dart' show Builder; +import 'package:test/test.dart'; + +void main() { + test('build with single value', () { + { + var flx = Builder(); + flx.addNull(); + expect(flx.finish(), [0, 0, 1]); + } + { + var flx = Builder(); + flx.addBool(true); + expect(flx.finish(), [1, 104, 1]); + } + { + var flx = Builder(); + flx.addBool(false); + expect(flx.finish(), [0, 104, 1]); + } + { + var flx = Builder(); + flx.addInt(1); + expect(flx.finish(), [1, 4, 1]); + } + { + var flx = Builder(); + flx.addInt(230); + expect(flx.finish(), [230, 0, 5, 2]); + } + { + var flx = Builder(); + flx.addInt(1025); + expect(flx.finish(), [1, 4, 5, 2]); + } + { + var flx = Builder(); + flx.addInt(-1025); + expect(flx.finish(), [255, 251, 5, 2]); + } + { + var builder = Builder()..addDouble(1.0); + expect(builder.finish(), [0, 0, 128, 63, 14, 4]); + } + { + var flx = Builder(); + flx.addDouble(0.1); + expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63, 15, 8]); + } + { + var flx = Builder(); + flx.addDouble(0.5); + expect(flx.finish(), [0, 0, 0, 63, 14, 4]); + } + { + var flx = Builder(); + flx.addString('Maxim'); + expect(flx.finish(), [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]); + } + { + var flx = Builder(); + flx.addString('hello 😱'); + expect(flx.finish(), + [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]); + } + }); + + test('build vector', () { + { + var flx = Builder() + ..startVector() + ..addInt(1) + ..addInt(2) + ..end(); + expect(flx.finish(), [1, 2, 2, 64, 1]); + } + { + var flx = Builder() + ..startVector() + ..addInt(-1) + ..addInt(256) + ..end(); + expect(flx.finish(), [255, 255, 0, 1, 4, 65, 1]); + } + { + var flx = Builder() + ..startVector() + ..addInt(-45) + ..addInt(256000) + ..end(); + expect(flx.finish(), [211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1]); + } + { + var flx = Builder() + ..startVector() + ..addDouble(1.1) + ..addDouble(-256) + ..end(); + expect(flx.finish(), [ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 192, + 16, + 75, + 1 + ]); + } + { + var flx = Builder() + ..startVector() + ..addInt(1) + ..addInt(2) + ..addInt(4) + ..end(); + expect(flx.finish(), [1, 2, 4, 3, 76, 1]); + } + { + var flx = Builder() + ..startVector() + ..addInt(-1) + ..addInt(256) + ..addInt(4) + ..end(); + expect(flx.finish(), [255, 255, 0, 1, 4, 0, 6, 77, 1]); + } + { + var flx = Builder() + ..startVector() + ..startVector() + ..addInt(61) + ..end() + ..addInt(64) + ..end(); + expect(flx.finish(), [1, 61, 2, 2, 64, 44, 4, 4, 40, 1]); + } + { + var flx = Builder() + ..startVector() + ..addString('foo') + ..addString('bar') + ..addString('baz') + ..end(); + expect(flx.finish(), [ + 3, + 102, + 111, + 111, + 0, + 3, + 98, + 97, + 114, + 0, + 3, + 98, + 97, + 122, + 0, + 3, + 15, + 11, + 7, + 3, + 60, + 1 + ]); + } + { + var flx = Builder() + ..startVector() + ..addString('foo') + ..addString('bar') + ..addString('baz') + ..addString('foo') + ..addString('bar') + ..addString('baz') + ..end(); + expect(flx.finish(), [ + 3, + 102, + 111, + 111, + 0, + 3, + 98, + 97, + 114, + 0, + 3, + 98, + 97, + 122, + 0, + 6, + 15, + 11, + 7, + 18, + 14, + 10, + 6, + 60, + 1 + ]); + } + { + var flx = Builder() + ..startVector() + ..addBool(true) + ..addBool(false) + ..addBool(true) + ..end(); + expect(flx.finish(), [3, 1, 0, 1, 3, 144, 1]); + } + { + var flx = Builder() + ..startVector() + ..addString('foo') + ..addInt(1) + ..addInt(-5) + ..addDouble(1.3) + ..addBool(true) + ..end(); + expect(flx.finish(), [ + 3, + 102, + 111, + 111, + 0, + 0, + 0, + 0, + 5, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 15, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 251, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 205, + 204, + 204, + 204, + 204, + 204, + 244, + 63, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 20, + 4, + 4, + 15, + 104, + 45, + 43, + 1 + ]); + } + }); + + test('build map', () { + { + var flx = Builder() + ..startMap() + ..addKey('a') + ..addInt(12) + ..end(); + expect(flx.finish(), [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]); + } + { + var flx = Builder() + ..startMap() + ..addKey('a') + ..addInt(12) + ..addKey('') + ..addInt(45) + ..end(); + expect( + flx.finish(), [97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]); + } + { + var flx = Builder() + ..startVector() + ..startMap() + ..addKey('something') + ..addInt(12) + ..end() + ..startMap() + ..addKey('something') + ..addInt(45) + ..end() + ..end(); + expect(flx.finish(), [ + 115, + 111, + 109, + 101, + 116, + 104, + 105, + 110, + 103, + 0, + 1, + 11, + 1, + 1, + 1, + 12, + 4, + 6, + 1, + 1, + 45, + 4, + 2, + 8, + 4, + 36, + 36, + 4, + 40, + 1 + ]); + } + }); + + test('build blob', () { + { + var flx = Builder()..addBlob(Uint8List.fromList([1, 2, 3]).buffer); + expect(flx.finish(), [3, 1, 2, 3, 3, 100, 1]); + } + }); + + test('build from object', () { + expect( + Builder.buildFromObject(Uint8List.fromList([1, 2, 3]).buffer) + .asUint8List(), + [3, 1, 2, 3, 3, 100, 1]); + expect(Builder.buildFromObject(null).asUint8List(), [0, 0, 1]); + expect(Builder.buildFromObject(true).asUint8List(), [1, 104, 1]); + expect(Builder.buildFromObject(false).asUint8List(), [0, 104, 1]); + expect(Builder.buildFromObject(25).asUint8List(), [25, 4, 1]); + expect(Builder.buildFromObject(-250).asUint8List(), [6, 255, 5, 2]); + expect( + Builder.buildFromObject(-2.50).asUint8List(), [0, 0, 32, 192, 14, 4]); + expect(Builder.buildFromObject('Maxim').asUint8List(), + [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]); + expect( + Builder.buildFromObject([1, 3.3, 'max', true, null, false]) + .asUint8List(), + [ + 3, + 109, + 97, + 120, + 0, + 0, + 0, + 0, + 6, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 102, + 102, + 102, + 102, + 102, + 102, + 10, + 64, + 31, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 4, + 15, + 20, + 104, + 0, + 104, + 54, + 43, + 1 + ]); + expect( + Builder.buildFromObject([ + {'something': 12}, + {'something': 45} + ]).asUint8List(), + [ + 115, + 111, + 109, + 101, + 116, + 104, + 105, + 110, + 103, + 0, + 1, + 11, + 1, + 1, + 1, + 12, + 4, + 6, + 1, + 1, + 45, + 4, + 2, + 8, + 4, + 36, + 36, + 4, + 40, + 1 + ]); + }); + + test('add double indirectly', () { + var flx = Builder()..addDoubleIndirectly(0.1); + expect(flx.finish(), [154, 153, 153, 153, 153, 153, 185, 63, 8, 35, 1]); + }); + + test('add double indirectly to vector with cache', () { + var flx = Builder() + ..startVector() + ..addDoubleIndirectly(0.1, cache: true) + ..addDoubleIndirectly(0.1, cache: true) + ..addDoubleIndirectly(0.1, cache: true) + ..addDoubleIndirectly(0.1, cache: true) + ..end(); + expect(flx.finish(), [ + 154, + 153, + 153, + 153, + 153, + 153, + 185, + 63, + 4, + 9, + 10, + 11, + 12, + 35, + 35, + 35, + 35, + 8, + 40, + 1 + ]); + }); + + test('add int indirectly', () { + var flx = Builder()..addIntIndirectly(2345234523452345); + expect(flx.finish(), [185, 115, 175, 118, 250, 84, 8, 0, 8, 27, 1]); + }); + + test('add int indirectly to vector with cache', () { + var flx = Builder() + ..startVector() + ..addIntIndirectly(2345234523452345, cache: true) + ..addIntIndirectly(2345234523452345, cache: true) + ..addIntIndirectly(2345234523452345, cache: true) + ..addIntIndirectly(2345234523452345, cache: true) + ..end(); + expect(flx.finish(), [ + 185, + 115, + 175, + 118, + 250, + 84, + 8, + 0, + 4, + 9, + 10, + 11, + 12, + 27, + 27, + 27, + 27, + 8, + 40, + 1 + ]); + }); + + test('snapshot', () { + var flx = Builder(); + flx.startVector(); + flx.addInt(12); + expect(flx.snapshot().asUint8List(), [1, 12, 1, 44, 1]); + flx.addInt(24); + expect(flx.snapshot().asUint8List(), [12, 24, 2, 64, 1]); + flx.addInt(45); + expect(flx.snapshot().asUint8List(), [12, 24, 45, 3, 76, 1]); + }); +} diff --git a/third_party/flatbuffers/dart/test/flex_reader_test.dart b/third_party/flatbuffers/dart/test/flex_reader_test.dart new file mode 100644 index 00000000000..6e0855fc2b9 --- /dev/null +++ b/third_party/flatbuffers/dart/test/flex_reader_test.dart @@ -0,0 +1,991 @@ +import 'dart:typed_data'; + +import 'package:flat_buffers/flex_buffers.dart' show Reference, Builder; +import 'package:test/test.dart'; + +void main() { + test('is null', () { + expect(Reference.fromBuffer(b([0, 0, 1])).isNull, isTrue); + }); + + test('bool value', () { + expect(Reference.fromBuffer(b([1, 104, 1])).boolValue, isTrue); + expect(Reference.fromBuffer(b([0, 104, 1])).boolValue, isFalse); + }); + test('int value', () { + expect(Reference.fromBuffer(b([25, 4, 1])).intValue, 25); + expect(Reference.fromBuffer(b([231, 4, 1])).intValue, -25); + expect(Reference.fromBuffer(b([230, 8, 1])).intValue, 230); + expect(Reference.fromBuffer(b([230, 0, 5, 2])).intValue, 230); + expect(Reference.fromBuffer(b([1, 4, 5, 2])).intValue, 1025); + expect(Reference.fromBuffer(b([255, 251, 5, 2])).intValue, -1025); + expect(Reference.fromBuffer(b([1, 4, 9, 2])).intValue, 1025); + expect(Reference.fromBuffer(b([255, 255, 255, 127, 6, 4])).intValue, + 2147483647); + expect(Reference.fromBuffer(b([0, 0, 0, 128, 6, 4])).intValue, -2147483648); + expect( + Reference.fromBuffer(b([255, 255, 255, 255, 0, 0, 0, 0, 7, 8])) + .intValue, + 4294967295); + expect( + Reference.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 127, 7, 8])) + .intValue, + 9223372036854775807); + expect(Reference.fromBuffer(b([0, 0, 0, 0, 0, 0, 0, 128, 7, 8])).intValue, + -9223372036854775808); + // Dart does not really support UInt64 +// expect(FlxValue.fromBuffer(b([255, 255, 255, 255, 255, 255, 255, 255, 11, 8])).intValue, 18446744073709551615); + }); + test('double value', () { + expect(Reference.fromBuffer(b([0, 0, 128, 63, 14, 4])).doubleValue, 1.0); + expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).doubleValue, 4.5); + expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).doubleValue, + closeTo(.1, .001)); + expect( + Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8])) + .doubleValue, + .1); + }); + test('num value', () { + expect(Reference.fromBuffer(b([0, 0, 144, 64, 14, 4])).numValue, 4.5); + expect(Reference.fromBuffer(b([205, 204, 204, 61, 14, 4])).numValue, + closeTo(.1, .001)); + expect( + Reference.fromBuffer(b([154, 153, 153, 153, 153, 153, 185, 63, 15, 8])) + .numValue, + .1); + expect(Reference.fromBuffer(b([255, 251, 5, 2])).numValue, -1025); + }); + test('string value', () { + expect( + Reference.fromBuffer(b([5, 77, 97, 120, 105, 109, 0, 6, 20, 1])) + .stringValue, + 'Maxim'); + expect( + Reference.fromBuffer(b([ + 10, + 104, + 101, + 108, + 108, + 111, + 32, + 240, + 159, + 152, + 177, + 0, + 11, + 20, + 1 + ])).stringValue, + 'hello 😱'); + }); + test('blob value', () { + expect( + Reference.fromBuffer(b([3, 1, 2, 3, 3, 100, 1])).blobValue, [1, 2, 3]); + }); + test('bool vector', () { + var flx = Reference.fromBuffer(b([3, 1, 0, 1, 3, 144, 1])); + expect(flx[0].boolValue, true); + expect(flx[1].boolValue, false); + expect(flx[2].boolValue, true); + }); + test('number vector', () { + testNumbers([3, 1, 2, 3, 3, 44, 1], [1, 2, 3]); + testNumbers([3, 255, 2, 3, 3, 44, 1], [-1, 2, 3]); + testNumbers([3, 0, 1, 0, 43, 2, 3, 0, 6, 45, 1], [1, 555, 3]); + testNumbers([3, 0, 0, 0, 1, 0, 0, 0, 204, 216, 0, 0, 3, 0, 0, 0, 12, 46, 1], + [1, 55500, 3]); + testNumbers([ + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 172, + 128, + 94, + 239, + 12, + 0, + 0, + 0, + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 24, + 47, + 1 + ], [ + 1, + 55555555500, + 3 + ]); + testNumbers( + [3, 0, 0, 0, 0, 0, 192, 63, 0, 0, 32, 64, 0, 0, 96, 64, 12, 54, 1], + [1.5, 2.5, 3.5]); + testNumbers([ + 3, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 154, + 153, + 153, + 153, + 153, + 153, + 1, + 64, + 102, + 102, + 102, + 102, + 102, + 102, + 10, + 64, + 24, + 55, + 1 + ], [ + 1.1, + 2.2, + 3.3 + ]); + }); + test('number vector, fixed type', () { + testNumbers([1, 2, 2, 64, 1], [1, 2]); + testNumbers([255, 255, 0, 1, 4, 65, 1], [-1, 256]); + testNumbers([211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1], [-45, 256000]); + testNumbers([ + 211, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 127, + 16, + 67, + 1 + ], [ + -45, + 9223372036854775807 + ]); + + testNumbers([1, 2, 2, 68, 1], [1, 2]); + testNumbers([1, 0, 0, 1, 4, 69, 1], [1, 256]); + testNumbers([45, 0, 0, 0, 0, 232, 3, 0, 8, 70, 1], [45, 256000]); + + testNumbers([205, 204, 140, 63, 0, 0, 0, 192, 8, 74, 1], [1.1, -2]); + testNumbers([ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 192, + 16, + 75, + 1 + ], [ + 1.1, + -256 + ]); + + testNumbers([211, 255, 255, 255, 0, 232, 3, 0, 4, 0, 0, 0, 12, 78, 1], + [-45, 256000, 4]); + + testNumbers([ + 211, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 127, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 9, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 32, + 91, + 1 + ], [ + -45, + 9223372036854775807, + 4, + 9 + ]); + + testNumbers([ + 45, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 127, + 4, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 9, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 32, + 95, + 1 + ], [ + 45, + 9223372036854775807, + 4, + 9 + ]); + + testNumbers([ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 64, + 0, + 0, + 0, + 0, + 0, + 0, + 16, + 64, + 24, + 87, + 1 + ], [ + 1.1, + 256, + 4 + ]); + + testNumbers([ + 154, + 153, + 153, + 153, + 153, + 153, + 241, + 63, + 0, + 0, + 0, + 0, + 0, + 0, + 112, + 64, + 0, + 0, + 0, + 0, + 0, + 0, + 16, + 64, + 0, + 0, + 0, + 0, + 0, + 0, + 34, + 64, + 32, + 99, + 1 + ], [ + 1.1, + 256, + 4, + 9 + ]); + }); + test('string vector', () { + testStrings([ + 3, + 102, + 111, + 111, + 0, + 3, + 98, + 97, + 114, + 0, + 3, + 98, + 97, + 122, + 0, + 3, + 15, + 11, + 7, + 3, + 60, + 1 + ], [ + 'foo', + 'bar', + 'baz' + ]); + testStrings([ + 3, + 102, + 111, + 111, + 0, + 3, + 98, + 97, + 114, + 0, + 3, + 98, + 97, + 122, + 0, + 6, + 15, + 11, + 7, + 18, + 14, + 10, + 6, + 60, + 1 + ], [ + 'foo', + 'bar', + 'baz', + 'foo', + 'bar', + 'baz' + ]); + }); + test('mixed vector', () { + var flx = Reference.fromBuffer(b([ + 3, + 102, + 111, + 111, + 0, + 0, + 0, + 0, + 5, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 15, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 251, + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 205, + 204, + 204, + 204, + 204, + 204, + 244, + 63, + 1, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 20, + 4, + 4, + 15, + 104, + 45, + 43, + 1 + ])); + expect(flx.length, 5); + expect(flx[0].stringValue, 'foo'); + expect(flx[1].numValue, 1); + expect(flx[2].numValue, -5); + expect(flx[3].numValue, 1.3); + expect(flx[4].boolValue, true); + }); + + test('single value map', () { + var flx = Reference.fromBuffer(b([97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1])); + expect(flx.length, 1); + expect(flx['a'].numValue, 12); + }); + test('two value map', () { + var flx = Reference.fromBuffer( + b([0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1])); + expect(flx.length, 2); + expect(flx['a'].numValue, 12); + expect(flx[''].numValue, 45); + }); + test('complex map', () { + var flx = complexMap(); + expect(flx.length, 5); + expect(flx['age'].numValue, 35); + expect(flx['weight'].numValue, 72.5); + expect(flx['name'].stringValue, 'Maxim'); + + expect(flx['flags'].length, 4); + expect(flx['flags'][0].boolValue, true); + expect(flx['flags'][1].boolValue, false); + expect(flx['flags'][2].boolValue, true); + expect(flx['flags'][3].boolValue, true); + + expect(flx['address'].length, 3); + expect(flx['address']['city'].stringValue, 'Bla'); + expect(flx['address']['zip'].stringValue, '12345'); + expect(flx['address']['countryCode'].stringValue, 'XX'); + + expect( + () => flx['address']['country'].stringValue, + throwsA(predicate((dynamic e) => + e is ArgumentError && + e.message == + 'Key: [country] is not applicable on: //address of: ValueType.Map'))); + expect( + () => flx['address']['countryCode'][0], + throwsA(predicate((dynamic e) => + e is ArgumentError && + e.message == + 'Key: [0] is not applicable on: //address/countryCode of: ValueType.String'))); + expect( + () => flx[1], + throwsA(predicate((dynamic e) => + e is ArgumentError && + e.message == + 'Key: [1] is not applicable on: / of: ValueType.Map'))); + expect( + () => flx['flags'][4], + throwsA(predicate((dynamic e) => + e is ArgumentError && + e.message == + 'Key: [4] is not applicable on: //flags of: ValueType.VectorBool length: 4'))); + expect( + () => flx['flags'][-1], + throwsA(predicate((dynamic e) => + e is ArgumentError && + e.message == + 'Key: [-1] is not applicable on: //flags of: ValueType.VectorBool length: 4'))); + }); + test('complex map to json', () { + var flx = complexMap(); + expect(flx.json, + '{"address":{"city":"Bla","countryCode":"XX","zip":"12345"},"age":35,"flags":[true,false,true,true],"name":"Maxim","weight":72.5}'); + }); + + test('complex map iterators', () { + var flx = complexMap(); + expect(flx.mapKeyIterable.map((e) => e).toList(), + ['address', 'age', 'flags', 'name', 'weight']); + expect(flx.mapValueIterable.map((e) => e.json).toList(), [ + flx['address'].json, + flx['age'].json, + flx['flags'].json, + flx['name'].json, + flx['weight'].json + ]); + expect(flx['flags'].vectorIterable.map((e) => e.boolValue).toList(), + [true, false, true, true]); + }); + + test('bug where offest were stored as int instead of uint', () { + const data = [ + 99, + 104, + 97, + 110, + 110, + 101, + 108, + 115, + 95, + 105, + 110, + 0, + 100, + 105, + 108, + 97, + 116, + 105, + 111, + 110, + 95, + 104, + 101, + 105, + 103, + 104, + 116, + 95, + 102, + 97, + 99, + 116, + 111, + 114, + 0, + 100, + 105, + 108, + 97, + 116, + 105, + 111, + 110, + 95, + 119, + 105, + 100, + 116, + 104, + 95, + 102, + 97, + 99, + 116, + 111, + 114, + 0, + 102, + 117, + 115, + 101, + 100, + 95, + 97, + 99, + 116, + 105, + 118, + 97, + 116, + 105, + 111, + 110, + 95, + 102, + 117, + 110, + 99, + 116, + 105, + 111, + 110, + 0, + 112, + 97, + 100, + 95, + 118, + 97, + 108, + 117, + 101, + 115, + 0, + 112, + 97, + 100, + 100, + 105, + 110, + 103, + 0, + 115, + 116, + 114, + 105, + 100, + 101, + 95, + 104, + 101, + 105, + 103, + 104, + 116, + 0, + 115, + 116, + 114, + 105, + 100, + 101, + 95, + 119, + 105, + 100, + 116, + 104, + 0, + 8, + 130, + 119, + 97, + 76, + 51, + 41, + 34, + 21, + 8, + 1, + 8, + 64, + 1, + 1, + 1, + 1, + 0, + 1, + 1, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 4, + 16, + 36, + 1 + ]; + var flx = Reference.fromBuffer(b(data)); + expect(flx.json, + '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}'); + const object = { + "channels_in": 64, + "dilation_height_factor": 1, + "dilation_width_factor": 1, + "fused_activation_function": 1, + "pad_values": 1, + "padding": 0, + "stride_height": 1, + "stride_width": 1 + }; + var data1 = Builder.buildFromObject(object).asUint8List(); + expect(data1.length, data.length); + var flx1 = Reference.fromBuffer(b(data1)); + expect(flx1.json, + '{"channels_in":64,"dilation_height_factor":1,"dilation_width_factor":1,"fused_activation_function":1,"pad_values":1,"padding":0,"stride_height":1,"stride_width":1}'); + }); +} + +ByteBuffer b(List values) { + var data = Uint8List.fromList(values); + return data.buffer; +} + +void testNumbers(List buffer, List numbers) { + var flx = Reference.fromBuffer(b(buffer)); + expect(flx.length, numbers.length); + for (var i = 0; i < flx.length; i++) { + expect(flx[i].numValue, closeTo(numbers[i], 0.001)); + } +} + +void testStrings(List buffer, List numbers) { + var flx = Reference.fromBuffer(b(buffer)); + expect(flx.length, numbers.length); + for (var i = 0; i < flx.length; i++) { + expect(flx[i].stringValue, numbers[i]); + } +} + +Reference complexMap() { +// { +// "age": 35, +// "flags": [True, False, True, True], +// "weight": 72.5, +// "name": "Maxim", +// "address": { +// "city": "Bla", +// "zip": "12345", +// "countryCode": "XX", +// } +// } + return Reference.fromBuffer(b([ + 97, + 100, + 100, + 114, + 101, + 115, + 115, + 0, + 99, + 105, + 116, + 121, + 0, + 3, + 66, + 108, + 97, + 0, + 99, + 111, + 117, + 110, + 116, + 114, + 121, + 67, + 111, + 100, + 101, + 0, + 2, + 88, + 88, + 0, + 122, + 105, + 112, + 0, + 5, + 49, + 50, + 51, + 52, + 53, + 0, + 3, + 38, + 29, + 14, + 3, + 1, + 3, + 38, + 22, + 15, + 20, + 20, + 20, + 97, + 103, + 101, + 0, + 102, + 108, + 97, + 103, + 115, + 0, + 4, + 1, + 0, + 1, + 1, + 110, + 97, + 109, + 101, + 0, + 5, + 77, + 97, + 120, + 105, + 109, + 0, + 119, + 101, + 105, + 103, + 104, + 116, + 0, + 5, + 93, + 36, + 33, + 23, + 12, + 0, + 0, + 7, + 0, + 0, + 0, + 1, + 0, + 0, + 0, + 5, + 0, + 0, + 0, + 60, + 0, + 0, + 0, + 35, + 0, + 0, + 0, + 51, + 0, + 0, + 0, + 45, + 0, + 0, + 0, + 0, + 0, + 145, + 66, + 36, + 4, + 144, + 20, + 14, + 25, + 38, + 1 + ])); +} diff --git a/third_party/flatbuffers/dart/test/flex_types_test.dart b/third_party/flatbuffers/dart/test/flex_types_test.dart new file mode 100644 index 00000000000..76ce0704983 --- /dev/null +++ b/third_party/flatbuffers/dart/test/flex_types_test.dart @@ -0,0 +1,184 @@ +import 'package:flat_buffers/src/types.dart'; +import 'package:test/test.dart'; + +void main() { + test('is inline', () { + expect(ValueTypeUtils.isInline(ValueType.Bool), isTrue); + expect(ValueTypeUtils.isInline(ValueType.Int), isTrue); + expect(ValueTypeUtils.isInline(ValueType.UInt), isTrue); + expect(ValueTypeUtils.isInline(ValueType.Float), isTrue); + expect(ValueTypeUtils.isInline(ValueType.Null), isTrue); + expect(ValueTypeUtils.isInline(ValueType.String), isFalse); + }); + test('is type vector element', () { + expect(ValueTypeUtils.isTypedVectorElement(ValueType.Bool), isTrue); + expect(ValueTypeUtils.isTypedVectorElement(ValueType.Int), isTrue); + expect(ValueTypeUtils.isTypedVectorElement(ValueType.UInt), isTrue); + expect(ValueTypeUtils.isTypedVectorElement(ValueType.Float), isTrue); + expect(ValueTypeUtils.isTypedVectorElement(ValueType.Key), isTrue); + expect(ValueTypeUtils.isTypedVectorElement(ValueType.String), isTrue); + + expect(ValueTypeUtils.isTypedVectorElement(ValueType.Null), isFalse); + expect(ValueTypeUtils.isTypedVectorElement(ValueType.Blob), isFalse); + }); + test('is typed vector', () { + expect(ValueTypeUtils.isTypedVector(ValueType.VectorInt), isTrue); + expect(ValueTypeUtils.isTypedVector(ValueType.VectorUInt), isTrue); + expect(ValueTypeUtils.isTypedVector(ValueType.VectorFloat), isTrue); + expect(ValueTypeUtils.isTypedVector(ValueType.VectorBool), isTrue); + expect(ValueTypeUtils.isTypedVector(ValueType.VectorKey), isTrue); + expect(ValueTypeUtils.isTypedVector(ValueType.VectorString), isTrue); + + expect(ValueTypeUtils.isTypedVector(ValueType.Vector), isFalse); + expect(ValueTypeUtils.isTypedVector(ValueType.Map), isFalse); + expect(ValueTypeUtils.isTypedVector(ValueType.Bool), isFalse); + expect(ValueTypeUtils.isTypedVector(ValueType.VectorInt2), isFalse); + }); + test('is fixed typed vector', () { + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt2), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt3), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt4), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorUInt2), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorUInt3), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorUInt4), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorFloat2), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorFloat3), isTrue); + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorFloat4), isTrue); + + expect(ValueTypeUtils.isFixedTypedVector(ValueType.VectorInt), isFalse); + }); + test('to typed vector', () { + expect(ValueTypeUtils.toTypedVector(ValueType.Int, 0), + equals(ValueType.VectorInt)); + expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 0), + equals(ValueType.VectorUInt)); + expect(ValueTypeUtils.toTypedVector(ValueType.Bool, 0), + equals(ValueType.VectorBool)); + expect(ValueTypeUtils.toTypedVector(ValueType.Float, 0), + equals(ValueType.VectorFloat)); + expect(ValueTypeUtils.toTypedVector(ValueType.Key, 0), + equals(ValueType.VectorKey)); + expect(ValueTypeUtils.toTypedVector(ValueType.String, 0), + equals(ValueType.VectorString)); + + expect(ValueTypeUtils.toTypedVector(ValueType.Int, 2), + equals(ValueType.VectorInt2)); + expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 2), + equals(ValueType.VectorUInt2)); + expect(ValueTypeUtils.toTypedVector(ValueType.Float, 2), + equals(ValueType.VectorFloat2)); + + expect(ValueTypeUtils.toTypedVector(ValueType.Int, 3), + equals(ValueType.VectorInt3)); + expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 3), + equals(ValueType.VectorUInt3)); + expect(ValueTypeUtils.toTypedVector(ValueType.Float, 3), + equals(ValueType.VectorFloat3)); + + expect(ValueTypeUtils.toTypedVector(ValueType.Int, 4), + equals(ValueType.VectorInt4)); + expect(ValueTypeUtils.toTypedVector(ValueType.UInt, 4), + equals(ValueType.VectorUInt4)); + expect(ValueTypeUtils.toTypedVector(ValueType.Float, 4), + equals(ValueType.VectorFloat4)); + }); + test('typed vector element type', () { + expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorInt), + equals(ValueType.Int)); + expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorUInt), + equals(ValueType.UInt)); + expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorFloat), + equals(ValueType.Float)); + expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorString), + equals(ValueType.String)); + expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorKey), + equals(ValueType.Key)); + expect(ValueTypeUtils.typedVectorElementType(ValueType.VectorBool), + equals(ValueType.Bool)); + }); + test('fixed typed vector element type', () { + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt2), + equals(ValueType.Int)); + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt3), + equals(ValueType.Int)); + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorInt4), + equals(ValueType.Int)); + + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt2), + equals(ValueType.UInt)); + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt3), + equals(ValueType.UInt)); + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorUInt4), + equals(ValueType.UInt)); + + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat2), + equals(ValueType.Float)); + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat3), + equals(ValueType.Float)); + expect(ValueTypeUtils.fixedTypedVectorElementType(ValueType.VectorFloat4), + equals(ValueType.Float)); + }); + test('fixed typed vector element size', () { + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt2), + equals(2)); + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt3), + equals(3)); + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorInt4), + equals(4)); + + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt2), + equals(2)); + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt3), + equals(3)); + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorUInt4), + equals(4)); + + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat2), + equals(2)); + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat3), + equals(3)); + expect(ValueTypeUtils.fixedTypedVectorElementSize(ValueType.VectorFloat4), + equals(4)); + }); + test('packed type', () { + expect( + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width8), equals(0)); + expect( + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width16), equals(1)); + expect( + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width32), equals(2)); + expect( + ValueTypeUtils.packedType(ValueType.Null, BitWidth.width64), equals(3)); + + expect( + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width8), equals(4)); + expect( + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width16), equals(5)); + expect( + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width32), equals(6)); + expect( + ValueTypeUtils.packedType(ValueType.Int, BitWidth.width64), equals(7)); + }); + test('bit width', () { + expect(BitWidthUtil.width(0), BitWidth.width8); + expect(BitWidthUtil.width(-20), BitWidth.width8); + expect(BitWidthUtil.width(127), BitWidth.width8); + expect(BitWidthUtil.width(128), BitWidth.width16); + expect(BitWidthUtil.width(128123), BitWidth.width32); + expect(BitWidthUtil.width(12812324534), BitWidth.width64); + expect(BitWidthUtil.width(-127), BitWidth.width8); + expect(BitWidthUtil.width(-128), BitWidth.width16); + expect(BitWidthUtil.width(-12812324534), BitWidth.width64); + expect(BitWidthUtil.width(-0.1), BitWidth.width64); + expect(BitWidthUtil.width(0.25), BitWidth.width32); + }); + test('padding size', () { + expect(BitWidthUtil.paddingSize(10, 8), 6); + expect(BitWidthUtil.paddingSize(10, 4), 2); + expect(BitWidthUtil.paddingSize(15, 4), 1); + expect(BitWidthUtil.paddingSize(15, 2), 1); + expect(BitWidthUtil.paddingSize(15, 1), 0); + expect(BitWidthUtil.paddingSize(16, 8), 0); + expect(BitWidthUtil.paddingSize(17, 8), 7); + }); +} diff --git a/third_party/flatbuffers/dart/test/include_test1_generated.dart b/third_party/flatbuffers/dart/test/include_test1_generated.dart new file mode 100644 index 00000000000..c04bf6b2d22 --- /dev/null +++ b/third_party/flatbuffers/dart/test/include_test1_generated.dart @@ -0,0 +1,109 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +import './include_test2_my_game.other_name_space_generated.dart' as my_game_other_name_space; + +class TableA { + TableA._(this._bc, this._bcOffset); + factory TableA(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableAReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + my_game_other_name_space.TableB? get b => my_game_other_name_space.TableB.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'TableA{b: ${b}}'; + } + + TableAT unpack() => TableAT( + b: b?.unpack()); + + static int pack(fb.Builder fbBuilder, TableAT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableAT implements fb.Packable { + my_game_other_name_space.TableBT? b; + + TableAT({ + this.b}); + + @override + int pack(fb.Builder fbBuilder) { + final int? bOffset = b?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, bOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableAT{b: ${b}}'; + } +} + +class _TableAReader extends fb.TableReader { + const _TableAReader(); + + @override + TableA createObject(fb.BufferContext bc, int offset) => + TableA._(bc, offset); +} + +class TableABuilder { + TableABuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addBOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableAObjectBuilder extends fb.ObjectBuilder { + final my_game_other_name_space.TableBObjectBuilder? _b; + + TableAObjectBuilder({ + my_game_other_name_space.TableBObjectBuilder? b, + }) + : _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? bOffset = _b?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, bOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/include_test2_my_game.other_name_space_generated.dart b/third_party/flatbuffers/dart/test/include_test2_my_game.other_name_space_generated.dart new file mode 100644 index 00000000000..365ed3ceb5d --- /dev/null +++ b/third_party/flatbuffers/dart/test/include_test2_my_game.other_name_space_generated.dart @@ -0,0 +1,231 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.other_name_space; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +import './include_test1_generated.dart'; + +enum FromInclude { + IncludeVal(0); + + final int value; + const FromInclude(this.value); + + factory FromInclude.fromValue(int value) { + switch (value) { + case 0: return FromInclude.IncludeVal; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static FromInclude? _createOrNull(int? value) => + value == null ? null : FromInclude.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 0; + static const fb.Reader reader = _FromIncludeReader(); +} + +class _FromIncludeReader extends fb.Reader { + const _FromIncludeReader(); + + @override + int get size => 8; + + @override + FromInclude read(fb.BufferContext bc, int offset) => + FromInclude.fromValue(const fb.Int64Reader().read(bc, offset)); +} + +class Unused { + Unused._(this._bc, this._bcOffset); + + static const fb.Reader reader = _UnusedReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get a => const fb.Int32Reader().read(_bc, _bcOffset + 0); + + @override + String toString() { + return 'Unused{a: ${a}}'; + } + + UnusedT unpack() => UnusedT( + a: a); + + static int pack(fb.Builder fbBuilder, UnusedT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class UnusedT implements fb.Packable { + int a; + + UnusedT({ + required this.a}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'UnusedT{a: ${a}}'; + } +} + +class _UnusedReader extends fb.StructReader { + const _UnusedReader(); + + @override + int get size => 4; + + @override + Unused createObject(fb.BufferContext bc, int offset) => + Unused._(bc, offset); +} + +class UnusedBuilder { + UnusedBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int a) { + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + +} + +class UnusedObjectBuilder extends fb.ObjectBuilder { + final int _a; + + UnusedObjectBuilder({ + required int a, + }) + : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putInt32(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class TableB { + TableB._(this._bc, this._bcOffset); + factory TableB(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableBReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + TableA? get a => TableA.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'TableB{a: ${a}}'; + } + + TableBT unpack() => TableBT( + a: a?.unpack()); + + static int pack(fb.Builder fbBuilder, TableBT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableBT implements fb.Packable { + TableAT? a; + + TableBT({ + this.a}); + + @override + int pack(fb.Builder fbBuilder) { + final int? aOffset = a?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, aOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableBT{a: ${a}}'; + } +} + +class _TableBReader extends fb.TableReader { + const _TableBReader(); + + @override + TableB createObject(fb.BufferContext bc, int offset) => + TableB._(bc, offset); +} + +class TableBBuilder { + TableBBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addAOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableBObjectBuilder extends fb.ObjectBuilder { + final TableAObjectBuilder? _a; + + TableBObjectBuilder({ + TableAObjectBuilder? a, + }) + : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? aOffset = _a?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, aOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/keyword_test_keyword_test_generated.dart b/third_party/flatbuffers/dart/test/keyword_test_keyword_test_generated.dart new file mode 100644 index 00000000000..e0118af1624 --- /dev/null +++ b/third_party/flatbuffers/dart/test/keyword_test_keyword_test_generated.dart @@ -0,0 +1,369 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library keyword_test; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +enum Abc { + $void(0), + where(1), + stackalloc(2); + + final int value; + const Abc(this.value); + + factory Abc.fromValue(int value) { + switch (value) { + case 0: return Abc.$void; + case 1: return Abc.where; + case 2: return Abc.stackalloc; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static Abc? _createOrNull(int? value) => + value == null ? null : Abc.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 2; + static const fb.Reader reader = _AbcReader(); +} + +class _AbcReader extends fb.Reader { + const _AbcReader(); + + @override + int get size => 4; + + @override + Abc read(fb.BufferContext bc, int offset) => + Abc.fromValue(const fb.Int32Reader().read(bc, offset)); +} + +enum Public { + NONE(0); + + final int value; + const Public(this.value); + + factory Public.fromValue(int value) { + switch (value) { + case 0: return Public.NONE; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static Public? _createOrNull(int? value) => + value == null ? null : Public.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 0; + static const fb.Reader reader = _PublicReader(); +} + +class _PublicReader extends fb.Reader { + const _PublicReader(); + + @override + int get size => 4; + + @override + Public read(fb.BufferContext bc, int offset) => + Public.fromValue(const fb.Int32Reader().read(bc, offset)); +} + +enum KeywordsInUnionTypeId { + NONE(0), + $static(1), + internal(2); + + final int value; + const KeywordsInUnionTypeId(this.value); + + factory KeywordsInUnionTypeId.fromValue(int value) { + switch (value) { + case 0: return KeywordsInUnionTypeId.NONE; + case 1: return KeywordsInUnionTypeId.$static; + case 2: return KeywordsInUnionTypeId.internal; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static KeywordsInUnionTypeId? _createOrNull(int? value) => + value == null ? null : KeywordsInUnionTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 2; + static const fb.Reader reader = _KeywordsInUnionTypeIdReader(); +} + +class _KeywordsInUnionTypeIdReader extends fb.Reader { + const _KeywordsInUnionTypeIdReader(); + + @override + int get size => 1; + + @override + KeywordsInUnionTypeId read(fb.BufferContext bc, int offset) => + KeywordsInUnionTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +class KeywordsInTable { + KeywordsInTable._(this._bc, this._bcOffset); + factory KeywordsInTable(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _KeywordsInTableReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Abc get $is => Abc.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 4, 0)); + Public get private => Public.fromValue(const fb.Int32Reader().vTableGet(_bc, _bcOffset, 6, 0)); + int get type => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 8, 0); + bool get $default => const fb.BoolReader().vTableGet(_bc, _bcOffset, 10, false); + + @override + String toString() { + return 'KeywordsInTable{\$is: ${$is}, private: ${private}, type: ${type}, \$default: ${$default}}'; + } + + KeywordsInTableT unpack() => KeywordsInTableT( + $is: $is, + private: private, + type: type, + $default: $default); + + static int pack(fb.Builder fbBuilder, KeywordsInTableT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class KeywordsInTableT implements fb.Packable { + Abc $is; + Public private; + int type; + bool $default; + + KeywordsInTableT({ + this.$is = Abc.$void, + this.private = Public.NONE, + this.type = 0, + this.$default = false}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(4); + fbBuilder.addInt32(0, $is.value); + fbBuilder.addInt32(1, private.value); + fbBuilder.addInt32(2, type); + fbBuilder.addBool(3, $default); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'KeywordsInTableT{\$is: ${$is}, private: ${private}, type: ${type}, \$default: ${$default}}'; + } +} + +class _KeywordsInTableReader extends fb.TableReader { + const _KeywordsInTableReader(); + + @override + KeywordsInTable createObject(fb.BufferContext bc, int offset) => + KeywordsInTable._(bc, offset); +} + +class KeywordsInTableBuilder { + KeywordsInTableBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(4); + } + + int addIs(Abc? $is) { + fbBuilder.addInt32(0, $is?.value); + return fbBuilder.offset; + } + int addPrivate(Public? private) { + fbBuilder.addInt32(1, private?.value); + return fbBuilder.offset; + } + int addType(int? type) { + fbBuilder.addInt32(2, type); + return fbBuilder.offset; + } + int addDefault(bool? $default) { + fbBuilder.addBool(3, $default); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class KeywordsInTableObjectBuilder extends fb.ObjectBuilder { + final Abc? _$is; + final Public? _private; + final int? _type; + final bool? _$default; + + KeywordsInTableObjectBuilder({ + Abc? $is, + Public? private, + int? type, + bool? $default, + }) + : _$is = $is, + _private = private, + _type = type, + _$default = $default; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(4); + fbBuilder.addInt32(0, _$is?.value); + fbBuilder.addInt32(1, _private?.value); + fbBuilder.addInt32(2, _type); + fbBuilder.addBool(3, _$default); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Table2 { + Table2._(this._bc, this._bcOffset); + factory Table2(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _Table2Reader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + KeywordsInUnionTypeId? get typeType => KeywordsInUnionTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 4)); + dynamic get type { + switch (typeType?.value) { + case 1: return KeywordsInTable.reader.vTableGetNullable(_bc, _bcOffset, 6); + case 2: return KeywordsInTable.reader.vTableGetNullable(_bc, _bcOffset, 6); + default: return null; + } + } + + @override + String toString() { + return 'Table2{typeType: ${typeType}, type: ${type}}'; + } + + Table2T unpack() => Table2T( + typeType: typeType, + type: type); + + static int pack(fb.Builder fbBuilder, Table2T? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class Table2T implements fb.Packable { + KeywordsInUnionTypeId? typeType; + dynamic type; + + Table2T({ + this.typeType, + this.type}); + + @override + int pack(fb.Builder fbBuilder) { + final int? typeOffset = type?.pack(fbBuilder); + fbBuilder.startTable(2); + fbBuilder.addUint8(0, typeType?.value); + fbBuilder.addOffset(1, typeOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'Table2T{typeType: ${typeType}, type: ${type}}'; + } +} + +class _Table2Reader extends fb.TableReader { + const _Table2Reader(); + + @override + Table2 createObject(fb.BufferContext bc, int offset) => + Table2._(bc, offset); +} + +class Table2Builder { + Table2Builder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addTypeType(KeywordsInUnionTypeId? typeType) { + fbBuilder.addUint8(0, typeType?.value); + return fbBuilder.offset; + } + int addTypeOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class Table2ObjectBuilder extends fb.ObjectBuilder { + final KeywordsInUnionTypeId? _typeType; + final dynamic _type; + + Table2ObjectBuilder({ + KeywordsInUnionTypeId? typeType, + dynamic type, + }) + : _typeType = typeType, + _type = type; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? typeOffset = _type?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(2); + fbBuilder.addUint8(0, _typeType?.value); + fbBuilder.addOffset(1, typeOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/monster_test.fbs b/third_party/flatbuffers/dart/test/monster_test.fbs new file mode 100644 index 00000000000..b40ecf58f95 --- /dev/null +++ b/third_party/flatbuffers/dart/test/monster_test.fbs @@ -0,0 +1,180 @@ +// test schema file + +include "include_test1.fbs"; + +namespace MyGame; + +table InParentNamespace {} + +namespace MyGame.Example2; + +table Monster {} // Test having same name as below, but in different namespace. + +namespace MyGame.Example; + +attribute "priority"; + +/// Composite components of Monster color. +enum Color:ubyte (bit_flags) { + Red = 0, // color Red = (1u << 0) + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Green, + /// \brief color Blue (1u << 3) + Blue = 3, +} + +enum Race:byte { + None = -1, + Human = 0, + Dwarf, + Elf, +} + +enum LongEnum:ulong (bit_flags) { + LongOne = 1, + LongTwo = 2, + // Because this is a bitflag, 40 will be out of range of a 32-bit integer, + // allowing us to exercise any logic special to big numbers. + LongBig = 40, +} + +union Any { Monster, TestSimpleTableWithEnum, MyGame.Example2.Monster } + +union AnyUniqueAliases { M: Monster, TS: TestSimpleTableWithEnum, M2: MyGame.Example2.Monster } +union AnyAmbiguousAliases { M1: Monster, M2: Monster, M3: Monster } + +struct Test { a:short; b:byte; } + +table TestSimpleTableWithEnum (csharp_partial, private) { + color: Color = Green; +} + +struct Vec3 (force_align: 8) { + x:float; + y:float; + z:float; + test1:double; + test2:Color; + test3:Test; +} + +struct Ability { + id:uint(key); + distance:uint; +} + +struct StructOfStructs { + a: Ability; + b: Test; + c: Ability; +} + +struct StructOfStructsOfStructs { + a: StructOfStructs; +} + +table Stat { + id:string; + val:long; + count:ushort (key); +} + +table Referrable { + id:ulong(key, hash:"fnv1a_64"); +} + +/// an example documentation comment: "monster object" +table Monster { + pos:Vec3 (id: 0); + hp:short = 100 (id: 2); + mana:short = 150 (id: 1); + name:string (id: 3, key); + color:Color = Blue (id: 6); + inventory:[ubyte] (id: 5); + friendly:bool = false (deprecated, priority: 1, id: 4); + /// an example documentation comment: this will end up in the generated code + /// multiline too + testarrayoftables:[Monster] (id: 11); + testarrayofstring:[string] (id: 10); + testarrayofstring2:[string] (id: 28); + testarrayofbools:[bool] (id: 24); + testarrayofsortedstruct:[Ability] (id: 29); + enemy:MyGame.Example.Monster (id:12); // Test referring by full namespace. + test:Any (id: 8); + test4:[Test] (id: 9); + test5:[Test] (id: 31); + testnestedflatbuffer:[ubyte] (id:13, nested_flatbuffer: "Monster"); + testempty:Stat (id:14); + testbool:bool (id:15); + testhashs32_fnv1:int (id:16, hash:"fnv1_32"); + testhashu32_fnv1:uint (id:17, hash:"fnv1_32"); + testhashs64_fnv1:long (id:18, hash:"fnv1_64"); + testhashu64_fnv1:ulong (id:19, hash:"fnv1_64"); + testhashs32_fnv1a:int (id:20, hash:"fnv1a_32"); + testhashu32_fnv1a:uint (id:21, hash:"fnv1a_32", cpp_type:"Stat"); + testhashs64_fnv1a:long (id:22, hash:"fnv1a_64"); + testhashu64_fnv1a:ulong (id:23, hash:"fnv1a_64"); + testf:float = 3.14159 (id:25); + testf2:float = 3 (id:26); + testf3:float (id:27); + flex:[ubyte] (id:30, flexbuffer); + vector_of_longs:[long] (id:32); + vector_of_doubles:[double] (id:33); + parent_namespace_test:InParentNamespace (id:34); + vector_of_referrables:[Referrable](id:35); + single_weak_reference:ulong(id:36, hash:"fnv1a_64", cpp_type:"ReferrableT"); + vector_of_weak_references:[ulong](id:37, hash:"fnv1a_64", cpp_type:"ReferrableT"); + vector_of_strong_referrables:[Referrable](id:38, cpp_ptr_type:"default_ptr_type"); //was shared_ptr + co_owning_reference:ulong(id:39, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked"); //was shared_ptr as well + vector_of_co_owning_references:[ulong](id:40, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"default_ptr_type", cpp_ptr_type_get:".get()"); //was shared_ptr + non_owning_reference:ulong(id:41, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked", cpp_ptr_type_get:""); //was weak_ptr + vector_of_non_owning_references:[ulong](id:42, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked", cpp_ptr_type_get:""); //was weak_ptr + any_unique:AnyUniqueAliases(id:44); + any_ambiguous:AnyAmbiguousAliases (id:46); + vector_of_enums:[Color] (id:47); + signed_enum:Race = None (id:48); + testrequirednestedflatbuffer:[ubyte] (id:49, nested_flatbuffer: "Monster"); + scalar_key_sorted_tables:[Stat] (id: 50); + native_inline:Test (id: 51, native_inline); + // The default value of this enum will be a numeric zero, which isn't a valid + // enum value. + long_enum_non_enum_default:LongEnum (id: 52); + long_enum_normal_default:LongEnum = LongOne (id: 53); + // Test that default values nan and +/-inf work. + nan_default:float = nan (id: 54); + inf_default:float = inf (id: 55); + positive_inf_default:float = +inf (id: 56); + infinity_default:float = infinity (id: 57); + positive_infinity_default:float = +infinity (id: 58); + negative_inf_default:float = -inf (id: 59); + negative_infinity_default:float = -infinity (id: 60); + double_inf_default:double = inf (id: 61); +} + +table TypeAliases { + i8:int8; + u8:uint8; + i16:int16; + u16:uint16; + i32:int32; + u32:uint32; + i64:int64; + u64:uint64; + f32:float32; + f64:float64; + v8:[int8]; + vf64:[float64]; +} + +rpc_service MonsterStorage { + Store(Monster):Stat (streaming: "none"); + Retrieve(Stat):Monster (streaming: "server", idempotent); + GetMaxHitPoint(Monster):Stat (streaming: "client"); + GetMinMaxHitPoints(Monster):Stat (streaming: "bidi"); +} + +root_type Monster; + +file_identifier "MONS"; +file_extension "mon"; diff --git a/third_party/flatbuffers/dart/test/monster_test_my_game.example2_generated.dart b/third_party/flatbuffers/dart/test/monster_test_my_game.example2_generated.dart new file mode 100644 index 00000000000..c266f9ce72b --- /dev/null +++ b/third_party/flatbuffers/dart/test/monster_test_my_game.example2_generated.dart @@ -0,0 +1,79 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.example2; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './monster_test_my_game_generated.dart' as my_game; +import './monster_test_my_game.example_generated.dart' as my_game_example; + +import './include_test1_generated.dart'; + +class Monster { + Monster._(this._bc, this._bcOffset); + factory Monster(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MonsterReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + + @override + String toString() { + return 'Monster{}'; + } + + MonsterT unpack() => MonsterT(); + + static int pack(fb.Builder fbBuilder, MonsterT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class MonsterT implements fb.Packable { + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'MonsterT{}'; + } +} + +class _MonsterReader extends fb.TableReader { + const _MonsterReader(); + + @override + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); +} + +class MonsterObjectBuilder extends fb.ObjectBuilder { + + MonsterObjectBuilder(); + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/monster_test_my_game.example_generated.dart b/third_party/flatbuffers/dart/test/monster_test_my_game.example_generated.dart new file mode 100644 index 00000000000..5554c4c4b1d --- /dev/null +++ b/third_party/flatbuffers/dart/test/monster_test_my_game.example_generated.dart @@ -0,0 +1,2371 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.example; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './monster_test_my_game_generated.dart' as my_game; +import './monster_test_my_game.example2_generated.dart' as my_game_example2; + +import './include_test1_generated.dart'; + +/// Composite components of Monster color. +enum Color { + Red(1), + Green(2), + Blue(8), + _default(0); + + final int value; + const Color(this.value); + + factory Color.fromValue(int value) { + switch (value) { + case 1: return Color.Red; + case 2: return Color.Green; + case 8: return Color.Blue; + case 0: return Color._default; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static Color? _createOrNull(int? value) => + value == null ? null : Color.fromValue(value); + + static const fb.Reader reader = _ColorReader(); +} + +class _ColorReader extends fb.Reader { + const _ColorReader(); + + @override + int get size => 1; + + @override + Color read(fb.BufferContext bc, int offset) => + Color.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +enum Race { + None(-1), + Human(0), + Dwarf(1), + Elf(2); + + final int value; + const Race(this.value); + + factory Race.fromValue(int value) { + switch (value) { + case -1: return Race.None; + case 0: return Race.Human; + case 1: return Race.Dwarf; + case 2: return Race.Elf; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static Race? _createOrNull(int? value) => + value == null ? null : Race.fromValue(value); + + static const int minValue = -1; + static const int maxValue = 2; + static const fb.Reader reader = _RaceReader(); +} + +class _RaceReader extends fb.Reader { + const _RaceReader(); + + @override + int get size => 1; + + @override + Race read(fb.BufferContext bc, int offset) => + Race.fromValue(const fb.Int8Reader().read(bc, offset)); +} + +enum LongEnum { + LongOne(2), + LongTwo(4), + LongBig(1099511627776), + _default(0); + + final int value; + const LongEnum(this.value); + + factory LongEnum.fromValue(int value) { + switch (value) { + case 2: return LongEnum.LongOne; + case 4: return LongEnum.LongTwo; + case 1099511627776: return LongEnum.LongBig; + case 0: return LongEnum._default; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static LongEnum? _createOrNull(int? value) => + value == null ? null : LongEnum.fromValue(value); + + static const fb.Reader reader = _LongEnumReader(); +} + +class _LongEnumReader extends fb.Reader { + const _LongEnumReader(); + + @override + int get size => 8; + + @override + LongEnum read(fb.BufferContext bc, int offset) => + LongEnum.fromValue(const fb.Uint64Reader().read(bc, offset)); +} + +enum AnyTypeId { + NONE(0), + Monster(1), + TestSimpleTableWithEnum(2), + MyGame_Example2_Monster(3); + + final int value; + const AnyTypeId(this.value); + + factory AnyTypeId.fromValue(int value) { + switch (value) { + case 0: return AnyTypeId.NONE; + case 1: return AnyTypeId.Monster; + case 2: return AnyTypeId.TestSimpleTableWithEnum; + case 3: return AnyTypeId.MyGame_Example2_Monster; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static AnyTypeId? _createOrNull(int? value) => + value == null ? null : AnyTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 3; + static const fb.Reader reader = _AnyTypeIdReader(); +} + +class _AnyTypeIdReader extends fb.Reader { + const _AnyTypeIdReader(); + + @override + int get size => 1; + + @override + AnyTypeId read(fb.BufferContext bc, int offset) => + AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +enum AnyUniqueAliasesTypeId { + NONE(0), + M(1), + TS(2), + M2(3); + + final int value; + const AnyUniqueAliasesTypeId(this.value); + + factory AnyUniqueAliasesTypeId.fromValue(int value) { + switch (value) { + case 0: return AnyUniqueAliasesTypeId.NONE; + case 1: return AnyUniqueAliasesTypeId.M; + case 2: return AnyUniqueAliasesTypeId.TS; + case 3: return AnyUniqueAliasesTypeId.M2; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static AnyUniqueAliasesTypeId? _createOrNull(int? value) => + value == null ? null : AnyUniqueAliasesTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 3; + static const fb.Reader reader = _AnyUniqueAliasesTypeIdReader(); +} + +class _AnyUniqueAliasesTypeIdReader extends fb.Reader { + const _AnyUniqueAliasesTypeIdReader(); + + @override + int get size => 1; + + @override + AnyUniqueAliasesTypeId read(fb.BufferContext bc, int offset) => + AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +enum AnyAmbiguousAliasesTypeId { + NONE(0), + M1(1), + M2(2), + M3(3); + + final int value; + const AnyAmbiguousAliasesTypeId(this.value); + + factory AnyAmbiguousAliasesTypeId.fromValue(int value) { + switch (value) { + case 0: return AnyAmbiguousAliasesTypeId.NONE; + case 1: return AnyAmbiguousAliasesTypeId.M1; + case 2: return AnyAmbiguousAliasesTypeId.M2; + case 3: return AnyAmbiguousAliasesTypeId.M3; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) => + value == null ? null : AnyAmbiguousAliasesTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 3; + static const fb.Reader reader = _AnyAmbiguousAliasesTypeIdReader(); +} + +class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader { + const _AnyAmbiguousAliasesTypeIdReader(); + + @override + int get size => 1; + + @override + AnyAmbiguousAliasesTypeId read(fb.BufferContext bc, int offset) => + AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +class Test { + Test._(this._bc, this._bcOffset); + + static const fb.Reader reader = _TestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get a => const fb.Int16Reader().read(_bc, _bcOffset + 0); + int get b => const fb.Int8Reader().read(_bc, _bcOffset + 2); + + @override + String toString() { + return 'Test{a: ${a}, b: ${b}}'; + } + + TestT unpack() => TestT( + a: a, + b: b); + + static int pack(fb.Builder fbBuilder, TestT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TestT implements fb.Packable { + int a; + int b; + + TestT({ + required this.a, + required this.b}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.pad(1); + fbBuilder.putInt8(b); + fbBuilder.putInt16(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'TestT{a: ${a}, b: ${b}}'; + } +} + +class _TestReader extends fb.StructReader { + const _TestReader(); + + @override + int get size => 4; + + @override + Test createObject(fb.BufferContext bc, int offset) => + Test._(bc, offset); +} + +class TestBuilder { + TestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int a, int b) { + fbBuilder.pad(1); + fbBuilder.putInt8(b); + fbBuilder.putInt16(a); + return fbBuilder.offset; + } + +} + +class TestObjectBuilder extends fb.ObjectBuilder { + final int _a; + final int _b; + + TestObjectBuilder({ + required int a, + required int b, + }) + : _a = a, + _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.pad(1); + fbBuilder.putInt8(_b); + fbBuilder.putInt16(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class TestSimpleTableWithEnum { + TestSimpleTableWithEnum._(this._bc, this._bcOffset); + factory TestSimpleTableWithEnum(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TestSimpleTableWithEnumReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2)); + + @override + String toString() { + return 'TestSimpleTableWithEnum{color: ${color}}'; + } + + TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT( + color: color); + + static int pack(fb.Builder fbBuilder, TestSimpleTableWithEnumT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TestSimpleTableWithEnumT implements fb.Packable { + Color color; + + TestSimpleTableWithEnumT({ + this.color = Color.Green}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint8(0, color.value); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TestSimpleTableWithEnumT{color: ${color}}'; + } +} + +class _TestSimpleTableWithEnumReader extends fb.TableReader { + const _TestSimpleTableWithEnumReader(); + + @override + TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) => + TestSimpleTableWithEnum._(bc, offset); +} + +class TestSimpleTableWithEnumBuilder { + TestSimpleTableWithEnumBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addColor(Color? color) { + fbBuilder.addUint8(0, color?.value); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder { + final Color? _color; + + TestSimpleTableWithEnumObjectBuilder({ + Color? color, + }) + : _color = color; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint8(0, _color?.value); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Vec3 { + Vec3._(this._bc, this._bcOffset); + + static const fb.Reader reader = _Vec3Reader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + double get x => const fb.Float32Reader().read(_bc, _bcOffset + 0); + double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4); + double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8); + double get test1 => const fb.Float64Reader().read(_bc, _bcOffset + 16); + Color get test2 => Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24)); + Test get test3 => Test.reader.read(_bc, _bcOffset + 26); + + @override + String toString() { + return 'Vec3{x: ${x}, y: ${y}, z: ${z}, test1: ${test1}, test2: ${test2}, test3: ${test3}}'; + } + + Vec3T unpack() => Vec3T( + x: x, + y: y, + z: z, + test1: test1, + test2: test2, + test3: test3.unpack()); + + static int pack(fb.Builder fbBuilder, Vec3T? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class Vec3T implements fb.Packable { + double x; + double y; + double z; + double test1; + Color test2; + TestT test3; + + Vec3T({ + required this.x, + required this.y, + required this.z, + required this.test1, + required this.test2, + required this.test3}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.pad(2); + test3.pack(fbBuilder); + fbBuilder.pad(1); + fbBuilder.putUint8(test2.value); + fbBuilder.putFloat64(test1); + fbBuilder.pad(4); + fbBuilder.putFloat32(z); + fbBuilder.putFloat32(y); + fbBuilder.putFloat32(x); + return fbBuilder.offset; + } + + @override + String toString() { + return 'Vec3T{x: ${x}, y: ${y}, z: ${z}, test1: ${test1}, test2: ${test2}, test3: ${test3}}'; + } +} + +class _Vec3Reader extends fb.StructReader { + const _Vec3Reader(); + + @override + int get size => 32; + + @override + Vec3 createObject(fb.BufferContext bc, int offset) => + Vec3._(bc, offset); +} + +class Vec3Builder { + Vec3Builder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(double x, double y, double z, double test1, Color test2, fb.StructBuilder test3) { + fbBuilder.pad(2); + test3(); + fbBuilder.pad(1); + fbBuilder.putUint8(test2.value); + fbBuilder.putFloat64(test1); + fbBuilder.pad(4); + fbBuilder.putFloat32(z); + fbBuilder.putFloat32(y); + fbBuilder.putFloat32(x); + return fbBuilder.offset; + } + +} + +class Vec3ObjectBuilder extends fb.ObjectBuilder { + final double _x; + final double _y; + final double _z; + final double _test1; + final Color _test2; + final TestObjectBuilder _test3; + + Vec3ObjectBuilder({ + required double x, + required double y, + required double z, + required double test1, + required Color test2, + required TestObjectBuilder test3, + }) + : _x = x, + _y = y, + _z = z, + _test1 = test1, + _test2 = test2, + _test3 = test3; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.pad(2); + _test3.finish(fbBuilder); + fbBuilder.pad(1); + fbBuilder.putUint8(_test2.value); + fbBuilder.putFloat64(_test1); + fbBuilder.pad(4); + fbBuilder.putFloat32(_z); + fbBuilder.putFloat32(_y); + fbBuilder.putFloat32(_x); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Ability { + Ability._(this._bc, this._bcOffset); + + static const fb.Reader reader = _AbilityReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get id => const fb.Uint32Reader().read(_bc, _bcOffset + 0); + int get distance => const fb.Uint32Reader().read(_bc, _bcOffset + 4); + + @override + String toString() { + return 'Ability{id: ${id}, distance: ${distance}}'; + } + + AbilityT unpack() => AbilityT( + id: id, + distance: distance); + + static int pack(fb.Builder fbBuilder, AbilityT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class AbilityT implements fb.Packable { + int id; + int distance; + + AbilityT({ + required this.id, + required this.distance}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putUint32(distance); + fbBuilder.putUint32(id); + return fbBuilder.offset; + } + + @override + String toString() { + return 'AbilityT{id: ${id}, distance: ${distance}}'; + } +} + +class _AbilityReader extends fb.StructReader { + const _AbilityReader(); + + @override + int get size => 8; + + @override + Ability createObject(fb.BufferContext bc, int offset) => + Ability._(bc, offset); +} + +class AbilityBuilder { + AbilityBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int id, int distance) { + fbBuilder.putUint32(distance); + fbBuilder.putUint32(id); + return fbBuilder.offset; + } + +} + +class AbilityObjectBuilder extends fb.ObjectBuilder { + final int _id; + final int _distance; + + AbilityObjectBuilder({ + required int id, + required int distance, + }) + : _id = id, + _distance = distance; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putUint32(_distance); + fbBuilder.putUint32(_id); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class StructOfStructs { + StructOfStructs._(this._bc, this._bcOffset); + + static const fb.Reader reader = _StructOfStructsReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Ability get a => Ability.reader.read(_bc, _bcOffset + 0); + Test get b => Test.reader.read(_bc, _bcOffset + 8); + Ability get c => Ability.reader.read(_bc, _bcOffset + 12); + + @override + String toString() { + return 'StructOfStructs{a: ${a}, b: ${b}, c: ${c}}'; + } + + StructOfStructsT unpack() => StructOfStructsT( + a: a.unpack(), + b: b.unpack(), + c: c.unpack()); + + static int pack(fb.Builder fbBuilder, StructOfStructsT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StructOfStructsT implements fb.Packable { + AbilityT a; + TestT b; + AbilityT c; + + StructOfStructsT({ + required this.a, + required this.b, + required this.c}); + + @override + int pack(fb.Builder fbBuilder) { + c.pack(fbBuilder); + b.pack(fbBuilder); + a.pack(fbBuilder); + return fbBuilder.offset; + } + + @override + String toString() { + return 'StructOfStructsT{a: ${a}, b: ${b}, c: ${c}}'; + } +} + +class _StructOfStructsReader extends fb.StructReader { + const _StructOfStructsReader(); + + @override + int get size => 20; + + @override + StructOfStructs createObject(fb.BufferContext bc, int offset) => + StructOfStructs._(bc, offset); +} + +class StructOfStructsBuilder { + StructOfStructsBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(fb.StructBuilder a, fb.StructBuilder b, fb.StructBuilder c) { + c(); + b(); + a(); + return fbBuilder.offset; + } + +} + +class StructOfStructsObjectBuilder extends fb.ObjectBuilder { + final AbilityObjectBuilder _a; + final TestObjectBuilder _b; + final AbilityObjectBuilder _c; + + StructOfStructsObjectBuilder({ + required AbilityObjectBuilder a, + required TestObjectBuilder b, + required AbilityObjectBuilder c, + }) + : _a = a, + _b = b, + _c = c; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + _c.finish(fbBuilder); + _b.finish(fbBuilder); + _a.finish(fbBuilder); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class StructOfStructsOfStructs { + StructOfStructsOfStructs._(this._bc, this._bcOffset); + + static const fb.Reader reader = _StructOfStructsOfStructsReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + StructOfStructs get a => StructOfStructs.reader.read(_bc, _bcOffset + 0); + + @override + String toString() { + return 'StructOfStructsOfStructs{a: ${a}}'; + } + + StructOfStructsOfStructsT unpack() => StructOfStructsOfStructsT( + a: a.unpack()); + + static int pack(fb.Builder fbBuilder, StructOfStructsOfStructsT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StructOfStructsOfStructsT implements fb.Packable { + StructOfStructsT a; + + StructOfStructsOfStructsT({ + required this.a}); + + @override + int pack(fb.Builder fbBuilder) { + a.pack(fbBuilder); + return fbBuilder.offset; + } + + @override + String toString() { + return 'StructOfStructsOfStructsT{a: ${a}}'; + } +} + +class _StructOfStructsOfStructsReader extends fb.StructReader { + const _StructOfStructsOfStructsReader(); + + @override + int get size => 20; + + @override + StructOfStructsOfStructs createObject(fb.BufferContext bc, int offset) => + StructOfStructsOfStructs._(bc, offset); +} + +class StructOfStructsOfStructsBuilder { + StructOfStructsOfStructsBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(fb.StructBuilder a) { + a(); + return fbBuilder.offset; + } + +} + +class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { + final StructOfStructsObjectBuilder _a; + + StructOfStructsOfStructsObjectBuilder({ + required StructOfStructsObjectBuilder a, + }) + : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + _a.finish(fbBuilder); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Stat { + Stat._(this._bc, this._bcOffset); + factory Stat(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _StatReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get id => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + int get val => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0); + int get count => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 8, 0); + + @override + String toString() { + return 'Stat{id: ${id}, val: ${val}, count: ${count}}'; + } + + StatT unpack() => StatT( + id: id, + val: val, + count: count); + + static int pack(fb.Builder fbBuilder, StatT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StatT implements fb.Packable { + String? id; + int val; + int count; + + StatT({ + this.id, + this.val = 0, + this.count = 0}); + + @override + int pack(fb.Builder fbBuilder) { + final int? idOffset = id == null ? null + : fbBuilder.writeString(id!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, idOffset); + fbBuilder.addInt64(1, val); + fbBuilder.addUint16(2, count); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'StatT{id: ${id}, val: ${val}, count: ${count}}'; + } +} + +class _StatReader extends fb.TableReader { + const _StatReader(); + + @override + Stat createObject(fb.BufferContext bc, int offset) => + Stat._(bc, offset); +} + +class StatBuilder { + StatBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addIdOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + int addVal(int? val) { + fbBuilder.addInt64(1, val); + return fbBuilder.offset; + } + int addCount(int? count) { + fbBuilder.addUint16(2, count); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class StatObjectBuilder extends fb.ObjectBuilder { + final String? _id; + final int? _val; + final int? _count; + + StatObjectBuilder({ + String? id, + int? val, + int? count, + }) + : _id = id, + _val = val, + _count = count; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? idOffset = _id == null ? null + : fbBuilder.writeString(_id!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, idOffset); + fbBuilder.addInt64(1, _val); + fbBuilder.addUint16(2, _count); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Referrable { + Referrable._(this._bc, this._bcOffset); + factory Referrable(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _ReferrableReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get id => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 4, 0); + + @override + String toString() { + return 'Referrable{id: ${id}}'; + } + + ReferrableT unpack() => ReferrableT( + id: id); + + static int pack(fb.Builder fbBuilder, ReferrableT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class ReferrableT implements fb.Packable { + int id; + + ReferrableT({ + this.id = 0}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint64(0, id); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'ReferrableT{id: ${id}}'; + } +} + +class _ReferrableReader extends fb.TableReader { + const _ReferrableReader(); + + @override + Referrable createObject(fb.BufferContext bc, int offset) => + Referrable._(bc, offset); +} + +class ReferrableBuilder { + ReferrableBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addId(int? id) { + fbBuilder.addUint64(0, id); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ReferrableObjectBuilder extends fb.ObjectBuilder { + final int? _id; + + ReferrableObjectBuilder({ + int? id, + }) + : _id = id; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint64(0, _id); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +/// an example documentation comment: "monster object" +class Monster { + Monster._(this._bc, this._bcOffset); + factory Monster(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MonsterReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4); + int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); + int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); + String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + List? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); + Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8)); + AnyTypeId? get testType => AnyTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 18)); + dynamic get test { + switch (testType?.value) { + case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); + case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 20); + case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); + default: return null; + } + } + List? get test4 => const fb.ListReader(Test.reader).vTableGetNullable(_bc, _bcOffset, 22); + List? get testarrayofstring => const fb.ListReader(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 24); + /// an example documentation comment: this will end up in the generated code + /// multiline too + List? get testarrayoftables => const fb.ListReader(Monster.reader).vTableGetNullable(_bc, _bcOffset, 26); + Monster? get enemy => Monster.reader.vTableGetNullable(_bc, _bcOffset, 28); + List? get testnestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 30); + Stat? get testempty => Stat.reader.vTableGetNullable(_bc, _bcOffset, 32); + bool get testbool => const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false); + int get testhashs32Fnv1 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0); + int get testhashu32Fnv1 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0); + int get testhashs64Fnv1 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 40, 0); + int get testhashu64Fnv1 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 42, 0); + int get testhashs32Fnv1a => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 44, 0); + int get testhashu32Fnv1a => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0); + int get testhashs64Fnv1a => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0); + int get testhashu64Fnv1a => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0); + List? get testarrayofbools => const fb.ListReader(fb.BoolReader()).vTableGetNullable(_bc, _bcOffset, 52); + double get testf => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159); + double get testf2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0); + double get testf3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0); + List? get testarrayofstring2 => const fb.ListReader(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 60); + List? get testarrayofsortedstruct => const fb.ListReader(Ability.reader).vTableGetNullable(_bc, _bcOffset, 62); + List? get flex => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 64); + List? get test5 => const fb.ListReader(Test.reader).vTableGetNullable(_bc, _bcOffset, 66); + List? get vectorOfLongs => const fb.ListReader(fb.Int64Reader()).vTableGetNullable(_bc, _bcOffset, 68); + List? get vectorOfDoubles => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 70); + my_game.InParentNamespace? get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGetNullable(_bc, _bcOffset, 72); + List? get vectorOfReferrables => const fb.ListReader(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 74); + int get singleWeakReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0); + List? get vectorOfWeakReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 78); + List? get vectorOfStrongReferrables => const fb.ListReader(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 80); + int get coOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0); + List? get vectorOfCoOwningReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 84); + int get nonOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0); + List? get vectorOfNonOwningReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 88); + AnyUniqueAliasesTypeId? get anyUniqueType => AnyUniqueAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 90)); + dynamic get anyUnique { + switch (anyUniqueType?.value) { + case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); + case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 92); + case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); + default: return null; + } + } + AnyAmbiguousAliasesTypeId? get anyAmbiguousType => AnyAmbiguousAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 94)); + dynamic get anyAmbiguous { + switch (anyAmbiguousType?.value) { + case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + case 2: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + case 3: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + default: return null; + } + } + List? get vectorOfEnums => const fb.ListReader(Color.reader).vTableGetNullable(_bc, _bcOffset, 98); + Race get signedEnum => Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1)); + List? get testrequirednestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102); + List? get scalarKeySortedTables => const fb.ListReader(Stat.reader).vTableGetNullable(_bc, _bcOffset, 104); + Test? get nativeInline => Test.reader.vTableGetNullable(_bc, _bcOffset, 106); + LongEnum get longEnumNonEnumDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 108, 0)); + LongEnum get longEnumNormalDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 110, 2)); + double get nanDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 112, double.nan); + double get infDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 114, double.infinity); + double get positiveInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 116, double.infinity); + double get infinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 118, double.infinity); + double get positiveInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 120, double.infinity); + double get negativeInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 122, double.negativeInfinity); + double get negativeInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 124, double.negativeInfinity); + double get doubleInfDefault => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 126, double.infinity); + + @override + String toString() { + return 'Monster{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}'; + } + + MonsterT unpack() => MonsterT( + pos: pos?.unpack(), + mana: mana, + hp: hp, + name: name, + inventory: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 14), + color: color, + testType: testType, + test: test, + test4: test4?.map((e) => e.unpack()).toList(), + testarrayofstring: const fb.ListReader(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 24), + testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(), + enemy: enemy?.unpack(), + testnestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 30), + testempty: testempty?.unpack(), + testbool: testbool, + testhashs32Fnv1: testhashs32Fnv1, + testhashu32Fnv1: testhashu32Fnv1, + testhashs64Fnv1: testhashs64Fnv1, + testhashu64Fnv1: testhashu64Fnv1, + testhashs32Fnv1a: testhashs32Fnv1a, + testhashu32Fnv1a: testhashu32Fnv1a, + testhashs64Fnv1a: testhashs64Fnv1a, + testhashu64Fnv1a: testhashu64Fnv1a, + testarrayofbools: const fb.ListReader(fb.BoolReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 52), + testf: testf, + testf2: testf2, + testf3: testf3, + testarrayofstring2: const fb.ListReader(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 60), + testarrayofsortedstruct: testarrayofsortedstruct?.map((e) => e.unpack()).toList(), + flex: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 64), + test5: test5?.map((e) => e.unpack()).toList(), + vectorOfLongs: const fb.ListReader(fb.Int64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 68), + vectorOfDoubles: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 70), + parentNamespaceTest: parentNamespaceTest?.unpack(), + vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(), + singleWeakReference: singleWeakReference, + vectorOfWeakReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 78), + vectorOfStrongReferrables: vectorOfStrongReferrables?.map((e) => e.unpack()).toList(), + coOwningReference: coOwningReference, + vectorOfCoOwningReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 84), + nonOwningReference: nonOwningReference, + vectorOfNonOwningReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 88), + anyUniqueType: anyUniqueType, + anyUnique: anyUnique, + anyAmbiguousType: anyAmbiguousType, + anyAmbiguous: anyAmbiguous, + vectorOfEnums: const fb.ListReader(Color.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 98), + signedEnum: signedEnum, + testrequirednestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 102), + scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList(), + nativeInline: nativeInline?.unpack(), + longEnumNonEnumDefault: longEnumNonEnumDefault, + longEnumNormalDefault: longEnumNormalDefault, + nanDefault: nanDefault, + infDefault: infDefault, + positiveInfDefault: positiveInfDefault, + infinityDefault: infinityDefault, + positiveInfinityDefault: positiveInfinityDefault, + negativeInfDefault: negativeInfDefault, + negativeInfinityDefault: negativeInfinityDefault, + doubleInfDefault: doubleInfDefault); + + static int pack(fb.Builder fbBuilder, MonsterT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +/// an example documentation comment: "monster object" +class MonsterT implements fb.Packable { + Vec3T? pos; + int mana; + int hp; + String? name; + List? inventory; + Color color; + AnyTypeId? testType; + dynamic test; + List? test4; + List? testarrayofstring; + /// an example documentation comment: this will end up in the generated code + /// multiline too + List? testarrayoftables; + MonsterT? enemy; + List? testnestedflatbuffer; + StatT? testempty; + bool testbool; + int testhashs32Fnv1; + int testhashu32Fnv1; + int testhashs64Fnv1; + int testhashu64Fnv1; + int testhashs32Fnv1a; + int testhashu32Fnv1a; + int testhashs64Fnv1a; + int testhashu64Fnv1a; + List? testarrayofbools; + double testf; + double testf2; + double testf3; + List? testarrayofstring2; + List? testarrayofsortedstruct; + List? flex; + List? test5; + List? vectorOfLongs; + List? vectorOfDoubles; + my_game.InParentNamespaceT? parentNamespaceTest; + List? vectorOfReferrables; + int singleWeakReference; + List? vectorOfWeakReferences; + List? vectorOfStrongReferrables; + int coOwningReference; + List? vectorOfCoOwningReferences; + int nonOwningReference; + List? vectorOfNonOwningReferences; + AnyUniqueAliasesTypeId? anyUniqueType; + dynamic anyUnique; + AnyAmbiguousAliasesTypeId? anyAmbiguousType; + dynamic anyAmbiguous; + List? vectorOfEnums; + Race signedEnum; + List? testrequirednestedflatbuffer; + List? scalarKeySortedTables; + TestT? nativeInline; + LongEnum longEnumNonEnumDefault; + LongEnum longEnumNormalDefault; + double nanDefault; + double infDefault; + double positiveInfDefault; + double infinityDefault; + double positiveInfinityDefault; + double negativeInfDefault; + double negativeInfinityDefault; + double doubleInfDefault; + + MonsterT({ + this.pos, + this.mana = 150, + this.hp = 100, + this.name, + this.inventory, + this.color = Color.Blue, + this.testType, + this.test, + this.test4, + this.testarrayofstring, + this.testarrayoftables, + this.enemy, + this.testnestedflatbuffer, + this.testempty, + this.testbool = false, + this.testhashs32Fnv1 = 0, + this.testhashu32Fnv1 = 0, + this.testhashs64Fnv1 = 0, + this.testhashu64Fnv1 = 0, + this.testhashs32Fnv1a = 0, + this.testhashu32Fnv1a = 0, + this.testhashs64Fnv1a = 0, + this.testhashu64Fnv1a = 0, + this.testarrayofbools, + this.testf = 3.14159, + this.testf2 = 3.0, + this.testf3 = 0.0, + this.testarrayofstring2, + this.testarrayofsortedstruct, + this.flex, + this.test5, + this.vectorOfLongs, + this.vectorOfDoubles, + this.parentNamespaceTest, + this.vectorOfReferrables, + this.singleWeakReference = 0, + this.vectorOfWeakReferences, + this.vectorOfStrongReferrables, + this.coOwningReference = 0, + this.vectorOfCoOwningReferences, + this.nonOwningReference = 0, + this.vectorOfNonOwningReferences, + this.anyUniqueType, + this.anyUnique, + this.anyAmbiguousType, + this.anyAmbiguous, + this.vectorOfEnums, + this.signedEnum = Race.None, + this.testrequirednestedflatbuffer, + this.scalarKeySortedTables, + this.nativeInline, + this.longEnumNonEnumDefault = LongEnum._default, + this.longEnumNormalDefault = LongEnum.LongOne, + this.nanDefault = double.nan, + this.infDefault = double.infinity, + this.positiveInfDefault = double.infinity, + this.infinityDefault = double.infinity, + this.positiveInfinityDefault = double.infinity, + this.negativeInfDefault = double.negativeInfinity, + this.negativeInfinityDefault = double.negativeInfinity, + this.doubleInfDefault = double.infinity}); + + @override + int pack(fb.Builder fbBuilder) { + final int? nameOffset = name == null ? null + : fbBuilder.writeString(name!); + final int? inventoryOffset = inventory == null ? null + : fbBuilder.writeListUint8(inventory!); + final int? testOffset = test?.pack(fbBuilder); + int? test4Offset; + if (test4 != null) { + for (var e in test4!) { e.pack(fbBuilder); } + test4Offset = fbBuilder.endStructVector(test4!.length); + } + final int? testarrayofstringOffset = testarrayofstring == null ? null + : fbBuilder.writeList(testarrayofstring!.map(fbBuilder.writeString).toList()); + final int? testarrayoftablesOffset = testarrayoftables == null ? null + : fbBuilder.writeList(testarrayoftables!.map((b) => b.pack(fbBuilder)).toList()); + final int? enemyOffset = enemy?.pack(fbBuilder); + final int? testnestedflatbufferOffset = testnestedflatbuffer == null ? null + : fbBuilder.writeListUint8(testnestedflatbuffer!); + final int? testemptyOffset = testempty?.pack(fbBuilder); + final int? testarrayofboolsOffset = testarrayofbools == null ? null + : fbBuilder.writeListBool(testarrayofbools!); + final int? testarrayofstring2Offset = testarrayofstring2 == null ? null + : fbBuilder.writeList(testarrayofstring2!.map(fbBuilder.writeString).toList()); + int? testarrayofsortedstructOffset; + if (testarrayofsortedstruct != null) { + for (var e in testarrayofsortedstruct!) { e.pack(fbBuilder); } + testarrayofsortedstructOffset = fbBuilder.endStructVector(testarrayofsortedstruct!.length); + } + final int? flexOffset = flex == null ? null + : fbBuilder.writeListUint8(flex!); + int? test5Offset; + if (test5 != null) { + for (var e in test5!) { e.pack(fbBuilder); } + test5Offset = fbBuilder.endStructVector(test5!.length); + } + final int? vectorOfLongsOffset = vectorOfLongs == null ? null + : fbBuilder.writeListInt64(vectorOfLongs!); + final int? vectorOfDoublesOffset = vectorOfDoubles == null ? null + : fbBuilder.writeListFloat64(vectorOfDoubles!); + final int? parentNamespaceTestOffset = parentNamespaceTest?.pack(fbBuilder); + final int? vectorOfReferrablesOffset = vectorOfReferrables == null ? null + : fbBuilder.writeList(vectorOfReferrables!.map((b) => b.pack(fbBuilder)).toList()); + final int? vectorOfWeakReferencesOffset = vectorOfWeakReferences == null ? null + : fbBuilder.writeListUint64(vectorOfWeakReferences!); + final int? vectorOfStrongReferrablesOffset = vectorOfStrongReferrables == null ? null + : fbBuilder.writeList(vectorOfStrongReferrables!.map((b) => b.pack(fbBuilder)).toList()); + final int? vectorOfCoOwningReferencesOffset = vectorOfCoOwningReferences == null ? null + : fbBuilder.writeListUint64(vectorOfCoOwningReferences!); + final int? vectorOfNonOwningReferencesOffset = vectorOfNonOwningReferences == null ? null + : fbBuilder.writeListUint64(vectorOfNonOwningReferences!); + final int? anyUniqueOffset = anyUnique?.pack(fbBuilder); + final int? anyAmbiguousOffset = anyAmbiguous?.pack(fbBuilder); + final int? vectorOfEnumsOffset = vectorOfEnums == null ? null + : fbBuilder.writeListUint8(vectorOfEnums!.map((f) => f.value).toList()); + final int? testrequirednestedflatbufferOffset = testrequirednestedflatbuffer == null ? null + : fbBuilder.writeListUint8(testrequirednestedflatbuffer!); + final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null ? null + : fbBuilder.writeList(scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList()); + fbBuilder.startTable(62); + if (pos != null) { + fbBuilder.addStruct(0, pos!.pack(fbBuilder)); + } + fbBuilder.addInt16(1, mana); + fbBuilder.addInt16(2, hp); + fbBuilder.addOffset(3, nameOffset); + fbBuilder.addOffset(5, inventoryOffset); + fbBuilder.addUint8(6, color.value); + fbBuilder.addUint8(7, testType?.value); + fbBuilder.addOffset(8, testOffset); + fbBuilder.addOffset(9, test4Offset); + fbBuilder.addOffset(10, testarrayofstringOffset); + fbBuilder.addOffset(11, testarrayoftablesOffset); + fbBuilder.addOffset(12, enemyOffset); + fbBuilder.addOffset(13, testnestedflatbufferOffset); + fbBuilder.addOffset(14, testemptyOffset); + fbBuilder.addBool(15, testbool); + fbBuilder.addInt32(16, testhashs32Fnv1); + fbBuilder.addUint32(17, testhashu32Fnv1); + fbBuilder.addInt64(18, testhashs64Fnv1); + fbBuilder.addUint64(19, testhashu64Fnv1); + fbBuilder.addInt32(20, testhashs32Fnv1a); + fbBuilder.addUint32(21, testhashu32Fnv1a); + fbBuilder.addInt64(22, testhashs64Fnv1a); + fbBuilder.addUint64(23, testhashu64Fnv1a); + fbBuilder.addOffset(24, testarrayofboolsOffset); + fbBuilder.addFloat32(25, testf); + fbBuilder.addFloat32(26, testf2); + fbBuilder.addFloat32(27, testf3); + fbBuilder.addOffset(28, testarrayofstring2Offset); + fbBuilder.addOffset(29, testarrayofsortedstructOffset); + fbBuilder.addOffset(30, flexOffset); + fbBuilder.addOffset(31, test5Offset); + fbBuilder.addOffset(32, vectorOfLongsOffset); + fbBuilder.addOffset(33, vectorOfDoublesOffset); + fbBuilder.addOffset(34, parentNamespaceTestOffset); + fbBuilder.addOffset(35, vectorOfReferrablesOffset); + fbBuilder.addUint64(36, singleWeakReference); + fbBuilder.addOffset(37, vectorOfWeakReferencesOffset); + fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset); + fbBuilder.addUint64(39, coOwningReference); + fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset); + fbBuilder.addUint64(41, nonOwningReference); + fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset); + fbBuilder.addUint8(43, anyUniqueType?.value); + fbBuilder.addOffset(44, anyUniqueOffset); + fbBuilder.addUint8(45, anyAmbiguousType?.value); + fbBuilder.addOffset(46, anyAmbiguousOffset); + fbBuilder.addOffset(47, vectorOfEnumsOffset); + fbBuilder.addInt8(48, signedEnum.value); + fbBuilder.addOffset(49, testrequirednestedflatbufferOffset); + fbBuilder.addOffset(50, scalarKeySortedTablesOffset); + if (nativeInline != null) { + fbBuilder.addStruct(51, nativeInline!.pack(fbBuilder)); + } + fbBuilder.addUint64(52, longEnumNonEnumDefault.value); + fbBuilder.addUint64(53, longEnumNormalDefault.value); + fbBuilder.addFloat32(54, nanDefault); + fbBuilder.addFloat32(55, infDefault); + fbBuilder.addFloat32(56, positiveInfDefault); + fbBuilder.addFloat32(57, infinityDefault); + fbBuilder.addFloat32(58, positiveInfinityDefault); + fbBuilder.addFloat32(59, negativeInfDefault); + fbBuilder.addFloat32(60, negativeInfinityDefault); + fbBuilder.addFloat64(61, doubleInfDefault); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'MonsterT{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}'; + } +} + +class _MonsterReader extends fb.TableReader { + const _MonsterReader(); + + @override + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); +} + +class MonsterBuilder { + MonsterBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(62); + } + + int addPos(int offset) { + fbBuilder.addStruct(0, offset); + return fbBuilder.offset; + } + int addMana(int? mana) { + fbBuilder.addInt16(1, mana); + return fbBuilder.offset; + } + int addHp(int? hp) { + fbBuilder.addInt16(2, hp); + return fbBuilder.offset; + } + int addNameOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + int addInventoryOffset(int? offset) { + fbBuilder.addOffset(5, offset); + return fbBuilder.offset; + } + int addColor(Color? color) { + fbBuilder.addUint8(6, color?.value); + return fbBuilder.offset; + } + int addTestType(AnyTypeId? testType) { + fbBuilder.addUint8(7, testType?.value); + return fbBuilder.offset; + } + int addTestOffset(int? offset) { + fbBuilder.addOffset(8, offset); + return fbBuilder.offset; + } + int addTest4Offset(int? offset) { + fbBuilder.addOffset(9, offset); + return fbBuilder.offset; + } + int addTestarrayofstringOffset(int? offset) { + fbBuilder.addOffset(10, offset); + return fbBuilder.offset; + } + int addTestarrayoftablesOffset(int? offset) { + fbBuilder.addOffset(11, offset); + return fbBuilder.offset; + } + int addEnemyOffset(int? offset) { + fbBuilder.addOffset(12, offset); + return fbBuilder.offset; + } + int addTestnestedflatbufferOffset(int? offset) { + fbBuilder.addOffset(13, offset); + return fbBuilder.offset; + } + int addTestemptyOffset(int? offset) { + fbBuilder.addOffset(14, offset); + return fbBuilder.offset; + } + int addTestbool(bool? testbool) { + fbBuilder.addBool(15, testbool); + return fbBuilder.offset; + } + int addTesthashs32Fnv1(int? testhashs32Fnv1) { + fbBuilder.addInt32(16, testhashs32Fnv1); + return fbBuilder.offset; + } + int addTesthashu32Fnv1(int? testhashu32Fnv1) { + fbBuilder.addUint32(17, testhashu32Fnv1); + return fbBuilder.offset; + } + int addTesthashs64Fnv1(int? testhashs64Fnv1) { + fbBuilder.addInt64(18, testhashs64Fnv1); + return fbBuilder.offset; + } + int addTesthashu64Fnv1(int? testhashu64Fnv1) { + fbBuilder.addUint64(19, testhashu64Fnv1); + return fbBuilder.offset; + } + int addTesthashs32Fnv1a(int? testhashs32Fnv1a) { + fbBuilder.addInt32(20, testhashs32Fnv1a); + return fbBuilder.offset; + } + int addTesthashu32Fnv1a(int? testhashu32Fnv1a) { + fbBuilder.addUint32(21, testhashu32Fnv1a); + return fbBuilder.offset; + } + int addTesthashs64Fnv1a(int? testhashs64Fnv1a) { + fbBuilder.addInt64(22, testhashs64Fnv1a); + return fbBuilder.offset; + } + int addTesthashu64Fnv1a(int? testhashu64Fnv1a) { + fbBuilder.addUint64(23, testhashu64Fnv1a); + return fbBuilder.offset; + } + int addTestarrayofboolsOffset(int? offset) { + fbBuilder.addOffset(24, offset); + return fbBuilder.offset; + } + int addTestf(double? testf) { + fbBuilder.addFloat32(25, testf); + return fbBuilder.offset; + } + int addTestf2(double? testf2) { + fbBuilder.addFloat32(26, testf2); + return fbBuilder.offset; + } + int addTestf3(double? testf3) { + fbBuilder.addFloat32(27, testf3); + return fbBuilder.offset; + } + int addTestarrayofstring2Offset(int? offset) { + fbBuilder.addOffset(28, offset); + return fbBuilder.offset; + } + int addTestarrayofsortedstructOffset(int? offset) { + fbBuilder.addOffset(29, offset); + return fbBuilder.offset; + } + int addFlexOffset(int? offset) { + fbBuilder.addOffset(30, offset); + return fbBuilder.offset; + } + int addTest5Offset(int? offset) { + fbBuilder.addOffset(31, offset); + return fbBuilder.offset; + } + int addVectorOfLongsOffset(int? offset) { + fbBuilder.addOffset(32, offset); + return fbBuilder.offset; + } + int addVectorOfDoublesOffset(int? offset) { + fbBuilder.addOffset(33, offset); + return fbBuilder.offset; + } + int addParentNamespaceTestOffset(int? offset) { + fbBuilder.addOffset(34, offset); + return fbBuilder.offset; + } + int addVectorOfReferrablesOffset(int? offset) { + fbBuilder.addOffset(35, offset); + return fbBuilder.offset; + } + int addSingleWeakReference(int? singleWeakReference) { + fbBuilder.addUint64(36, singleWeakReference); + return fbBuilder.offset; + } + int addVectorOfWeakReferencesOffset(int? offset) { + fbBuilder.addOffset(37, offset); + return fbBuilder.offset; + } + int addVectorOfStrongReferrablesOffset(int? offset) { + fbBuilder.addOffset(38, offset); + return fbBuilder.offset; + } + int addCoOwningReference(int? coOwningReference) { + fbBuilder.addUint64(39, coOwningReference); + return fbBuilder.offset; + } + int addVectorOfCoOwningReferencesOffset(int? offset) { + fbBuilder.addOffset(40, offset); + return fbBuilder.offset; + } + int addNonOwningReference(int? nonOwningReference) { + fbBuilder.addUint64(41, nonOwningReference); + return fbBuilder.offset; + } + int addVectorOfNonOwningReferencesOffset(int? offset) { + fbBuilder.addOffset(42, offset); + return fbBuilder.offset; + } + int addAnyUniqueType(AnyUniqueAliasesTypeId? anyUniqueType) { + fbBuilder.addUint8(43, anyUniqueType?.value); + return fbBuilder.offset; + } + int addAnyUniqueOffset(int? offset) { + fbBuilder.addOffset(44, offset); + return fbBuilder.offset; + } + int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId? anyAmbiguousType) { + fbBuilder.addUint8(45, anyAmbiguousType?.value); + return fbBuilder.offset; + } + int addAnyAmbiguousOffset(int? offset) { + fbBuilder.addOffset(46, offset); + return fbBuilder.offset; + } + int addVectorOfEnumsOffset(int? offset) { + fbBuilder.addOffset(47, offset); + return fbBuilder.offset; + } + int addSignedEnum(Race? signedEnum) { + fbBuilder.addInt8(48, signedEnum?.value); + return fbBuilder.offset; + } + int addTestrequirednestedflatbufferOffset(int? offset) { + fbBuilder.addOffset(49, offset); + return fbBuilder.offset; + } + int addScalarKeySortedTablesOffset(int? offset) { + fbBuilder.addOffset(50, offset); + return fbBuilder.offset; + } + int addNativeInline(int offset) { + fbBuilder.addStruct(51, offset); + return fbBuilder.offset; + } + int addLongEnumNonEnumDefault(LongEnum? longEnumNonEnumDefault) { + fbBuilder.addUint64(52, longEnumNonEnumDefault?.value); + return fbBuilder.offset; + } + int addLongEnumNormalDefault(LongEnum? longEnumNormalDefault) { + fbBuilder.addUint64(53, longEnumNormalDefault?.value); + return fbBuilder.offset; + } + int addNanDefault(double? nanDefault) { + fbBuilder.addFloat32(54, nanDefault); + return fbBuilder.offset; + } + int addInfDefault(double? infDefault) { + fbBuilder.addFloat32(55, infDefault); + return fbBuilder.offset; + } + int addPositiveInfDefault(double? positiveInfDefault) { + fbBuilder.addFloat32(56, positiveInfDefault); + return fbBuilder.offset; + } + int addInfinityDefault(double? infinityDefault) { + fbBuilder.addFloat32(57, infinityDefault); + return fbBuilder.offset; + } + int addPositiveInfinityDefault(double? positiveInfinityDefault) { + fbBuilder.addFloat32(58, positiveInfinityDefault); + return fbBuilder.offset; + } + int addNegativeInfDefault(double? negativeInfDefault) { + fbBuilder.addFloat32(59, negativeInfDefault); + return fbBuilder.offset; + } + int addNegativeInfinityDefault(double? negativeInfinityDefault) { + fbBuilder.addFloat32(60, negativeInfinityDefault); + return fbBuilder.offset; + } + int addDoubleInfDefault(double? doubleInfDefault) { + fbBuilder.addFloat64(61, doubleInfDefault); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MonsterObjectBuilder extends fb.ObjectBuilder { + final Vec3ObjectBuilder? _pos; + final int? _mana; + final int? _hp; + final String? _name; + final List? _inventory; + final Color? _color; + final AnyTypeId? _testType; + final dynamic _test; + final List? _test4; + final List? _testarrayofstring; + final List? _testarrayoftables; + final MonsterObjectBuilder? _enemy; + final List? _testnestedflatbuffer; + final StatObjectBuilder? _testempty; + final bool? _testbool; + final int? _testhashs32Fnv1; + final int? _testhashu32Fnv1; + final int? _testhashs64Fnv1; + final int? _testhashu64Fnv1; + final int? _testhashs32Fnv1a; + final int? _testhashu32Fnv1a; + final int? _testhashs64Fnv1a; + final int? _testhashu64Fnv1a; + final List? _testarrayofbools; + final double? _testf; + final double? _testf2; + final double? _testf3; + final List? _testarrayofstring2; + final List? _testarrayofsortedstruct; + final List? _flex; + final List? _test5; + final List? _vectorOfLongs; + final List? _vectorOfDoubles; + final my_game.InParentNamespaceObjectBuilder? _parentNamespaceTest; + final List? _vectorOfReferrables; + final int? _singleWeakReference; + final List? _vectorOfWeakReferences; + final List? _vectorOfStrongReferrables; + final int? _coOwningReference; + final List? _vectorOfCoOwningReferences; + final int? _nonOwningReference; + final List? _vectorOfNonOwningReferences; + final AnyUniqueAliasesTypeId? _anyUniqueType; + final dynamic _anyUnique; + final AnyAmbiguousAliasesTypeId? _anyAmbiguousType; + final dynamic _anyAmbiguous; + final List? _vectorOfEnums; + final Race? _signedEnum; + final List? _testrequirednestedflatbuffer; + final List? _scalarKeySortedTables; + final TestObjectBuilder? _nativeInline; + final LongEnum? _longEnumNonEnumDefault; + final LongEnum? _longEnumNormalDefault; + final double? _nanDefault; + final double? _infDefault; + final double? _positiveInfDefault; + final double? _infinityDefault; + final double? _positiveInfinityDefault; + final double? _negativeInfDefault; + final double? _negativeInfinityDefault; + final double? _doubleInfDefault; + + MonsterObjectBuilder({ + Vec3ObjectBuilder? pos, + int? mana, + int? hp, + String? name, + List? inventory, + Color? color, + AnyTypeId? testType, + dynamic test, + List? test4, + List? testarrayofstring, + List? testarrayoftables, + MonsterObjectBuilder? enemy, + List? testnestedflatbuffer, + StatObjectBuilder? testempty, + bool? testbool, + int? testhashs32Fnv1, + int? testhashu32Fnv1, + int? testhashs64Fnv1, + int? testhashu64Fnv1, + int? testhashs32Fnv1a, + int? testhashu32Fnv1a, + int? testhashs64Fnv1a, + int? testhashu64Fnv1a, + List? testarrayofbools, + double? testf, + double? testf2, + double? testf3, + List? testarrayofstring2, + List? testarrayofsortedstruct, + List? flex, + List? test5, + List? vectorOfLongs, + List? vectorOfDoubles, + my_game.InParentNamespaceObjectBuilder? parentNamespaceTest, + List? vectorOfReferrables, + int? singleWeakReference, + List? vectorOfWeakReferences, + List? vectorOfStrongReferrables, + int? coOwningReference, + List? vectorOfCoOwningReferences, + int? nonOwningReference, + List? vectorOfNonOwningReferences, + AnyUniqueAliasesTypeId? anyUniqueType, + dynamic anyUnique, + AnyAmbiguousAliasesTypeId? anyAmbiguousType, + dynamic anyAmbiguous, + List? vectorOfEnums, + Race? signedEnum, + List? testrequirednestedflatbuffer, + List? scalarKeySortedTables, + TestObjectBuilder? nativeInline, + LongEnum? longEnumNonEnumDefault, + LongEnum? longEnumNormalDefault, + double? nanDefault, + double? infDefault, + double? positiveInfDefault, + double? infinityDefault, + double? positiveInfinityDefault, + double? negativeInfDefault, + double? negativeInfinityDefault, + double? doubleInfDefault, + }) + : _pos = pos, + _mana = mana, + _hp = hp, + _name = name, + _inventory = inventory, + _color = color, + _testType = testType, + _test = test, + _test4 = test4, + _testarrayofstring = testarrayofstring, + _testarrayoftables = testarrayoftables, + _enemy = enemy, + _testnestedflatbuffer = testnestedflatbuffer, + _testempty = testempty, + _testbool = testbool, + _testhashs32Fnv1 = testhashs32Fnv1, + _testhashu32Fnv1 = testhashu32Fnv1, + _testhashs64Fnv1 = testhashs64Fnv1, + _testhashu64Fnv1 = testhashu64Fnv1, + _testhashs32Fnv1a = testhashs32Fnv1a, + _testhashu32Fnv1a = testhashu32Fnv1a, + _testhashs64Fnv1a = testhashs64Fnv1a, + _testhashu64Fnv1a = testhashu64Fnv1a, + _testarrayofbools = testarrayofbools, + _testf = testf, + _testf2 = testf2, + _testf3 = testf3, + _testarrayofstring2 = testarrayofstring2, + _testarrayofsortedstruct = testarrayofsortedstruct, + _flex = flex, + _test5 = test5, + _vectorOfLongs = vectorOfLongs, + _vectorOfDoubles = vectorOfDoubles, + _parentNamespaceTest = parentNamespaceTest, + _vectorOfReferrables = vectorOfReferrables, + _singleWeakReference = singleWeakReference, + _vectorOfWeakReferences = vectorOfWeakReferences, + _vectorOfStrongReferrables = vectorOfStrongReferrables, + _coOwningReference = coOwningReference, + _vectorOfCoOwningReferences = vectorOfCoOwningReferences, + _nonOwningReference = nonOwningReference, + _vectorOfNonOwningReferences = vectorOfNonOwningReferences, + _anyUniqueType = anyUniqueType, + _anyUnique = anyUnique, + _anyAmbiguousType = anyAmbiguousType, + _anyAmbiguous = anyAmbiguous, + _vectorOfEnums = vectorOfEnums, + _signedEnum = signedEnum, + _testrequirednestedflatbuffer = testrequirednestedflatbuffer, + _scalarKeySortedTables = scalarKeySortedTables, + _nativeInline = nativeInline, + _longEnumNonEnumDefault = longEnumNonEnumDefault, + _longEnumNormalDefault = longEnumNormalDefault, + _nanDefault = nanDefault, + _infDefault = infDefault, + _positiveInfDefault = positiveInfDefault, + _infinityDefault = infinityDefault, + _positiveInfinityDefault = positiveInfinityDefault, + _negativeInfDefault = negativeInfDefault, + _negativeInfinityDefault = negativeInfinityDefault, + _doubleInfDefault = doubleInfDefault; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? nameOffset = _name == null ? null + : fbBuilder.writeString(_name!); + final int? inventoryOffset = _inventory == null ? null + : fbBuilder.writeListUint8(_inventory!); + final int? testOffset = _test?.getOrCreateOffset(fbBuilder); + final int? test4Offset = _test4 == null ? null + : fbBuilder.writeListOfStructs(_test4!); + final int? testarrayofstringOffset = _testarrayofstring == null ? null + : fbBuilder.writeList(_testarrayofstring!.map(fbBuilder.writeString).toList()); + final int? testarrayoftablesOffset = _testarrayoftables == null ? null + : fbBuilder.writeList(_testarrayoftables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? enemyOffset = _enemy?.getOrCreateOffset(fbBuilder); + final int? testnestedflatbufferOffset = _testnestedflatbuffer == null ? null + : fbBuilder.writeListUint8(_testnestedflatbuffer!); + final int? testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder); + final int? testarrayofboolsOffset = _testarrayofbools == null ? null + : fbBuilder.writeListBool(_testarrayofbools!); + final int? testarrayofstring2Offset = _testarrayofstring2 == null ? null + : fbBuilder.writeList(_testarrayofstring2!.map(fbBuilder.writeString).toList()); + final int? testarrayofsortedstructOffset = _testarrayofsortedstruct == null ? null + : fbBuilder.writeListOfStructs(_testarrayofsortedstruct!); + final int? flexOffset = _flex == null ? null + : fbBuilder.writeListUint8(_flex!); + final int? test5Offset = _test5 == null ? null + : fbBuilder.writeListOfStructs(_test5!); + final int? vectorOfLongsOffset = _vectorOfLongs == null ? null + : fbBuilder.writeListInt64(_vectorOfLongs!); + final int? vectorOfDoublesOffset = _vectorOfDoubles == null ? null + : fbBuilder.writeListFloat64(_vectorOfDoubles!); + final int? parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder); + final int? vectorOfReferrablesOffset = _vectorOfReferrables == null ? null + : fbBuilder.writeList(_vectorOfReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? vectorOfWeakReferencesOffset = _vectorOfWeakReferences == null ? null + : fbBuilder.writeListUint64(_vectorOfWeakReferences!); + final int? vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables == null ? null + : fbBuilder.writeList(_vectorOfStrongReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences == null ? null + : fbBuilder.writeListUint64(_vectorOfCoOwningReferences!); + final int? vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences == null ? null + : fbBuilder.writeListUint64(_vectorOfNonOwningReferences!); + final int? anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder); + final int? anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder); + final int? vectorOfEnumsOffset = _vectorOfEnums == null ? null + : fbBuilder.writeListUint8(_vectorOfEnums!.map((f) => f.value).toList()); + final int? testrequirednestedflatbufferOffset = _testrequirednestedflatbuffer == null ? null + : fbBuilder.writeListUint8(_testrequirednestedflatbuffer!); + final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null ? null + : fbBuilder.writeList(_scalarKeySortedTables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + fbBuilder.startTable(62); + if (_pos != null) { + fbBuilder.addStruct(0, _pos!.finish(fbBuilder)); + } + fbBuilder.addInt16(1, _mana); + fbBuilder.addInt16(2, _hp); + fbBuilder.addOffset(3, nameOffset); + fbBuilder.addOffset(5, inventoryOffset); + fbBuilder.addUint8(6, _color?.value); + fbBuilder.addUint8(7, _testType?.value); + fbBuilder.addOffset(8, testOffset); + fbBuilder.addOffset(9, test4Offset); + fbBuilder.addOffset(10, testarrayofstringOffset); + fbBuilder.addOffset(11, testarrayoftablesOffset); + fbBuilder.addOffset(12, enemyOffset); + fbBuilder.addOffset(13, testnestedflatbufferOffset); + fbBuilder.addOffset(14, testemptyOffset); + fbBuilder.addBool(15, _testbool); + fbBuilder.addInt32(16, _testhashs32Fnv1); + fbBuilder.addUint32(17, _testhashu32Fnv1); + fbBuilder.addInt64(18, _testhashs64Fnv1); + fbBuilder.addUint64(19, _testhashu64Fnv1); + fbBuilder.addInt32(20, _testhashs32Fnv1a); + fbBuilder.addUint32(21, _testhashu32Fnv1a); + fbBuilder.addInt64(22, _testhashs64Fnv1a); + fbBuilder.addUint64(23, _testhashu64Fnv1a); + fbBuilder.addOffset(24, testarrayofboolsOffset); + fbBuilder.addFloat32(25, _testf); + fbBuilder.addFloat32(26, _testf2); + fbBuilder.addFloat32(27, _testf3); + fbBuilder.addOffset(28, testarrayofstring2Offset); + fbBuilder.addOffset(29, testarrayofsortedstructOffset); + fbBuilder.addOffset(30, flexOffset); + fbBuilder.addOffset(31, test5Offset); + fbBuilder.addOffset(32, vectorOfLongsOffset); + fbBuilder.addOffset(33, vectorOfDoublesOffset); + fbBuilder.addOffset(34, parentNamespaceTestOffset); + fbBuilder.addOffset(35, vectorOfReferrablesOffset); + fbBuilder.addUint64(36, _singleWeakReference); + fbBuilder.addOffset(37, vectorOfWeakReferencesOffset); + fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset); + fbBuilder.addUint64(39, _coOwningReference); + fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset); + fbBuilder.addUint64(41, _nonOwningReference); + fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset); + fbBuilder.addUint8(43, _anyUniqueType?.value); + fbBuilder.addOffset(44, anyUniqueOffset); + fbBuilder.addUint8(45, _anyAmbiguousType?.value); + fbBuilder.addOffset(46, anyAmbiguousOffset); + fbBuilder.addOffset(47, vectorOfEnumsOffset); + fbBuilder.addInt8(48, _signedEnum?.value); + fbBuilder.addOffset(49, testrequirednestedflatbufferOffset); + fbBuilder.addOffset(50, scalarKeySortedTablesOffset); + if (_nativeInline != null) { + fbBuilder.addStruct(51, _nativeInline!.finish(fbBuilder)); + } + fbBuilder.addUint64(52, _longEnumNonEnumDefault?.value); + fbBuilder.addUint64(53, _longEnumNormalDefault?.value); + fbBuilder.addFloat32(54, _nanDefault); + fbBuilder.addFloat32(55, _infDefault); + fbBuilder.addFloat32(56, _positiveInfDefault); + fbBuilder.addFloat32(57, _infinityDefault); + fbBuilder.addFloat32(58, _positiveInfinityDefault); + fbBuilder.addFloat32(59, _negativeInfDefault); + fbBuilder.addFloat32(60, _negativeInfinityDefault); + fbBuilder.addFloat64(61, _doubleInfDefault); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class TypeAliases { + TypeAliases._(this._bc, this._bcOffset); + factory TypeAliases(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TypeAliasesReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get i8 => const fb.Int8Reader().vTableGet(_bc, _bcOffset, 4, 0); + int get u8 => const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 6, 0); + int get i16 => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 0); + int get u16 => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 10, 0); + int get i32 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 12, 0); + int get u32 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 14, 0); + int get i64 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 16, 0); + int get u64 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 18, 0); + double get f32 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 20, 0.0); + double get f64 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 22, 0.0); + List? get v8 => const fb.Int8ListReader().vTableGetNullable(_bc, _bcOffset, 24); + List? get vf64 => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 26); + + @override + String toString() { + return 'TypeAliases{i8: ${i8}, u8: ${u8}, i16: ${i16}, u16: ${u16}, i32: ${i32}, u32: ${u32}, i64: ${i64}, u64: ${u64}, f32: ${f32}, f64: ${f64}, v8: ${v8}, vf64: ${vf64}}'; + } + + TypeAliasesT unpack() => TypeAliasesT( + i8: i8, + u8: u8, + i16: i16, + u16: u16, + i32: i32, + u32: u32, + i64: i64, + u64: u64, + f32: f32, + f64: f64, + v8: const fb.Int8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 24), + vf64: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 26)); + + static int pack(fb.Builder fbBuilder, TypeAliasesT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TypeAliasesT implements fb.Packable { + int i8; + int u8; + int i16; + int u16; + int i32; + int u32; + int i64; + int u64; + double f32; + double f64; + List? v8; + List? vf64; + + TypeAliasesT({ + this.i8 = 0, + this.u8 = 0, + this.i16 = 0, + this.u16 = 0, + this.i32 = 0, + this.u32 = 0, + this.i64 = 0, + this.u64 = 0, + this.f32 = 0.0, + this.f64 = 0.0, + this.v8, + this.vf64}); + + @override + int pack(fb.Builder fbBuilder) { + final int? v8Offset = v8 == null ? null + : fbBuilder.writeListInt8(v8!); + final int? vf64Offset = vf64 == null ? null + : fbBuilder.writeListFloat64(vf64!); + fbBuilder.startTable(12); + fbBuilder.addInt8(0, i8); + fbBuilder.addUint8(1, u8); + fbBuilder.addInt16(2, i16); + fbBuilder.addUint16(3, u16); + fbBuilder.addInt32(4, i32); + fbBuilder.addUint32(5, u32); + fbBuilder.addInt64(6, i64); + fbBuilder.addUint64(7, u64); + fbBuilder.addFloat32(8, f32); + fbBuilder.addFloat64(9, f64); + fbBuilder.addOffset(10, v8Offset); + fbBuilder.addOffset(11, vf64Offset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TypeAliasesT{i8: ${i8}, u8: ${u8}, i16: ${i16}, u16: ${u16}, i32: ${i32}, u32: ${u32}, i64: ${i64}, u64: ${u64}, f32: ${f32}, f64: ${f64}, v8: ${v8}, vf64: ${vf64}}'; + } +} + +class _TypeAliasesReader extends fb.TableReader { + const _TypeAliasesReader(); + + @override + TypeAliases createObject(fb.BufferContext bc, int offset) => + TypeAliases._(bc, offset); +} + +class TypeAliasesBuilder { + TypeAliasesBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(12); + } + + int addI8(int? i8) { + fbBuilder.addInt8(0, i8); + return fbBuilder.offset; + } + int addU8(int? u8) { + fbBuilder.addUint8(1, u8); + return fbBuilder.offset; + } + int addI16(int? i16) { + fbBuilder.addInt16(2, i16); + return fbBuilder.offset; + } + int addU16(int? u16) { + fbBuilder.addUint16(3, u16); + return fbBuilder.offset; + } + int addI32(int? i32) { + fbBuilder.addInt32(4, i32); + return fbBuilder.offset; + } + int addU32(int? u32) { + fbBuilder.addUint32(5, u32); + return fbBuilder.offset; + } + int addI64(int? i64) { + fbBuilder.addInt64(6, i64); + return fbBuilder.offset; + } + int addU64(int? u64) { + fbBuilder.addUint64(7, u64); + return fbBuilder.offset; + } + int addF32(double? f32) { + fbBuilder.addFloat32(8, f32); + return fbBuilder.offset; + } + int addF64(double? f64) { + fbBuilder.addFloat64(9, f64); + return fbBuilder.offset; + } + int addV8Offset(int? offset) { + fbBuilder.addOffset(10, offset); + return fbBuilder.offset; + } + int addVf64Offset(int? offset) { + fbBuilder.addOffset(11, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TypeAliasesObjectBuilder extends fb.ObjectBuilder { + final int? _i8; + final int? _u8; + final int? _i16; + final int? _u16; + final int? _i32; + final int? _u32; + final int? _i64; + final int? _u64; + final double? _f32; + final double? _f64; + final List? _v8; + final List? _vf64; + + TypeAliasesObjectBuilder({ + int? i8, + int? u8, + int? i16, + int? u16, + int? i32, + int? u32, + int? i64, + int? u64, + double? f32, + double? f64, + List? v8, + List? vf64, + }) + : _i8 = i8, + _u8 = u8, + _i16 = i16, + _u16 = u16, + _i32 = i32, + _u32 = u32, + _i64 = i64, + _u64 = u64, + _f32 = f32, + _f64 = f64, + _v8 = v8, + _vf64 = vf64; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? v8Offset = _v8 == null ? null + : fbBuilder.writeListInt8(_v8!); + final int? vf64Offset = _vf64 == null ? null + : fbBuilder.writeListFloat64(_vf64!); + fbBuilder.startTable(12); + fbBuilder.addInt8(0, _i8); + fbBuilder.addUint8(1, _u8); + fbBuilder.addInt16(2, _i16); + fbBuilder.addUint16(3, _u16); + fbBuilder.addInt32(4, _i32); + fbBuilder.addUint32(5, _u32); + fbBuilder.addInt64(6, _i64); + fbBuilder.addUint64(7, _u64); + fbBuilder.addFloat32(8, _f32); + fbBuilder.addFloat64(9, _f64); + fbBuilder.addOffset(10, v8Offset); + fbBuilder.addOffset(11, vf64Offset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/monster_test_my_game_generated.dart b/third_party/flatbuffers/dart/test/monster_test_my_game_generated.dart new file mode 100644 index 00000000000..461d06dfa85 --- /dev/null +++ b/third_party/flatbuffers/dart/test/monster_test_my_game_generated.dart @@ -0,0 +1,79 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './monster_test_my_game.example_generated.dart' as my_game_example; +import './monster_test_my_game.example2_generated.dart' as my_game_example2; + +import './include_test1_generated.dart'; + +class InParentNamespace { + InParentNamespace._(this._bc, this._bcOffset); + factory InParentNamespace(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _InParentNamespaceReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + + @override + String toString() { + return 'InParentNamespace{}'; + } + + InParentNamespaceT unpack() => InParentNamespaceT(); + + static int pack(fb.Builder fbBuilder, InParentNamespaceT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class InParentNamespaceT implements fb.Packable { + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'InParentNamespaceT{}'; + } +} + +class _InParentNamespaceReader extends fb.TableReader { + const _InParentNamespaceReader(); + + @override + InParentNamespace createObject(fb.BufferContext bc, int offset) => + InParentNamespace._(bc, offset); +} + +class InParentNamespaceObjectBuilder extends fb.ObjectBuilder { + + InParentNamespaceObjectBuilder(); + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/dart/test/monsterdata_test.mon b/third_party/flatbuffers/dart/test/monsterdata_test.mon new file mode 100644 index 00000000000..da0ed8698fc Binary files /dev/null and b/third_party/flatbuffers/dart/test/monsterdata_test.mon differ diff --git a/third_party/flatbuffers/docs/README.md b/third_party/flatbuffers/docs/README.md new file mode 100644 index 00000000000..b4695a2eb14 --- /dev/null +++ b/third_party/flatbuffers/docs/README.md @@ -0,0 +1,24 @@ +# Documentation + +This is the source of the FlatBuffers documentation, that is served at +https://flatbuffers.dev. + + +## Local Building + +The documentation can be built and served locally during development, see [https//flatbuffers.dev/contributing/#local-development] for full details. + +__tl;dr__ + +Install: + +``` +pip install mkdocs-material +pip install mkdocs-redirects +``` + +Build and Serve: + +``` +mkdocs serve -f docs/mkdocs.yml +``` \ No newline at end of file diff --git a/third_party/flatbuffers/docs/mkdocs.yml b/third_party/flatbuffers/docs/mkdocs.yml new file mode 100644 index 00000000000..ce1496512d1 --- /dev/null +++ b/third_party/flatbuffers/docs/mkdocs.yml @@ -0,0 +1,159 @@ +site_name: FlatBuffers Docs +docs_dir: source +site_url: https://flatbuffers.dev +repo_name: google/FlatBuffers +repo_url: https://github.com/google/flatbuffers +edit_uri: edit/master/docs/source/ +copyright: Copyright © 2025 Google +theme: + name: material + logo: assets/flatbuffers_logo.svg + icon: + repo: fontawesome/brands/github + custom_dir: overrides + palette: + # Palette toggle for light mode + - scheme: default + toggle: + icon: material/brightness-7 + name: Switch to dark mode + + # Palette toggle for dark mode + - scheme: slate + toggle: + icon: material/brightness-4 + name: Switch to light mode + + features: + # Allows code block annotations + - content.code.annotate + + # Allows content tabs to link together + - content.tabs.link + + # Expand nav folders by default + - navigation.expand + + # Enable the footer + - navigation.footer + + # Auto hide the header after scrolling + - header.autohide + + - content.action.edit + +extra: + social: + - icon: fontawesome/brands/github + link: https://github.com/google/flatbuffers + + - icon: fontawesome/brands/discord + link: https:///discord.gg/6qgKs3R + + - icon: fontawesome/brands/x-twitter + link: https://twitter.com/dbaileychess + +plugins: + # Use redirects to update links from the original docs to the new ones. + # + # https://github.com/mkdocs/mkdocs-redirects + - redirects: + # Note the .html are suffixed with .md to avoid warnings. Got from + # https://github.com/mkdocs/mkdocs-redirects/issues/51#issuecomment-2408548029 + redirect_maps: + 'flatbuffers_guide_building.html.md': 'building.md' + 'flatbuffers_guide_tutorial.html.md': 'tutorial.md' + 'flatbuffers_guide_using_schema_compiler.html.md': 'flatc.md' + 'flatbuffers_guide_writing_schema.html.md': 'schema.md' + 'md__schemas.html.md': 'schema.md' # issue #8485 + 'flatbuffers_guide_use_c.html.md': 'languages/c.md' + 'flatbuffers_guide_use_cpp.html.md': 'languages/cpp.md' + 'flatbuffers_guide_use_c-sharp.html.md': 'languages/c_sharp.md' + 'flatbuffers_guide_use_dart.html.md': 'languages/dart.md' + 'flatbuffers_guide_use_go.html.md': 'languages/go.md' + 'flatbuffers_guide_use_java.html.md': 'languages/java.md' + 'flatbuffers_guide_use_javascript.html.md': 'languages/javascript.md' + 'flatbuffers_guide_use_lobster.html.md': 'languages/lobster.md' + 'flatbuffers_guide_use_lua.html.md': 'languages/lua.md' + 'flatbuffers_guide_use_php.html.md': 'languages/php.md' + 'flatbuffers_guide_use_python.html.md': 'languages/python.md' + 'flatbuffers_guide_use_rust.html.md': 'languages/rust.md' + 'flatbuffers_guide_use_swift.html.md': 'languages/swift.md' + 'flatbuffers_guide_use_typescript.html.md': 'languages/typescript.md' + 'flatbuffers_grpc_guide_use_cpp.html.md' : "languages/cpp.md#grpc" + 'flatbuffers_support.html.md': 'support.md' + 'flatbuffers_white_paper.html.md': 'white_paper.md' + 'flatbuffers_grammar.html.md': 'grammar.md' + 'flatbuffers_internals.html.md': 'internals.md' + 'intermediate_representation.html.md': 'intermediate_representation.md' + 'flatbuffers_benchmarks.html.md': 'benchmarks.md' + 'flexbuffers.html.md': 'flexbuffers.md' + 'contributing.html.md': 'contributing.md' + + +markdown_extensions: + - admonition + - attr_list + - md_in_html + - pymdownx.critic + - pymdownx.details + - pymdownx.emoji: + emoji_index: !!python/name:material.extensions.emoji.twemoji + emoji_generator: !!python/name:material.extensions.emoji.to_svg + - pymdownx.snippets: + # Allows direct embedded of remote files + url_download: true + - pymdownx.superfences + - pymdownx.tabbed: + alternate_style: true + slugify: !!python/object/apply:pymdownx.slugs.slugify + kwds: + case: lower + - pymdownx.highlight: + extend_pygments_lang: + # PHP wasn't highlighting correctly. This is a work around found + # https://github.com/squidfunk/mkdocs-material/issues/138#issuecomment-2294025627 + - name: php + lang: php + options: + startinline: true + - tables + + + +nav: + - Overview: "index.md" + - Quick Start: "quick_start.md" + - Tutorial: "tutorial.md" + - Compiler (flatc): + - Building: "building.md" + - Using: "flatc.md" + - Schema (.fbs): + - Overview: "schema.md" + - Evolution: "evolution.md" + - Grammar: "grammar.md" + - Language Guides: + - C: "languages/c.md" + - C++: "languages/cpp.md" + - C#: "languages/c_sharp.md" + - Dart: "languages/dart.md" + - Go: "languages/go.md" + - Java: "languages/java.md" + - JavasScript: "languages/javascript.md" + - Kotlin: "languages/kotlin.md" + - Lobster: "languages/lobster.md" + - Lua: "languages/lua.md" + - PHP: "languages/php.md" + - Python: "languages/python.md" + - Rust: "languages/rust.md" + - Swift: "languages/swift.md" + - TypeScript: "languages/typescript.md" + - Supported Configurations: "support.md" + - White Paper: "white_paper.md" + - Advanced: + - FlatBuffers Internals: "internals.md" + - Intermediate Representation: "intermediate_representation.md" + - Annotating Buffers (.afb): "annotation.md" + - Benchmarks: "benchmarks.md" + - FlexBuffers (Schema-less version): "flexbuffers.md" + - Contributing: "contributing.md" diff --git a/third_party/flatbuffers/docs/overrides/404.html b/third_party/flatbuffers/docs/overrides/404.html new file mode 100644 index 00000000000..f7981fcf4f5 --- /dev/null +++ b/third_party/flatbuffers/docs/overrides/404.html @@ -0,0 +1,10 @@ +{% extends "main.html" %} + + +{% block content %} +

404 - Not found

+
+ FlatBuffers has migrated their documentation system recently. + + Please file an issue indicating the broken link. +{% endblock %} \ No newline at end of file diff --git a/third_party/flatbuffers/docs/overrides/main.html b/third_party/flatbuffers/docs/overrides/main.html new file mode 100644 index 00000000000..94d9808cc76 --- /dev/null +++ b/third_party/flatbuffers/docs/overrides/main.html @@ -0,0 +1 @@ +{% extends "base.html" %} diff --git a/third_party/flatbuffers/docs/source/CNAME b/third_party/flatbuffers/docs/source/CNAME new file mode 100644 index 00000000000..398878ab794 --- /dev/null +++ b/third_party/flatbuffers/docs/source/CNAME @@ -0,0 +1 @@ +flatbuffers.dev \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/annotation.md b/third_party/flatbuffers/docs/source/annotation.md new file mode 100644 index 00000000000..1e66eb67c4f --- /dev/null +++ b/third_party/flatbuffers/docs/source/annotation.md @@ -0,0 +1,149 @@ +# Annotating FlatBuffers + +This provides a way to annotate flatbuffer binary data, byte-by-byte, with a +schema. It is useful for development purposes and understanding the details of +the internal format. + +## Annotating + +Given a `schema`, as either a plain-text (`.fbs`) or a binary schema (`.bfbs`), +and `binary` file(s) that were created by the `schema`. You can annotate them +using: + +```sh +flatc --annotate SCHEMA -- BINARY_FILES... +``` + +This will produce a set of annotated files (`.afb` Annotated FlatBuffer) +corresponding to the input binary files. + +### Example + +Taken from the [tests/annotated_binary](https://github.com/google/flatbuffers/tree/master/tests/annotated_binary). + +```sh +cd tests/annotated_binary +../../flatc --annotate annotated_binary.fbs -- annotated_binary.bin +``` + +Which will produce a `annotated_binary.afb` file in the current directory. + +The `annotated_binary.bin` is the flatbufer binary of the data contained within +`annotated_binary.json`, which was made by the following command: + +```sh +..\..\flatc -b annotated_binary.fbs annotated_binary.json +``` + +## .afb Text Format + +Currently there is a built-in text-based format for outputting the annotations. +A full example is shown here: +[`annotated_binary.afb`](https://github.com/google/flatbuffers/blob/master/tests/annotated_binary/annotated_binary.afb) + +The data is organized as a table with fixed [columns](#columns) grouped into +Binary [sections](#binary-sections) and [regions](#binary-regions), starting +from the beginning of the binary (offset `0`). + +### Columns + +The columns are as follows: + +1. The offset from the start of the binary, expressed in hexadecimal format + (e.g. `+0x003c`). + + The prefix `+` is added to make searching for the offset (compared to some + random value) a bit easier. + +2. The raw binary data, expressed in hexadecimal format. + + This is in the little endian format the buffer uses internally and what you + would see with a normal binary text viewer. + +3. The type of the data. + + This may be the type specified in the schema or some internally defined + types: + + + | Internal Type | Purpose | + |---------------|----------------------------------------------------| + | `VOffset16` | Virtual table offset, relative to the table offset | + | `UOffset32` | Unsigned offset, relative to the current offset | + | `SOffset32` | Signed offset, relative to the current offset | + + +4. The value of the data. + + This is shown in big endian format that is generally written for humans to + consume (e.g. `0x0013`). As well as the "casted" value (e.g. `0x0013 `is + `19` in decimal) in parentheses. + +5. Notes about the particular data. + + This describes what the data is about, either some internal usage, or tied + to the schema. + +### Binary Sections + +The file is broken up into Binary Sections, which are comprised of contiguous +[binary regions](#binary-regions) that are logically grouped together. For +example, a binary section may be a single instance of a flatbuffer `Table` or +its `vtable`. The sections may be labelled with the name of the associated type, +as defined in the input schema. + +An example of a `vtable` Binary Section that is associated with the user-defined +`AnnotateBinary.Bar` table. + +``` +vtable (AnnotatedBinary.Bar): + +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00A2 | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00A4 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00A6 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) +``` + +These are purely annotative, there is no embedded information about these +regions in the flatbuffer itself. + +### Binary Regions + +Binary regions are contiguous bytes regions that are grouped together to form +some sort of value, e.g. a `scalar` or an array of scalars. A binary region may +be split up over multiple text lines, if the size of the region is large. + +#### Annotation Example + +Looking at an example binary region: + +``` +vtable (AnnotatedBinary.Bar): + +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable +``` + +The first column (`+0x00A0`) is the offset to this region from the beginning of +the buffer. + +The second column are the raw bytes (hexadecimal) that make up this region. +These are expressed in the little-endian format that flatbuffers uses for the +wire format. + +The third column is the type to interpret the bytes as. For the above example, +the type is `uint16_t` which is a 16-bit unsigned integer type. + +The fourth column shows the raw bytes as a compacted, big-endian value. The raw +bytes are duplicated in this fashion since it is more intuitive to read the data +in the big-endian format (e.g., `0x0008`). This value is followed by the decimal +representation of the value (e.g., `(8)`). For strings, the raw string value is +shown instead. + +The fifth column is a textual comment on what the value is. As much metadata as +known is provided. + +### Offsets + +If the type in the 3rd column is of an absolute offset (`SOffet32` or +`Offset32`), the fourth column also shows an `Loc: +0x025A` value which shows +where in the binary this region is pointing to. These values are absolute from +the beginning of the file, their calculation from the raw value in the 4th +column depends on the context. \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/assets/flatbuffers_logo.svg b/third_party/flatbuffers/docs/source/assets/flatbuffers_logo.svg new file mode 100644 index 00000000000..e302c07dff0 --- /dev/null +++ b/third_party/flatbuffers/docs/source/assets/flatbuffers_logo.svg @@ -0,0 +1,318 @@ + + + + diff --git a/third_party/flatbuffers/docs/source/benchmarks.md b/third_party/flatbuffers/docs/source/benchmarks.md new file mode 100644 index 00000000000..848f4e39b5c --- /dev/null +++ b/third_party/flatbuffers/docs/source/benchmarks.md @@ -0,0 +1,63 @@ +C++ Benchmarks {#flatbuffers_benchmarks} +========== + +Comparing against other serialization solutions, running on Windows 7 +64bit. We use the LITE runtime for Protocol Buffers (less code / lower +overhead), Rapid JSON (one of the fastest C++ JSON parsers around), +and pugixml, also one of the fastest XML parsers. + +We also compare against code that doesn't use a serialization library +at all (the column "Raw structs"), which is what you get if you write +hardcoded code that just writes structs. This is the fastest possible, +but of course is not cross platform nor has any kind of forwards / +backwards compatibility. + +We compare against Flatbuffers with the binary wire format (as +intended), and also with JSON as the wire format with the optional JSON +parser (which, using a schema, parses JSON into a binary buffer that can +then be accessed as before). + +The benchmark object is a set of about 10 objects containing an array, 4 +strings, and a large variety of int/float scalar values of all sizes, +meant to be representative of game data, e.g. a scene format. + +| | FlatBuffers (binary) | Protocol Buffers LITE | Rapid JSON | FlatBuffers (JSON) | pugixml | Raw structs | +|--------------------------------------------------------|-----------------------|-----------------------|-----------------------|------------------------| ----------------------| ----------------------| +| Decode + Traverse + Dealloc (1 million times, seconds) | 0.08 | 302 | 583 | 105 | 196 | 0.02 | +| Decode / Traverse / Dealloc (breakdown) | 0 / 0.08 / 0 | 220 / 0.15 / 81 | 294 / 0.9 / 287 | 70 / 0.08 / 35 | 41 / 3.9 / 150 | 0 / 0.02 / 0 | +| Encode (1 million times, seconds) | 3.2 | 185 | 650 | 169 | 273 | 0.15 | +| Wire format size (normal / zlib, bytes) | 344 / 220 | 228 / 174 | 1475 / 322 | 1029 / 298 | 1137 / 341 | 312 / 187 | +| Memory needed to store decoded wire (bytes / blocks) | 0 / 0 | 760 / 20 | 65689 / 4 | 328 / 1 | 34194 / 3 | 0 / 0 | +| Transient memory allocated during decode (KB) | 0 | 1 | 131 | 4 | 34 | 0 | +| Generated source code size (KB) | 4 | 61 | 0 | 4 | 0 | 0 | +| Field access in handwritten traversal code | typed accessors | typed accessors | manual error checking | typed accessors | manual error checking | typed but no safety | +| Library source code (KB) | 15 | some subset of 3800 | 87 | 43 | 327 | 0 | + +### Some other serialization systems we compared against but did not benchmark (yet), in rough order of applicability: + +- Cap'n'Proto promises to reduce Protocol Buffers much like FlatBuffers does, + though with a more complicated binary encoding and less flexibility (no + optional fields to allow deprecating fields or serializing with missing + fields for which defaults exist). + It currently also isn't fully cross-platform portable (lack of VS support). +- msgpack: has very minimal forwards/backwards compatibility support when used + with the typed C++ interface. Also lacks VS2010 support. +- Thrift: very similar to Protocol Buffers, but appears to be less efficient, + and have more dependencies. +- YAML: a superset of JSON and otherwise very similar. Used by e.g. Unity. +- C# comes with built-in serialization functionality, as used by Unity also. + Being tied to the language, and having no automatic versioning support + limits its applicability. +- Project Anarchy (the free mobile engine by Havok) comes with a serialization + system, that however does no automatic versioning (have to code around new + fields manually), is very much tied to the rest of the engine, and works + without a schema to generate code (tied to your C++ class definition). + +### Code for benchmarks + +Code for these benchmarks sits in `benchmarks/` in git branch `benchmarks`. +It sits in its own branch because it has submodule dependencies that the main +project doesn't need, and the code standards do not meet those of the main +project. Please read `benchmarks/cpp/README.txt` before working with the code. + +
diff --git a/third_party/flatbuffers/docs/source/building.md b/third_party/flatbuffers/docs/source/building.md new file mode 100644 index 00000000000..93c4d2b84b1 --- /dev/null +++ b/third_party/flatbuffers/docs/source/building.md @@ -0,0 +1,177 @@ +# Building + +## Building with CMake + +The distribution main build system is configured by +[`cmake`](https://www.cmake.org) which allows you to build the project for any +platform. + +### Configuration + +Use `cmake` to configure a project based on your environment and platform. + +=== "Unix" + + ```sh + cmake -G "Unix Makefiles" -DCMAKE_BUILD_TYPE=Release + ``` + +To use `clang` instead of `gcc` you may need to set prepend some environment +variables e.g. `CC=/usr/bin/clang CXX=/usr/bin/clang++ cmake -G "Unix +MakeFiles"` + +=== "Windows" + + ```sh + cmake -G "Visual Studio 17 2022" -DCMAKE_BUILD_TYPE=Release + ``` + +=== "MacOS" + + ```sh + cmake -G "Xcode" -DCMAKE_BUILD_TYPE=Release + ``` + +#### Strict Mode + +By default, `cmake` will configure targets to **not** build with strict warnings +on (e.g. `-Werror` or `/WX`). This may cause into issues when submitting code +changes since our CI requires the code to compile in strict mode. + +To enable the extra warnings, turn on strict mode with the +`FLATBUFFERS_STRICT_MODE` cmake option. + +```cmake +cmake -DFLATBUFFERS_STRICT_MODE=ON +``` + + +### Building + +Once the project files are generated, build as normal for your platform. + +=== "Unix" + + ```sh + make -j + ``` + +=== "Windows" + + ```sh + msbuild.exe FlatBuffers.sln + ``` + +=== "MacOS" + + ```sh + xcodebuild -toolchain clang -configuration Release + ``` + + + + + + +## Building with Bazel + +You can use [Bazelisk](https://github.com/bazelbuild/bazelisk) to manage your Bazel environment. +For Swift support, you also need Clang and [Swift SDK](https://download.swift.org/). + +```sh +curl -sL --fail https://github.com/bazelbuild/bazelisk/releases/download/v1.25.0/bazelisk-linux-amd64 -o bazelisk && chmod +x bazelisk +sudo apt install -y clang +SWIFT_VERSION="6.0.3" +curl -L https://download.swift.org/swift-${SWIFT_VERSION}-release/debian12/swift-${SWIFT_VERSION}-RELEASE/swift-${SWIFT_VERSION}-RELEASE-debian12.tar.gz | tar xz +CC=clang PATH=$PATH:$(pwd)/swift-${SWIFT_VERSION}-RELEASE-debian12/usr/bin bazel build //... +CC=clang PATH=$PATH:$(pwd)/swift-${SWIFT_VERSION}-RELEASE-debian12/usr/bin bazel test //... +``` + +If you are unsure which versions to use, check our CI config at `.bazelci/presubmit.yml`. + +## Building with VCPKG + +You can download and install flatbuffers using the [vcpkg](https://github.com/Microsoft/vcpkg/) dependency manager: + + git clone https://github.com/Microsoft/vcpkg.git + cd vcpkg + ./bootstrap-vcpkg.sh + ./vcpkg integrate install + ./vcpkg install flatbuffers + +The flatbuffers port in vcpkg is kept up to date by Microsoft team members and community contributors. +If the version is out of date, please [create an issue or pull request](https://github.com/Microsoft/vcpkg) on the vcpkg repository. + + + +## Building for Android + +There is a `flatbuffers/android` directory that contains all you need to build +the test executable on android (use the included `build_apk.sh` script, or use +`ndk_build` / `adb` etc. as usual). Upon running, it will output to the log +if tests succeeded or not. + +You may also run an android sample from inside the `flatbuffers/samples`, by +running the `android_sample.sh` script. Optionally, you may go to the +`flatbuffers/samples/android` folder and build the sample with the +`build_apk.sh` script or `ndk_build` / `adb` etc. + +## Using FlatBuffers in your own projects + +For C++, there is usually no runtime to compile, as the code consists of a +single header, `include/flatbuffers/flatbuffers.h`. You should add the +`include` folder to your include paths. If you wish to be +able to load schemas and/or parse text into binary buffers at runtime, +you additionally need the other headers in `include/flatbuffers`. You must +also compile/link `src/idl_parser.cpp` (and `src/idl_gen_text.cpp` if you +also want to be able convert binary to text). + +To see how to include FlatBuffers in any of our supported languages, please +view the [Tutorial](tutorial.md) and select your appropriate +language using the radio buttons. + +### Using in CMake-based projects +If you want to use FlatBuffers in a project which already uses CMake, then a more +robust and flexible approach is to build FlatBuffers as part of that project directly. +This is done by making the FlatBuffers source code available to the main build +and adding it using CMake's `add_subdirectory()` command. This has the +significant advantage that the same compiler and linker settings are used +between FlatBuffers and the rest of your project, so issues associated with using +incompatible libraries (eg debug/release), etc. are avoided. This is +particularly useful on Windows. + +Suppose you put FlatBuffers source code in directory `${FLATBUFFERS_SRC_DIR}`. +To build it as part of your project, add following code to your `CMakeLists.txt` file: +```cmake +# Add FlatBuffers directly to our build. This defines the `flatbuffers` target. +add_subdirectory(${FLATBUFFERS_SRC_DIR} + ${CMAKE_CURRENT_BINARY_DIR}/flatbuffers-build + EXCLUDE_FROM_ALL) + +# Now simply link against flatbuffers as needed to your already declared target. +# The flatbuffers target carry header search path automatically if CMake > 2.8.11. +target_link_libraries(own_project_target PRIVATE flatbuffers) +``` +When build your project the `flatbuffers` library will be compiled and linked +to a target as part of your project. + +#### Override default depth limit of nested objects +To override [the depth limit of recursion](languages/cpp.md), +add this directive: +```cmake +set(FLATBUFFERS_MAX_PARSING_DEPTH 16) +``` +to `CMakeLists.txt` file before `add_subdirectory(${FLATBUFFERS_SRC_DIR})` line. + +## Downloading binaries +You can download the binaries from the +[GitHub release page](https://github.com/google/flatbuffers/releases). + +We generate [SLSA3 signatures](http://slsa.dev) using the OpenSSF's [slsa-framework/slsa-github-generator](https://github.com/slsa-framework/slsa-github-generator). To verify the binaries: +1. Install the verification tool from [slsa-framework/slsa-verifier#installation](https://github.com/slsa-framework/slsa-verifier#installation) +1. Download the file named `attestation.intoto.jsonl` from the GitHub release +1. Run: +```shell +$ slsa-verifier -artifact-path -provenance attestation.intoto.jsonl -source github.com/google/flatbuffers -tag + PASSED: Verified SLSA provenance +``` \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/contributing.md b/third_party/flatbuffers/docs/source/contributing.md new file mode 100644 index 00000000000..a65b60ac5ee --- /dev/null +++ b/third_party/flatbuffers/docs/source/contributing.md @@ -0,0 +1,80 @@ +# Contributing + +We encourage community contributions to FlatBuffers through pull requests at the +main +[http://github.com/google/flatbuffers](http://github.com/google/flatbuffers) +repository. + +!!! note + + The FlatBuffers project is not staffed by any full time Google employee, and + is managed by a small team of 20%ers. So response time and expertise vary. + +## Before you contribute + +Before we can use your contributions, you __must__ sign one of the following license agreements. The agreements are self-served at the following links. + +Our code review process will automatically check if you have signed the CLA, so +don't fret. Though it may be prudent to check before spending a lot of time on +contribution. + +### Individual Contributions + +For individuals, the [Google Individual +Contributor License Agreement +(CLA)](https://cla.developers.google.com/about/google-individual?csw=1) which is +self served at the link. The CLA is required since you own the copyright to your +changes, even after your contribution becomes part of our codebase, so we need +your permission to use and distribute your code. + +### Corporate Contributions + +Contributions made by corporations are covered by the [Google Software Grant and +Corporate Contributor License +Agreement](https://cla.developers.google.com/about/google-corporate). + +## Code Reviews + +All submissions require a code review via Github Pull Requests. + +1. Please adhere to the [Google Style Guide](https://google.github.io/styleguide/cppguide.html) for the language(s) you are submitting in. +2. Keep PRs small and focused. Its good practice and makes it more likely your PR will be approved. +3. Please add tests if possible. +4. Include descriptive commit messages and context to the change/issues fixed. + +## Documentation + +FlatBuffers uses [MkDocs](https://www.mkdocs.org/) to generate the static +documentation pages served at +[https://flatbuffers.dev](https://flatbuffers.dev). Specifically, we use the +[Material for MkDocs](https://squidfunk.github.io/mkdocs-material/) framework. + +The documentation source is contained in the main repo under the +[docs/](https://github.com/google/flatbuffers/tree/master/docs) directory. This +[automatically](https://github.com/google/flatbuffers/blob/46cc3d6432da17cca7694777dcce12e49dd48387/.github/workflows/docs.yml#L6-L11) get built and published when the commit is made. + +### Local Development + +We encourage contributors to keep the documentation up-to-date as well, and it +is easy to with `MkDocs` local building and serving tools. + +First install `mkdocs-material` (see +[Installation](https://squidfunk.github.io/mkdocs-material/getting-started/) for +other ways) + +``` +pip install mkdocs-material +pip install mkdocs-redirects +``` + +Then, in the `root` directory of flatbuffers, run + +``` +mkdocs serve -f docs/mkdocs.yml +``` + +This will continually watch the repo for changes to the documentation and serve +the rendered pages locally. + +Submit your documentation changes with your code changes and they will +automatically get published when your code is submitted. \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/evolution.md b/third_party/flatbuffers/docs/source/evolution.md new file mode 100644 index 00000000000..0f22cac722b --- /dev/null +++ b/third_party/flatbuffers/docs/source/evolution.md @@ -0,0 +1,276 @@ +# Evolution + +FlatBuffers enables the [schema](schema.md) to evolve over time while still +maintaining forwards and backwards compatibility with old flatbuffers. + +Some rules must be followed to ensure the evolution of a schema is valid. + +## Rules + +Adding new tables, vectors, structs to the schema is always allowed. Its only +when you add a new field to a [`table`](schema.md#tables) that certain rules +must be followed. + +### Addition + +**New fields MUST be added to the end of the table definition.** + +This allows older data to still be read correctly (giving you the default value +of the added field if accessed). + +Older code will simply ignore the new field in the flatbuffer. + +You can ignore this rule if you use the `id` attribute on all the fields of a +table. + +### Removal + +**You MUST not remove a field from the schema, even if you don't use it +anymore.** You simply stop writing them to the buffer. + +Its encouraged to mark the field deprecated by adding the `deprecated` +attribute. This will skip the generation of accessors and setters in the code, +to enforce the field not to be used any more. + +### Name Changes + +Its generally OK to change the name of tables and fields, as these are not +serialized to the buffer. It may break code that would have to be refactored +with the updated name. + +## Examples + +The following examples uses a base schema and attempts to evolve it a few times. +The versions are tracked by `V1`, `V2`, etc.. and `CodeV1` means code compiled +against the `V1` schema. + +### Table Evolution + +Lets start with a simple table `T` with two fields. + +```c++ title="Schema V1" +table T { + a:int; + b:int; +} +``` + +=== "Well Evolved" + + First lets extend the table with a new field. + + ```c++ title="Schema V2" + table T { + a:int; + b:int; + c:int; + } + ``` + + This is OK. `CodeV1` reading `V2` data will simply ignore the presence of the + new field `c`. `CodeV2` reading `V1` data will get a default value (0) when + reading `c`. + + ```c++ title="Schema V3" + table T { + a:int (deprecated); + b:int; + c:int; + } + ``` + + This is OK, removing field `a` via deprecation. `CodeV1`, `CodeV2` and `CodeV3` + reading `V3` data will now always get the default value of `a`, since it is not + present. `CodeV3` cannot write `a` anymore. `CodeV3` reading old data (`V1` or + `V2`) will not be able to access the field anymore, since no generated accessors + are omitted. + +=== "Improper Addition" + + Add a new field, but this time at the beginning. + + ```c++ title="Schema V2" + table T { + c:int; + a:int; + b:int; + } + ``` + + This is NOT OK, as it makes `V2` incompatible. `CodeV1` reading `V2` data + will access `a` but will read `c` data. + + `CodeV2` reading `V1` data will access `c` but will read `a` data. + +=== "Improper Deletion" + + Remove a field from the schema. + + ```c++ title="Schema V2" + table T { + b:int; + } + ``` + + This is NOT OK. `CodeV1` reading `V2` data will access `a` but read `b` data. + + `CodeV2` reading `V1` data will access `b` but will read `a` data. + +=== "Proper Reordering" + + Lets add a new field to the beginning, but use `id` attributes. + + ```c++ title="Schema V2" + table T { + c:int (id: 2); + a:int (id: 0); + b:int (id: 1); + } + ``` + + This is OK. This adds the a new field in the beginning, but because all the + `id` attributes were added, it is OK. + +=== "Changing Types" + + Let change the types of the fields. + + ```c++ title="Schema V2" + table T { + a:uint; + b:uint; + } + ``` + + This is MAYBE OK, and only in the case where the type change is the same + width. This is tricky if the `V1` data contained any negative numbers. So + this should be done with care. + +=== "Changing Defaults" + + Lets change the default values of the existing fields. + + ```c++ title="Schema V2" + table T { + a:int = 1; + b:int = 2; + } + ``` + + This is NOT OK. Any `V1` data that did not have a value written to the + buffer relied on generated code to provide the default value. + + There MAY be cases where this is OK, if you control all the producers and + consumers, and you can update them in tandem. + +=== "Renaming Fields" + + Lets change the name of the fields + + ```c++ title="Schema V2" + table T { + aa:int; + bb:int; + } + ``` + + This is generally OK. You've renamed fields will break all code and JSON + files that use this schema, but you can refactor those without affecting the + binary data, since the binary only address fields by id and offset, not by + names. + +### Union Evolution + +Lets start with a simple union `U` with two members. + +```c++ title="Schema V1" +union U { + A, + B +} +``` + +=== "Well Evolved" + + Lets add a another variant to the end. + + ```c++ title="Schema V2" + union U { + A, + B, + another_a: A + } + ``` + + This is OK. `CodeV1` will not recognize the `another_a`. + +=== "Improper Evolved" + + Lets add a another variant to the middle. + + ```c++ title="Schema V2" + union U { + A, + another_a: A, + B + } + ``` + + This is NOT OK. `CodeV1` reading `V2` data will interpret `B` as `another_a`. + `CodeV2` reading `V1` data will interpret `another_a` as `B`. + +=== "Evolved With Discriminant" + + Lets add a another variant to the middle, this time adding a union "discriminant". + + ```c++ title="Schema V2" + union U { + A = 1, + another_a: A = 3, + B = 2 + } + ``` + + This is OK. Its like you added it to the end, but using the discriminant + value to physically place it elsewhere in the union. + +## Version Control + +FlatBuffers relies on new field declarations being added at the end, and earlier +declarations to not be removed, but be marked deprecated when needed. We think +this is an improvement over the manual number assignment that happens in +Protocol Buffers (and which is still an option using the `id` attribute +mentioned above). + +One place where this is possibly problematic however is source control. If user +`A` adds a field, generates new binary data with this new schema, then tries to +commit both to source control after user `B` already committed a new field also, +and just auto-merges the schema, the binary files are now invalid compared to +the new schema. + +The solution of course is that you should not be generating binary data before +your schema changes have been committed, ensuring consistency with the rest of +the world. If this is not practical for you, use explicit field `id`s, which +should always generate a merge conflict if two people try to allocate the same +id. + +## Checking Conformity + +To check that schema are properly evolved, the [`flatc`](flatc.md) compiler has +a [option](flatc.md#additional-options) to do just that: + +```sh +--conform FILE +``` + +Where `FILE` is the base schema the rest of the input schemas must evolve from. +It returns `0` if they are properly evolved, otherwise returns a non-zero value +and provides errors on the reason why the schema are not properly evolved. + +As an example, the following checks if `schema_v2.fbs` is properly evolved from +`schema_v1.fbs`. + +```sh +flatc --conform schema_v1.fbs schema_v2.fbs +``` + diff --git a/third_party/flatbuffers/docs/source/flatc.md b/third_party/flatbuffers/docs/source/flatc.md new file mode 100644 index 00000000000..6fcbf8f50de --- /dev/null +++ b/third_party/flatbuffers/docs/source/flatc.md @@ -0,0 +1,303 @@ +# FlatBuffers Compiler (`flatc`) + +The main compiler for FlatBuffers is called `flatc` and is used to convert +schema definitions into generated code files for a variety of languages. + +After [building](building.md) `flatc`, it is used as follows: + +```sh +flatc [ GENERATOR_OPTIONS ] [ -o PATH ] [- I PATH ] + FILES... + [ -- BINARY_FILES... ] +``` + +* The `GENERATOR_OPTIONS` specify the language(s) to compile code for as well as +various features to enable/disable. + +* The `-o PATH` specifies the path where the generated files are placed. It +defaults to the current path if not specified. + +* The `-I PATH` specifies the paths where included schema files are located. It + defaults to the current path if not specified. + +## Input Files + +`FILES...` specifies one or more schema or data files to process. They are +processed in the order provided. + +### Schema Files + +For schema files, language specifiers indicate what languages to generate code +for. + + * `--cpp`: C++ + * `--java`: Java + * `--kotlin`: Kotlin + * `--csharp`: C# + * `--go`: Golang + * `--python`: Python + * `--js`: JavaScript + * `--ts`: TypeScript + * `--php`: PHP + * `--dart`: Dart + * `--lua`: Lua + * `--lobster`: Lobster + * `--rust`: Rust + * `--swift`: Swift + * `--nim`: Nim + +Additionally, adding: + + * `--grpc` Will generate RPC stub code for gRPC (not available in all + languages) + +### Data Files + +If `FILES...` contain data files, they can be exported to either a binary or +JSON representation. + +* `--binary`, `-b`: Generate a binary file containing a serialized flatbuffer. +* `--json`, `-j`: Generate JSON file from a serialized flatbuffer. + +Both options require the corresponding schema file to be included first in the +list of `FILES...`. + +=== "To Binary" + + To serialize the JSON data in `mydata.json` using the schema `myschema.fbs`: + + ```sh + flatc --binary myschema.fbs mydata.json + ``` + + This will generate a `mydata_wire.bin` file containing the serialized + flatbuffer data. + +=== "To JSON" + + To convert the serialized binary flatbuffer `mydata.bin` using the schema + `myschema.fbs` to JSON: + + ```sh + flatc --json myschema.fbs mydata.bin + ``` + + This will generate a `mydata.json` file. + + +### Additional options + +- `-o PATH` : Output all generated files to PATH (either absolute, or + relative to the current directory). If omitted, PATH will be the + current directory. PATH should end in your systems path separator, + e.g. `/` or `\`. + +- `-I PATH` : when encountering `include` statements, attempt to load the + files from this path. Paths will be tried in the order given, and if all + fail (or none are specified) it will try to load relative to the path of + the schema file being parsed. + +- `-M` : Print make rules for generated files. + +- `--strict-json` : Require & generate strict JSON (field names are enclosed + in quotes, no trailing commas in tables/vectors). By default, no quotes are + required/generated, and trailing commas are allowed. + +- `--allow-non-utf8` : Pass non-UTF-8 input through parser and emit nonstandard + \x escapes in JSON. (Default is to raise parse error on non-UTF-8 input.) + +- `--natural-utf8` : Output strings with UTF-8 as human-readable strings. + By default, UTF-8 characters are printed as \uXXXX escapes." + +- `--defaults-json` : Output fields whose value is equal to the default value + when writing JSON text. + +- `--no-prefix` : Don't prefix enum values in generated C++ by their enum + type. + +- `--scoped-enums` : Use C++11 style scoped and strongly typed enums in + generated C++. This also implies `--no-prefix`. + +- `--no-emit-min-max-enum-values` : Disable generation of MIN and MAX + enumerated values for scoped enums and prefixed enums. + +- `--gen-includes` : (deprecated), this is the default behavior. + If the original behavior is required (no include + statements) use `--no-includes.` + +- `--no-includes` : Don't generate include statements for included schemas the + generated file depends on (C++ / Python). + +- `--gen-mutable` : Generate additional non-const accessors for mutating + FlatBuffers in-place. + +- `--gen-onefile` : Generate single output file for C#, Go, and Python. + +- `--gen-name-strings` : Generate type name functions for C++. + +- `--gen-object-api` : Generate an additional object-based API. This API is + more convenient for object construction and mutation than the base API, + at the cost of efficiency (object allocation). Recommended only to be used + if other options are insufficient. + +- `--gen-compare` : Generate operator== for object-based API types. + +- `--gen-nullable` : Add Clang \_Nullable for C++ pointer. or @Nullable for Java. + +- `--gen-generated` : Add @Generated annotation for Java. + +- `--gen-jvmstatic` : Add @JvmStatic annotation for Kotlin methods + in companion object for interop from Java to Kotlin. + +- `--gen-all` : Generate not just code for the current schema files, but + for all files it includes as well. If the language uses a single file for + output (by default the case for C++ and JS), all code will end up in + this one file. + +- `--cpp-include` : Adds an #include in generated file + +- `--cpp-ptr-type T` : Set object API pointer type (default std::unique_ptr) + +- `--cpp-str-type T` : Set object API string type (default std::string) + T::c_str(), T::length() and T::empty() must be supported. + The custom type also needs to be constructible from std::string (see the + --cpp-str-flex-ctor option to change this behavior). + +- `--cpp-str-flex-ctor` : Don't construct custom string types by passing + std::string from Flatbuffers, but (char* + length). This allows efficient + construction of custom string types, including zero-copy construction. + +- `--no-cpp-direct-copy` : Don't generate direct copy methods for C++ + object-based API. + +- `--cpp-std CPP_STD` : Generate a C++ code using features of selected C++ standard. + Supported `CPP_STD` values: + * `c++0x` - generate code compatible with old compilers (VS2010), + * `c++11` - use C++11 code generator (default), + * `c++17` - use C++17 features in generated code (experimental). + +- `--object-prefix` : Customise class prefix for C++ object-based API. + +- `--object-suffix` : Customise class suffix for C++ object-based API. + +- `--go-namespace` : Generate the overrided namespace in Golang. + +- `--go-import` : Generate the overrided import for flatbuffers in Golang. + (default is "github.com/google/flatbuffers/go"). + +- `--raw-binary` : Allow binaries without a file_indentifier to be read. + This may crash flatc given a mismatched schema. + +- `--size-prefixed` : Input binaries are size prefixed buffers. + +- `--proto`: Expect input files to be .proto files (protocol buffers). + Output the corresponding .fbs file. + Currently supports: `package`, `message`, `enum`, nested declarations, + `import` (use `-I` for paths), `extend`, `oneof`, `group`. + Does not support, but will skip without error: `option`, `service`, + `extensions`, and most everything else. + +- `--oneof-union` : Translate .proto oneofs to flatbuffer unions. + +- `--grpc` : Generate GRPC interfaces for the specified languages. + +- `--schema`: Serialize schemas instead of JSON (use with -b). This will + output a binary version of the specified schema that itself corresponds + to the reflection/reflection.fbs schema. Loading this binary file is the + basis for reflection functionality. + +- `--bfbs-comments`: Add doc comments to the binary schema files. + +- `--conform FILE` : Specify a schema the following schemas should be + an evolution of. Gives errors if not. Useful to check if schema + modifications don't break schema evolution rules. + +- `--conform-includes PATH` : Include path for the schema given with + `--conform PATH`. + +- `--filename-suffix SUFFIX` : The suffix appended to the generated + file names. Default is '\_generated'. + +- `--filename-ext EXTENSION` : The extension appended to the generated + file names. Default is language-specific (e.g. "h" for C++). This + should not be used when multiple languages are specified. + +- `--include-prefix PATH` : Prefix this path to any generated include + statements. + +- `--keep-prefix` : Keep original prefix of schema include statement. + +- `--reflect-types` : Add minimal type reflection to code generation. + +- `--reflect-names` : Add minimal type/name reflection. + +- `--root-type T` : Select or override the default root_type. + +- `--require-explicit-ids` : When parsing schemas, require explicit ids (id: x). + +- `--force-defaults` : Emit default values in binary output from JSON. + +- `--force-empty` : When serializing from object API representation, force + strings and vectors to empty rather than null. + +- `--force-empty-vectors` : When serializing from object API representation, force + vectors to empty rather than null. + +- `--flexbuffers` : Used with "binary" and "json" options, it generates + data using schema-less FlexBuffers. + +- `--no-warnings` : Inhibit all warning messages. + +- `--cs-global-alias` : Prepend `global::` to all user generated csharp classes and structs. + +- `--json-nested-bytes` : Allow a nested_flatbuffer field to be parsed as a + vector of bytes in JSON, which is unsafe unless checked by a verifier + afterwards. + +- `--python-no-type-prefix-suffix` : Skip emission of Python functions that are prefixed + with typenames + +- `--python-typing` : Generate Python type annotations + +Additional gRPC options: + +- `--grpc-filename-suffix`: `[C++]` An optional suffix for the generated + files' names. For example, compiling gRPC for C++ with + `--grpc-filename-suffix=.fbs` will generate `{name}.fbs.h` and + `{name}.fbs.cc` files. + +- `--grpc-additional-header`: `[C++]` Additional headers to include in the + generated files. + +- `--grpc-search-path`: `[C++]` An optional prefix for the gRPC runtime path. + For example, compiling gRPC for C++ with `--grpc-search-path=some/path` will + generate the following includes: + + ```cpp + #include "some/path/grpcpp/impl/codegen/async_stream.h" + #include "some/path/grpcpp/impl/codegen/async_unary_call.h" + #include "some/path/grpcpp/impl/codegen/method_handler.h" + ... + ``` + +- `--grpc-use-system-headers`: `[C++]` Whether to generate `#include
` + instead of `#include "header.h"` for all headers when compiling gRPC for + C++. For example, compiling gRPC for C++ with `--grpc-use-system-headers` + will generate the following includes: + + ```cpp + #include + #include + #include + ... + ``` + + NOTE: This option can be negated with `--no-grpc-use-system-headers`. + +- `--grpc-python-typed-handlers`: `[Python]` Whether to generate the typed + handlers that use the generated Python classes instead of raw bytes for + requests/responses. + +NOTE: short-form options for generators are deprecated, use the long form +whenever possible. + diff --git a/third_party/flatbuffers/docs/source/flexbuffers.md b/third_party/flatbuffers/docs/source/flexbuffers.md new file mode 100644 index 00000000000..bf8bbcc474a --- /dev/null +++ b/third_party/flatbuffers/docs/source/flexbuffers.md @@ -0,0 +1,204 @@ +FlexBuffers {#flexbuffers} +========== + +FlatBuffers was designed around schemas, because when you want maximum +performance and data consistency, strong typing is helpful. + +There are however times when you want to store data that doesn't fit a +schema, because you can't know ahead of time what all needs to be stored. + +For this, FlatBuffers has a dedicated format, called FlexBuffers. +This is a binary format that can be used in conjunction +with FlatBuffers (by storing a part of a buffer in FlexBuffers +format), or also as its own independent serialization format. + +While it loses the strong typing, you retain the most unique advantage +FlatBuffers has over other serialization formats (schema-based or not): +FlexBuffers can also be accessed without parsing / copying / object allocation. +This is a huge win in efficiency / memory friendly-ness, and allows unique +use cases such as mmap-ing large amounts of free-form data. + +FlexBuffers' design and implementation allows for a very compact encoding, +combining automatic pooling of strings with automatic sizing of containers to +their smallest possible representation (8/16/32/64 bits). Many values and +offsets can be encoded in just 8 bits. While a schema-less representation is +usually more bulky because of the need to be self-descriptive, FlexBuffers +generates smaller binaries for many cases than regular FlatBuffers. + +FlexBuffers is still slower than regular FlatBuffers though, so we recommend to +only use it if you need it. + + +# Usage in C++ + +Include the header `flexbuffers.h`, which in turn depends on `flatbuffers.h` +and `util.h`. + +To create a buffer: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} +flexbuffers::Builder fbb; +fbb.Int(13); +fbb.Finish(); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +You create any value, followed by `Finish`. Unlike FlatBuffers which requires +the root value to be a table, here any value can be the root, including a lonely +int value. + +You can now access the `std::vector` that contains the encoded value +as `fbb.GetBuffer()`. Write it, send it, or store it in a parent FlatBuffer. In +this case, the buffer is just 3 bytes in size. + +To read this value back, you could just say: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} +auto root = flexbuffers::GetRoot(my_buffer); +int64_t i = root.AsInt64(); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +FlexBuffers stores ints only as big as needed, so it doesn't differentiate +between different sizes of ints. You can ask for the 64 bit version, +regardless of what you put in. In fact, since you demand to read the root +as an int, if you supply a buffer that actually contains a float, or a +string with numbers in it, it will convert it for you on the fly as well, +or return 0 if it can't. If instead you actually want to know what is inside +the buffer before you access it, you can call `root.GetType()` or `root.IsInt()` +etc. + +Here's a slightly more complex value you could write instead of `fbb.Int` above: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} +fbb.Map([&]() { + fbb.Vector("vec", [&]() { + fbb.Int(-100); + fbb.String("Fred"); + fbb.IndirectFloat(4.0f); + }); + fbb.UInt("foo", 100); +}); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +This stores the equivalent of the JSON value +`{ vec: [ -100, "Fred", 4.0 ], foo: 100 }`. The root is a dictionary that has +just two key-value pairs, with keys `vec` and `foo`. Unlike FlatBuffers, it +actually has to store these keys in the buffer (which it does only once if +you store multiple such objects, by pooling key values), but also unlike +FlatBuffers it has no restriction on the keys (fields) that you use. + +The map constructor uses a C++11 Lambda to group its children, but you can +also use more conventional start/end calls if you prefer. + +The first value in the map is a vector. You'll notice that unlike FlatBuffers, +you can use mixed types. There is also a `TypedVector` variant that only +allows a single type, and uses a bit less memory. + +`IndirectFloat` is an interesting feature that allows you to store values +by offset rather than inline. Though that doesn't make any visible change +to the user, the consequence is that large values (especially doubles or +64 bit ints) that occur more than once can be shared (see ReuseValue). +Another use case is inside of vectors, where the largest element makes +up the size of all elements (e.g. a single double forces all elements to +64bit), so storing a lot of small integers together with a double is more efficient if the double is indirect. + +Accessing it: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cpp} +auto map = flexbuffers::GetRoot(my_buffer).AsMap(); +map.size(); // 2 +auto vec = map["vec"].AsVector(); +vec.size(); // 3 +vec[0].AsInt64(); // -100; +vec[1].AsString().c_str(); // "Fred"; +vec[1].AsInt64(); // 0 (Number parsing failed). +vec[2].AsDouble(); // 4.0 +vec[2].AsString().IsTheEmptyString(); // true (Wrong Type). +vec[2].AsString().c_str(); // "" (This still works though). +vec[2].ToString().c_str(); // "4" (Or have it converted). +map["foo"].AsUInt8(); // 100 +map["unknown"].IsNull(); // true +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +# Usage in Java + +Java implementation follows the C++ one, closely. + +For creating the equivalent of the same JSON `{ vec: [ -100, "Fred", 4.0 ], foo: 100 }`, +one could use the following code: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} +FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512), + FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); +int smap = builder.startMap(); +int svec = builder.startVector(); +builder.putInt(-100); +builder.putString("Fred"); +builder.putFloat(4.0); +builder.endVector("vec", svec, false, false); +builder.putInt("foo", 100); +builder.endMap(null, smap); +ByteBuffer bb = builder.finish(); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Similarly, to read the data, just: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} +FlexBuffers.Map map = FlexBuffers.getRoot(bb).asMap(); +map.size(); // 2 +FlexBuffers.Vector vec = map.get("vec").asVector(); +vec.size(); // 3 +vec.get(0).asLong(); // -100; +vec.get(1).asString(); // "Fred"; +vec.get(1).asLong(); // 0 (Number parsing failed). +vec.get(2).asFloat(); // 4.0 +vec.get(2).asString().isEmpty(); // true (Wrong Type). +vec.get(2).asString(); // "" (This still works though). +vec.get(2).toString(); // "4.0" (Or have it converted). +map.get("foo").asUInt(); // 100 +map.get("unknown").isNull(); // true +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +# Binary encoding + +A description of how FlexBuffers are encoded is in the +[internals](internals.md) document. + + +# Nesting inside a FlatBuffer + +You can mark a field as containing a FlexBuffer, e.g. + + a:[ubyte] (flexbuffer); + +A special accessor will be generated that allows you to access the root value +directly, e.g. `a_flexbuffer_root().AsInt64()`. + + +# Efficiency tips + +* Vectors generally are a lot more efficient than maps, so prefer them over maps + when possible for small objects. Instead of a map with keys `x`, `y` and `z`, + use a vector. Better yet, use a typed vector. Or even better, use a fixed + size typed vector. +* Maps are backwards compatible with vectors, and can be iterated as such. + You can iterate either just the values (`map.Values()`), or in parallel with + the keys vector (`map.Keys()`). If you intend + to access most or all elements, this is faster than looking up each element + by key, since that involves a binary search of the key vector. +* When possible, don't mix values that require a big bit width (such as double) + in a large vector of smaller values, since all elements will take on this + width. Use `IndirectDouble` when this is a possibility. Note that + integers automatically use the smallest width possible, i.e. if you ask + to serialize an int64_t whose value is actually small, you will use less + bits. Doubles are represented as floats whenever possible losslessly, but + this is only possible for few values. + Since nested vectors/maps are stored over offsets, they typically don't + affect the vector width. +* To store large arrays of byte data, use a blob. If you'd use a typed + vector, the bit width of the size field may make it use more space than + expected, and may not be compatible with `memcpy`. + Similarly, large arrays of (u)int16_t may be better off stored as a + binary blob if their size could exceed 64k elements. + Construction and use are otherwise similar to strings. diff --git a/third_party/flatbuffers/docs/source/grammar.md b/third_party/flatbuffers/docs/source/grammar.md new file mode 100644 index 00000000000..ab0a5bf2ad6 --- /dev/null +++ b/third_party/flatbuffers/docs/source/grammar.md @@ -0,0 +1,73 @@ +## EBNF + +```ebnf +schema = include* ( namespace_decl | type_decl | enum_decl | root_decl | + file_extension_decl | file_identifier_decl | + attribute_decl | rpc_decl | object )* + +include = `include` string_constant `;` + +namespace_decl = `namespace` ident ( `.` ident )* `;` + +attribute_decl = `attribute` ident | `"` ident `"` `;` + +type_decl = ( `table` | `struct` ) ident metadata `{` field_decl+ `}` + +enum_decl = ( `enum` ident `:` type | `union` ident ) metadata `{` +commasep( enumval_decl ) `}` + +root_decl = `root_type` ident `;` + +field_decl = ident `:` type [ `=` scalar ] metadata `;` + +rpc_decl = `rpc_service` ident `{` rpc_method+ `}` + +rpc_method = ident `(` ident `)` `:` ident metadata `;` + +type = `bool` | `byte` | `ubyte` | `short` | `ushort` | `int` | `uint` | + `float` | `long` | `ulong` | `double` | `int8` | `uint8` | `int16` | + `uint16` | `int32` | `uint32`| `int64` | `uint64` | `float32` | + `float64` | `string` | `[` type `]` | ident + +enumval_decl = ident [ `=` integer_constant ] metadata + +metadata = [ `(` commasep( ident [ `:` single_value ] ) `)` ] + +scalar = boolean_constant | integer_constant | float_constant + +object = `{` commasep( ident `:` value ) `}` + +single_value = scalar | string_constant + +value = single_value | object | `[` commasep( value ) `]` + +commasep(x) = [ x ( `,` x )\* ] + +file_extension_decl = `file_extension` string_constant `;` + +file_identifier_decl = `file_identifier` string_constant `;` + +string_constant = `\".*?\"` + +ident = `[a-zA-Z_][a-zA-Z0-9_]*` + +`[:digit:]` = `[0-9]` + +`[:xdigit:]` = `[0-9a-fA-F]` + +dec_integer_constant = `[-+]?[:digit:]+` + +hex_integer_constant = `[-+]?0[xX][:xdigit:]+` + +integer_constant = dec_integer_constant | hex_integer_constant + +dec_float_constant = `[-+]?(([.][:digit:]+)|([:digit:]+[.][:digit:]*)|([:digit:]+))([eE][-+]?[:digit:]+)?` + +hex_float_constant = `[-+]?0[xX](([.][:xdigit:]+)|([:xdigit:]+[.][:xdigit:]*)|([:xdigit:]+))([pP][-+]?[:digit:]+)` + +special_float_constant = `[-+]?(nan|inf|infinity)` + +float_constant = dec_float_constant | hex_float_constant | special_float_constant + +boolean_constant = `true` | `false` +``` diff --git a/third_party/flatbuffers/docs/source/index.md b/third_party/flatbuffers/docs/source/index.md new file mode 100644 index 00000000000..269fda309b1 --- /dev/null +++ b/third_party/flatbuffers/docs/source/index.md @@ -0,0 +1,59 @@ +# Overview + +FlatBuffers is an efficient cross platform serialization library for C++, C#, C, +Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and +Swift. It was originally created at Google for game development and other +performance-critical applications. + +It is available as Open Source on +[GitHub](https://github.com/google/flatbuffers) under the Apache license v2.0. + +## Why Use FlatBuffers? + +
+ +- :material-clock-fast:{ .lg .middle } **Access to serialized data without + parsing/unpacking** + + --- + Access the data directly without unpacking or parsing. + +- :material-memory:{ .lg .middle } **Memory Efficiency and Speed** + + --- + The only memory needed to access your data is that of the buffer. No heap is + required. + +- :material-compare-horizontal:{ .lg .middle } **Backwards and Forwards + Compatibility** + + --- + The only memory needed to access your data is that of the buffer. No heap is + required. + +- :material-scale-off:{ .lg .middle } **Small Footprint** + + --- + Minimal dependencies and small code footprint. + +
+ +## Why not use... + +=== "Protocol Buffers" + + Protocol Buffers is indeed relatively similar to FlatBuffers, with the primary + difference being that FlatBuffers does not need a parsing/unpacking step to a + secondary representation before you can access data, often coupled with + per-object memory allocation. The code is an order of magnitude bigger, too. + +=== "JSON" + + JSON is very readable (which is why we use it as our optional text format) and + very convenient when used together with dynamically typed languages (such as + JavaScript). When serializing data from statically typed languages, however, + JSON not only has the obvious drawback of runtime inefficiency, but also forces + you to write more code to access data (counterintuitively) due to its + dynamic-typing serialization system. In this context, it is only a better choice + for systems that have very little to no information ahead of time about what + data needs to be stored. diff --git a/third_party/flatbuffers/docs/source/intermediate_representation.md b/third_party/flatbuffers/docs/source/intermediate_representation.md new file mode 100644 index 00000000000..f4eb0753900 --- /dev/null +++ b/third_party/flatbuffers/docs/source/intermediate_representation.md @@ -0,0 +1,35 @@ +# Flatbuffers Intermediate Representation {#intermediate_representation} + +We use [reflection.fbs](https://github.com/google/flatbuffers/blob/master/reflection/reflection.fbs) +as our intermediate representation. `flatc` parses `.fbs` files, checks them for +errors and stores the resulting data in this IR, outputting `.bfbs` files. +Since this IR is a Flatbuffer, you can load and use it at runtime for runtime +reflection purposes. + +There are some quirks: +- Tables and Structs are serialized as `Object`s. +- Unions and Enums are serialized as `Enum`s. +- It is the responsibility of the code generator to check the `advanced_features` + field of `Schema`. These mark the presence of new, backwards incompatible, + schema features. Code generators must error if generating a schema with + unrecognized advanced features. +- Filenames are relative to a "project root" denoted by "//" in the path. This + may be specified in flatc with `--bfbs-filenames=$PROJECT_ROOT`, or it will be + inferred to be the directory containing the first provided schema file. + + +## Invocation +You can invoke it like so +```{.sh} +flatc -b --schema ${your_fbs_files} +``` +This generates `.bfbs` (binary flatbuffer schema) files. + +Some information is not included by default. See the `--bfbs-filenames` and +`--bfbs-comments` flags. These may be necessary for code-generators, so they can +add documentation and maybe name generated files (depending on the generator). + + +TODO(cneo): Flags to output bfbs as flexbuffers or json. + +TODO(cneo): Tutorial for building a flatc plugin. diff --git a/third_party/flatbuffers/docs/source/internals.md b/third_party/flatbuffers/docs/source/internals.md new file mode 100644 index 00000000000..5b126ba75fd --- /dev/null +++ b/third_party/flatbuffers/docs/source/internals.md @@ -0,0 +1,466 @@ +FlatBuffer Internals {#flatbuffers_internals} +==================== + +This section is entirely optional for the use of FlatBuffers. In normal +usage, you should never need the information contained herein. If you're +interested however, it should give you more of an appreciation of why +FlatBuffers is both efficient and convenient. + +### Format components + +A FlatBuffer is a binary file and in-memory format consisting mostly of +scalars of various sizes, all aligned to their own size. Each scalar is +also always represented in little-endian format, as this corresponds to +all commonly used CPUs today. FlatBuffers will also work on big-endian +machines, but will be slightly slower because of additional +byte-swap intrinsics. + +It is assumed that the following conditions are met, to ensure +cross-platform interoperability: +- The binary `IEEE-754` format is used for floating-point numbers. +- The `two's complemented` representation is used for signed integers. +- The endianness is the same for floating-point numbers as for integers. + +On purpose, the format leaves a lot of details about where exactly +things live in memory undefined, e.g. fields in a table can have any +order, and objects to some extent can be stored in many orders. This is +because the format doesn't need this information to be efficient, and it +leaves room for optimization and extension (for example, fields can be +packed in a way that is most compact). Instead, the format is defined in +terms of offsets and adjacency only. This may mean two different +implementations may produce different binaries given the same input +values, and this is perfectly valid. + +### Format identification + +The format also doesn't contain information for format identification +and versioning, which is also by design. FlatBuffers is a statically typed +system, meaning the user of a buffer needs to know what kind of buffer +it is. FlatBuffers can of course be wrapped inside other containers +where needed, or you can use its union feature to dynamically identify +multiple possible sub-objects stored. Additionally, it can be used +together with the schema parser if full reflective capabilities are +desired. + +Versioning is something that is intrinsically part of the format (the +optionality / extensibility of fields), so the format itself does not +need a version number (it's a meta-format, in a sense). We're hoping +that this format can accommodate all data needed. If format breaking +changes are ever necessary, it would become a new kind of format rather +than just a variation. + +### Offsets + +The most important and generic offset type (see `flatbuffers.h`) is +`uoffset_t`, which is currently always a `uint32_t`, and is used to +refer to all tables/unions/strings/vectors (these are never stored +in-line). 32bit is +intentional, since we want to keep the format binary compatible between +32 and 64bit systems, and a 64bit offset would bloat the size for almost +all uses. A version of this format with 64bit (or 16bit) offsets is easy to set +when needed. Unsigned means they can only point in one direction, which +typically is forward (towards a higher memory location). Any backwards +offsets will be explicitly marked as such. + +The format starts with an `uoffset_t` to the root table in the buffer. + +We have two kinds of objects, structs and tables. + +### Structs + +These are the simplest, and as mentioned, intended for simple data that +benefits from being extra efficient and doesn't need versioning / +extensibility. They are always stored inline in their parent (a struct, +table, or vector) for maximum compactness. Structs define a consistent +memory layout where all components are aligned to their size, and +structs aligned to their largest scalar member. This is done independent +of the alignment rules of the underlying compiler to guarantee a cross +platform compatible layout. This layout is then enforced in the generated +code. + +### Tables + +Unlike structs, these are not stored in inline in their parent, but are +referred to by offset. + +They start with an `soffset_t` to a vtable. This is a signed version of +`uoffset_t`, since vtables may be stored anywhere relative to the object. +This offset is subtracted (not added) from the object start to arrive at +the vtable start. This offset is followed by all the +fields as aligned scalars (or offsets). Unlike structs, not all fields +need to be present. There is no set order and layout. A table may contain +field offsets that point to the same value if the user explicitly +serializes the same offset twice. + +To be able to access fields regardless of these uncertainties, we go +through a vtable of offsets. Vtables are shared between any objects that +happen to have the same vtable values. + +The elements of a vtable are all of type `voffset_t`, which is +a `uint16_t`. The first element is the size of the vtable in bytes, +including the size element. The second one is the size of the object, in bytes +(including the vtable offset). This size could be used for streaming, to know +how many bytes to read to be able to access all *inline* fields of the object. +The remaining elements are the N offsets, where N is the amount of fields +declared in the schema when the code that constructed this buffer was +compiled (thus, the size of the table is N + 2). + +All accessor functions in the generated code for tables contain the +offset into this table as a constant. This offset is checked against the +first field (the number of elements), to protect against newer code +reading older data. If this offset is out of range, or the vtable entry +is 0, that means the field is not present in this object, and the +default value is return. Otherwise, the entry is used as offset to the +field to be read. + +### Unions + +Unions are encoded as the combination of two fields: an enum representing the +union choice and the offset to the actual element. FlatBuffers reserves the +enumeration constant `NONE` (encoded as 0) to mean that the union field is not +set. + +### Strings and Vectors + +Strings are simply a vector of bytes, and are always +null-terminated. Vectors are stored as contiguous aligned scalar +elements prefixed by a 32bit element count (not including any +null termination). Neither is stored inline in their parent, but are referred to +by offset. A vector may consist of more than one offset pointing to the same +value if the user explicitly serializes the same offset twice. + +### Construction + +The current implementation constructs these buffers backwards (starting +at the highest memory address of the buffer), since +that significantly reduces the amount of bookkeeping and simplifies the +construction API. + +### Code example + +Here's an example of the code that gets generated for the `samples/monster.fbs`. +What follows is the entire file, broken up by comments: + + // automatically generated, do not modify + + #include "flatbuffers/flatbuffers.h" + + namespace MyGame { + namespace Sample { + +Nested namespace support. + + enum { + Color_Red = 0, + Color_Green = 1, + Color_Blue = 2, + }; + + inline const char **EnumNamesColor() { + static const char *names[] = { "Red", "Green", "Blue", nullptr }; + return names; + } + + inline const char *EnumNameColor(int e) { return EnumNamesColor()[e]; } + +Enums and convenient reverse lookup. + + enum { + Any_NONE = 0, + Any_Monster = 1, + }; + + inline const char **EnumNamesAny() { + static const char *names[] = { "NONE", "Monster", nullptr }; + return names; + } + + inline const char *EnumNameAny(int e) { return EnumNamesAny()[e]; } + +Unions share a lot with enums. + + struct Vec3; + struct Monster; + +Predeclare all data types since circular references between types are allowed +(circular references between object are not, though). + + FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vec3 { + private: + float x_; + float y_; + float z_; + + public: + Vec3(float x, float y, float z) + : x_(flatbuffers::EndianScalar(x)), y_(flatbuffers::EndianScalar(y)), z_(flatbuffers::EndianScalar(z)) {} + + float x() const { return flatbuffers::EndianScalar(x_); } + float y() const { return flatbuffers::EndianScalar(y_); } + float z() const { return flatbuffers::EndianScalar(z_); } + }; + FLATBUFFERS_STRUCT_END(Vec3, 12); + +These ugly macros do a couple of things: they turn off any padding the compiler +might normally do, since we add padding manually (though none in this example), +and they enforce alignment chosen by FlatBuffers. This ensures the layout of +this struct will look the same regardless of compiler and platform. Note that +the fields are private: this is because these store little endian scalars +regardless of platform (since this is part of the serialized data). +`EndianScalar` then converts back and forth, which is a no-op on all current +mobile and desktop platforms, and a single machine instruction on the few +remaining big endian platforms. + + struct Monster : private flatbuffers::Table { + const Vec3 *pos() const { return GetStruct(4); } + int16_t mana() const { return GetField(6, 150); } + int16_t hp() const { return GetField(8, 100); } + const flatbuffers::String *name() const { return GetPointer(10); } + const flatbuffers::Vector *inventory() const { return GetPointer *>(14); } + int8_t color() const { return GetField(16, 2); } + }; + +Tables are a bit more complicated. A table accessor struct is used to point at +the serialized data for a table, which always starts with an offset to its +vtable. It derives from `Table`, which contains the `GetField` helper functions. +GetField takes a vtable offset, and a default value. It will look in the vtable +at that offset. If the offset is out of bounds (data from an older version) or +the vtable entry is 0, the field is not present and the default is returned. +Otherwise, it uses the entry as an offset into the table to locate the field. + + struct MonsterBuilder { + flatbuffers::FlatBufferBuilder &fbb_; + flatbuffers::uoffset_t start_; + void add_pos(const Vec3 *pos) { fbb_.AddStruct(4, pos); } + void add_mana(int16_t mana) { fbb_.AddElement(6, mana, 150); } + void add_hp(int16_t hp) { fbb_.AddElement(8, hp, 100); } + void add_name(flatbuffers::Offset name) { fbb_.AddOffset(10, name); } + void add_inventory(flatbuffers::Offset> inventory) { fbb_.AddOffset(14, inventory); } + void add_color(int8_t color) { fbb_.AddElement(16, color, 2); } + MonsterBuilder(flatbuffers::FlatBufferBuilder &_fbb) : fbb_(_fbb) { start_ = fbb_.StartTable(); } + flatbuffers::Offset Finish() { return flatbuffers::Offset(fbb_.EndTable(start_, 7)); } + }; + +`MonsterBuilder` is the base helper struct to construct a table using a +`FlatBufferBuilder`. You can add the fields in any order, and the `Finish` +call will ensure the correct vtable gets generated. + + inline flatbuffers::Offset CreateMonster(flatbuffers::FlatBufferBuilder &_fbb, + const Vec3 *pos, int16_t mana, + int16_t hp, + flatbuffers::Offset name, + flatbuffers::Offset> inventory, + int8_t color) { + MonsterBuilder builder_(_fbb); + builder_.add_inventory(inventory); + builder_.add_name(name); + builder_.add_pos(pos); + builder_.add_hp(hp); + builder_.add_mana(mana); + builder_.add_color(color); + return builder_.Finish(); + } + +`CreateMonster` is a convenience function that calls all functions in +`MonsterBuilder` above for you. Note that if you pass values which are +defaults as arguments, it will not actually construct that field, so +you can probably use this function instead of the builder class in +almost all cases. + + inline const Monster *GetMonster(const void *buf) { return flatbuffers::GetRoot(buf); } + +This function is only generated for the root table type, to be able to +start traversing a FlatBuffer from a raw buffer pointer. + + }; // namespace MyGame + }; // namespace Sample + +### Encoding example. + +Below is a sample encoding for the following JSON corresponding to the above +schema: + + { pos: { x: 1, y: 2, z: 3 }, name: "fred", hp: 50 } + +Resulting in this binary buffer: + + // Start of the buffer: + uint32_t 20 // Offset to the root table. + + // Start of the vtable. Not shared in this example, but could be: + uint16_t 16 // Size of table, starting from here. + uint16_t 22 // Size of object inline data. + uint16_t 4, 0, 20, 16, 0, 0 // Offsets to fields from start of (root) table, 0 for not present. + + // Start of the root table: + int32_t 16 // Offset to vtable used (default negative direction) + float 1, 2, 3 // the Vec3 struct, inline. + uint32_t 8 // Offset to the name string. + int16_t 50 // hp field. + int16_t 0 // Padding for alignment. + + // Start of name string: + uint32_t 4 // Length of string. + int8_t 'f', 'r', 'e', 'd', 0, 0, 0, 0 // Text + 0 termination + padding. + +Note that this not the only possible encoding, since the writer has some +flexibility in which of the children of root object to write first (though in +this case there's only one string), and what order to write the fields in. +Different orders may also cause different alignments to happen. + +### Additional reading. + +The author of the C language implementation has made a similar +[document](https://github.com/dvidelabs/flatcc/blob/master/doc/binary-format.md#flatbuffers-binary-format) +that may further help clarify the format. + +# FlexBuffers + +The [schema-less](flexbuffers.md) version of FlatBuffers have their +own encoding, detailed here. + +It shares many properties mentioned above, in that all data is accessed +over offsets, all scalars are aligned to their own size, and +all data is always stored in little endian format. + +One difference is that FlexBuffers are built front to back, so children are +stored before parents, and the root of the data starts at the last byte. + +Another difference is that scalar data is stored with a variable number of bits +(8/16/32/64). The current width is always determined by the *parent*, i.e. if +the scalar sits in a vector, the vector determines the bit width for all +elements at once. Selecting the minimum bit width for a particular vector is +something the encoder does automatically and thus is typically of no concern +to the user, though being aware of this feature (and not sticking a double in +the same vector as a bunch of byte sized elements) is helpful for efficiency. + +Unlike FlatBuffers there is only one kind of offset, and that is an unsigned +integer indicating the number of bytes in a negative direction from the address +of itself (where the offset is stored). + +### Vectors + +The representation of the vector is at the core of how FlexBuffers works (since +maps are really just a combination of 2 vectors), so it is worth starting there. + +As mentioned, a vector is governed by a single bit width (supplied by its +parent). This includes the size field. For example, a vector that stores the +integer values `1, 2, 3` is encoded as follows: + + uint8_t 3, 1, 2, 3, 4, 4, 4 + +The first `3` is the size field, and is placed before the vector (an offset +from the parent to this vector points to the first element, not the size +field, so the size field is effectively at index -1). +Since this is an untyped vector `SL_VECTOR`, it is followed by 3 type +bytes (one per element of the vector), which are always following the vector, +and are always a uint8_t even if the vector is made up of bigger scalars. + +A vector may include more than one offset pointing to the same value if the +user explicitly serializes the same offset twice. + +### Types + +A type byte is made up of 2 components (see flexbuffers.h for exact values): + +* 2 lower bits representing the bit-width of the child (8, 16, 32, 64). + This is only used if the child is accessed over an offset, such as a child + vector. It is ignored for inline types. +* 6 bits representing the actual type (see flexbuffers.h). + +Thus, in this example `4` means 8 bit child (value 0, unused, since the value is +in-line), type `SL_INT` (value 1). + +### Typed Vectors + +These are like the Vectors above, but omit the type bytes. The type is instead +determined by the vector type supplied by the parent. Typed vectors are only +available for a subset of types for which these savings can be significant, +namely inline signed/unsigned integers (`TYPE_VECTOR_INT` / `TYPE_VECTOR_UINT`), +floats (`TYPE_VECTOR_FLOAT`), and keys (`TYPE_VECTOR_KEY`, see below). + +Additionally, for scalars, there are fixed length vectors of sizes 2 / 3 / 4 +that don't store the size (`TYPE_VECTOR_INT2` etc.), for an additional savings +in space when storing common vector or color data. + +### Scalars + +FlexBuffers supports integers (`TYPE_INT` and `TYPE_UINT`) and floats +(`TYPE_FLOAT`), available in the bit-widths mentioned above. They can be stored +both inline and over an offset (`TYPE_INDIRECT_*`). + +The offset version is useful to encode costly 64bit (or even 32bit) quantities +into vectors / maps of smaller sizes, and to share / repeat a value multiple +times. + +### Booleans and Nulls + +Booleans (`TYPE_BOOL`) and nulls (`TYPE_NULL`) are encoded as inlined unsigned integers. + +### Blobs, Strings and Keys. + +A blob (`TYPE_BLOB`) is encoded similar to a vector, with one difference: the +elements are always `uint8_t`. The parent bit width only determines the width of +the size field, allowing blobs to be large without the elements being large. + +Strings (`TYPE_STRING`) are similar to blobs, except they have an additional 0 +termination byte for convenience, and they MUST be UTF-8 encoded (since an +accessor in a language that does not support pointers to UTF-8 data may have to +convert them to a native string type). + +A "Key" (`TYPE_KEY`) is similar to a string, but doesn't store the size +field. They're so named because they are used with maps, which don't care +for the size, and can thus be even more compact. Unlike strings, keys cannot +contain bytes of value 0 as part of their data (size can only be determined by +`strlen`), so while you can use them outside the context of maps if you so +desire, you're usually better off with strings. + +### Maps + +A map (`TYPE_MAP`) is like an (untyped) vector, but with 2 prefixes before the +size field: + +| index | field | +| ----: | :----------------------------------------------------------- | +| -3 | An offset to the keys vector (may be shared between tables). | +| -2 | Byte width of the keys vector. | +| -1 | Size (from here on it is compatible with `TYPE_VECTOR`) | +| 0 | Elements. | +| Size | Types. | + +Since a map is otherwise the same as a vector, it can be iterated like +a vector (which is probably faster than lookup by key). + +The keys vector is a typed vector of keys. Both the keys and corresponding +values *have* to be stored in sorted order (as determined by `strcmp`), such +that lookups can be made using binary search. + +The reason the key vector is a separate structure from the value vector is +such that it can be shared between multiple value vectors, and also to +allow it to be treated as its own individual vector in code. + +An example map { foo: 13, bar: 14 } would be encoded as: + + 0 : uint8_t 'b', 'a', 'r', 0 + 4 : uint8_t 'f', 'o', 'o', 0 + 8 : uint8_t 2 // key vector of size 2 + // key vector offset points here + 9 : uint8_t 9, 6 // offsets to bar_key and foo_key + 11: uint8_t 2, 1 // offset to key vector, and its byte width + 13: uint8_t 2 // value vector of size + // value vector offset points here + 14: uint8_t 14, 13 // values + 16: uint8_t 4, 4 // types + +### The root + +As mentioned, the root starts at the end of the buffer. +The last uint8_t is the width in bytes of the root (normally the parent +determines the width, but the root has no parent). The uint8_t before this is +the type of the root, and the bytes before that are the root value (of the +number of bytes specified by the last byte). + +So for example, the integer value `13` as root would be: + + uint8_t 13, 4, 1 // Value, type, root byte width. + diff --git a/third_party/flatbuffers/docs/source/languages/c.md b/third_party/flatbuffers/docs/source/languages/c.md new file mode 100644 index 00000000000..a0c2690874e --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/c.md @@ -0,0 +1,224 @@ +Use in C {#flatbuffers_guide_use_c} +========== + +The C language binding exists in a separate project named [FlatCC](https://github.com/dvidelabs/flatcc). + +The `flatcc` C schema compiler can generate code offline as well as +online via a C library. It can also generate buffer verifiers and fast +JSON parsers, printers. + +Great care has been taken to ensure compatibility with the main `flatc` +project. + +## General Documention + +- [Tutorial](../tutorial.md) - select C as language + when scrolling down +- [FlatCC Guide](https://github.com/dvidelabs/flatcc#flatcc-flatbuffers-in-c-for-c) +- [The C Builder Interface](https://github.com/dvidelabs/flatcc/blob/master/doc/builder.md#the-builder-interface) +- [The Monster Sample in C](https://github.com/dvidelabs/flatcc/blob/master/samples/monster/monster.c) +- [GitHub](https://github.com/dvidelabs/flatcc) + + +## Supported Platforms + +- Ubuntu (clang / gcc, ninja / gnu make) +- OS-X (clang / gcc, ninja / gnu make) +- Windows MSVC 2010, 2013, 2015 + +CI builds recent versions of gcc, clang and MSVC on OS-X, Ubuntu, and +Windows, and occasionally older compiler versions. See main project [Status](https://github.com/dvidelabs/flatcc#status). + +Other platforms may well work, including Centos, but are not tested +regularly. + +The monster sample project was specifically written for C99 in order to +follow the C++ version and for that reason it will not work with MSVC +2010. + +## Modular Object Creation + +In the tutorial we used the call `Monster_create_as_root` to create the +root buffer object since this is easier in simple use cases. Sometimes +we need more modularity so we can reuse a function to create nested +tables and root tables the same way. For this we need the +`flatcc_builder_buffer_create_call`. It is best to keep `flatcc_builder` +calls isolated at the top driver level, so we get: + +
+~~~{.c} + ns(Monster_ref_t) create_orc(flatcc_builder_t *B) + { + // ... same as in the tutorial. + return s(Monster_create(B, ...)); + } + + void create_monster_buffer() + { + uint8_t *buf; + size_t size; + flatcc_builder_t builder, *B; + + // Initialize the builder object. + B = &builder; + flatcc_builder_init(B); + // Only use `buffer_create` without `create/start/end_as_root`. + flatcc_builder_buffer_create(create_orc(B)); + // Allocate and copy buffer to user memory. + buf = flatcc_builder_finalize_buffer(B, &size); + // ... write the buffer to disk or network, or something. + + free(buf); + flatcc_builder_clear(B); + } +~~~ +
+ +The same principle applies with `start/end` vs `start/end_as_root` in +the top-down approach. + + +## Top Down Example + +The tutorial uses a bottom up approach. In C it is also possible to use +a top-down approach by starting and ending objects nested within each +other. In the tutorial there is no deep nesting, so the difference is +limited, but it shows the idea: + +
+
+~~~{.c} + uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + size_t treasure_count = c_vec_len(treasure); + ns(Weapon_ref_t) axe; + + // NOTE: if we use end_as_root, we MUST also start as root. + ns(Monster_start_as_root(B)); + ns(Monster_pos_create(B, 1.0f, 2.0f, 3.0f)); + ns(Monster_hp_add(B, 300)); + ns(Monster_mana_add(B, 150)); + // We use create_str instead of add because we have no existing string reference. + ns(Monster_name_create_str(B, "Orc")); + // Again we use create because we no existing vector object, only a C-array. + ns(Monster_inventory_create(B, treasure, treasure_count)); + ns(Monster_color_add(B, ns(Color_Red))); + if (1) { + ns(Monster_weapons_start(B)); + ns(Monster_weapons_push_create(B, flatbuffers_string_create_str(B, "Sword"), 3)); + // We reuse the axe object later. Note that we dereference a pointer + // because push always returns a short-term pointer to the stored element. + // We could also have created the axe object first and simply pushed it. + axe = *ns(Monster_weapons_push_create(B, flatbuffers_string_create_str(B, "Axe"), 5)); + ns(Monster_weapons_end(B)); + } else { + // We can have more control with the table elements added to a vector: + // + ns(Monster_weapons_start(B)); + ns(Monster_weapons_push_start(B)); + ns(Weapon_name_create_str(B, "Sword")); + ns(Weapon_damage_add(B, 3)); + ns(Monster_weapons_push_end(B)); + ns(Monster_weapons_push_start(B)); + ns(Monster_weapons_push_start(B)); + ns(Weapon_name_create_str(B, "Axe")); + ns(Weapon_damage_add(B, 5)); + axe = *ns(Monster_weapons_push_end(B)); + ns(Monster_weapons_end(B)); + } + // Unions can get their type by using a type-specific add/create/start method. + ns(Monster_equipped_Weapon_add(B, axe)); + + ns(Monster_end_as_root(B)); +~~~ +
+ + +## Basic Reflection + +The C-API does support reading binary schema (.bfbs) +files via code generated from the `reflection.fbs` schema, and an +[example usage](https://github.com/dvidelabs/flatcc/tree/master/samples/reflection) +shows how to use this. The reflection schema files are pre-generated +in the [runtime distribution](https://github.com/dvidelabs/flatcc/tree/master/include/flatcc/reflection). + + +## Mutations and Reflection + +The C-API does not support mutating reflection like C++ does, nor does +the reader interface support mutating scalars (and it is generally +unsafe to do so even after verification). + +The generated reader interface supports sorting vectors in-place after +casting them to a mutating type because it is not practical to do so +while building a buffer. This is covered in the builder documentation. +The reflection example makes use of this feature to look up objects by +name. + +It is possible to build new buffers using complex objects from existing +buffers as source. This can be very efficient due to direct copy +semantics without endian conversion or temporary stack allocation. + +Scalars, structs and strings can be used as source, as well vectors of +these. + +It is currently not possible to use an existing table or vector of table +as source, but it would be possible to add support for this at some +point. + + +## Namespaces + +The `FLATBUFFERS_WRAP_NAMESPACE` approach used in the tutorial is convenient +when each function has a very long namespace prefix. But it isn't always +the best approach. If the namespace is absent, or simple and +informative, we might as well use the prefix directly. The +[reflection example](https://github.com/dvidelabs/flatcc/blob/master/samples/reflection/bfbs2json.c) +mentioned above uses this approach. + + +## Checking for Present Members + +Not all languages support testing if a field is present, but in C we can +elaborate the reader section of the tutorial with tests for this. Recall +that `mana` was set to the default value `150` and therefore shouldn't +be present. + +
+~~~{.c} + int hp_present = ns(Monster_hp_is_present(monster)); // 1 + int mana_present = ns(Monster_mana_is_present(monster)); // 0 +~~~ +
+ +## Alternative ways to add a Union + +In the tutorial we used a single call to add a union. Here we show +different ways to accomplish the same thing. The last form is rarely +used, but is the low-level way to do it. It can be used to group small +values together in the table by adding type and data at different +points in time. + +
+~~~{.c} + ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe)); + ns(Monster_equipped_add(B, equipped)); + // or alternatively + ns(Monster_equipped_Weapon_add(B, axe); + // or alternatively + ns(Monster_equipped_add_type(B, ns(Equipment_Weapon)); + ns(Monster_equipped_add_member(B, axe)); +~~~ +
+ +## Why not integrate with the `flatc` tool? + +[It was considered how the C code generator could be integrated into the +`flatc` tool](https://github.com/dvidelabs/flatcc/issues/1), but it +would either require that the standalone C implementation of the schema +compiler was dropped, or it would lead to excessive code duplication, or +a complicated intermediate representation would have to be invented. +Neither of these alternatives are very attractive, and it isn't a big +deal to use the `flatcc` tool instead of `flatc` given that the +FlatBuffers C runtime library needs to be made available regardless. + + diff --git a/third_party/flatbuffers/docs/source/languages/c_sharp.md b/third_party/flatbuffers/docs/source/languages/c_sharp.md new file mode 100644 index 00000000000..07f879a4765 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/c_sharp.md @@ -0,0 +1,265 @@ +Use in C\# {#flatbuffers_guide_use_c-sharp} +============== + +## Before you get started + +Before diving into the FlatBuffers usage in C#, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide to +general FlatBuffers usage in all of the supported languages (including C#). +This page is designed to cover the nuances of FlatBuffers usage, +specific to C#. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers C# code location + +The code for the FlatBuffers C# library can be found at +`flatbuffers/net/FlatBuffers`. You can browse the library on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/net/ +FlatBuffers). + +## Building the FlatBuffers C# library + +The `FlatBuffers.csproj` project contains multitargeting for .NET Standard 2.1, +.NET 6 and .NET 8. + +You can build for a specific framework target when using the cross-platform +[.NET Core SDK](https://dotnet.microsoft.com/download) by adding the `-f` +command line option: + +~~~{.sh} + dotnet build -f netstandard2.1 "FlatBuffers.csproj" +~~~ + +The `FlatBuffers.csproj` project also provides support for defining various +conditional compilation symbols (see "Conditional compilation symbols" section +below) using the `-p` command line option: + +~~~{.sh} + dotnet build -f netstandard2.1 -p:ENABLE_SPAN_T=true -p:UNSAFE_BYTEBUFFER=true "FlatBuffers.csproj" +~~~ + +## Testing the FlatBuffers C# library + +The code to test the libraries can be found at `flatbuffers/tests`. + +The test code for C# is located in the [FlatBuffers.Test](https://github.com/ +google/flatbuffers/tree/master/tests/FlatBuffers.Test) subfolder. To run the +tests, open `FlatBuffers.Test.csproj` in [Visual Studio]( +https://www.visualstudio.com), and compile/run the project. + +Optionally, you can run this using [Mono](http://www.mono-project.com/) instead. +Once you have installed Mono, you can run the tests from the command line +by running the following commands from inside the `FlatBuffers.Test` folder: + +~~~{.sh} + mcs *.cs ../MyGame/Example/*.cs ../../net/FlatBuffers/*.cs + mono Assert.exe +~~~ + +## Using the FlatBuffers C# library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in C#.* + +FlatBuffers supports reading and writing binary FlatBuffers in C#. + +To use FlatBuffers in your own code, first generate C# classes from your +schema with the `--csharp` option to `flatc`. +Then you can include both FlatBuffers and the generated code to read +or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in C#: +First, import the library and generated code. Then, you read a FlatBuffer binary +file into a `byte[]`. You then turn the `byte[]` into a `ByteBuffer`, which you +pass to the `GetRootAsMyRootType` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + using MyGame.Example; + using Google.FlatBuffers; + + // This snippet ignores exceptions for brevity. + byte[] data = File.ReadAllBytes("monsterdata_test.mon"); + + ByteBuffer bb = new ByteBuffer(data); + Monster monster = Monster.GetRootAsMonster(bb); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access the data from the `Monster monster`: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + short hp = monster.Hp; + Vec3 pos = monster.Pos; +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +C# code naming follows standard C# style with PascalCasing identifiers, +e.g. `GetRootAsMyRootType`. Also, values (except vectors and unions) are +available as properties instead of parameterless accessor methods. +The performance-enhancing methods to which you can pass an already created +object are prefixed with `Get`, e.g.: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + // property + var pos = monster.Pos; + + // method filling a preconstructed object + var preconstructedPos = new Vec3(); + monster.GetPos(preconstructedPos); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +## Storing dictionaries in a FlatBuffer + +FlatBuffers doesn't support dictionaries natively, but there is support to +emulate their behavior with vectors and binary search, which means you +can have fast lookups directly from a FlatBuffer without having to unpack +your data into a `Dictionary` or similar. + +To use it: +- Designate one of the fields in a table as the "key" field. You do this + by setting the `key` attribute on this field, e.g. + `name:string (key)`. + You may only have one key field, and it must be of string or scalar type. +- Write out tables of this type as usual, collect their offsets in an + array. +- Instead of calling standard generated method, + e.g.: `Monster.createTestarrayoftablesVector`, + call `CreateSortedVectorOfMonster` in C# + which will first sort all offsets such that the tables they refer to + are sorted by the key field, then serialize it. +- Now when you're accessing the FlatBuffer, you can use + the `ByKey` accessor to access elements of the vector, e.g.: + `monster.TestarrayoftablesByKey("Frodo")` in C#, + which returns an object of the corresponding table type, + or `null` if not found. + `ByKey` performs a binary search, so should have a similar + speed to `Dictionary`, though may be faster because of better caching. + `ByKey` only works if the vector has been sorted, it will + likely not find elements if it hasn't been sorted. + +## Buffer verification + +As mentioned in [C++ Usage](cpp.md) buffer +accessor functions do not verify buffer offsets at run-time. +If it is necessary, you can optionally use a buffer verifier before you +access the data. This verifier will check all offsets, all sizes of +fields, and null termination of strings to ensure that when a buffer +is accessed, all reads will end up inside the buffer. + +Each root type will have a verification function generated for it, +e.g. `Monster.VerifyMonster`. This can be called as shown: +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + var ok = Monster.VerifyMonster(buf); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +if `ok` is true, the buffer is safe to read. + +For a more detailed control of verification `MonsterVerify.Verify` +for `Monster` type can be used: +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + # Sequence of calls + FlatBuffers.Verifier verifier = new FlatBuffers.Verifier(buf); + var ok = verifier.VerifyBuffer("MONS", false, MonsterVerify.Verify); + + # Or single line call + var ok = new FlatBuffers.Verifier(bb).setStringCheck(true).\ + VerifyBuffer("MONS", false, MonsterVerify.Verify); + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +if `ok` is true, the buffer is safe to read. + +A second parameter of `verifyBuffer` specifies whether buffer content is +size prefixed or not. In the example above, the buffer is assumed to not include +size prefix (`false`). + +Verifier supports options that can be set using appropriate fluent methods: +* SetMaxDepth - limit the nesting depth. Default: 1000000 +* SetMaxTables - total amount of tables the verifier may encounter. Default: 64 +* SetAlignmentCheck - check content alignment. Default: True +* SetStringCheck - check if strings contain termination '0' character. Default: true + + +## Text parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from C#, though you could use the C++ parser through native call +interfaces available to each language. Please see the +C++ documentation for more on text parsing. + +## Object based API + +FlatBuffers is all about memory efficiency, which is why its base API is written +around using as little as possible of it. This does make the API clumsier +(requiring pre-order construction of all data, and making mutation harder). + +For times when efficiency is less important a more convenient object based API +can be used (through `--gen-object-api`) that is able to unpack & pack a +FlatBuffer into objects and standard `System.Collections.Generic` containers, +allowing for convenient construction, access and mutation. + +To use: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + // Deserialize from buffer into object. + MonsterT monsterobj = GetMonster(flatbuffer).UnPack(); + + // Update object directly like a C# class instance. + Console.WriteLine(monsterobj.Name); + monsterobj.Name = "Bob"; // Change the name. + + // Serialize into new flatbuffer. + FlatBufferBuilder fbb = new FlatBufferBuilder(1); + fbb.Finish(Monster.Pack(fbb, monsterobj).Value); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +### Json Serialization + +An additional feature of the object API is the ability to allow you to +serialize & deserialize a JSON text. +To use Json Serialization, add `--cs-gen-json-serializer` option to `flatc` and +add `Newtonsoft.Json` nuget package to csproj. This requires explicitly setting +the `--gen-object-api` option as well. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.cs} + // Deserialize MonsterT from json + string jsonText = File.ReadAllText(@"Resources/monsterdata_test.json"); + MonsterT mon = MonsterT.DeserializeFromJson(jsonText); + + // Serialize MonsterT to json + string jsonText2 = mon.SerializeToJson(); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +* Limitation + * `hash` attribute currently not supported. +* NuGet package Dependency + * [Newtonsoft.Json](https://github.com/JamesNK/Newtonsoft.Json) + +## Conditional compilation symbols + +There are three conditional compilation symbols that have an impact on +performance/features of the C# `ByteBuffer` implementation. + +* `UNSAFE_BYTEBUFFER` + + This will use unsafe code to manipulate the underlying byte array. This can + yield a reasonable performance increase. + +* `BYTEBUFFER_NO_BOUNDS_CHECK` + + This will disable the bounds check asserts to the byte array. This can yield a + small performance gain in normal code. + +* `ENABLE_SPAN_T` + + This will enable reading and writing blocks of memory with a `Span` instead + of just `T[]`. You can also enable writing directly to shared memory or other + types of memory by providing a custom implementation of `ByteBufferAllocator`. + `ENABLE_SPAN_T` also requires `UNSAFE_BYTEBUFFER` to be defined, or .NET + Standard 2.1. + +Using `UNSAFE_BYTEBUFFER` and `BYTEBUFFER_NO_BOUNDS_CHECK` together can yield a +performance gain of ~15% for some operations, however doing so is potentially +dangerous. Do so at your own risk! + +
diff --git a/third_party/flatbuffers/docs/source/languages/cpp.md b/third_party/flatbuffers/docs/source/languages/cpp.md new file mode 100644 index 00000000000..e44e34bbf1b --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/cpp.md @@ -0,0 +1,672 @@ +# Language Guide: C++ + +## Before you get started + +Before diving into the FlatBuffers usage in C++, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide +to general FlatBuffers usage in all of the supported languages (including C++). +This page is designed to cover the nuances of FlatBuffers usage, specific to +C++. + +#### Prerequisites + +This page assumes you have written a FlatBuffers schema and compiled it +with the Schema Compiler. If you have not, please see +[Using the schema compiler](../flatc.md) +and [Writing a schema](../schema.md). + +Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't +matter), you've generated a C++ header called `mygame_generated.h` using the +compiler (e.g. `flatc -c mygame.fbs`), you can now start using this in +your program by including the header. As noted, this header relies on +`flatbuffers/flatbuffers.h`, which should be in your include path. + +## FlatBuffers C++ library code location + +The code for the FlatBuffers C++ library can be found at +`flatbuffers/include/flatbuffers`. You can browse the library code on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/include/flatbuffers). + +## Testing the FlatBuffers C++ library + +The code to test the C++ library can be found at `flatbuffers/tests`. +The test code itself is located in +[test.cpp](https://github.com/google/flatbuffers/blob/master/tests/test.cpp). + +This test file is built alongside `flatc`. To review how to build the project, +please read the [Building](../building.md) documentation. + +To run the tests, execute `flattests` from the root `flatbuffers/` directory. +For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply +run: `./flattests`. + +## Using the FlatBuffers C++ library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in C++.* + +FlatBuffers supports both reading and writing FlatBuffers in C++. + +To use FlatBuffers in your code, first generate the C++ classes from your +schema with the `--cpp` option to `flatc`. Then you can include both FlatBuffers +and the generated code to read or write FlatBuffers. + +For example, here is how you would read a FlatBuffer binary file in C++: +First, include the library and generated code. Then read the file into +a `char *` array, which you pass to `GetMonster()`. + +```cpp + #include "flatbuffers/flatbuffers.h" + #include "monster_test_generate.h" + #include // C++ header file for printing + #include // C++ header file for file access + + + std::ifstream infile; + infile.open("monsterdata_test.mon", std::ios::binary | std::ios::in); + infile.seekg(0,std::ios::end); + int length = infile.tellg(); + infile.seekg(0,std::ios::beg); + char *data = new char[length]; + infile.read(data, length); + infile.close(); + + auto monster = GetMonster(data); +``` + +`monster` is of type `Monster *`, and points to somewhere *inside* your +buffer (root object pointers are not the same as `buffer_pointer` \!). +If you look in your generated header, you'll see it has +convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: + +```cpp + std::cout << "hp : " << monster->hp() << std::endl; // '80' + std::cout << "mana : " << monster->mana() << std::endl; // default value of '150' + std::cout << "name : " << monster->name()->c_str() << std::endl; // "MyMonster" +``` + +*Note: That we never stored a `mana` value, so it will return the default.* + +The following attributes are supported: + +- `shared` (on a field): For string fields, this enables the usage of string + pooling (i.e. `CreateSharedString`) as default serialization behavior. + + Specifically, `CreateXxxDirect` functions and `Pack` functions for object + based API (see below) will use `CreateSharedString` to create strings. + +## Object based API + +FlatBuffers is all about memory efficiency, which is why its base API is written +around using as little as possible of it. This does make the API clumsier +(requiring pre-order construction of all data, and making mutation harder). + +For times when efficiency is less important a more convenient object based API +can be used (through `--gen-object-api`) that is able to unpack & pack a +FlatBuffer into objects and standard STL containers, allowing for convenient +construction, access and mutation. + +To use: + +```cpp + // Autogenerated class from table Monster. + MonsterT monsterobj; + + // Deserialize from buffer into object. + GetMonster(flatbuffer)->UnPackTo(&monsterobj); + + // Update object directly like a C++ class instance. + cout << monsterobj.name; // This is now a std::string! + monsterobj.name = "Bob"; // Change the name. + + // Serialize into new flatbuffer. + FlatBufferBuilder fbb; + fbb.Finish(Monster::Pack(fbb, &monsterobj)); +``` + +The following attributes are specific to the object-based API code generation: + +- `native_inline` (on a field): Because FlatBuffer tables and structs are + optionally present in a given buffer, they are best represented as pointers + (specifically std::unique_ptrs) in the native class since they can be null. + This attribute changes the member declaration to use the type directly + rather than wrapped in a unique_ptr. + +- `native_default("value")` (on a field): For members that are declared + "native_inline", the value specified with this attribute will be included + verbatim in the class constructor initializer list for this member. + +- `native_custom_alloc("custom_allocator")` (on a table or struct): When using the + object-based API all generated NativeTables that are allocated when unpacking + your flatbuffer will use "custom allocator". The allocator is also used by + any std::vector that appears in a table defined with `native_custom_alloc`. + This can be used to provide allocation from a pool for example, for faster + unpacking when using the object-based API. + +Minimal Example: + +schema: + +```cpp + table mytable(native_custom_alloc:"custom_allocator") { + ... + } +``` + +with `custom_allocator` defined before `flatbuffers.h` is included, as: + +```cpp + template struct custom_allocator : public std::allocator { + + typedef T *pointer; + + template + struct rebind { + typedef custom_allocator other; + }; + + pointer allocate(const std::size_t n) { + return std::allocator::allocate(n); + } + + void deallocate(T* ptr, std::size_t n) { + return std::allocator::deallocate(ptr,n); + } + + custom_allocator() throw() {} + + template + custom_allocator(const custom_allocator&) throw() {} + }; +``` + +- `native_type("type")` (on a struct): In some cases, a more optimal C++ data +type exists for a given struct. For example, the following schema: + +```cpp + struct Vec2 { + x: float; + y: float; + } +``` + +generates the following Object-Based API class: + +```cpp + struct Vec2T : flatbuffers::NativeTable { + float x; + float y; + }; +``` + +However, it can be useful to instead use a user-defined C++ type since it +can provide more functionality, eg. + +```cpp + struct vector2 { + float x = 0, y = 0; + vector2 operator+(vector2 rhs) const { ... } + vector2 operator-(vector2 rhs) const { ... } + float length() const { ... } + // etc. + }; +``` + +The `native_type` attribute will replace the usage of the generated class +with the given type. So, continuing with the example, the generated +code would use `vector2` in place of `Vec2T` for all generated code of +the Object-Based API. + +However, because the `native_type` is unknown to flatbuffers, the user must +provide the following functions to aide in the serialization process: + +```cpp + namespace flatbuffers { + Vec2 Pack(const vector2& obj); + vector2 UnPack(const Vec2& obj); + } +``` + +- `native_type_pack_name("name")` (on a struct when `native_type` is + specified, too): when you want to use the same `native_type` multiple times + (e. g. with different precision) you must make the names of the Pack/UnPack + functions unique, otherwise you will run into compile errors. This attribute + appends a name to the expected Pack/UnPack functions. So when you + specify `native_type_pack_name("Vec2")` in the above example you now need to + implement these serialization functions instead: + +```cpp + namespace flatbuffers { + Vec2 PackVec2(const vector2& obj); + vector2 UnPackVec2(const Vec2& obj); + } +``` + +Finally, the following top-level attributes: + +- `native_include("path")` (at file level): Because the `native_type` attribute + can be used to introduce types that are unknown to flatbuffers, it may be + necessary to include "external" header files in the generated code. This + attribute can be used to directly add an #include directive to the top of + the generated code that includes the specified path directly. + +- `force_align`: this attribute may not be respected in the object API, + depending on the aligned of the allocator used with `new`. + +## External references + +An additional feature of the object API is the ability to allow you to load +multiple independent FlatBuffers, and have them refer to eachothers objects +using hashes which are then represented as typed pointers in the object API. + +To make this work have a field in the objects you want to referred to which is +using the string hashing feature (see `hash` attribute in the +[schema](../schema.md) documentation). Then you have +a similar hash in the field referring to it, along with a `cpp_type` +attribute specifying the C++ type this will refer to (this can be any C++ +type, and will get a `*` added). + +Then, in JSON or however you create these buffers, make sure they use the +same string (or hash). + +When you call `UnPack` (or `Create`), you'll need a function that maps from +hash to the object (see `resolver_function_t` for details). + +## Using different pointer types + +By default the object tree is built out of `std::unique_ptr`, but you can +influence this either globally (using the `--cpp-ptr-type` argument to +`flatc`) or per field (using the `cpp_ptr_type` attribute) to by any smart +pointer type (`my_ptr`), or by specifying `naked` as the type to get `T *` +pointers. Unlike the smart pointers, naked pointers do not manage memory for +you, so you'll have to manage their lifecycles manually. To reference the +pointer type specified by the `--cpp-ptr-type` argument to `flatc` from a +flatbuffer field set the `cpp_ptr_type` attribute to `default_ptr_type`. + +## Using different string type + +By default the object tree is built out of `std::string`, but you can +influence this either globally (using the `--cpp-str-type` argument to +`flatc`) or per field using the `cpp_str_type` attribute. + +The type must support `T::c_str()`, `T::length()` and `T::empty()` as member functions. + +Further, the type must be constructible from std::string, as by default a +std::string instance is constructed and then used to initialize the custom +string type. This behavior impedes efficient and zero-copy construction of +custom string types; the `--cpp-str-flex-ctor` argument to `flatc` or the +per field attribute `cpp_str_flex_ctor` can be used to change this behavior, +so that the custom string type is constructed by passing the pointer and +length of the FlatBuffers String. The custom string class will require a +constructor in the following format: `custom_str_class(const char *, size_t)`. +Please note that the character array is not guaranteed to be NULL terminated, +you should always use the provided size to determine end of string. + +## Reflection (& Resizing) + +There is experimental support for reflection in FlatBuffers, allowing you to +read and write data even if you don't know the exact format of a buffer, and +even allows you to change sizes of strings and vectors in-place. + +The way this works is very elegant; there is actually a FlatBuffer schema that +describes schemas (\!) which you can find in `reflection/reflection.fbs`. +The compiler, `flatc`, can write out any schemas it has just parsed as a binary +FlatBuffer, corresponding to this meta-schema. + +Loading in one of these binary schemas at runtime allows you traverse any +FlatBuffer data that corresponds to it without knowing the exact format. You +can query what fields are present, and then read/write them after. + +For convenient field manipulation, you can include the header +`flatbuffers/reflection.h` which includes both the generated code from the meta +schema, as well as a lot of helper functions. + +And example of usage, for the time being, can be found in +`test.cpp/ReflectionTest()`. + +## Mini Reflection + +A more limited form of reflection is available for direct inclusion in +generated code, which doesn't do any (binary) schema access at all. It was designed +to keep the overhead of reflection as low as possible (on the order of 2-6 +bytes per field added to your executable), but doesn't contain all the +information the (binary) schema contains. + +You add this information to your generated code by specifying `--reflect-types` +(or instead `--reflect-names` if you also want field / enum names). + +You can now use this information, for example to print a FlatBuffer to text: + + auto s = flatbuffers::FlatBufferToString(flatbuf, MonsterTypeTable()); + +`MonsterTypeTable()` is declared in the generated code for each type. The +string produced is very similar to the JSON produced by the `Parser` based +text generator. + +You'll need `flatbuffers/minireflect.h` for this functionality. In there is also +a convenient visitor/iterator so you can write your own output / functionality +based on the mini reflection tables without having to know the FlatBuffers or +reflection encoding. + +## Storing maps / dictionaries in a FlatBuffer + +FlatBuffers doesn't support maps natively, but there is support to +emulate their behavior with vectors and binary search, which means you +can have fast lookups directly from a FlatBuffer without having to unpack +your data into a `std::map` or similar. + +To use it: +- Designate one of the fields in a table as they "key" field. You do this + by setting the `key` attribute on this field, e.g. + `name:string (key)`. + You may only have one key field, and it must be of string or scalar type. +- Write out tables of this type as usual, collect their offsets in an + array or vector. +- Instead of `CreateVector`, call `CreateVectorOfSortedTables`, + which will first sort all offsets such that the tables they refer to + are sorted by the key field, then serialize it. +- Now when you're accessing the FlatBuffer, you can use `Vector::LookupByKey` + instead of just `Vector::Get` to access elements of the vector, e.g.: + `myvector->LookupByKey("Fred")`, which returns a pointer to the + corresponding table type, or `nullptr` if not found. + `LookupByKey` performs a binary search, so should have a similar speed to + `std::map`, though may be faster because of better caching. `LookupByKey` + only works if the vector has been sorted, it will likely not find elements + if it hasn't been sorted. + +## Direct memory access + +As you can see from the above examples, all elements in a buffer are +accessed through generated accessors. This is because everything is +stored in little endian format on all platforms (the accessor +performs a swap operation on big endian machines), and also because +the layout of things is generally not known to the user. + +For structs, layout is deterministic and guaranteed to be the same +across platforms (scalars are aligned to their +own size, and structs themselves to their largest member), and you +are allowed to access this memory directly by using `sizeof()` and +`memcpy` on the pointer to a struct, or even an array of structs. + +To compute offsets to sub-elements of a struct, make sure they +are a structs themselves, as then you can use the pointers to +figure out the offset without having to hardcode it. This is +handy for use of arrays of structs with calls like `glVertexAttribPointer` +in OpenGL or similar APIs. + +It is important to note is that structs are still little endian on all +machines, so only use tricks like this if you can guarantee you're not +shipping on a big endian machine (an `assert(FLATBUFFERS_LITTLEENDIAN)` +would be wise). + +## Access of untrusted buffers + +The generated accessor functions access fields over offsets, which is +very quick. These offsets are not verified at run-time, so a malformed +buffer could cause a program to crash by accessing random memory. + +When you're processing large amounts of data from a source you know (e.g. +your own generated data on disk), this is acceptable, but when reading +data from the network that can potentially have been modified by an +attacker, this is undesirable. + +For this reason, you can optionally use a buffer verifier before you +access the data. This verifier will check all offsets, all sizes of +fields, and null termination of strings to ensure that when a buffer +is accessed, all reads will end up inside the buffer. + +Each root type will have a verification function generated for it, +e.g. for `Monster`, you can call: + +```cpp + bool ok = VerifyMonsterBuffer(Verifier(buf, len)); +``` + +if `ok` is true, the buffer is safe to read. + +Besides untrusted data, this function may be useful to call in debug +mode, as extra insurance against data being corrupted somewhere along +the way. + +While verifying a buffer isn't "free", it is typically faster than +a full traversal (since any scalar data is not actually touched), +and since it may cause the buffer to be brought into cache before +reading, the actual overhead may be even lower than expected. + +In specialized cases where a denial of service attack is possible, +the verifier has two additional constructor arguments that allow +you to limit the nesting depth and total amount of tables the +verifier may encounter before declaring the buffer malformed. The default is +`Verifier(buf, len, 64 /* max depth */, 1000000, /* max tables */)` which +should be sufficient for most uses. + +## Text & schema parsing + +Using binary buffers with the generated header provides a super low +overhead use of FlatBuffer data. There are, however, times when you want +to use text formats, for example because it interacts better with source +control, or you want to give your users easy access to data. + +Another reason might be that you already have a lot of data in JSON +format, or a tool that generates JSON, and if you can write a schema for +it, this will provide you an easy way to use that data directly. + +(see the schema documentation for some specifics on the JSON format +accepted). + +Schema evolution compatibility for the JSON format follows the same rules as the binary format (JSON formatted data will be forwards/backwards compatible with schemas that evolve in a compatible way). + +There are two ways to use text formats: + +#### Using the compiler as a conversion tool + +This is the preferred path, as it doesn't require you to add any new +code to your program, and is maximally efficient since you can ship with +binary data. The disadvantage is that it is an extra step for your +users/developers to perform, though you might be able to automate it. + + flatc -b myschema.fbs mydata.json + +This will generate the binary file `mydata_wire.bin` which can be loaded +as before. + +#### Making your program capable of loading text directly + +This gives you maximum flexibility. You could even opt to support both, +i.e. check for both files, and regenerate the binary from text when +required, otherwise just load the binary. + +This option is currently only available for C++, or Java through JNI. + +As mentioned in the section "Building" above, this technique requires +you to link a few more files into your program, and you'll want to include +`flatbuffers/idl.h`. + +Load text (either a schema or json) into an in-memory buffer (there is a +convenient `LoadFile()` utility function in `flatbuffers/util.h` if you +wish). Construct a parser: + +```cpp + flatbuffers::Parser parser; +``` + +Now you can parse any number of text files in sequence: + +```cpp + parser.Parse(text_file.c_str()); +``` + +This works similarly to how the command-line compiler works: a sequence +of files parsed by the same `Parser` object allow later files to +reference definitions in earlier files. Typically this means you first +load a schema file (which populates `Parser` with definitions), followed +by one or more JSON files. + +As optional argument to `Parse`, you may specify a null-terminated list of +include paths. If not specified, any include statements try to resolve from +the current directory. + +If there were any parsing errors, `Parse` will return `false`, and +`Parser::error_` contains a human readable error string with a line number +etc, which you should present to the creator of that file. + +After each JSON file, the `Parser::fbb` member variable is the +`FlatBufferBuilder` that contains the binary buffer version of that +file, that you can access as described above. + +`samples/sample_text.cpp` is a code sample showing the above operations. + +## Threading + +Reading a FlatBuffer does not touch any memory outside the original buffer, +and is entirely read-only (all const), so is safe to access from multiple +threads even without synchronisation primitives. + +Creating a FlatBuffer is not thread safe. All state related to building +a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory +outside of it is touched. To make this thread safe, either do not +share instances of FlatBufferBuilder between threads (recommended), or +manually wrap it in synchronisation primitives. There's no automatic way to +accomplish this, by design, as we feel multithreaded construction +of a single buffer will be rare, and synchronisation overhead would be costly. + +## Advanced union features + +The C++ implementation currently supports vectors of unions (i.e. you can +declare a field as `[T]` where `T` is a union type instead of a table type). It +also supports structs and strings in unions, besides tables. + +For an example of these features, see `tests/union_vector`, and +`UnionVectorTest` in `test.cpp`. + +Since these features haven't been ported to other languages yet, if you +choose to use them, you won't be able to use these buffers in other languages +(`flatc` will refuse to compile a schema that uses these features). + +These features reduce the amount of "table wrapping" that was previously +needed to use unions. + +To use scalars, simply wrap them in a struct. + +## Depth limit of nested objects and stack-overflow control +The parser of Flatbuffers schema or json-files is kind of recursive parser. +To avoid stack-overflow problem the parser has a built-in limiter of +recursion depth. Number of nested declarations in a schema or number of +nested json-objects is limited. By default, this depth limit set to `64`. +It is possible to override this limit with `FLATBUFFERS_MAX_PARSING_DEPTH` +definition. This definition can be helpful for testing purposes or embedded +applications. For details see [build](../building.md) of +CMake-based projects. + +## Dependence from C-locale {#flatbuffers_locale_cpp} +The Flatbuffers [grammar](../grammar.md) uses ASCII +character set for identifiers, alphanumeric literals, reserved words. + +Internal implementation of the Flatbuffers depends from functions which +depend from C-locale: `strtod()` or `strtof()`, for example. +The library expects the dot `.` symbol as the separator of an integer +part from the fractional part of a float number. +Another separator symbols (`,` for example) will break the compatibility +and may lead to an error while parsing a Flatbuffers schema or a json file. + +The Standard C locale is a global resource, there is only one locale for +the entire application. Some modern compilers and platforms have +locale-independent or locale-narrow functions `strtof_l`, `strtod_l`, +`strtoll_l`, `strtoull_l` to resolve this dependency. +These functions use specified locale rather than the global or per-thread +locale instead. They are part of POSIX-2008 but not part of the C/C++ +standard library, therefore, may be missing on some platforms. +The Flatbuffers library try to detect these functions at configuration and +compile time: +- CMake `"CMakeLists.txt"`: + - Check existence of `strtol_l` and `strtod_l` in the ``. +- Compile-time `"/include/base.h"`: + - `_MSC_VER >= 1900`: MSVC2012 or higher if build with MSVC. + - `_XOPEN_SOURCE>=700`: POSIX-2008 if build with GCC/Clang. + +After detection, the definition `FLATBUFFERS_LOCALE_INDEPENDENT` will be +set to `0` or `1`. +To override or stop this detection use CMake `-DFLATBUFFERS_LOCALE_INDEPENDENT={0|1}` +or predefine `FLATBUFFERS_LOCALE_INDEPENDENT` symbol. + +To test the compatibility of the Flatbuffers library with +a specific locale use the environment variable `FLATBUFFERS_TEST_LOCALE`: +```sh +>FLATBUFFERS_TEST_LOCALE="" ./flattests +>FLATBUFFERS_TEST_LOCALE="ru_RU.CP1251" ./flattests +``` + +## Support of floating-point numbers +The Flatbuffers library assumes that a C++ compiler and a CPU are +compatible with the `IEEE-754` floating-point standard. +The schema and json parser may fail if `fast-math` or `/fp:fast` mode is active. + +### Support of hexadecimal and special floating-point numbers +According to the [grammar](../grammar.md) `fbs` and `json` files +may use hexadecimal and special (`NaN`, `Inf`) floating-point literals. +The Flatbuffers uses `strtof` and `strtod` functions to parse floating-point +literals. The Flatbuffers library has a code to detect a compiler compatibility +with the literals. If necessary conditions are met the preprocessor constant +`FLATBUFFERS_HAS_NEW_STRTOD` will be set to `1`. +The support of floating-point literals will be limited at compile time +if `FLATBUFFERS_HAS_NEW_STRTOD` constant is less than `1`. +In this case, schemas with hexadecimal or special literals cannot be used. + +### Comparison of floating-point NaN values +The floating-point `NaN` (`not a number`) is special value which +representing an undefined or unrepresentable value. +`NaN` may be explicitly assigned to variables, typically as a representation +for missing values or may be a result of a mathematical operation. +The `IEEE-754` defines two kind of `NaNs`: +- Quiet NaNs, or `qNaNs`. +- Signaling NaNs, or `sNaNs`. + +According to the `IEEE-754`, a comparison with `NaN` always returns +an unordered result even when compared with itself. As a result, a whole +Flatbuffers object will be not equal to itself if has one or more `NaN`. +Flatbuffers scalar fields that have the default value are not actually stored +in the serialized data but are generated in code (see [Writing a schema](../schema.md)). +Scalar fields with `NaN` defaults break this behavior. +If a schema has a lot of `NaN` defaults the Flatbuffers can override +the unordered comparison by the ordered: `(NaN==NaN)->true`. +This ordered comparison is enabled when compiling a program with the symbol +`FLATBUFFERS_NAN_DEFAULTS` defined. +Additional computations added by `FLATBUFFERS_NAN_DEFAULTS` are very cheap +if GCC or Clang used. These compilers have a compile-time implementation +of `isnan` checking which MSVC does not. + +## gRPC + +### Before you get started + +Before diving into the FlatBuffers gRPC usage in C++, you should already be +familiar with the following: + +- FlatBuffers as a serialization format +- [gRPC](http://www.grpc.io/docs/) usage + +### Using the FlatBuffers gRPC C++ library + +NOTE: The examples below are also in the `grpc/samples/greeter` directory. + +We will illustrate usage with the following schema: + +```c++ title="grpc/samples/greeter/greeter.fbs" +--8<-- "https://raw.githubusercontent.com/google/flatbuffers/refs/heads/master/grpc/samples/greeter/greeter.fbs" +``` + +When we run `flatc`, we pass in the `--grpc` option and generage an additional +`greeter.grpc.fb.h` and `greeter.grpc.fb.cc`. + +Example server code looks like this: + +```c++ title="grpc/samples/greeter/server.cpp" +--8<-- "https://raw.githubusercontent.com/google/flatbuffers/refs/heads/master/grpc/samples/greeter/server.cpp" +``` + +Example client code looks like this: + +```c++ title="grpc/samples/greeter/client.cpp" +--8<-- "https://raw.githubusercontent.com/google/flatbuffers/refs/heads/master/grpc/samples/greeter/client.cpp" +``` + diff --git a/third_party/flatbuffers/docs/source/languages/dart.md b/third_party/flatbuffers/docs/source/languages/dart.md new file mode 100644 index 00000000000..ca370c71f3d --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/dart.md @@ -0,0 +1,131 @@ +Use in Dart {#flatbuffers_guide_use_dart} +=========== + +## Before you get started + +Before diving into the FlatBuffers usage in Dart, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide +to general FlatBuffers usage in all of the supported languages (including Dart). +This page is designed to cover the nuances of FlatBuffers usage, specific to +Dart. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Dart library code location + +The code for the FlatBuffers Dart library can be found at +`flatbuffers/dart`. You can browse the library code on the [FlatBuffers +GitHub page](https://github.com/google/flatbuffers/tree/master/dart). + +## Testing the FlatBuffers Dart library + +The code to test the Dart library can be found at `flatbuffers/tests`. +The test code itself is located in [dart_test.dart](https://github.com/google/ +flatbuffers/blob/master/tests/dart_test.dart). + +To run the tests, use the [DartTest.sh](https://github.com/google/flatbuffers/ +blob/master/tests/DartTest.sh) shell script. + +*Note: The shell script requires the [Dart SDK](https://www.dartlang.org/tools/sdk) +to be installed.* + +## Using the FlatBuffers Dart library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Dart.* + +FlatBuffers supports reading and writing binary FlatBuffers in Dart. + +To use FlatBuffers in your own code, first generate Dart classes from your +schema with the `--dart` option to `flatc`. Then you can include both FlatBuffers +and the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Dart: First, +include the library and generated code. Then read a FlatBuffer binary file into +a `List`, which you pass to the factory constructor for `Monster`: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} +import 'dart:io' as io; + +import 'package:flat_buffers/flat_buffers.dart' as fb; +import './monster_my_game.sample_generated.dart' as myGame; + +List data = await new io.File('monster.dat').readAsBytes(); +var monster = new myGame.Monster(data); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access values like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} +var hp = monster.hp; +var pos = monster.pos; +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +## Differences from the Dart SDK Front End flat_buffers + +The work in this repository is signfiicantly based on the implementation used +internally by the Dart SDK in the front end/analyzer package. Several +significant changes have been made. + +1. Support for packed boolean lists has been removed. This is not standard + in other implementations and is not compatible with them. Do note that, + like in the JavaScript implementation, __null values in boolean lists + will be treated as false__. It is also still entirely possible to pack data + in a single scalar field, but that would have to be done on the application + side. +2. The SDK implementation supports enums with regular Dart enums, which + works if enums are always indexed at 1; however, FlatBuffers does not + require that. This implementation uses specialized enum-like classes to + ensure proper mapping from FlatBuffers to Dart and other platforms. +3. The SDK implementation does not appear to support FlatBuffer structs or + vectors of structs - it treated everything as a built-in scalar or a table. + This implementation treats structs in a way that is compatible with other + non-Dart implementations, and properly handles vectors of structs. Many of + the methods prefixed with 'low' have been prepurposed to support this. +4. The SDK implementation treats int64 and uint64 as float64s. This + implementation does not. This may cause problems with JavaScript + compatibility - however, it should be possible to use the JavaScript + implementation, or to do a customized implementation that treats all 64 bit + numbers as floats. Supporting the Dart VM and Flutter was a more important + goal of this implementation. Support for 16 bit integers was also added. +5. The code generation in this offers an "ObjectBuilder", which generates code + very similar to the SDK classes that consume FlatBuffers, as well as Builder + classes, which produces code which more closely resembles the builders in + other languages. The ObjectBuilder classes are easier to use, at the cost of + additional references allocated. + +## Text Parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from Dart, though you could use the C++ parser through Dart Native Extensions. +Please see the C++ documentation for more on text parsing (note that this is +not currently an option in Flutter - follow [this issue](https://github.com/flutter/flutter/issues/7053) +for the latest). + +## Object based API + +FlatBuffers is all about memory efficiency, which is why its base API is written +around using as little as possible of it. This does make the API clumsier +(requiring pre-order construction of all data, and making mutation harder). + +For times when efficiency is less important a more convenient object based API +can be used (through `--gen-object-api`) that is able to unpack & pack a FlatBuffer +into objects and lists, allowing for convenient construction, access and mutation. + +To use: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.dart} + // Deserialize from buffer into object. + MonsterT monster = Monster(flatbuffer).unpack(); + + // Update object directly like a Dart class instance. + print(monster.Name); + monster.Name = "Bob"; // Change the name. + + // Serialize into new flatbuffer. + final fbb = Builder(); + fbb.Finish(monster.pack(fbb)); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/third_party/flatbuffers/docs/source/languages/go.md b/third_party/flatbuffers/docs/source/languages/go.md new file mode 100644 index 00000000000..75ee79dfee1 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/go.md @@ -0,0 +1,99 @@ +Use in Go {#flatbuffers_guide_use_go} +========= + +## Before you get started + +Before diving into the FlatBuffers usage in Go, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide +to general FlatBuffers usage in all of the supported languages (including Go). +This page is designed to cover the nuances of FlatBuffers usage, specific to +Go. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Go library code location + +The code for the FlatBuffers Go library can be found at +`flatbuffers/go`. You can browse the library code on the [FlatBuffers +GitHub page](https://github.com/google/flatbuffers/tree/master/go). + +## Testing the FlatBuffers Go library + +The code to test the Go library can be found at `flatbuffers/tests`. +The test code itself is located in [go_test.go](https://github.com/google/ +flatbuffers/blob/master/tests/go_test.go). + +To run the tests, use the [GoTest.sh](https://github.com/google/flatbuffers/ +blob/master/tests/GoTest.sh) shell script. + +*Note: The shell script requires [Go](https://golang.org/doc/install) to +be installed.* + +## Using the FlatBuffers Go library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Go.* + +FlatBuffers supports reading and writing binary FlatBuffers in Go. + +To use FlatBuffers in your own code, first generate Go classes from your +schema with the `--go` option to `flatc`. Then you can include both FlatBuffers +and the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Go: First, +include the library and generated code. Then read a FlatBuffer binary file into +a `[]byte`, which you pass to the `GetRootAsMonster` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} + import ( + example "MyGame/Example" + flatbuffers "github.com/google/flatbuffers/go" + + "os" + ) + + buf, err := os.ReadFile("monster.dat") + // handle err + monster := example.GetRootAsMonster(buf, 0) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access values like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} + hp := monster.Hp() + pos := monster.Pos(nil) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.go} + monster := example.GetRootAsMonster(buf, 0) + + // Set table field. + if ok := monster.MutateHp(10); !ok { + panic("failed to mutate Hp") + } + + // Set struct field. + monster.Pos().MutateZ(4) + + // This mutation will fail because the mana field is not available in + // the buffer. It should be set when creating the buffer. + if ok := monster.MutateMana(20); !ok { + panic("failed to mutate Hp") + } +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The term `mutate` is used instead of `set` to indicate that this is a special use case. All mutate functions return a boolean value which is false if the field we're trying to mutate is not available in the buffer. + +## Text Parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from Go, though you could use the C++ parser through cgo. Please see the +C++ documentation for more on text parsing. + +
diff --git a/third_party/flatbuffers/docs/source/languages/java.md b/third_party/flatbuffers/docs/source/languages/java.md new file mode 100644 index 00000000000..bfbd3e41cc7 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/java.md @@ -0,0 +1,114 @@ +Use in Java {#flatbuffers_guide_use_java} +============== + +## Before you get started + +Before diving into the FlatBuffers usage in Java, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide to +general FlatBuffers usage in all of the supported languages (including Java). +This page is designed to cover the nuances of FlatBuffers usage, +specific to Java. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Java code location + +The code for the FlatBuffers Java library can be found at +`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ +java/com/google/flatbuffers). + +## Testing the FlatBuffers Java libraries + +The code to test the libraries can be found at `flatbuffers/tests`. + +The test code for Java is located in [JavaTest.java](https://github.com/google +/flatbuffers/blob/master/tests/JavaTest.java). + +To run the tests, use either [JavaTest.sh](https://github.com/google/ +flatbuffers/blob/master/tests/JavaTest.sh) or [JavaTest.bat](https://github.com/ +google/flatbuffers/blob/master/tests/JavaTest.bat), depending on your operating +system. + +*Note: These scripts require that [Java](https://www.oracle.com/java/index.html) +is installed.* + +## Using the FlatBuffers Java library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Java.* + +FlatBuffers supports reading and writing binary FlatBuffers in Java. + +To use FlatBuffers in your own code, first generate Java classes from your +schema with the `--java` option to `flatc`. +Then you can include both FlatBuffers and the generated code to read +or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Java: +First, import the library and generated code. Then, you read a FlatBuffer binary +file into a `byte[]`. You then turn the `byte[]` into a `ByteBuffer`, which you +pass to the `getRootAsMyRootType` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} + import MyGame.Example.*; + import com.google.flatbuffers.FlatBufferBuilder; + + // This snippet ignores exceptions for brevity. + File file = new File("monsterdata_test.mon"); + RandomAccessFile f = new RandomAccessFile(file, "r"); + byte[] data = new byte[(int)f.length()]; + f.readFully(data); + f.close(); + + ByteBuffer bb = ByteBuffer.wrap(data); + Monster monster = Monster.getRootAsMonster(bb); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access the data from the `Monster monster`: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.java} + short hp = monster.hp(); + Vec3 pos = monster.pos(); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +## Storing dictionaries in a FlatBuffer + +FlatBuffers doesn't support dictionaries natively, but there is support to +emulate their behavior with vectors and binary search, which means you +can have fast lookups directly from a FlatBuffer without having to unpack +your data into a `Dictionary` or similar. + +To use it: +- Designate one of the fields in a table as the "key" field. You do this + by setting the `key` attribute on this field, e.g. + `name:string (key)`. + You may only have one key field, and it must be of string or scalar type. +- Write out tables of this type as usual, collect their offsets in an + array. +- Instead of calling standard generated method, + e.g.: `Monster.createTestarrayoftablesVector`, + call `createSortedVectorOfTables` (from the `FlatBufferBuilder` object). + which will first sort all offsets such that the tables they refer to + are sorted by the key field, then serialize it. +- Now when you're accessing the FlatBuffer, you can use + the `ByKey` accessor to access elements of the vector, e.g.: + `monster.testarrayoftablesByKey("Frodo")`. + which returns an object of the corresponding table type, + or `null` if not found. + `ByKey` performs a binary search, so should have a similar + speed to `Dictionary`, though may be faster because of better caching. + `ByKey` only works if the vector has been sorted, it will + likely not find elements if it hasn't been sorted. + +## Text parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from Java, though you could use the C++ parser through native call +interfaces available to each language. Please see the +C++ documentation for more on text parsing. + +
diff --git a/third_party/flatbuffers/docs/source/languages/javascript.md b/third_party/flatbuffers/docs/source/languages/javascript.md new file mode 100644 index 00000000000..d75442d23b3 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/javascript.md @@ -0,0 +1,93 @@ +Use in JavaScript {#flatbuffers_guide_use_javascript} +================= + +## Before you get started + +Before diving into the FlatBuffers usage in JavaScript, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide to +general FlatBuffers usage in all of the supported languages +(including JavaScript). This page is specifically designed to cover the nuances +of FlatBuffers usage in JavaScript. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers JavaScript library code location + +The generated code for the FlatBuffers JavaScript library can be found at +https://www.npmjs.com/package/flatbuffers. To use it from sources: + +1. Run `npm run compile` from the main folder to generate JS files from TS. +1. In your project, install it as a normal dependency, using the flatbuffers +folder as the source. + +## Using the FlatBuffers JavaScript library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers.* + +Due to the complexity related with large amounts of JS flavors and module types, +native JS support has been replaced in 2.0 by transpilation from TypeScript. + +Please look at [TypeScript usage](typescript.md) and +transpile your sources to desired JS flavor. The minimal steps to get up and +running with JS are: + +1. Generate TS files from `*.fbs` by using the `--ts` option. +1. Transpile resulting TS files to desired JS flavor using `tsc` (see + https://www.typescriptlang.org/download for installation instructions). + +~~~{.js} + // Note: These require functions are an example - use your desired module flavor. + var fs = require('fs'); + + var flatbuffers = require('../flatbuffers').flatbuffers; + var MyGame = require('./monster_generated').MyGame; + + var data = new Uint8Array(fs.readFileSync('monster.dat')); + var buf = new flatbuffers.ByteBuffer(data); + + var monster = MyGame.Example.Monster.getRootAsMonster(buf); + + //--------------------------------------------------------------------------// + + // Note: This code is an example of browser-based HTML/JavaScript. See above + // for the code using JavaScript module loaders (e.g. Node.js). + + + + + // Open the HTML file in a browser and select "monster.dat" from with the + // field. + +~~~ + +Now you can access values like this: + +~~~{.js} + var hp = monster.hp(); + var pos = monster.pos(); +~~~ + +## Text parsing FlatBuffers in JavaScript + +There currently is no support for parsing text (Schema's and JSON) directly +from JavaScript. diff --git a/third_party/flatbuffers/docs/source/languages/kotlin.md b/third_party/flatbuffers/docs/source/languages/kotlin.md new file mode 100644 index 00000000000..43e7eaa0ec6 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/kotlin.md @@ -0,0 +1,84 @@ +Use in Kotlin {#flatbuffers_guide_use_kotlin} +============== + +## Before you get started + +Before diving into the FlatBuffers usage in Kotlin, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide to +general FlatBuffers usage in all of the supported languages (including K). + +This page is designed to cover the nuances of FlatBuffers usage, specific to Kotlin. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## Kotlin and FlatBuffers Java code location + +Code generated for Kotlin currently uses the flatbuffers java runtime library. That means that Kotlin generated code can only have Java virtual machine as target architecture (which includes Android). Kotlin Native and Kotlin.js are currently not supported. + +The code for the FlatBuffers Java library can be found at +`flatbuffers/java/com/google/flatbuffers`. You can browse the library on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ +java/com/google/flatbuffers). + +## Testing FlatBuffers Kotlin + +The test code for Java is located in [KotlinTest.java](https://github.com/google +/flatbuffers/blob/master/tests/KotlinTest.kt). + +To run the tests, use [KotlinTest.sh](https://github.com/google/ +flatbuffers/blob/master/tests/KotlinTest.sh) shell script. + +*Note: These scripts require that [Kotlin](https://kotlinlang.org/) is installed.* + +## Using the FlatBuffers Kotlin library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Kotlin.* + +FlatBuffers supports reading and writing binary FlatBuffers in Kotlin. + +To use FlatBuffers in your own code, first generate Java classes from your +schema with the `--kotlin` option to `flatc`. +Then you can include both FlatBuffers and the generated code to read +or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Kotlin: +First, import the library and generated code. Then, you read a FlatBuffer binary +file into a `ByteArray`. You then turn the `ByteArray` into a `ByteBuffer`, which you +pass to the `getRootAsMyRootType` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt} + import MyGame.Example.* + import com.google.flatbuffers.FlatBufferBuilder + + // This snippet ignores exceptions for brevity. + val data = RandomAccessFile(File("monsterdata_test.mon"), "r").use { + val temp = ByteArray(it.length().toInt()) + it.readFully(temp) + temp + } + + val bb = ByteBuffer.wrap(data) + val monster = Monster.getRootAsMonster(bb) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access the data from the `Monster monster`: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.kt} + val hp = monster.hp + val pos = monster.pos!!; +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + + +## Differences between Kotlin and Java code + +Kotlin generated code was designed to be as close as possible to the java counterpart, as for now, we only support kotlin on java virtual machine. So the differences in implementation and usage are basically the ones introduced by the Kotlin language itself. You can find more in-depth information [here](https://kotlinlang.org/docs/reference/comparison-to-java.html). + +The most obvious ones are: + +* Fields as accessed as Kotlin [properties](https://kotlinlang.org/docs/reference/properties.html) +* Static methods are accessed in [companion object](https://kotlinlang.org/docs/reference/classes.html#companion-objects) \ No newline at end of file diff --git a/third_party/flatbuffers/docs/source/languages/lobster.md b/third_party/flatbuffers/docs/source/languages/lobster.md new file mode 100644 index 00000000000..109341f7154 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/lobster.md @@ -0,0 +1,85 @@ +Use in Lobster {#flatbuffers_guide_use_lobster} +============== + +## Before you get started + +Before diving into the FlatBuffers usage in Lobster, it should be noted that the +[Tutorial](../tutorial.md) page has a complete guide to general +FlatBuffers usage in all of the supported languages (including Lobster). This +page is designed to cover the nuances of FlatBuffers usage, specific to +Lobster. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Lobster library code location + +The code for the FlatBuffers Lobster library can be found at +`flatbuffers/lobster`. You can browse the library code on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ +lobster). + +## Testing the FlatBuffers Lobster library + +The code to test the Lobster library can be found at `flatbuffers/tests`. +The test code itself is located in [lobstertest.lobster](https://github.com/google/ +flatbuffers/blob/master/tests/lobstertest.lobster). + +To run the tests, run `lobster lobstertest.lobster`. To obtain Lobster itself, +go to the [Lobster homepage](http://strlen.com/lobster) or +[github](https://github.com/aardappel/lobster) to learn how to build it for your +platform. + +## Using the FlatBuffers Lobster library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Lobster.* + +There is support for both reading and writing FlatBuffers in Lobster. + +To use FlatBuffers in your own code, first generate Lobster classes from your +schema with the `--lobster` option to `flatc`. Then you can include both +FlatBuffers and the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Lobster: +First, import the library and the generated code. Then read a FlatBuffer binary +file into a string, which you pass to the `GetRootAsMonster` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lobster} + include "monster_generated.lobster" + + let fb = read_file("monsterdata_test.mon") + assert fb + let monster = MyGame_Example_GetRootAsMonster(fb) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access values like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lobster} + let hp = monster.hp + let pos = monster.pos +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +As you can see, even though `hp` and `pos` are functions that access FlatBuffer +data in-place in the string buffer, they appear as field accesses. + +## Speed + +Using FlatBuffers in Lobster should be relatively fast, as the implementation +makes use of native support for writing binary values, and access of vtables. +Both generated code and the runtime library are therefore small and fast. + +Actual speed will depend on whether you use Lobster as bytecode VM or compiled to +C++. + +## Text Parsing + +Lobster has full support for parsing JSON into FlatBuffers, or generating +JSON from FlatBuffers. See `samples/sample_test.lobster` for an example. + +This uses the C++ parser and generator underneath, so should be both fast and +conformant. + +
diff --git a/third_party/flatbuffers/docs/source/languages/lua.md b/third_party/flatbuffers/docs/source/languages/lua.md new file mode 100644 index 00000000000..6843d468f82 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/lua.md @@ -0,0 +1,81 @@ +Use in Lua {#flatbuffers_guide_use_lua} +============= + +## Before you get started + +Before diving into the FlatBuffers usage in Lua, it should be noted that the +[Tutorial](../tutorial.md) page has a complete guide to general +FlatBuffers usage in all of the supported languages (including Lua). This +page is designed to cover the nuances of FlatBuffers usage, specific to +Lua. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Lua library code location + +The code for the FlatBuffers Lua library can be found at +`flatbuffers/lua`. You can browse the library code on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/lua). + +## Testing the FlatBuffers Lua library + +The code to test the Lua library can be found at `flatbuffers/tests`. +The test code itself is located in [luatest.lua](https://github.com/google/ +flatbuffers/blob/master/tests/luatest.lua). + +To run the tests, use the [LuaTest.sh](https://github.com/google/flatbuffers/ +blob/master/tests/LuaTest.sh) shell script. + +*Note: This script requires [Lua 5.3](https://www.lua.org/) and +[LuaJIT](http://luajit.org/) to be installed.* + +## Using the FlatBuffers Lua library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Lua.* + +There is support for both reading and writing FlatBuffers in Lua. + +To use FlatBuffers in your own code, first generate Lua classes from your +schema with the `--lua` option to `flatc`. Then you can include both +FlatBuffers and the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Lua: +First, require the module and the generated code. Then read a FlatBuffer binary +file into a `string`, which you pass to the `GetRootAsMonster` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lua} + -- require the library + local flatbuffers = require("flatbuffers") + + -- require the generated code + local monster = require("MyGame.Sample.Monster") + + -- read the flatbuffer from a file into a string + local f = io.open('monster.dat', 'rb') + local buf = f:read('*a') + f:close() + + -- parse the flatbuffer to get an instance to the root monster + local monster1 = monster.GetRootAsMonster(buf, 0) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access values like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.lua} + -- use the : notation to access member data + local hp = monster1:Hp() + local pos = monster1:Pos() +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +## Text Parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from Lua, though you could use the C++ parser through SWIG or ctypes. Please +see the C++ documentation for more on text parsing. + +
diff --git a/third_party/flatbuffers/docs/source/languages/php.md b/third_party/flatbuffers/docs/source/languages/php.md new file mode 100644 index 00000000000..8cb96648180 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/php.md @@ -0,0 +1,89 @@ +Use in PHP {#flatbuffers_guide_use_php} +========== + +## Before you get started + +Before diving into the FlatBuffers usage in PHP, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide to +general FlatBuffers usage in all of the supported languages +(including PHP). This page is specifically designed to cover the nuances of +FlatBuffers usage in PHP. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers PHP library code location + +The code for FlatBuffers PHP library can be found at `flatbuffers/php`. You +can browse the library code on the [FlatBuffers +GitHub page](https://github.com/google/flatbuffers/tree/master/php). + +## Testing the FlatBuffers JavaScript library + +The code to test the PHP library can be found at `flatbuffers/tests`. +The test code itself is located in [phpTest.php](https://github.com/google/ +flatbuffers/blob/master/tests/phpTest.php). + +You can run the test with `php phpTest.php` from the command line. + +*Note: The PHP test file requires +[PHP](http://php.net/manual/en/install.php) to be installed.* + +## Using theFlatBuffers PHP library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in PHP.* + +FlatBuffers supports both reading and writing FlatBuffers in PHP. + +To use FlatBuffers in your own code, first generate PHP classes from your schema +with the `--php` option to `flatc`. Then you can include both FlatBuffers and +the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in PHP: +First, include the library and generated code (using the PSR `autoload` +function). Then you can read a FlatBuffer binary file, which you +pass the contents of to the `GetRootAsMonster` function: + +~~~{.php} + // It is recommended that your use PSR autoload when using FlatBuffers in PHP. + // Here is an example: + function __autoload($class_name) { + // The last segment of the class name matches the file name. + $class = substr($class_name, strrpos($class_name, "\\") + 1); + $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); // `flatbuffers` root. + + // Contains the `*.php` files for the FlatBuffers library and the `flatc` generated files. + $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), + join(DIRECTORY_SEPARATOR, array($root_dir, "tests", "MyGame", "Example"))); + foreach ($paths as $path) { + $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); + if (file_exists($file)) { + require($file); + break; + } + } + + // Read the contents of the FlatBuffer binary file. + $filename = "monster.dat"; + $handle = fopen($filename, "rb"); + $contents = $fread($handle, filesize($filename)); + fclose($handle); + + // Pass the contents to `GetRootAsMonster`. + $monster = \MyGame\Example\Monster::GetRootAsMonster($contents); +~~~ + +Now you can access values like this: + +~~~{.php} + $hp = $monster->GetHp(); + $pos = $monster->GetPos(); +~~~ + +## Text Parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from PHP. diff --git a/third_party/flatbuffers/docs/source/languages/python.md b/third_party/flatbuffers/docs/source/languages/python.md new file mode 100644 index 00000000000..a16ed6c6e65 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/python.md @@ -0,0 +1,100 @@ +Use in Python {#flatbuffers_guide_use_python} +============= + +## Before you get started + +Before diving into the FlatBuffers usage in Python, it should be noted that the +[Tutorial](../tutorial.md) page has a complete guide to general +FlatBuffers usage in all of the supported languages (including Python). This +page is designed to cover the nuances of FlatBuffers usage, specific to +Python. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Python library code location + +The code for the FlatBuffers Python library can be found at +`flatbuffers/python/flatbuffers`. You can browse the library code on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/ +python). + +## Testing the FlatBuffers Python library + +The code to test the Python library can be found at `flatbuffers/tests`. +The test code itself is located in [py_test.py](https://github.com/google/ +flatbuffers/blob/master/tests/py_test.py). + +To run the tests, use the [PythonTest.sh](https://github.com/google/flatbuffers/ +blob/master/tests/PythonTest.sh) shell script. + +*Note: This script requires [python](https://www.python.org/) to be +installed.* + +## Using the FlatBuffers Python library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Python.* + +There is support for both reading and writing FlatBuffers in Python. + +To use FlatBuffers in your own code, first generate Python classes from your +schema with the `--python` option to `flatc`. Then you can include both +FlatBuffers and the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in Python: +First, import the library and the generated code. Then read a FlatBuffer binary +file into a `bytearray`, which you pass to the `GetRootAsMonster` function: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} + import MyGame.Example as example + import flatbuffers + + buf = open('monster.dat', 'rb').read() + buf = bytearray(buf) + monster = example.GetRootAsMonster(buf, 0) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access values like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} + hp = monster.Hp() + pos = monster.Pos() +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +## Support for Numpy arrays + +The Flatbuffers python library also has support for accessing scalar +vectors as numpy arrays. This can be orders of magnitude faster than +iterating over the vector one element at a time, and is particularly +useful when unpacking large nested flatbuffers. The generated code for +a scalar vector will have a method `AsNumpy()`. In the +case of the Monster example, you could access the inventory vector +like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} + inventory = monster.InventoryAsNumpy() + # inventory is a numpy array of type np.dtype('uint8') +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +instead of + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.py} + inventory = [] + for i in range(monster.InventoryLength()): + inventory.append(int(monster.Inventory(i))) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Numpy is not a requirement. If numpy is not installed on your system, +then attempting to access one of the `*asNumpy()` methods will result +in a `NumpyRequiredForThisFeature` exception. + +## Text Parsing + +There currently is no support for parsing text (Schema's and JSON) directly +from Python, though you could use the C++ parser through SWIG or ctypes. Please +see the C++ documentation for more on text parsing. + +
diff --git a/third_party/flatbuffers/docs/source/languages/rust.md b/third_party/flatbuffers/docs/source/languages/rust.md new file mode 100644 index 00000000000..0d5af187173 --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/rust.md @@ -0,0 +1,186 @@ +Use in Rust {#flatbuffers_guide_use_rust} +========== + +## Before you get started + +Before diving into the FlatBuffers usage in Rust, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide +to general FlatBuffers usage in all of the supported languages (including Rust). +This page is designed to cover the nuances of FlatBuffers usage, specific to +Rust. + +#### Prerequisites + +This page assumes you have written a FlatBuffers schema and compiled it +with the Schema Compiler. If you have not, please see +[Using the schema compiler](../flatc.md) +and [Writing a schema](../schema.md). + +Assuming you wrote a schema, say `mygame.fbs` (though the extension doesn't +matter), you've generated a Rust file called `mygame_generated.rs` using the +compiler (e.g. `flatc --rust mygame.fbs` or via helpers listed in "Useful +tools created by others" section bellow), you can now start using this in +your program by including the file. As noted, this header relies on the crate +`flatbuffers`, which should be in your include `Cargo.toml`. + +## FlatBuffers Rust library code location + +The code for the FlatBuffers Rust library can be found at +`flatbuffers/rust`. You can browse the library code on the +[FlatBuffers GitHub page](https://github.com/google/flatbuffers/tree/master/rust). + +## Testing the FlatBuffers Rust library + +The code to test the Rust library can be found at `flatbuffers/tests/rust_usage_test`. +The test code itself is located in +[integration_test.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/tests/integration_test.rs) + +This test file requires `flatc` to be present. To review how to build the project, +please read the [Building](../building.md) documentation. + +To run the tests, execute `RustTest.sh` from the `flatbuffers/tests` directory. +For example, on [Linux](https://en.wikipedia.org/wiki/Linux), you would simply +run: `cd tests && ./RustTest.sh`. + +*Note: The shell script requires [Rust](https://www.rust-lang.org) to +be installed.* + +## Using the FlatBuffers Rust library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Rust.* + +FlatBuffers supports both reading and writing FlatBuffers in Rust. + +To use FlatBuffers in your code, first generate the Rust modules from your +schema with the `--rust` option to `flatc`. Then you can import both FlatBuffers +and the generated code to read or write FlatBuffers. + +For example, here is how you would read a FlatBuffer binary file in Rust: +First, include the library and generated code. Then read the file into +a `u8` vector, which you pass, as a byte slice, to `root_as_monster()`. + +This full example program is available in the Rust test suite: +[monster_example.rs](https://github.com/google/flatbuffers/blob/master/tests/rust_usage_test/bin/monster_example.rs) + +It can be run by `cd`ing to the `rust_usage_test` directory and executing: `cargo run monster_example`. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} + extern crate flatbuffers; + + #[allow(dead_code, unused_imports)] + #[path = "../../monster_test_generated.rs"] + mod monster_test_generated; + pub use monster_test_generated::my_game; + + use std::io::Read; + + fn main() { + let mut f = std::fs::File::open("../monsterdata_test.mon").unwrap(); + let mut buf = Vec::new(); + f.read_to_end(&mut buf).expect("file reading failed"); + + let monster = my_game::example::root_as_monster(&buf[..]); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +`monster` is of type `Monster`, and points to somewhere *inside* your +buffer (root object pointers are not the same as `buffer_pointer` !). +If you look in your generated header, you'll see it has +convenient accessors for all fields, e.g. `hp()`, `mana()`, etc: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.rs} + println!("{}", monster.hp()); // `80` + println!("{}", monster.mana()); // default value of `150` + println!("{:?}", monster.name()); // Some("MyMonster") + } +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +*Note: That we never stored a `mana` value, so it will return the default.* + +## Direct memory access + +As you can see from the above examples, all elements in a buffer are +accessed through generated accessors. This is because everything is +stored in little endian format on all platforms (the accessor +performs a swap operation on big endian machines), and also because +the layout of things is generally not known to the user. + +For structs, layout is deterministic and guaranteed to be the same +across platforms (scalars are aligned to their +own size, and structs themselves to their largest member), and you +are allowed to access this memory directly by using `safe_slice` +on the reference to a struct, or even an array of structs. + +To compute offsets to sub-elements of a struct, make sure they +are structs themselves, as then you can use the pointers to +figure out the offset without having to hardcode it. This is +handy for use of arrays of structs with calls like `glVertexAttribPointer` +in OpenGL or similar APIs. + +It is important to note is that structs are still little endian on all +machines, so the functions to enable tricks like this are only exposed on little +endian machines. If you also ship on big endian machines, using an +`#[cfg(target_endian = "little")]` attribute would be wise or your code will not +compile. + +The special function `safe_slice` is implemented on Vector objects that are +represented in memory the same way as they are represented on the wire. This +function is always available on vectors of struct, bool, u8, and i8. It is +conditionally-compiled on little-endian systems for all the remaining scalar +types. + +The FlatBufferBuilder function `create_vector_direct` is implemented for all +types that are endian-safe to write with a `memcpy`. It is the write-equivalent +of `safe_slice`. + +## Access of untrusted buffers + +The safe Rust functions to interpret a slice as a table (`root`, +`size_prefixed_root`, `root_with_opts`, and `size_prefixed_root_with_opts`) +verify the data first. This has some performance cost, but is intended to be +safe for use on flatbuffers from untrusted sources. There are corresponding +`unsafe` versions with names ending in `_unchecked` which skip this +verification, and may access arbitrary memory. + +The generated accessor functions access fields over offsets, which is +very quick. The current implementation uses these to access memory without any +further bounds checking. All of the safe Rust APIs ensure the verifier is run +over these flatbuffers before accessing them. + +When you're processing large amounts of data from a source you know (e.g. +your own generated data on disk), the `_unchecked` versions are acceptable, but +when reading data from the network that can potentially have been modified by an +attacker, it is desirable to use the safe versions which use the verifier. + +## Threading + +Reading a FlatBuffer does not touch any memory outside the original buffer, +and is entirely read-only (all immutable), so is safe to access from multiple +threads even without synchronisation primitives. + +Creating a FlatBuffer is not thread safe. All state related to building +a FlatBuffer is contained in a FlatBufferBuilder instance, and no memory +outside of it is touched. To make this thread safe, either do not +share instances of FlatBufferBuilder between threads (recommended), or +manually wrap it in synchronisation primitives. There's no automatic way to +accomplish this, by design, as we feel multithreaded construction +of a single buffer will be rare, and synchronisation overhead would be costly. + +Unlike most other languages, in Rust these properties are exposed to and +enforced by the type system. `flatbuffers::Table` and the generated table types +are `Send + Sync`, indicating they may be freely shared across threads and data +may be accessed from any thread which receives a const (aka shared) reference. +There are no functions which require a mutable (aka exclusive) reference, which +means all the available functions may be called like this. +`flatbuffers::FlatBufferBuilder` is also `Send + Sync`, but all of the mutating +functions require a mutable (aka exclusive) reference which can only be created +when no other references to the `FlatBufferBuilder` exist, and may not be copied +within the same thread, let alone to a second thread. + +## Useful tools created by others + +* [flatc-rust](https://github.com/frol/flatc-rust) - FlatBuffers compiler +(flatc) as API for transparent `.fbs` to `.rs` code-generation via Cargo +build scripts integration. + +
diff --git a/third_party/flatbuffers/docs/source/languages/swift.md b/third_party/flatbuffers/docs/source/languages/swift.md new file mode 100644 index 00000000000..b967c54d19b --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/swift.md @@ -0,0 +1,97 @@ +Use in Swift {#flatbuffers_guide_use_swift} +========= + +## Before you get started + +Before diving into the FlatBuffers usage in Swift, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide +to general FlatBuffers usage in all of the supported languages (including Swift). +This page is designed to cover the nuances of FlatBuffers usage, specific to +Swift. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers Swift library code location + +The code for the FlatBuffers Swift library can be found at +`flatbuffers/swift`. You can browse the library code on the [FlatBuffers +GitHub page](https://github.com/google/flatbuffers/tree/master/swift). + +## Testing the FlatBuffers Swift library + +The code to test the Swift library can be found at `flatbuffers/tests/swift/tests`. +The test code itself is located in [flatbuffers/tests/swift/tests](https://github.com/google/flatbuffers/blob/master/tests/swift/tests). + +To run the tests, use the [SwiftTest.sh](https://github.com/google/flatbuffers/blob/master/tests/swift/tests/SwiftTest.sh) shell script. + +*Note: The shell script requires [Swift](https://swift.org) to +be installed.* + +## Using the FlatBuffers Swift library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in Swift.* + +FlatBuffers supports reading and writing binary FlatBuffers in Swift. + +To use FlatBuffers in your own code, first generate Swift structs from your +schema with the `--swift` option to `flatc`. Then include FlatBuffers using `SPM` in +by adding the path to `FlatBuffers/swift` into it. The generated code should also be +added to xcode or the path of the package you will be using. Note: sometimes xcode cant +and wont see the generated files, so it's better that you copy them to xcode. + +For example, here is how you would read a FlatBuffer binary file in Swift: First, +include the library and copy thegenerated code. Then read a FlatBuffer binary file or +a data object from the server, which you can pass into the `GetRootAsMonster` function. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift} + import FlatBuffers + + typealias Monster1 = MyGame.Sample.Monster + typealias Vec3 = MyGame.Sample.Vec3 + + let path = FileManager.default.currentDirectoryPath + let url = URL(fileURLWithPath: path, isDirectory: true).appendingPathComponent("monsterdata_test").appendingPathExtension("mon") + guard let data = try? Data(contentsOf: url) else { return } + + let monster = Monster.getRootAsMonster(bb: ByteBuffer(data: data)) +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +Now you can access values like this: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift} + let hp = monster.hp + let pos = monster.pos // uses native swift structs + let pos = monster.mutablePos // uses flatbuffers structs +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + + +In some cases it's necessary to modify values in an existing FlatBuffer in place (without creating a copy). For this reason, scalar fields of a Flatbuffer table or struct can be mutated. + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.swift} + var byteBuffer = ByteBuffer(bytes: data) + // Get an accessor to the root object inside the buffer. + let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) + // let monster: Monster = getRoot(byteBuffer: &byteBuffer) + + if !monster.mutate(hp: 10) { + fatalError("couldn't mutate") + } + // mutate a struct field using flatbuffers struct + // DONT use monster.pos to mutate since swift copy on write + // will not mutate the value in the buffer + let vec = monster.mutablePos.mutate(z: 4) + + // This mutation will fail because the mana field is not available in + // the buffer. It should be set when creating the buffer. + if !monster.mutate(mana: 20) { + fatalError("couldn't mutate") + } +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +The term `mutate` is used instead of `set` to indicate that this is a special use case. All mutate functions return a boolean value which is false if the field we're trying to mutate is not available in the buffer. + +
diff --git a/third_party/flatbuffers/docs/source/languages/typescript.md b/third_party/flatbuffers/docs/source/languages/typescript.md new file mode 100644 index 00000000000..f0e333c588e --- /dev/null +++ b/third_party/flatbuffers/docs/source/languages/typescript.md @@ -0,0 +1,96 @@ +Use in TypeScript {#flatbuffers_guide_use_typescript} +================= + +## Before you get started + +Before diving into the FlatBuffers usage in TypeScript, it should be noted that +the [Tutorial](../tutorial.md) page has a complete guide to +general FlatBuffers usage in all of the supported languages +(including TypeScript). This page is specifically designed to cover the nuances +of FlatBuffers usage in TypeScript. + +You should also have read the [Building](../building.md) +documentation to build `flatc` and should be familiar with +[Using the schema compiler](../flatc.md) and +[Writing a schema](../schema.md). + +## FlatBuffers TypeScript library code location + +The code for the FlatBuffers TypeScript library can be found at +https://www.npmjs.com/package/flatbuffers. + +## Testing the FlatBuffers TypeScript library + +To run the tests, use the [TypeScriptTest.py](https://github.com/google/ +flatbuffers/blob/master/tests/TypeScriptTest.py) Python3 script. + +*Note: The TypeScript test file requires [Node.js](https://nodejs.org/en/).* + +## Using the FlatBuffers TypeScript library + +*Note: See [Tutorial](../tutorial.md) for a more in-depth +example of how to use FlatBuffers in TypeScript.* + +FlatBuffers supports both reading and writing FlatBuffers in TypeScript. + +To use FlatBuffers in your own code, first generate TypeScript classes from your +schema with the `--ts` option to `flatc`. Then you can include both FlatBuffers +and the generated code to read or write a FlatBuffer. + +For example, here is how you would read a FlatBuffer binary file in TypeScript: +First, include the library and generated code. Then read the file into an +`Uint8Array`. Make a `flatbuffers.ByteBuffer` out of the `Uint8Array`, and pass +the ByteBuffer to the `getRootAsMonster` function. + +~~~{.ts} + import * as flatbuffers from 'flatbuffers'; + + import { MyGame } from './monster_generated'; + + let data = new Uint8Array(fs.readFileSync('monster.dat')); + let buf = new flatbuffers.ByteBuffer(data); + + let monster = MyGame.Example.Monster.getRootAsMonster(buf); +~~~ + +Now you can access values like this: + +~~~{.ts} + let hp = monster.hp(); + let pos = monster.pos(); +~~~ + +## Object based API + +FlatBuffers is all about memory efficiency, which is why its base API is written +around using as little as possible of it. This does make the API clumsier +(requiring pre-order construction of all data, and making mutation harder). + +For times when efficiency is less important a more convenient object based API +can be used (through `--gen-object-api`) that is able to unpack & pack a +FlatBuffer into objects and standard TS types. + +To use: + +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~{.ts} + // Autogenerated class from table Monster. + let monsterobj = new MonsterT(); + + // Deserialize from buffer into object. + Monster.getRootAsMonster(flatbuffer).unpackTo(monsterobj); + // or + let monsterobj = Monster.getRootAsMonster(flatbuffer).unpack(); + + // Update object directly like a regular TS class instance. + console.log(monsterobj.name); + monsterobj.name = "Bob"; + + // Serialize into new flatbuffer. + let fbb = new flatbuffers.Builder(1); + Monster.finishMonsterBuffer(fbb, monsterobj.pack(fbb)); +~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ + +## Text parsing FlatBuffers in TypeScript + +There currently is no support for parsing text (Schema's and JSON) directly +from TypeScript. diff --git a/third_party/flatbuffers/docs/source/quick_start.md b/third_party/flatbuffers/docs/source/quick_start.md new file mode 100644 index 00000000000..1be1061ce1f --- /dev/null +++ b/third_party/flatbuffers/docs/source/quick_start.md @@ -0,0 +1,90 @@ +# Quick Start + +This will quickly go over the parts of using FlatBuffers to serialize some data. +See the [Tutorial](tutorial.md) for a more in depth guide. + +1. **Build the compiler for FlatBuffers ([`flatc`](flatc.md))** + + ```sh + cmake -G "Unix Makefiles" + make -j + ``` + +2. **Define your FlatBuffer [schema](schema.md) (`.fbs`)** + + ```c title="monster.fbs" linenums="1" + table Monster { + name:string; + health:int; + } + + root_type Monster; + ``` + + See [monster.fbs](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) + for an complete example. + +3. **Generate code for your language(s)** + + Use the `flatc` compiler to take your schema and generate language-specific + code: + + ```sh + ./flatc --cpp --rust mosnter.fbs + ``` + + Which generates `monster_generated.h` and `monster_generated.rs` files. + +4. **Serialize data** + + Use the generated code files, as well as the `FlatBufferBuilder` to construct + your serialized buffer. + + ```c++ title="my_monster_factory.cc" linenums="1" + #include "flatbuffers.h" + #include "monster_generated.h" + + int main() { + // Used to build the flatbuffer + FlatBufferBuilder builder; + + // Auto-generated function emitted from `flatc` and the input + // `monster.fbs` schema. + auto monster = CreateMonsterDirect(builder, "Abominable Snowman", 100); + + // Finalize the buffer. + builder.Finish(monster); + } + ``` + + See complete [C++ Example](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.cpp#L24-L56). + +5. **Transmit/Store the serialized FlatBuffer** + + Use your serialized buffer however you want. Send it to someone, save if for + later, etc... + + ```c++ title="my_monster_factory.cc" linenums="13" + // Get a pointer to the flatbuffer. + const uint8_t* flatbuffer = builder.GetBufferPointer(); + ``` + +6. **Read the data** + + Use the generated accessors to read the data from the serialized buffer. + + It doesn't need to be the same language, or even schema version (see + [Evolving](evolution.md)), FlatBuffers ensures the data is readable across + languages and schema versions. + + ```c++ title="my_monster_factory.cc" linenums="15" + // Get a view of the root monster from the flatbuffer. + const Monster snowman = GetMonster(flatbuffer); + + // Access the monster's fields directly. + ASSERT_EQ(snowman->name(), "Abominable Snowman"); + ASSERT_EQ(snowman->health(), 100); + ``` + + See [`Rust` examples](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs#L92-L106) + for reading the data written by `C++`. diff --git a/third_party/flatbuffers/docs/source/schema.md b/third_party/flatbuffers/docs/source/schema.md new file mode 100644 index 00000000000..2baa5b78a1d --- /dev/null +++ b/third_party/flatbuffers/docs/source/schema.md @@ -0,0 +1,645 @@ +# Schema + +The syntax of the schema language (aka IDL, +[Interface Definition Language](https://en.wikipedia.org/wiki/Interface_description_language)) +should look quite familiar to users of any of the C family of languages, and +also to users of other IDLs. Let's look at an example first: + +```c title="monster.fbs" linenums="1" +// example IDL file + +namespace MyGame; + +attribute "priority"; + +enum Color : byte { Red = 1, Green, Blue } + +union Any { Monster, Weapon, Pickup } + +struct Vec3 { + x:float; + y:float; + z:float; +} + +table Monster { + pos:Vec3; + mana:short = 150; + hp:short = 100; + name:string; + friendly:bool = false (deprecated, priority: 1); + inventory:[ubyte]; + color:Color = Blue; + test:Any; +} + +table Weapon {} +table Pickup {} + +root_type Monster; +``` + +## Tables + +Tables are the main way of defining objects in FlatBuffers. + +```c title="monster.fbs - Example Table" linenums="17" +table Monster { + pos:Vec3; + mana:short = 150; + hp:short = 100; + name:string; + friendly:bool = false (deprecated, priority: 1); + inventory:[ubyte]; + color:Color = Blue; + test:Any; +} +``` + +They consist of a name (here `Monster`) and a list of [fields](#fields). This +field list can be appended to (and deprecated from) while still maintaining +compatibility. + +### Fields + +Table fields have a name identifier, a [type](#types), optional default value, +optional [attributes](#attributes) and ends with a `;`. See the +[grammar](grammar.md) for full details. + +```ebnf +field_decl = ident `:` type [ `=` scalar ] metadata `;` +``` + +Fields do not have to appear in the wire representation, and you can choose to +omit fields when constructing an object. You have the flexibility to add fields +without fear of bloating your data. This design is also FlatBuffer's mechanism +for forward and backwards compatibility. + +There are three, mutually exclusive, reactions to the non-presence of a table's +field in the binary data. + +#### 1. Default + +Default value fields with return the default value as defined in the schema. If +the default value is not specified in the schema, it will be `0` for scalar +types, or `null` for other types. + +```c++ +mana:short = 150; +hp:short; +inventory:[ubyte]; +``` + +Here `mana` would default to the value `150`, `hp` to value `0`, and `inventory` +to `null`, if those fields are not set. + +Only scalar values can have explicit defaults, non-scalar fields (strings, +vectors, tables) are `null` when not present. + +This is the normal mode that fields will take. + +??? danger "Don't change Default values" + + You generally do not want to change default values after they're initially + defined. Fields that have the default value are not actually stored in the + serialized data (see also Gotchas below). Values explicitly written by code + generated by the old schema old version, if they happen to be the default, will + be read as a different value by code generated with the new schema. This is + slightly less bad when converting an optional scalar into a default valued + scalar since non-presence would not be overloaded with a previous default value. + There are situations, however, where this may be desirable, especially if you + can ensure a simultaneous rebuild of all code. + +#### 2. Optional + +Optional value fields will return some form of `null` in the language generated. + +=== "C++" + + ```c++ + std::optional field; + ``` + +For optional scalars, just set the field default value to `null`. If the +producer of the buffer does not explicitly set that field, it will be marked +`null`. + +```c++ + hp:short = null; +``` + +!!! note + + Not every languages support scalar defaults yet + +#### 3. Required + +Required valued fields will cause an error if they are not set. The FlatBuffers +verifier would consider the whole buffer invalid. + +This is enabled by the [`required` attribute](#required) on the field. + +``` + hp:short (required) +``` + +You cannot have `required` set with an explicit default value, it will result in +a compiler error. + +## Structs + +Similar to a table, `structs` consist of fields are required (so no defaults +either), and fields may not be added or be deprecated. + +```c title="monster.fbs - Example Struct" linenums="11" +struct Vec3 { + x:float; + y:float; + z:float; +} +``` + +Structs may only contain scalars or other structs. Use this for simple objects +where you are very sure no changes will ever be made (as quite clear in the +example `Vec3`). Structs use less memory than tables and are even faster to +access (they are always stored in-line in their parent object, and use no +virtual table). + +### Arrays + +Arrays are a convenience short-hand for a fixed-length collection of elements. +Arrays allow the following syntax, while maintaining binary equivalency. + +
+ +- **Normal Syntax** + + === + + ```c++ + struct Vec3 { + x:float; + y:float; + z:float; + } + ``` + +- **Array Syntax** + + === + + ```c++ + struct Vec3 { + v:[float:3]; + } + ``` + +
+ +Arrays are currently only supported in a `struct`. + +## Types + +The following are the built-in types that can be used in FlatBuffers. + +### Scalars + +The standard assortment of fixed sized scalars are available. There are no +variable sized integers (e.g., `varints`). + +| Size | Signed | Unsigned | Floating Point | +| ------ | ----------------- | ------------------- | -------------------- | +| 8-bit | `byte`, `bool` | `ubyte` (`uint8`) | | +| 16-bit | `short` (`int16`) | `ushort` (`uint16`) | +| 32-bit | `int` (`int32`) | `uint` (`uint32`) | `float` (`float32`) | +| 64-bit | `long` (`int64`) | `ulong` (`uint64`) | `double` (`float64`) | + +The type names in parentheses are alias names such that for example `uint8` can +be used in place of `ubyte`, and `int32` can be used in place of `int` without +affecting code generation. + +### Non-scalars + +#### Vectors + +Vector of any other type (denoted with `[type]`). + +```c++ +inventory:[ubyte]; +``` + +!!! note "Nesting vectors" + + Nesting vectors is not supported, instead you can wrap the inner vector with + a table. + + ``` + table nest{ + a:[ubyte] + } + + table monster { + a:[nest] + } + ``` + +#### Strings + +Strings (indicated by `string`) are zero-terminated strings, prefixed by their +length. Strings may only hold UTF-8 or 7-bit ASCII. For other text encodings or +general binary data use vectors (`[byte]` or `[ubyte]`) instead. + +```c++ +name:string; +``` + +## Enums + +Define a sequence of named constants, each with a given value, or increasing by +one from the previous one. The default first value is `0`. As you can see in the +enum declaration, you specify the underlying integral type of the enum with `:` +(in this case `byte`), which then determines the type of any fields declared +with this enum type. + +Only integer types are allowed, i.e. `byte`, `ubyte`, `short` `ushort`, `int`, +`uint`, `long` and `ulong`. + +Typically, enum values should only ever be added, never removed (there is no +deprecation for enums). This requires code to handle forwards compatibility +itself, by handling unknown enum values. + +## Unions + +Unions share a lot of properties with enums, but instead of new names for +constants, you use names of tables. You can then declare a union field, which +can hold a reference to any of those types, and additionally a field with the +suffix `_type` is generated that holds the corresponding enum value, allowing +you to know which type to cast to at runtime. + +It's possible to give an alias name to a type union. This way a type can even be +used to mean different things depending on the name used: + +```txt +table PointPosition { x:uint; y:uint; } +table MarkerPosition {} +union Position { + Start:MarkerPosition, + Point:PointPosition, + Finish:MarkerPosition +} +``` + +Unions contain a special `NONE` marker to denote that no value is stored so that +name cannot be used as an alias. + +Unions are a good way to be able to send multiple message types as a FlatBuffer. +Note that because a union field is really two fields, it must always be part of +a table, it cannot be the root of a FlatBuffer by itself. + +If you have a need to distinguish between different FlatBuffers in a more +open-ended way, for example for use as files, see the file identification +feature below. + +There is an experimental support only in C++ for a vector of unions (and types). +In the example IDL file above, use [Any] to add a vector of Any to Monster +table. There is also experimental support for other types besides tables in +unions, in particular structs and strings. There's no direct support for scalars +in unions, but they can be wrapped in a struct at no space cost. + +## Namespaces + +These will generate the corresponding namespace in C++ for all helper code, and +packages in Java. You can use `.` to specify nested namespaces / packages. + +## Includes + +You can include other schemas files in your current one, e.g.: + +```txt +include "mydefinitions.fbs"; +``` + +This makes it easier to refer to types defined elsewhere. `include` +automatically ensures each file is parsed just once, even when referred to more +than once. + +When using the `flatc` compiler to generate code for schema definitions, only +definitions in the current file will be generated, not those from the included +files (those you still generate separately). + +## Root type + +This declares what you consider to be the root table of the serialized data. +This is particularly important for parsing JSON data, which doesn't include +object type information. + +## File identification and extension + +Typically, a FlatBuffer binary buffer is not self-describing, i.e. it needs you +to know its schema to parse it correctly. But if you want to use a FlatBuffer as +a file format, it would be convenient to be able to have a "magic number" in +there, like most file formats have, to be able to do a sanity check to see if +you're reading the kind of file you're expecting. + +Now, you can always prefix a FlatBuffer with your own file header, but +FlatBuffers has a built-in way to add an identifier to a FlatBuffer that takes +up minimal space, and keeps the buffer compatible with buffers that don't have +such an identifier. + +You can specify in a schema, similar to `root_type`, that you intend for this +type of FlatBuffer to be used as a file format: + +```txt +file_identifier "MYFI"; +``` + +Identifiers must always be exactly 4 characters long. These 4 characters will +end up as bytes at offsets 4-7 (inclusive) in the buffer. + +For any schema that has such an identifier, `flatc` will automatically add the +identifier to any binaries it generates (with `-b`), and generated calls like +`FinishMonsterBuffer` also add the identifier. If you have specified an +identifier and wish to generate a buffer without one, you can always still do so +by calling `FlatBufferBuilder::Finish` explicitly. + +After loading a buffer, you can use a call like `MonsterBufferHasIdentifier` to +check if the identifier is present. + +Note that this is best for open-ended uses such as files. If you simply wanted +to send one of a set of possible messages over a network for example, you'd be +better off with a union. + +Additionally, by default `flatc` will output binary files as `.bin`. This +declaration in the schema will change that to whatever you want: + +```txt +file_extension "ext"; +``` + +## RPC interface declarations + +You can declare RPC calls in a schema, that define a set of functions that take +a FlatBuffer as an argument (the request) and return a FlatBuffer as the +response (both of which must be table types): + +```txt +rpc_service MonsterStorage { + Store(Monster):StoreResponse; + Retrieve(MonsterId):Monster; +} +``` + +What code this produces and how it is used depends on language and RPC system +used, there is preliminary support for GRPC through the `--grpc` code generator, +see `grpc/tests` for an example. + +## Comments & documentation + +May be written as in most C-based languages. Additionally, a triple comment +(`///`) on a line by itself signals that a comment is documentation for whatever +is declared on the line after it (table/struct/field/enum/union/element), and +the comment is output in the corresponding C++ code. Multiple such lines per +item are allowed. + +## Attributes + +Attributes may be attached to a declaration, behind a field/enum value, or after +the name of a table/struct/enum/union. These may either have a value or not. +Some attributes like `deprecated` are understood by the compiler; user defined +ones need to be declared with the attribute declaration (like `priority` in the +example above), and are available to query if you parse the schema at runtime. +This is useful if you write your own code generators/editors etc., and you wish +to add additional information specific to your tool (such as a help text). + +Current understood attributes: + +- `id: n` (on a table field): manually set the field identifier to `n`. If you + use this attribute, you must use it on ALL fields of this table, and the + numbers must be a contiguous range from 0 onwards. Additionally, since a union + type effectively adds two fields, its id must be that of the second field (the + first field is the type field and not explicitly declared in the schema). For + example, if the last field before the union field had id 6, the union field + should have id 8, and the unions type field will implicitly be 7. IDs allow + the fields to be placed in any order in the schema. When a new field is added + to the schema it must use the next available ID. +- `deprecated` (on a field): do not generate accessors for this field anymore, + code should stop using this data. Old data may still contain this field, but + it won't be accessible anymore by newer code. Note that if you deprecate a + field that was previous required, old code may fail to validate new data (when + using the optional verifier). + +### `required` + +- `required` (on a non-scalar table field): this field must always be set. By + default, fields do not need to be present in the binary. This is desirable, as + it helps with forwards/backwards compatibility, and flexibility of data + structures. By specifying this attribute, you make non- presence in an error + for both reader and writer. The reading code may access the field directly, + without checking for null. If the constructing code does not initialize this + field, they will get an assert, and also the verifier will fail on buffers + that have missing required fields. Both adding and removing this attribute may + be forwards/backwards incompatible as readers will be unable read old or new + data, respectively, unless the data happens to always have the field set. +- `force_align: size` (on a struct): force the alignment of this struct to be + something higher than what it is naturally aligned to. Causes these structs to + be aligned to that amount inside a buffer, IF that buffer is allocated with + that alignment (which is not necessarily the case for buffers accessed + directly inside a `FlatBufferBuilder`). Note: currently not guaranteed to have + an effect when used with `--object-api`, since that may allocate objects at + alignments less than what you specify with `force_align`. +- `force_align: size` (on a vector): force the alignment of this vector to be + something different than what the element size would normally dictate. Note: + Now only work for generated C++ code. +- `bit_flags` (on an unsigned enum): the values of this field indicate bits, + meaning that any unsigned value N specified in the schema will end up + representing 1< diff --git a/third_party/flatbuffers/docs/source/tutorial.md b/third_party/flatbuffers/docs/source/tutorial.md new file mode 100644 index 00000000000..cfa0b1c9917 --- /dev/null +++ b/third_party/flatbuffers/docs/source/tutorial.md @@ -0,0 +1,3001 @@ +# Tutorial + +This tutorial provides an example of how to work with FlatBuffers in a variety +of languages. The following topics will cover all the steps of using FlatBuffers +in your application. + +1. Writing a FlatBuffers schema file (`.fbs`). +2. Using the `flatc` compiler to transform the schema into language-specific + code. +3. Importing the generated code and libraries into your application. +4. Serializing data into a flatbuffer. +5. Deserializing a flatbuffer. + +The tutorial is structured to be language agnostic, with language specifics in +code blocks providing more context. Additionally, this tries to cover the major +parts and type system of flatbuffers to give a general overview. It's not +expected to be an exhaustive list of all features, or provide the best way to do +things. + +## FlatBuffers Schema (`.fbs`) + +To start working with FlatBuffers, you first need to create a +[schema](schema.md) file which defines the format of the data structures you +wish to serialize. The schema is processed by the `flatc` compiler to generate +language-specific code that you use in your projects. + +The following +[`monster.fbs`](https://github.com/google/flatbuffers/blob/master/samples/monster.fbs) +schema will be used for this tutorial. This is part of the FlatBuffers +[sample code](https://github.com/google/flatbuffers/tree/master/samples) to give +complete sample binaries demonstrations. + +FlatBuffers schema is a Interface Definition Language (IDL) that has a couple +data structures, see the [schema](schema.md) documentation for a detail +description. Use the inline code annotations to get a brief synopsis of each +part of the schema. + +```proto title="monster.fbs" linenums="1" +// Example IDL file for our monster's schema. + +namespace MyGame.Sample; //(1)! + +enum Color:byte { Red = 0, Green, Blue = 2 } //(2)! + +// Optionally add more tables. +union Equipment { Weapon } //(3)! + +struct Vec3 { //(4)! + x:float; //(5)! + y:float; + z:float; +} + +table Monster { //(6)! + pos:Vec3; //(7)! + mana:short = 150; //(8)! + hp:short = 100; + name:string; //(9)! + friendly:bool = false (deprecated); //(10)! + inventory:[ubyte]; //(11)! + color:Color = Blue; + weapons:[Weapon]; //(12)! + equipped:Equipment; //(13)! + path:[Vec3]; +} + +table Weapon { + name:string; + damage:short; +} + +root_type Monster; //(14)! +``` + +1. FlatBuffers has support for namespaces to place the generated code into. + There is mixed level of support for namespaces (some languages don't have + namespaces), but for the C family of languages, it is fully supported. + +2. Enums definitions can be defined with the backing numerical type. Implicit + numbering is supported, so that `Green` would have a value of 1. + +3. A union represents a single value from a set of possible values. Its + effectively an enum (to represent the type actually store) and a value, + combined into one. In this example, the union is not very useful, since it + only has a single type. + +4. A struct is a collection of scalar fields with names. It is itself a scalar + type, which uses less memory and has faster lookup. However, once a struct is + defined, it cannot be changed. Use tables for data structures that can evolve + over time. + +5. FlatBuffers has the standard set of scalar numerical types (`int8`, `int16`, + `int32`, `int64`, `uint8`, `uint16`, `uint32`, `uint64`, `float`, `double`), + as well as `bool`. Note, scalars are fixed width, `varints` are not + supported. + +6. Tables are the main data structure for grouping data together. It can evolve + by adding and deprecating fields over time, while preserving forward and + backwards compatibility. + +7. A field that happens to be a `struct`. This means the data of the `Vec3` + struct will be serialized inline in the table without any need for offset. + +8. Fields can be provided a default value. Default values can be configured to + not be serialized at all while still providing the default value while + deserializing. However, once set, a default value cannot be changed. + +9. A `string` field which points to a serialized string external to the table. + +10. A deprecated field that is no longer being used. This is used instead of + removing the field outright. + +11. A `vector` field that points to a vector of bytes. Like `strings`, the + vector data is serialized elsewhere and this field just stores an offset to + the vector. + +12. Vector of `tables` and `structs` are also possible. + +13. A field to a `union` type. + +14. The root of the flatbuffer is always a `table`. This indicates the type of + `table` the "entry" point of the flatbuffer will point to. + +## Compiling Schema to Code (`flatc`) + +After a schema file is written, you compile it to code in the languages you wish +to work with. This compilation is done by the [FlatBuffers Compiler](flatc.md) +(`flatc`) which is one of the binaries built in the repo. + +### Building `flatc` + +FlatBuffers uses [`cmake`](https://cmake.org/) to build projects files for your +environment. + +=== "Unix" + + ```sh + cmake -G "Unix Makefiles" + make flatc + ``` + +=== "Windows" + + ```sh + cmake -G "Visual Studio 17 2022" + msbuild.exe FlatBuffers.sln + ``` + +See the documentation on [building](building.md) for more details and other +environments. Some languages also include a prebuilt `flatc` via their package +manager. + +### Compiling Schema + +To compile the schema, invoke `flatc` with the schema file and the language +flags you wish to generate code for. This compilation will generate files that +you include in your application code. These files provide convenient APIs for +serializing and deserializing the flatbuffer binary data. + +=== "C++" + + ```sh + flatc --cpp monster.fbs + ``` + +=== "C" + + !!! Note + + If you're working in C, you need to use the separate project + [FlatCC](https://github.com/dvidelabs/flatcc) which contains a schema + compiler and runtime library in C for C. See + [flatcc build instructions](https://github.com/dvidelabs/flatcc#building). + + Please be aware of the difference between `flatc` and `flatcc` tools. + + ```sh + cd flatcc + mkdir -p build/tmp/samples/monster + bin/flatcc -a -o build/tmp/samples/monster samples/monster/monster.fbs + # or just + flatcc/samples/monster/build.sh + ``` + +=== "C#" + + ```sh + flatc --csharp monster.fbs + ``` + +=== "Dart" + + ```sh + flatc --dart monster.fbs + ``` + +=== "Go" + + ```sh + flatc --go monster.fbs + ``` + +=== "Java" + + ```sh + flatc --java monster.fbs + ``` + +=== "JavaScript" + + ```sh + flatc --js monster.fbs + ``` + +=== "Kotlin" + + ```sh + flatc --kotlin monster.fbs + ``` + +=== "Lobster" + + ```sh + flatc --lobster monster.fbs + ``` + +=== "Lua" + + ```sh + flatc --lua monster.fbs + ``` + +=== "PHP" + + ```sh + flatc --php monster.fbs + ``` + +=== "Python" + + ```sh + flatc --python monster.fbs + ``` + +=== "Rust" + + ```sh + flatc --rust monster.fbs + ``` + +=== "Swift" + + ```sh + flatc --swift monster.fbs + ``` + +=== "TypeScript" + + ```sh + flatc --ts monster.fbs + ``` + +You can deserialize flatbuffers in languages that differ from the language that +serialized it. For purpose of this tutorial, we assume one language is used for +both serializing and deserializing. + +## Application Integration + +The generated files are then included in your project to be built into your +application. This is heavily dependent on your build system and language, but +generally involves two things: + +1. Importing the generated code. +2. Importing the "runtime" libraries. + +=== "C++" + + ```c++ + #include "monster_generated.h" // This was generated by `flatc` + #include "flatbuffers.h" // The runtime library for C++ + + // Simplifies naming in the following examples. + using namespace MyGame::Sample; // Specified in the schema. + ``` + +=== "C" + + ```c + #include "monster_builder.h" // Generated by `flatcc`. + + // Convenient namespace macro to manage long namespace prefix. + #undef ns + // Specified in the schema. + #define ns(x) FLATBUFFERS_WRAP_NAMESPACE(MyGame_Sample, x) + + // A helper to simplify creating vectors from C-arrays. + #define c_vec_len(V) (sizeof(V)/sizeof((V)[0])) + ``` + +=== "C#" + + ```c# + using Google.FlatBuffers; // The runtime library for C# + using MyGame.Sample; // The generated files from `flatc` + ``` + +=== "Dart" + + ```dart + import 'package:flat_buffers/flat_buffers.dart' as fb; + + // Generated by `flatc`. + import 'monster_my_game.sample_generated.dart' as myGame; + ``` + +=== "Go" + + ```go + import ( + flatbuffers "github.com/google/flatbuffers/go" + sample "MyGame/Sample" + ) + ``` + +=== "Java" + + ```java + import MyGame.Sample.*; //The `flatc` generated files. (Monster, Vec3, etc.) + + import com.google.flatbuffers.FlatBufferBuilder; + ``` + +=== "JavaScript" + + ```javascript + // The following code is an example - use your desired module flavor by + // transpiling from TS. + var flatbuffers = require('/js/flatbuffers').flatbuffers; + var MyGame = require('./monster_generated').MyGame; // Generated by `flatc`. + + //------------------------------------------------------------------------// + + // The following code is for browser-based HTML/JavaScript. Use the above + // code for JavaScript module loaders (e.g. Node.js). + + // Generated by `flatc`. + ``` + +=== "Kotlin" + + ```kotlin + import MyGame.Sample.* //The `flatc` generated files. (Monster, Vec3, etc.) + + import com.google.flatbuffers.FlatBufferBuilder + ``` + +=== "Lobster" + + ```lobster + import from "../lobster/" // Where to find flatbuffers.lobster + import monster_generated + ``` + +=== "Lua" + + ```lua + -- require the flatbuffers module + local flatbuffers = require("flatbuffers") + + -- require the generated files from `flatc`. + local color = require("MyGame.Sample.Color") + local equipment = require("MyGame.Sample.Equipment") + local monster = require("MyGame.Sample.Monster") + local vec3 = require("MyGame.Sample.Vec3") + local weapon = require("MyGame.Sample.Weapon") + ``` + +=== "PHP" + + ```php + // It is recommended that your use PSR autoload when using FlatBuffers in + // PHP. Here is an example from `SampleBinary.php`: + function __autoload($class_name) { + // The last segment of the class name matches the file name. + $class = substr($class_name, strrpos($class_name, "\\") + 1); + // `flatbuffers` root. + $root_dir = join(DIRECTORY_SEPARATOR, array(dirname(dirname(__FILE__)))); + + // Contains the `*.php` files for the FlatBuffers library and the `flatc` + // generated files. + $paths = array(join(DIRECTORY_SEPARATOR, array($root_dir, "php")), + join(DIRECTORY_SEPARATOR, + array($root_dir, "samples", "MyGame", "Sample"))); + foreach ($paths as $path) { + $file = join(DIRECTORY_SEPARATOR, array($path, $class . ".php")); + if (file_exists($file)) { + require($file); + break; + } + } + } + ``` + +=== "Python" + + ```py + import flatbuffers + + # Generated by `flatc`. + import MyGame.Sample.Color + import MyGame.Sample.Equipment + import MyGame.Sample.Monster + import MyGame.Sample.Vec3 + import MyGame.Sample.Weapon + ``` + +=== "Rust" + + ```rust + // import the flatbuffers runtime library + extern crate flatbuffers; + + // import the generated code + #[allow(dead_code, unused_imports)] + #[path = "./monster_generated.rs"] + mod monster_generated; + pub use monster_generated::my_game::sample::{root_as_monster, + Color, Equipment, + Monster, MonsterArgs, + Vec3, + Weapon, WeaponArgs}; + ``` + +=== "Swift" + + ```swift + /** + // make sure that monster_generated.swift is included in your project + */ + import Flatbuffers + + // typealiases for convenience + typealias Monster = MyGame1_Sample_Monster + typealias Weapon = MyGame1_Sample_Weapon + typealias Color = MyGame1_Sample_Color + typealias Vec3 = MyGame1_Sample_Vec3 + ``` + +=== "TypeScript" + + ```ts + // note: import flatbuffers with your desired import method + + import { MyGame } from './monster_generated'; + ``` + +For some languages the runtime libraries are just code files you compile into +your application. While other languages provide packaged libraries via their +package managers. + +The generated files include APIs for both serializing and deserializing +FlatBuffers. So these steps are identical for both the consumer and producer. + +## Serialization + +Once all the files are included into your application, it's time to start +serializing some data! + +With FlatBuffers, serialization can be a bit verbose, since each piece of data +must be serialized separately and in a particular order (depth-first, pre-order +traversal). The verbosity allows efficient serialization without heap +allocations, at the cost of more complex serialization APIs. + +For example, any reference type (e.g. `table`, `vector`, `string`) must be +serialized before it can be referred to by other structures. So its typical to +serialize the data from leaf to root node, as will be shown below. + +### FlatBufferBuilder + +Most languages use a Builder object for managing the binary array that the data +is serialized into. It provides an API for serializing data, as well as keeps +track of some internal state. The generated code wraps methods on the Builder +object to provide an API tailored to the schema. + +First instantiate a Builder (or reuse an existing one) and specify some memory +for it. The builder will automatically resize the backing buffer when necessary. + +=== "C++" + + ```c++ + // Construct a Builder with 1024 byte backing array. + flatbuffers::FlatBufferBuilder builder(1024); + ``` + +=== "C" + + ```c + flatcc_builder_t builder, *B; + B = &builder; + // Initialize the builder object. + flatcc_builder_init(B); + ``` + +=== "C#" + + ```c# + // Construct a Builder with 1024 byte backing array. + FlatBufferBuilder builder = new FlatBufferBuilder(1024); + ``` + +=== "Dart" + + ```dart + // Construct a Builder with 1024 byte backing array. + var builder = new fb.Builder(initialSize: 1024); + ``` + +=== "Go" + + ```go + // Construct a Builder with 1024 byte backing array. + builder := flatbuffers.NewBuilder(1024) + ``` + +=== "Java" + + ```java + // Construct a Builder with 1024 byte backing array. + FlatBufferBuilder builder = new FlatBufferBuilder(1024); + ``` + +=== "JavaScript" + + ```javascript + // Construct a Builder with 1024 byte backing array. + var builder = new flatbuffers.Builder(1024); + ``` + +=== "Kotlin" + + ```kotlin + // Construct a Builder with 1024 byte backing array. + val builder = FlatBufferBuilder(1024) + ``` + +=== "Lobster" + + ```lobster + // Construct a Builder with 1024 byte backing array. + let builder = flatbuffers_builder {} + ``` + +=== "Lua" + + ```lua + -- Construct a Builder with 1024 byte backing array. + local builder = flatbuffers.Builder(1024) + ``` + +=== "PHP" + + ```php + // Construct a Builder with 1024 byte backing array. + $builder = new Google\FlatBuffers\FlatbufferBuilder(1024); + ``` + +=== "Python" + + ```py + # Construct a Builder with 1024 byte backing array. + builder = flatbuffers.Builder(1024) + ``` + +=== "Rust" + + ```rust + // Construct a Builder with 1024 byte backing array. + let mut builder = flatbuffers::FlatBufferBuilder::with_capacity(1024); + ``` + +=== "Swift" + + ```swift + // Construct a Builder with 1024 byte backing array. + let builder = FlatBufferBuilder(initialSize: 1024) + ``` + +=== "TypeScript" + + ```ts + // Construct a Builder with 1024 byte backing array. + let builder = new flatbuffers.Builder(1024); + ``` + +Once a Builder is available, data can be serialized to it via the Builder APIs +and the generated code. + +### Serializing Data + +In this tutorial, we are building `Monsters` and `Weapons` for a computer game. +A `Weapon` is represented by a flatbuffer `table` with some fields. One field is +the `name` field, which is type `string` and the other `damage` field is a +numerical scalar. + +```c title="monster.fbs" linenums="28" +table Weapon { + name:string; + damage:short; +} +``` + +#### Strings + +Since `string` is a reference type, we first need to serialize it before +assigning it to the `name` field of the `Weapon` table. This is done through the +Builder `CreateString` method. + +Let's serialize two weapon strings. + +=== "C++" + + ```c++ + flatbuffers::Offset weapon_one_name = builder.CreateString("Sword"); + flatbuffers::Offset weapon_two_name = builder.CreateString("Axe"); + ``` + + `flatbuffers::Offset<>` is a just a "typed" integer tied to a particular + type. It helps make the numerical offset more strongly typed. + +=== "C" + + ```c + flatbuffers_string_ref_t weapon_one_name + = flatbuffers_string_create_str(B, "Sword"); + flatbuffers_string_ref_t weapon_two_name + = flatbuffers_string_create_str(B, "Axe"); + ``` + +=== "C#" + + ```c# + Offset weaponOneName = builder.CreateString("Sword"); + Offset weaponTwoName = builder.CreateString("Axe"); + ``` + +=== "Dart" + + ```dart + final int weaponOneName = builder.writeString("Sword"); + final int weaponTwoName = builder.writeString("Axe"); + ``` + +=== "Go" + + ```go + weaponOne := builder.CreateString("Sword") + weaponTwo := builder.CreateString("Axe") + ``` + +=== "Java" + + ```java + int weaponOneName = builder.createString("Sword") + int weaponTwoName = builder.createString("Axe"); + ``` + +=== "JavaScript" + + ```javascript + var weaponOne = builder.createString('Sword'); + var weaponTwo = builder.createString('Axe'); + ``` + +=== "Kotlin" + + ```kotlin + val weaponOneName = builder.createString("Sword") + val weaponTwoName = builder.createString("Axe") + ``` + +=== "Lobster" + + ```lobster + let weapon_one = builder.CreateString("Sword") + let weapon_two = builder.CreateString("Axe") + ``` + +=== "Lua" + + ```lua + local weaponOne = builder:CreateString("Sword") + local weaponTwo = builder:CreateString("Axe") + ``` + +=== "PHP" + + ```php + $weapon_one_name = $builder->createString("Sword") + $weapon_two_name = $builder->createString("Axe"); + ``` + +=== "Python" + + ```py + weapon_one = builder.CreateString('Sword') + weapon_two = builder.CreateString('Axe') + ``` + +=== "Rust" + + ```rust + let weapon_one_name = builder.create_string("Sword"); + let weapon_two_name = builder.create_string("Axe"); + ``` + +=== "Swift" + + ```swift + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + ``` + +=== "TypeScript" + + ```ts + let weaponOne = builder.createString('Sword'); + let weaponTwo = builder.createString('Axe'); + ``` + + +This performs the actual serialization (the string data is copied into the +backing array) and returns an offset. Think of the offset as a handle to that +reference. It's just a "typed" numerical offset to where that data resides in +the buffer. + +#### Tables + +Now that we have some names serialized, we can serialize the `Weapon` tables. +Here we will use one of the generated helper functions that was emitted by +`flatc`. The `CreateWeapon` function takes in the Builder object, as well as the +offset to the weapon's name and a numerical value for the damage field. + +=== "C++" + + ```c++ + short weapon_one_damage = 3; + short weapon_two_damage = 5; + + // Use the `CreateWeapon()` shortcut to create Weapons with all the fields + // set. + flatbuffers::Offset sword = + CreateWeapon(builder, weapon_one_name, weapon_one_damage); + flatbuffers::Offset axe = + CreateWeapon(builder, weapon_two_name, weapon_two_damage); + ``` + +=== "C" + + ```c + uint16_t weapon_one_damage = 3; + uint16_t weapon_two_damage = 5; + + ns(Weapon_ref_t) sword + = ns(Weapon_create(B, weapon_one_name, weapon_one_damage)); + ns(Weapon_ref_t) axe + = ns(Weapon_create(B, weapon_two_name, weapon_two_damage)); + ``` + +=== "C#" + + ```c# + short weaponOneDamage = 3; + short weaponTwoDamage = 5; + + // Use the `CreateWeapon()` helper function to create the weapons, since we + // set every field. + Offset sword = + Weapon.CreateWeapon(builder, weaponOneName, weaponOneDamage); + Offset axe = + Weapon.CreateWeapon(builder, weaponTwoName, weaponTwoDamage); + ``` + +=== "Dart" + + ```dart + final int weaponOneDamage = 3; + final int weaponTwoDamage = 5; + + final swordBuilder = new myGame.WeaponBuilder(builder) + ..begin() + ..addNameOffset(weaponOneName) + ..addDamage(weaponOneDamage); + final int sword = swordBuilder.finish(); + + final axeBuilder = new myGame.WeaponBuilder(builder) + ..begin() + ..addNameOffset(weaponTwoName) + ..addDamage(weaponTwoDamage); + final int axe = axeBuilder.finish(); + ``` + + Note, as an alternative, the previous steps can be combined using the + generative Builder classes. + + ```dart + final myGame.WeaponBuilder sword = new myGame.WeaponObjectBuilder( + name: "Sword", + damage: 3, + ); + + final myGame.WeaponBuilder axe = new myGame.WeaponObjectBuilder( + name: "Axe", + damage: 5, + ); + ``` + +=== "Go" + + ```go + // Create the first `Weapon` ("Sword"). + sample.WeaponStart(builder) + sample.WeaponAddName(builder, weaponOne) + sample.WeaponAddDamage(builder, 3) + sword := sample.WeaponEnd(builder) + + // Create the second `Weapon` ("Axe"). + sample.WeaponStart(builder) + sample.WeaponAddName(builder, weaponTwo) + sample.WeaponAddDamage(builder, 5) + axe := sample.WeaponEnd(builder) + ``` + +=== "Java" + + ```java + short weaponOneDamage = 3; + short weaponTwoDamage = 5; + + // Use the `createWeapon()` helper function to create the weapons, since we + // set every field. + int sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage); + int axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage); + ``` + +=== "JavaScript" + + ```javascript + // Create the first `Weapon` ('Sword'). + MyGame.Sample.Weapon.startWeapon(builder); + MyGame.Sample.Weapon.addName(builder, weaponOne); + MyGame.Sample.Weapon.addDamage(builder, 3); + var sword = MyGame.Sample.Weapon.endWeapon(builder); + + // Create the second `Weapon` ('Axe'). + MyGame.Sample.Weapon.startWeapon(builder); + MyGame.Sample.Weapon.addName(builder, weaponTwo); + MyGame.Sample.Weapon.addDamage(builder, 5); + var axe = MyGame.Sample.Weapon.endWeapon(builder); + ``` + +=== "Kotlin" + + ```kotlin + val weaponOneDamage: Short = 3; + val weaponTwoDamage: Short = 5; + + // Use the `createWeapon()` helper function to create the weapons, since we + // set every field. + val sword = Weapon.createWeapon(builder, weaponOneName, weaponOneDamage) + val axe = Weapon.createWeapon(builder, weaponTwoName, weaponTwoDamage) + ``` + +=== "Lobster" + + ```lobster + let sword = MyGame_Sample_WeaponBuilder { b } + .start() + .add_name(weapon_one) + .add_damage(3) + .end() + + let axe = MyGame_Sample_WeaponBuilder { b } + .start() + .add_name(weapon_two) + .add_damage(5) + .end() + ``` + +=== "Lua" + + ```lua + -- Create the first 'Weapon' + weapon.Start(builder) + weapon.AddName(builder, weaponOne) + weapon.AddDamage(builder, 3) + local sword = weapon.End(builder) + + -- Create the second 'Weapon' + weapon.Start(builder) + weapon.AddName(builder, weaponTwo) + weapon.AddDamage(builder, 5) + local axe = weapon.End(builder) + ``` + +=== "PHP" + + ```php + $sword = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_one_name, 3); + $axe = \MyGame\Sample\Weapon::CreateWeapon($builder, $weapon_two_name, 5); + ``` + +=== "Python" + + ```py + # Create the first `Weapon` ('Sword'). + MyGame.Sample.Weapon.Start(builder) + MyGame.Sample.Weapon.AddName(builder, weapon_one) + MyGame.Sample.Weapon.AddDamage(builder, 3) + sword = MyGame.Sample.Weapon.End(builder) + + # Create the second `Weapon` ('Axe'). + MyGame.Sample.Weapon.Start(builder) + MyGame.Sample.Weapon.AddName(builder, weapon_two) + MyGame.Sample.Weapon.AddDamage(builder, 5) + axe = MyGame.Sample.Weapon.End(builder) + ``` + +=== "Rust" + + ```rust + // Use the `Weapon::create` shortcut to create Weapons with named field + // arguments. + let sword = Weapon::create(&mut builder, &WeaponArgs{ + name: Some(weapon_one_name), + damage: 3, + }); + let axe = Weapon::create(&mut builder, &WeaponArgs{ + name: Some(weapon_two_name), + damage: 5, + }); + ``` + +=== "Swift" + + ```swift + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) + ``` + +=== "TypeScript" + + ```ts + // Create the first `Weapon` ('Sword'). + MyGame.Sample.Weapon.startWeapon(builder); + MyGame.Sample.Weapon.addName(builder, weaponOne); + MyGame.Sample.Weapon.addDamage(builder, 3); + let sword = MyGame.Sample.Weapon.endWeapon(builder); + + // Create the second `Weapon` ('Axe'). + MyGame.Sample.Weapon.startWeapon(builder); + MyGame.Sample.Weapon.addName(builder, weaponTwo); + MyGame.Sample.Weapon.addDamage(builder, 5); + let axe = MyGame.Sample.Weapon.endWeapon(builder); + ``` + + +The generated functions from `flatc`, like `CreateWeapon`, are just composed of +various Builder API methods. So its not required to use the generated code, but +it does make things much simpler and compact. + +Just like the `CreateString` methods, the table serialization functions return +an offset to the location of the serialized `Weapon` table. + +Now that we have some `Weapons` serialized, we can serialize a `Monster`. +Looking at the schema again, this table has a lot more fields of various types. +Some of these need to be serialized beforehand, for the same reason we +serialized the name string before the weapon table. + +!!! note inline end + + There is no prescribed ordering of which table fields must be serialized + first, you could serialize in any order you want. You can also not serialize + a field to provide a `null` value, this is done by using an 0 offset value. + +```c title="monster.fbs" linenums="15" +table Monster { + pos:Vec3; + mana:short = 150; + hp:short = 100; + name:string; + friendly:bool = false (deprecated); + inventory:[ubyte]; + color:Color = Blue; + weapons:[Weapon]; + equipped:Equipment; + path:[Vec3]; +} +``` + +#### Vectors + +The `weapons` field is a `vector` of `Weapon` tables. We already have two +`Weapons` serialized, so we just need to serialize a `vector` of those offsets. +The Builder provides multiple ways to create `vectors`. + +=== "C++" + + ```c++ + // Create a std::vector of the offsets we had previous made. + std::vector> weapons_vector; + weapons_vector.push_back(sword); + weapons_vector.push_back(axe); + + // Then serialize that std::vector into the buffer and again get an Offset + // to that vector. Use `auto` here since the full type is long, and it just + // a "typed" number. + auto weapons = builder.CreateVector(weapons_vector); + ``` + +=== "C" + + ```c + // We use the internal builder stack to implement a dynamic vector. + ns(Weapon_vec_start(B)); + ns(Weapon_vec_push(B, sword)); + ns(Weapon_vec_push(B, axe)); + ns(Weapon_vec_ref_t) weapons = ns(Weapon_vec_end(B)); + ``` + +=== "C#" + + ```c# + // Create an array of the two weapon offsets. + var weaps = new Offset[2]; + weaps[0] = sword; + weaps[1] = axe; + + // Pass the `weaps` array into the `CreateWeaponsVector()` method to create + // a FlatBuffer vector. + var weapons = Monster.CreateWeaponsVector(builder, weaps); + ``` + +=== "Dart" + + ```dart + // If using the Builder classes, serialize the `[sword,axe]` + final weapons = builder.writeList([sword, axe]); + + // If using the ObjectBuilders, just create an array from the two `Weapon`s + final List weaps = [sword, axe]; + ``` + +=== "Go" + + ```go + // Create a FlatBuffer vector and prepend the weapons. + // Note: Since we prepend the data, prepend them in reverse order. + sample.MonsterStartWeaponsVector(builder, 2) + builder.PrependUOffsetT(axe) + builder.PrependUOffsetT(sword) + weapons := builder.EndVector(2) + ``` + +=== "Java" + + ```java + // Place the two weapons into an array, and pass it to the + // `createWeaponsVector()` method to create a FlatBuffer vector. + int[] weaps = new int[2]; + weaps[0] = sword; + weaps[1] = axe; + + // Pass the `weaps` array into the `createWeaponsVector()` method to create + // a FlatBuffer vector. + int weapons = Monster.createWeaponsVector(builder, weaps); + ``` + +=== "JavaScript" + + ```javascript + // Create an array from the two `Weapon`s and pass it to the + // `createWeaponsVector()` method to create a FlatBuffer vector. + var weaps = [sword, axe]; + var weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); + ``` + +=== "Kotlin" + + ```kotlin + // Place the two weapons into an array, and pass it to the + // `createWeaponsVector()` method to create a FlatBuffer vector. + val weaps = intArrayOf(sword, axe) + + // Pass the `weaps` array into the `createWeaponsVector()` method to create + // a FlatBuffer vector. + val weapons = Monster.createWeaponsVector(builder, weaps) + ``` + +=== "Lobster" + + ```lobster + let weapons = builder.MyGame_Sample_MonsterCreateWeaponsVector([sword, axe]) + ``` + +=== "Lua" + + ```lua + -- Create a FlatBuffer vector and prepend the weapons. + -- Note: Since we prepend the data, prepend them in reverse order. + monster.StartWeaponsVector(builder, 2) + builder:PrependUOffsetTRelative(axe) + builder:PrependUOffsetTRelative(sword) + local weapons = builder:EndVector(2) + ``` + +=== "PHP" + + ```php + // Create an array from the two `Weapon`s and pass it to the + // `CreateWeaponsVector()` method to create a FlatBuffer vector. + $weaps = array($sword, $axe); + $weapons = \MyGame\Sample\Monster::CreateWeaponsVector($builder, $weaps); + ``` + +=== "Python" + + ```py + # Create a FlatBuffer vector and prepend the weapons. + # Note: Since we prepend the data, prepend them in reverse order. + MyGame.Sample.Monster.StartWeaponsVector(builder, 2) + builder.PrependUOffsetTRelative(axe) + builder.PrependUOffsetTRelative(sword) + weapons = builder.EndVector() + ``` + +=== "Rust" + + ```rust + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weapons = builder.create_vector(&[sword, axe]); + ``` + +=== "Swift" + + ```swift + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) + ``` + +=== "TypeScript" + + ```ts + // Create an array from the two `Weapon`s and pass it to the + // `createWeaponsVector()` method to create a FlatBuffer vector. + let weaps = [sword, axe]; + let weapons = MyGame.Sample.Monster.createWeaponsVector(builder, weaps); + ``` + + +While we are at it, let us serialize the other two vector fields: the +`inventory` field is just a vector of scalars, and the `path` field is a vector +of structs (which are scalar data as well). So these vectors can be serialized a +bit more directly. + +=== "C++" + + ```c++ + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + unsigned char treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + flatbuffers::Offset> inventory = + builder.CreateVector(treasure, 10); + + // Construct an array of two `Vec3` structs. + Vec3 points[] = { Vec3(1.0f, 2.0f, 3.0f), Vec3(4.0f, 5.0f, 6.0f) }; + + // Serialize it as a vector of structs. + flatbuffers::Offset> path = + builder.CreateVectorOfStructs(points, 2); + ``` + +=== "C" + + ```c + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + uint8_t treasure[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + flatbuffers_uint8_vec_ref_t inventory; + // `c_vec_len` is the convenience macro we defined earlier. + inventory = flatbuffers_uint8_vec_create(B, treasure, c_vec_len(treasure)); + ``` + +=== "C#" + + ```c# + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + // Note: Since we prepend the bytes, this loop iterates in reverse order. + Monster.StartInventoryVector(builder, 10); + for (int i = 9; i >= 0; i--) + { + builder.AddByte((byte)i); + } + Offset> inventory = builder.EndVector(); + + // Start building a path vector of length 2. + Monster.StartPathVector(fbb, 2); + + // Serialize the individual Vec3 structs + Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f); + Vec3.CreateVec3(builder, 4.0f, 5.0f, 6.0f); + + // End the vector to get the offset + Offset> path = fbb.EndVector(); + ``` + +=== "Dart" + + ```dart + // Create a list representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + final List treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + final inventory = builder.writeListUint8(treasure); + + // Using the Builder classes, you can write a list of structs like so: + // Note that the intended order should be reversed if order is important. + final vec3Builder = new myGame.Vec3Builder(builder); + vec3Builder.finish(4.0, 5.0, 6.0); + vec3Builder.finish(1.0, 2.0, 3.0); + final int path = builder.endStructVector(2); // the length of the vector + ``` + +=== "Go" + + ```go + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + // Note: Since we prepend the bytes, this loop iterates in reverse. + sample.MonsterStartInventoryVector(builder, 10) + for i := 9; i >= 0; i-- { + builder.PrependByte(byte(i)) + } + inv := builder.EndVector(10) + + sample.MonsterStartPathVector(builder, 2) + sample.CreateVec3(builder, 1.0, 2.0, 3.0) + sample.CreateVec3(builder, 4.0, 5.0, 6.0) + path := builder.EndVector(2) + ``` + +=== "Java" + + ```java + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + byte[] treasure = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + int inv = Monster.createInventoryVector(builder, treasure); + + Monster.startPathVector(fbb, 2); + Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f); + Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f); + int path = fbb.endVector(); + ``` + +=== "JavaScript" + + ```javascript + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + var treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + var inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); + + MyGame.Sample.Monster.startPathVector(builder, 2); + MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); + MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); + var path = builder.endVector(); + ``` + +=== "Kotlin" + + ```kotlin + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + val treasure = byteArrayOf(0, 1, 2, 3, 4, 5, 6, 7, 8, 9) + val inv = Monster.createInventoryVector(builder, treasure) + + Monster.startPathVector(fbb, 2) + Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f) + Vec3.createVec3(builder, 4.0f, 5.0f, 6.0f) + val path = fbb.endVector() + ``` + +=== "Lobster" + + ```lobster + // Inventory. + let inv = builder.MyGame_Sample_MonsterCreateInventoryVector(map(10): _) + + builder.MyGame_Sample_MonsterStartPathVector(2) + builder.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0) + builder.MyGame_Sample_CreateVec3(4.0, 5.0, 6.0) + let path = builder.EndVector(2) + ``` + +=== "Lua" + + ```lua + -- Create a `vector` representing the inventory of the Orc. Each number + -- could correspond to an item that can be claimed after he is slain. + -- Note: Since we prepend the bytes, this loop iterates in reverse. + monster.StartInventoryVector(builder, 10) + for i=10,1,-1 do + builder:PrependByte(i) + end + local inv = builder:EndVector(10) + + -- Create a FlatBuffer vector and prepend the path locations. + -- Note: Since we prepend the data, prepend them in reverse order. + monster.StartPathVector(builder, 2) + vec3.CreateVec3(builder, 1.0, 2.0, 3.0) + vec3.CreateVec3(builder, 4.0, 5.0, 6.0) + local path = builder:EndVector(2) + ``` + +=== "PHP" + + ```php + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + $treasure = array(0, 1, 2, 3, 4, 5, 6, 7, 8, 9); + $inv = \MyGame\Sample\Monster::CreateInventoryVector($builder, $treasure); + + \MyGame\Example\Monster::StartPathVector($builder, 2); + \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); + \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0); + $path = $builder->endVector(); + ``` + +=== "Python" + + ```py + # Create a `vector` representing the inventory of the Orc. Each number + # could correspond to an item that can be claimed after he is slain. + # Note: Since we prepend the bytes, this loop iterates in reverse. + MyGame.Sample.Monster.StartInventoryVector(builder, 10) + for i in reversed(range(0, 10)): + builder.PrependByte(i) + inv = builder.EndVector() + + MyGame.Sample.Monster.StartPathVector(builder, 2) + MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0) + MyGame.Sample.Vec3.CreateVec3(builder, 4.0, 5.0, 6.0) + path = builder.EndVector() + ``` + +=== "Rust" + + ```rust + // Inventory. + let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4, 5, 6, 7, 8, 9]); + + // Create the path vector of Vec3 objects. + let x = Vec3::new(1.0, 2.0, 3.0); + let y = Vec3::new(4.0, 5.0, 6.0); + let path = builder.create_vector(&[x, y]); + ``` + +=== "Swift" + + ```swift + // create inventory + let inventory: [Byte] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + let inventoryOffset = builder.createVector(inventory) + + let path = fbb.createVector(ofStructs: [ + Vec3(x: 1, y: 2, z: 3), + Vec3(x: 4, y: 5, z: 6) + ]) + ``` + +=== "TypeScript" + + ```ts + // Create a `vector` representing the inventory of the Orc. Each number + // could correspond to an item that can be claimed after he is slain. + let treasure = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]; + let inv = MyGame.Sample.Monster.createInventoryVector(builder, treasure); + + MyGame.Sample.Monster.startPathVector(builder, 2); + MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0); + MyGame.Sample.Vec3.createVec3(builder, 4.0, 5.0, 6.0); + let path = builder.endVector(); + ``` + + +#### Unions + +The last non-scalar data field for the `Monster` table is the `equipped` `union` +field. For this case, we will reuse an already serialized `Weapon` (the only +type in the union), without needing to reserialize it. Union fields implicitly +add a hidden `_type` field that stores the type of value stored in the union. +When serializing a union, you must explicitly set this type field, along with +providing the union value. + +We will also serialize the other scalar data at the same time, since we have all +the necessary values and Offsets to make a `Monster`. + +=== "C++" + + ```c++ + // Create the remaining data needed for the Monster. + auto name = builder.CreateString("Orc"); + + // Create the position struct + auto position = Vec3(1.0f, 2.0f, 3.0f); + + // Set his hit points to 300 and his mana to 150. + int hp = 300; + int mana = 150; + + // Finally, create the monster using the `CreateMonster` helper function + // to set all fields. + // + // Here we set the union field by using the `.Union()` method of the + // `Offset` axe we already serialized above. We just have to specify + // which type of object we put in the union, and do that with the + // auto-generated `Equipment_Weapon` enum. + flatbuffers::Offset orc = + CreateMonster(builder, &position, mana, hp, name, inventory, + Color_Red, weapons, Equipment_Weapon, axe.Union(), + path); + + ``` + +=== "C" + + ```c + // Serialize a name for our monster, called "Orc". + // The _str suffix indicates the source is an ascii-z string. + flatbuffers_string_ref_t name = flatbuffers_string_create_str(B, "Orc"); + + // Set his hit points to 300 and his mana to 150. + uint16_t hp = 300; + uint16_t mana = 150; + + // Define an equipment union. `create` calls in C has a single + // argument for unions where C++ has both a type and a data argument. + ns(Equipment_union_ref_t) equipped = ns(Equipment_as_Weapon(axe)); + ns(Vec3_t) pos = { 1.0f, 2.0f, 3.0f }; + ns(Monster_create_as_root(B, &pos, mana, hp, name, inventory, ns(Color_Red), + weapons, equipped, path)); + ``` + +=== "C#" + + ```c# + // Create the remaining data needed for the Monster. + var name = builder.CreateString("Orc"); + + // Create our monster using `StartMonster()` and `EndMonster()`. + Monster.StartMonster(builder); + Monster.AddPos(builder, Vec3.CreateVec3(builder, 1.0f, 2.0f, 3.0f)); + Monster.AddHp(builder, (short)300); + Monster.AddName(builder, name); + Monster.AddInventory(builder, inv); + Monster.AddColor(builder, Color.Red); + Monster.AddWeapons(builder, weapons); + // For union fields, we explicitly add the auto-generated enum for the type + // of value stored in the union. + Monster.AddEquippedType(builder, Equipment.Weapon); + // And we just use the `.Value` property of the already serialized axe. + Monster.AddEquipped(builder, axe.Value); // Axe + Monster.AddPath(builder, path); + Offset orc = Monster.EndMonster(builder); + ``` + +=== "Dart" + + ```dart + // Serialize a name for our monster, called "Orc". + final int name = builder.writeString('Orc'); + + // Using the Builder API: + // Set his hit points to 300 and his mana to 150. + final int hp = 300; + final int mana = 150; + + final monster = new myGame.MonsterBuilder(builder) + ..begin() + ..addNameOffset(name) + ..addInventoryOffset(inventory) + ..addWeaponsOffset(weapons) + ..addEquippedType(myGame.EquipmentTypeId.Weapon) + ..addEquippedOffset(axe) + ..addHp(hp) + ..addMana(mana) + ..addPos(vec3Builder.finish(1.0, 2.0, 3.0)) + ..addPathOffset(path) + ..addColor(myGame.Color.Red); + + final int orc = monster.finish(); + ``` + +=== "Go" + + ```go + // Serialize a name for our monster, called "Orc". + name := builder.CreateString("Orc") + + // Create our monster using `MonsterStart()` and `MonsterEnd()`. + sample.MonsterStart(builder) + sample.MonsterAddPos(builder, sample.CreateVec3(builder, 1.0, 2.0, 3.0)) + sample.MonsterAddHp(builder, 300) + sample.MonsterAddName(builder, name) + sample.MonsterAddInventory(builder, inv) + sample.MonsterAddColor(builder, sample.ColorRed) + sample.MonsterAddWeapons(builder, weapons) + sample.MonsterAddEquippedType(builder, sample.EquipmentWeapon) + sample.MonsterAddEquipped(builder, axe) + sample.MonsterAddPath(builder, path) + orc := sample.MonsterEnd(builder) + ``` + +=== "Java" + + ```java + // Serialize a name for our monster, called "Orc". + int name = builder.createString("Orc"); + + // Create our monster using `startMonster()` and `endMonster()`. + Monster.startMonster(builder); + Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)); + Monster.addName(builder, name); + Monster.addColor(builder, Color.Red); + Monster.addHp(builder, (short)300); + Monster.addInventory(builder, inv); + Monster.addWeapons(builder, weapons); + Monster.addEquippedType(builder, Equipment.Weapon); + Monster.addEquipped(builder, axe); + Monster.addPath(builder, path); + int orc = Monster.endMonster(builder); + ``` + +=== "JavaScript" + + ```javascript + // Serialize a name for our monster, called 'Orc'. + var name = builder.createString('Orc'); + + // Create our monster by using `startMonster()` and `endMonster()`. + MyGame.Sample.Monster.startMonster(builder); + MyGame.Sample.Monster.addPos(builder, + MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); + MyGame.Sample.Monster.addHp(builder, 300); + MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) + MyGame.Sample.Monster.addName(builder, name); + MyGame.Sample.Monster.addInventory(builder, inv); + MyGame.Sample.Monster.addWeapons(builder, weapons); + MyGame.Sample.Monster.addEquippedType(builder, + MyGame.Sample.Equipment.Weapon); + MyGame.Sample.Monster.addEquipped(builder, axe); + MyGame.Sample.Monster.addPath(builder, path); + var orc = MyGame.Sample.Monster.endMonster(builder); + ``` + +=== "Kotlin" + + ```kotlin + // Serialize a name for our monster, called "Orc". + val name = builder.createString("Orc") + + // Create our monster using `startMonster()` and `endMonster()`. + Monster.startMonster(builder) + Monster.addPos(builder, Vec3.createVec3(builder, 1.0f, 2.0f, 3.0f)) + Monster.addName(builder, name) + Monster.addColor(builder, Color.Red) + Monster.addHp(builder, 300.toShort()) + Monster.addInventory(builder, inv) + Monster.addWeapons(builder, weapons) + Monster.addEquippedType(builder, Equipment.Weapon) + Monster.addEquipped(builder, axe) + Monster.addPath(builder, path) + val orc = Monster.endMonster(builder) + ``` + +=== "Lobster" + + ```lobster + // Name of the monster. + let name = builder.CreateString("Orc") + + let orc = MyGame_Sample_MonsterBuilder { b } + .start() + .add_pos(b.MyGame_Sample_CreateVec3(1.0, 2.0, 3.0)) + .add_hp(300) + .add_name(name) + .add_inventory(inv) + .add_color(MyGame_Sample_Color_Red) + .add_weapons(weapons) + .add_equipped_type(MyGame_Sample_Equipment_Weapon) + .add_equipped(weapon_offsets[1]) + .add_path(path) + .end() + ``` + +=== "Lua" + + ```lua + -- Serialize a name for our monster, called 'orc' + local name = builder:CreateString("Orc") + + -- Create our monster by using Start() andEnd() + monster.Start(builder) + monster.AddPos(builder, vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) + monster.AddHp(builder, 300) + monster.AddName(builder, name) + monster.AddInventory(builder, inv) + monster.AddColor(builder, color.Red) + monster.AddWeapons(builder, weapons) + monster.AddEquippedType(builder, equipment.Weapon) + monster.AddEquipped(builder, axe) + monster.AddPath(builder, path) + local orc = monster.End(builder) + ``` + +=== "PHP" + + ```php + // Serialize a name for our monster, called "Orc". + $name = $builder->createString("Orc"); + + // Create our monster by using `StartMonster()` and `EndMonster()`. + \MyGame\Sample\Monster::StartMonster($builder); + \MyGame\Sample\Monster::AddPos($builder, + \MyGame\Sample\Vec3::CreateVec3($builder, 1.0, 2.0, 3.0)); + \MyGame\Sample\Monster::AddHp($builder, 300); + \MyGame\Sample\Monster::AddName($builder, $name); + \MyGame\Sample\Monster::AddInventory($builder, $inv); + \MyGame\Sample\Monster::AddColor($builder, \MyGame\Sample\Color::Red); + \MyGame\Sample\Monster::AddWeapons($builder, $weapons); + \MyGame\Sample\Monster::AddEquippedType($builder, + \MyGame\Sample\Equipment::Weapon); + \MyGame\Sample\Monster::AddEquipped($builder, $axe); + \MyGame\Sample\Monster::AddPath($builder, $path); + $orc = \MyGame\Sample\Monster::EndMonster($builder); + ``` + +=== "Python" + + ```py + # Serialize a name for our monster, called "Orc". + name = builder.CreateString("Orc") + + # Create our monster by using `Monster.Start()` and `Monster.End()`. + MyGame.Sample.Monster.Start(builder) + MyGame.Sample.Monster.AddPos(builder, + MyGame.Sample.Vec3.CreateVec3(builder, 1.0, 2.0, 3.0)) + MyGame.Sample.Monster.AddHp(builder, 300) + MyGame.Sample.Monster.AddName(builder, name) + MyGame.Sample.Monster.AddInventory(builder, inv) + MyGame.Sample.Monster.AddColor(builder, + MyGame.Sample.Color.Color().Red) + MyGame.Sample.Monster.AddWeapons(builder, weapons) + MyGame.Sample.Monster.AddEquippedType( + builder, MyGame.Sample.Equipment.Equipment().Weapon) + MyGame.Sample.Monster.AddEquipped(builder, axe) + MyGame.Sample.Monster.AddPath(builder, path) + orc = MyGame.Sample.Monster.End(builder) + ``` + +=== "Rust" + + ```rust + // Name of the Monster. + let name = builder.create_string("Orc"); + + // Create the monster using the `Monster::create` helper function. This + // function accepts a `MonsterArgs` struct, which supplies all of the data + // needed to build a `Monster`. To supply empty/default fields, just use the + // Rust built-in `Default::default()` function, as demonstrated below. + let orc = Monster::create(&mut builder, &MonsterArgs{ + pos: Some(&Vec3::new(1.0f32, 2.0f32, 3.0f32)), + mana: 150, + hp: 80, + name: Some(name), + inventory: Some(inventory), + color: Color::Red, + weapons: Some(weapons), + equipped_type: Equipment::Weapon, + equipped: Some(axe.as_union_value()), + path: Some(path), + ..Default::default() + }); + ``` + +=== "Swift" + + ```swift + // Name of the Monster. + let name = builder.create(string: "Orc") + + let orc = Monster.createMonster( + &builder, + pos: MyGame_Sample_Vec3(x: 1, y: 2, z: 3), + hp: 300, + nameOffset: name, + inventoryVectorOffset: inventoryOffset, + color: .red, + weaponsVectorOffset: weaponsOffset, + equippedType: .weapon, + equippedOffset: axe) + ``` + +=== "TypeScript" + + ```ts + // Serialize a name for our monster, called 'Orc'. + let name = builder.createString('Orc'); + + // Create our monster by using `startMonster()` and `endMonster()`. + MyGame.Sample.Monster.startMonster(builder); + MyGame.Sample.Monster.addPos(builder, + MyGame.Sample.Vec3.createVec3(builder, 1.0, 2.0, 3.0)); + MyGame.Sample.Monster.addHp(builder, 300); + MyGame.Sample.Monster.addColor(builder, MyGame.Sample.Color.Red) + MyGame.Sample.Monster.addName(builder, name); + MyGame.Sample.Monster.addInventory(builder, inv); + MyGame.Sample.Monster.addWeapons(builder, weapons); + MyGame.Sample.Monster.addEquippedType(builder, + MyGame.Sample.Equipment.Weapon); + MyGame.Sample.Monster.addEquipped(builder, axe); + MyGame.Sample.Monster.addPath(builder, path); + let orc = MyGame.Sample.Monster.endMonster(builder); + ``` + + +### Finishing + +At this point, we have serialized a `Monster` we've named "orc" to the +flatbuffer and have its offset. The `root_type` of the schema is also a +`Monster`, so we have everything we need to finish the serialization step. + +This is done by calling the appropriate `finish` method on the Builder, passing +in the orc offset to indicate this `table` is the "entry" point when +deserializing the buffer later. + +=== "C++" + + ```c++ + // Call `Finish()` to instruct the builder that this monster is complete. + // You could also call `FinishMonsterBuffer(builder, orc);` + builder.Finish(orc); + ``` + +=== "C" + + ```c + // Because we used `Monster_create_as_root`, we do not need a `finish` call + // in C. + ``` + +=== "C#" + + ```c# + // Call `Finish()` to instruct the builder that this monster is complete. + // You could also call `Monster.FinishMonsterBuffer(builder, orc);` + builder.Finish(orc.Value); + ``` + +=== "Dart" + + ```dart + // Call `finish()` to instruct the builder that this monster is complete. + // See the next code section, as in Dart `finish` will also return the byte + // array. + ``` + +=== "Go" + + ```go + // Call `Finish()` to instruct the builder that this monster is complete. + builder.Finish(orc) + ``` + +=== "Java" + + ```java + // Call `finish()` to instruct the builder that this monster is complete. + builder.finish(orc); + ``` + +=== "JavaScript" + + ```javascript + // Call `finish()` to instruct the builder that this monster is complete. + builder.finish(orc); + ``` + +=== "Kotlin" + + ```kotlin + // Call `finish()` to instruct the builder that this monster is complete. + builder.finish(orc) ; + ``` + +=== "Lobster" + + ```lobster + // Call `Finish()` to instruct the builder that this monster is complete. + builder.Finish(orc) + ``` + +=== "Lua" + + ```lua + -- Call 'Finish()' to instruct the builder that this monster is complete. + builder:Finish(orc) + ``` + +=== "PHP" + + ```php + // Call `finish()` to instruct the builder that this monster is complete. + $builder->finish($orc); + ``` + +=== "Python" + + ```py + # Call `Finish()` to instruct the builder that this monster is complete. + builder.Finish(orc) + ``` + +=== "Rust" + + ```rust + // Call `finish()` to instruct the builder that this monster is complete. + builder.finish(orc, None); + ``` + +=== "Swift" + + ```swift + // Call `finish()` to instruct the builder that this monster is complete. + builder.finish(offset: orc) + ``` + +=== "TypeScript" + + ```ts + // Call `finish()` to instruct the builder that this monster is complete. + builder.finish(orc); + ``` + + +Once you finish a Builder, you can no longer serialize more data to it. + +#### Buffer Access + +The flatbuffer is now ready to be stored somewhere, sent over the network, +compressed, or whatever you would like to do with it. You access the raw buffer +like so: + +=== "C++" + + ```c++ + // This must be called after `Finish()`. + uint8_t *buf = builder.GetBufferPointer(); + + // Returns the size of the buffer that `GetBufferPointer()` points to. + int size = builder.GetSize(); + ``` + +=== "C" + + ```c + uint8_t *buf; + size_t size; + + // Allocate and extract a readable buffer from internal builder heap. + // The returned buffer must be deallocated using `free`. + // NOTE: Finalizing the buffer does NOT change the builder, it + // just creates a snapshot of the builder content. + buf = flatcc_builder_finalize_buffer(B, &size); + // use buf + free(buf); + + // Optionally reset builder to reuse builder without deallocating + // internal stack and heap. + flatcc_builder_reset(B); + // build next buffer. + // ... + + // Cleanup. + flatcc_builder_clear(B); + ``` + +=== "C#" + + ```c# + // This must be called after `Finish()`. + // + // The data in this ByteBuffer does NOT start at 0, but at buf.Position. + // The end of the data is marked by buf.Length, so the size is + // buf.Length - buf.Position. + FlatBuffers.ByteBuffer dataBuffer = builder.DataBuffer; + + // Alternatively this copies the above data out of the ByteBuffer for you: + byte[] buf = builder.SizedByteArray(); + ``` + +=== "Dart" + + ```dart + final Uint8List buf = builder.finish(orc); + ``` + +=== "Go" + + ```go + // This must be called after `Finish()`. + buf := builder.FinishedBytes() // Of type `byte[]`. + ``` + +=== "Java" + + ```java + // This must be called after `finish()`. + java.nio.ByteBuffer buf = builder.dataBuffer(); + // The data in this ByteBuffer does NOT start at 0, but at buf.position(). + // The number of bytes is buf.remaining(). + + // Alternatively this copies the above data out of the ByteBuffer for you: + byte[] buf = builder.sizedByteArray(); + ``` + +=== "JavaScript" + + ```javascript + // This must be called after `finish()`. + var buf = builder.asUint8Array(); // Of type `Uint8Array`. + ``` + +=== "Kotlin" + + ```kotlin + // This must be called after `finish()`. + val buf = builder.dataBuffer() + // The data in this ByteBuffer does NOT start at 0, but at buf.position(). + // The number of bytes is buf.remaining(). + + // Alternatively this copies the above data out of the ByteBuffer for you: + val buf = builder.sizedByteArray() + ``` + +=== "Lobster" + + ```lobster + // This must be called after `Finish()`. + let buf = builder.SizedCopy() // Of type `string`. + ``` + +=== "Lua" + + ```lua + local bufAsString = builder:Output() + ``` + +=== "PHP" + + ```php + // This must be called after `finish()`. + $buf = $builder->dataBuffer(); // Of type `Google\FlatBuffers\ByteBuffer` + // The data in this ByteBuffer does NOT start at 0, but at + // buf->getPosition(). + // The end of the data is marked by buf->capacity(), so the size is + // buf->capacity() - buf->getPosition(). + ``` + +=== "Python" + + ```py + # This must be called after `Finish()`. + buf = builder.Output() // Of type `bytearray`. + ``` + +=== "Rust" + + ```rust + // This must be called after `finish()`. + // `finished_data` returns a byte slice. + let buf = builder.finished_data(); // Of type `&[u8]` + ``` + +=== "Swift" + + ```swift + // This must be called after `finish()`. + // `sizedByteArray` returns the finished buf of type [UInt8]. + let buf = builder.sizedByteArray + // or you can use to get an object of type Data + let bufData = ByteBuffer(data: builder.data) + ``` + +=== "TypeScript" + + ```ts + // This must be called after `finish()`. + let buf = builder.asUint8Array(); // Of type `Uint8Array`. + ``` + + +Now you can write the bytes to a file or send them over the network. The buffer +stays valid until the Builder is cleared or destroyed. + +Make sure your file mode (or transfer protocol) is set to BINARY, and not TEXT. +If you try to transfer a flatbuffer in TEXT mode, the buffer will be corrupted +and be hard to diagnose. + +## Deserialization + +Deserialization is a bit of a misnomer, since FlatBuffers doesn't deserialize +the whole buffer when accessed. It just "decodes" the data that is requested, +leaving all the other data untouched. It is up to the application to decide if +the data is copied out or even read in the first place. However, we continue to +use the word `deserialize` to mean accessing data from a binary flatbuffer. + +Now that we have successfully create an orc FlatBuffer, the data can be saved, +sent over a network, etc. At some point, the buffer will be accessed to obtain +the underlying data. + +The same application setup used for serialization is needed for deserialization +(see [application integration](#application-integration)). + +### Root Access + +All access to the data in the flatbuffer must first go through the root object. +There is only one root object per flatbuffer. The generated code provides +functions to get the root object given the buffer. + +=== "C++" + + ```c++ + uint8_t *buffer_pointer = /* the data you just read */; + + // Get an view to the root object inside the buffer. + Monster monster = GetMonster(buffer_pointer); + ``` + +=== "C" + + ```c + // Note that we use the `table_t` suffix when reading a table object + // as opposed to the `ref_t` suffix used during the construction of + // the buffer. + ns(Monster_table_t) monster = ns(Monster_as_root(buffer)); + + // Note: root object pointers are NOT the same as the `buffer` pointer. + ``` + +=== "C#" + + ```c# + byte[] bytes = /* the data you just read */ + + // Get an view to the root object inside the buffer. + Monster monster = Monster.GetRootAsMonster(new ByteBuffer(bytes)); + ``` + +=== "Dart" + + ```dart + List data = ... // the data, e.g. from file or network + // A generated factory constructor that will read the data. + myGame.Monster monster = new myGame.Monster(data); + ``` + +=== "Go" + + ```go + var buf []byte = /* the data you just read */ + + // Get an accessor to the root object inside the buffer. + monster := sample.GetRootAsMonster(buf, 0) + + // Note: We use `0` for the offset here, which is typical for most buffers + // you would read. If you wanted to read from `builder.Bytes` directly, you + // would need to pass in the offset of `builder.Head()`, as the builder + // constructs the buffer backwards, so may not start at offset 0. + ``` + +=== "Java" + + ```java + byte[] bytes = /* the data you just read */ + java.nio.ByteBuffer buf = java.nio.ByteBuffer.wrap(bytes); + + // Get an accessor to the root object inside the buffer. + Monster monster = Monster.getRootAsMonster(buf); + ``` + +=== "JavaScript" + + ```javascript + // the data you just read, as a `Uint8Array` + // Note that the example here uses `readFileSync` from the built-in `fs` + // module, but other methods for accessing the file contents will also work. + var bytes = new Uint8Array(readFileSync('./monsterdata.bin')); + + var buf = new flatbuffers.ByteBuffer(bytes); + + // Get an accessor to the root object inside the buffer. + var monster = MyGame.Sample.Monster.getRootAsMonster(buf); + ``` + +=== "Kotlin" + + ```kotlin + val bytes = /* the data you just read */ + val buf = java.nio.ByteBuffer.wrap(bytes) + + // Get an accessor to the root object inside the buffer. + Monster monster = Monster.getRootAsMonster(buf) + ``` + +=== "Lobster" + + ```lobster + buf = /* the data you just read, in a string */ + + // Get an accessor to the root object inside the buffer. + let monster = MyGame_Sample_GetRootAsMonster(buf) + ``` + +=== "Lua" + + ```lua + local bufAsString = -- The data you just read in + + -- Convert the string representation into binary array Lua structure + local buf = flatbuffers.binaryArray.New(bufAsString) + + -- Get an accessor to the root object insert the buffer + local mon = monster.GetRootAsMonster(buf, 0) + ``` + +=== "PHP" + + ```php + $bytes = /* the data you just read, in a string */ + $buf = Google\FlatBuffers\ByteBuffer::wrap($bytes); + + // Get an accessor to the root object inside the buffer. + $monster = \MyGame\Sample\Monster::GetRootAsMonster($buf); + ``` + +=== "Python" + + ```py + buf = /* the data you just read, in an object of type "bytearray" */ + + # Get an accessor to the root object inside the buffer. + monster = MyGame.Sample.Monster.Monster.GetRootAs(buf, 0) + + # Note: We use `0` for the offset here, which is typical for most buffers + # you would read. If you wanted to read from the `builder.Bytes` directly, + # you would need to pass in the offset of `builder.Head()`, as the builder + # constructs the buffer backwards, so may not start at offset 0. + ``` + +=== "Rust" + + ```rust + let buf = /* the data you just read, in a &[u8] */ + + // Get an accessor to the root object inside the buffer. + let monster = root_as_monster(buf).unwrap(); + ``` + +=== "Swift" + + ```swift + // create a ByteBuffer(:) from an [UInt8] or Data() + var buf = // Get your data + // Get an accessor to the root object inside the buffer. + let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) + // let monster: Monster = getRoot(byteBuffer: &byteBuffer) + ``` + +=== "TypeScript" + + ```ts + // the data you just read, as a `Uint8Array`. + // Note that the example here uses `readFileSync` from the built-in `fs` + // module, but other methods for accessing the file contents will also work. + let bytes = new Uint8Array(readFileSync('./monsterdata.bin')); + + let buf = new flatbuffers.ByteBuffer(bytes); + + // Get an accessor to the root object inside the buffer. + let monster = MyGame.Sample.Monster.getRootAsMonster(buf); + ``` + + +Again, make sure you read the bytes in BINARY mode, otherwise the buffer may be +corrupted. + +In most languages, the returned object is just a "view" of the data with helpful +accessors. Data is typically not copied out of the backing buffer. This also +means the backing buffer must remain alive for the duration of the views. + +### Table Access + +If you look in the generated files emitted by `flatc`, you will see it generated +, for each `table`, accessors of all its non-`deprecated` fields. For example, +some of the accessors of the `Monster` root table would look like: + +=== "C++" + + ```c++ + auto hp = monster->hp(); + auto mana = monster->mana(); + auto name = monster->name()->c_str(); + ``` + +=== "C" + + ```c + uint16_t hp = ns(Monster_hp(monster)); + uint16_t mana = ns(Monster_mana(monster)); + flatbuffers_string_t name = ns(Monster_name(monster)); + ``` + +=== "C#" + + ```c# + // For C#, unlike most other languages support by FlatBuffers, most values + // (except for vectors and unions) are available as properties instead of + // accessor methods. + var hp = monster.Hp; + var mana = monster.Mana; + var name = monster.Name; + ``` + +=== "Dart" + + ```dart + // For Dart, unlike other languages support by FlatBuffers, most values + // are available as properties instead of accessor methods. + var hp = monster.hp; + var mana = monster.mana; + var name = monster.name; + ``` + +=== "Go" + + ```go + hp := monster.Hp() + mana := monster.Mana() + name := string(monster.Name()) // Note: `monster.Name()` returns a byte[]. + ``` + +=== "Java" + + ```java + short hp = monster.hp(); + short mana = monster.mana(); + String name = monster.name(); + ``` + +=== "JavaScript" + + ```javascript + var hp = monster.hp(); + var mana = monster.mana(); + var name = monster.name(); + ``` + +=== "Kotlin" + + ```kotlin + val hp = monster.hp + val mana = monster.mana + val name = monster.name + ``` + +=== "Lobster" + + ```lobster + let hp = monster.hp + let mana = monster.mana + let name = monster.name + ``` + +=== "Lua" + + ```lua + local hp = mon:Hp() + local mana = mon:Mana() + local name = mon:Name() + ``` + +=== "PHP" + + ```php + $hp = $monster->getHp(); + $mana = $monster->getMana(); + $name = monster->getName(); + ``` + +=== "Python" + + ```py + hp = monster.Hp() + mana = monster.Mana() + name = monster.Name() + ``` + +=== "Rust" + + ```rust + // Get and test some scalar types from the FlatBuffer. + let hp = monster.hp(); + let mana = monster.mana(); + let name = monster.name(); + ``` + +=== "Swift" + + ```swift + let hp = monster.hp + let mana = monster.mana + let name = monster.name // returns an optional string + ``` + +=== "TypeScript" + + ```ts + let hp = monster.hp(); + let mana = monster.mana(); + let name = monster.name(); + ``` + + +These accessors should hold the values `300`, `150`, and `"Orc"` respectively. + +The default value of `150` wasn't stored in the `mana` field, but we are still +able to retrieve it. That is because the generated accessors return a hard-coded +default value when it doesn't find the value in the buffer. + +#### Nested Object Access + +Accessing nested objects is very similar, with the nested field pointing to +another object type. Be careful, the field could be `null` if not present. + +For example, accessing the `pos` `struct`, which is type `Vec3` you would do: + +=== "C++" + + ```c++ + auto pos = monster->pos(); + auto x = pos->x(); + auto y = pos->y(); + auto z = pos->z(); + ``` + +=== "C" + + ```c + ns(Vec3_struct_t) pos = ns(Monster_pos(monster)); + float x = ns(Vec3_x(pos)); + float y = ns(Vec3_y(pos)); + float z = ns(Vec3_z(pos)); + ``` + +=== "C#" + + ```c# + var pos = monster.Pos.Value; + var x = pos.X; + var y = pos.Y; + var z = pos.Z; + ``` + +=== "Dart" + + ```dart + myGame.Vec3 pos = monster.pos; + double x = pos.x; + double y = pos.y; + double z = pos.z; + ``` + +=== "Go" + + ```go + pos := monster.Pos(nil) + x := pos.X() + y := pos.Y() + z := pos.Z() + + // Note: Whenever you access a new object, like in `Pos()`, a new temporary + // accessor object gets created. If your code is very performance sensitive, + // you can pass in a pointer to an existing `Vec3` instead of `nil`. This + // allows you to reuse it across many calls to reduce the amount of object + // allocation/garbage collection. + ``` + +=== "Java" + + ```java + Vec3 pos = monster.pos(); + float x = pos.x(); + float y = pos.y(); + float z = pos.z(); + ``` + +=== "JavaScript" + + ```javascript + var pos = monster.pos(); + var x = pos.x(); + var y = pos.y(); + var z = pos.z(); + ``` + +=== "Kotlin" + + ```kotlin + val pos = monster.pos!! + val x = pos.x + val y = pos.y + val z = pos.z + ``` + +=== "Lobster" + + ```lobster + let pos = monster.pos + let x = pos.x + let y = pos.y + let z = pos.z + ``` + +=== "Lua" + + ```lua + local pos = mon:Pos() + local x = pos:X() + local y = pos:Y() + local z = pos:Z() + ``` + +=== "PHP" + + ```php + $pos = $monster->getPos(); + $x = $pos->getX(); + $y = $pos->getY(); + $z = $pos->getZ(); + ``` + +=== "Python" + + ```py + pos = monster.Pos() + x = pos.X() + y = pos.Y() + z = pos.Z() + ``` + +=== "Rust" + + ```rust + let pos = monster.pos().unwrap(); + let x = pos.x(); + let y = pos.y(); + let z = pos.z(); + ``` + +=== "Swift" + + ```swift + let pos = monster.pos + let x = pos.x + let y = pos.y + let z = pos.z + ``` + +=== "TypeScript" + + ```ts + let pos = monster.pos(); + let x = pos.x(); + let y = pos.y(); + let z = pos.z(); + ``` + + +Where `x`, `y`, and `z` will contain `1.0`, `2.0`, and `3.0` respectively. + +### Vector Access + +Similarly, we can access elements of the `inventory` `vector` by indexing it. +You can also iterate over the length of the vector. + +=== "C++" + + ```c++ + flatbuffers::Vector inv = monster->inventory(); + auto inv_len = inv->size(); + auto third_item = inv->Get(2); + ``` + +=== "C" + + ```c + // If `inv` hasn't been set, it will be null. It is valid get + // the length of null which will be 0, useful for iteration. + flatbuffers_uint8_vec_t inv = ns(Monster_inventory(monster)); + size_t inv_len = flatbuffers_uint8_vec_len(inv); + ``` + +=== "C#" + + ```c# + int invLength = monster.InventoryLength; + var thirdItem = monster.Inventory(2); + ``` + +=== "Dart" + + ```dart + int invLength = monster.inventory.length; + var thirdItem = monster.inventory[2]; + ``` + +=== "Go" + + ```go + invLength := monster.InventoryLength() + thirdItem := monster.Inventory(2) + ``` + +=== "Java" + + ```java + int invLength = monster.inventoryLength(); + byte thirdItem = monster.inventory(2); + ``` + +=== "JavaScript" + + ```javascript + var invLength = monster.inventoryLength(); + var thirdItem = monster.inventory(2); + ``` + +=== "Kotlin" + + ```kotlin + val invLength = monster.inventoryLength + val thirdItem = monster.inventory(2)!! + ``` + +=== "Lobster" + + ```lobster + let inv_len = monster.inventory_length + let third_item = monster.inventory(2) + ``` + +=== "Lua" + + ```lua + local invLength = mon:InventoryLength() + local thirdItem = mon:Inventory(3) -- Lua is 1-based + ``` + +=== "PHP" + + ```php + $inv_len = $monster->getInventoryLength(); + $third_item = $monster->getInventory(2); + ``` + +=== "Python" + + ```py + inv_len = monster.InventoryLength() + third_item = monster.Inventory(2) + ``` + +=== "Rust" + + ```rust + // Get and test an element from the `inventory` FlatBuffer's `vector`. + let inv = monster.inventory().unwrap(); + + // Note that this vector is returned as a slice, because direct access for + // this type, a `u8` vector, is safe on all platforms: + let third_item = inv[2]; + ``` + +=== "Swift" + + ```swift + // Get a the count of objects in the vector + let count = monster.inventoryCount + + // get item at index 4 + let object = monster.inventory(at: 4) + + // or you can fetch the entire array + let inv = monster.inventory + // inv[4] should equal object + ``` + +=== "TypeScript" + + ```ts + let invLength = monster.inventoryLength(); + let thirdItem = monster.inventory(2); + ``` + + +For vectors of tables, you can access the elements like any other vector, except +you need to handle the result as a FlatBuffer table. Here we iterate over the +`weapons` vector that is houses `Weapon` `tables`. + +=== "C++" + + ```c++ + flatbuffers::Vector weapons = monster->weapons(); + auto weapon_len = weapons->size(); + auto second_weapon_name = weapons->Get(1)->name()->str(); + auto second_weapon_damage = weapons->Get(1)->damage() + ``` + +=== "C" + + ```c + ns(Weapon_vec_t) weapons = ns(Monster_weapons(monster)); + size_t weapons_len = ns(Weapon_vec_len(weapons)); + // We can use `const char *` instead of `flatbuffers_string_t`. + const char *second_weapon_name = + ns(Weapon_name(ns(Weapon_vec_at(weapons, 1)))); + uint16_t second_weapon_damage = + ns(Weapon_damage(ns(Weapon_vec_at(weapons, 1)))); + ``` + +=== "C#" + + ```c# + int weaponsLength = monster.WeaponsLength; + var secondWeaponName = monster.Weapons(1).Name; + var secondWeaponDamage = monster.Weapons(1).Damage; + ``` + +=== "Dart" + + ```dart + int weaponsLength = monster.weapons.length; + var secondWeaponName = monster.weapons[1].name; + var secondWeaponDamage = monster.Weapons[1].damage; + ``` + +=== "Go" + + ```go + weaponLength := monster.WeaponsLength() + // We need a `sample.Weapon` to pass into `monster.Weapons()` + // to capture the output of the function.k + weapon := new(sample.Weapon) + if monster.Weapons(weapon, 1) { + secondWeaponName := weapon.Name() + secondWeaponDamage := weapon.Damage() + } + ``` + +=== "Java" + + ```java + int weaponsLength = monster.weaponsLength(); + String secondWeaponName = monster.weapons(1).name(); + short secondWeaponDamage = monster.weapons(1).damage(); + ``` + +=== "JavaScript" + + ```javascript + var weaponsLength = monster.weaponsLength(); + var secondWeaponName = monster.weapons(1).name(); + var secondWeaponDamage = monster.weapons(1).damage(); + ``` + +=== "Kotlin" + + ```kotlin + val weaponsLength = monster.weaponsLength + val secondWeaponName = monster.weapons(1)!!.name + val secondWeaponDamage = monster.weapons(1)!!.damage + ``` + +=== "Lobster" + + ```lobster + let weapons_length = monster.weapons_length + let second_weapon_name = monster.weapons(1).name + let second_weapon_damage = monster.weapons(1).damage + ``` + +=== "Lua" + + ```lua + local weaponsLength = mon:WeaponsLength() + local secondWeaponName = mon:Weapon(2):Name() + local secondWeaponDamage = mon:Weapon(2):Damage() + ``` + +=== "PHP" + + ```php + $weapons_len = $monster->getWeaponsLength(); + $second_weapon_name = $monster->getWeapons(1)->getName(); + $second_weapon_damage = $monster->getWeapons(1)->getDamage(); + ``` + +=== "Python" + + ```py + weapons_length = monster.WeaponsLength() + second_weapon_name = monster.Weapons(1).Name() + second_weapon_damage = monster.Weapons(1).Damage() + ``` + +=== "Rust" + + ```rust + // Get and test the `weapons` FlatBuffers's `vector`. + let weps = monster.weapons().unwrap(); + let weps_len = weps.len(); + + let wep2 = weps.get(1); + let second_weapon_name = wep2.name(); + let second_weapon_damage = wep2.damage(); + ``` + +=== "Swift" + + ```swift + // Get the count of weapon objects + let wepsCount = monster.weaponsCount + + let weapon2 = monster.weapons(at: 1) + let weaponName = weapon2.name + let weaponDmg = weapon2.damage + ``` + +=== "TypeScript" + + ```ts + let weaponsLength = monster.weaponsLength(); + let secondWeaponName = monster.weapons(1).name(); + let secondWeaponDamage = monster.weapons(1).damage(); + ``` + + +### Union Access + +Lastly , we can access our `equipped` `union` field. Just like when we created +the union, we need to get both parts of the union: the type and the data. + +We can access the type to dynamically cast the data as needed (since the union +only stores a FlatBuffer `table`). + +=== "C++" + + ```c++ + auto union_type = monster.equipped_type(); + + if (union_type == Equipment_Weapon) { + // Requires `static_cast` to type `const Weapon*`. + auto weapon = static_cast(monster->equipped()); + + auto weapon_name = weapon->name()->str(); // "Axe" + auto weapon_damage = weapon->damage(); // 5 + } + ``` + +=== "C" + + ```c + // Access union type field. + if (ns(Monster_equipped_type(monster)) == ns(Equipment_Weapon)) { + // Cast to appropriate type: + // C allows for silent void pointer assignment, so we need no + // explicit cast. + ns(Weapon_table_t) weapon = ns(Monster_equipped(monster)); + const char *weapon_name = ns(Weapon_name(weapon)); // "Axe" + uint16_t weapon_damage = ns(Weapon_damage(weapon)); // 5 + } + ``` + +=== "C#" + + ```c# + var unionType = monster.EquippedType; + + if (unionType == Equipment.Weapon) { + var weapon = monster.Equipped().Value; + + var weaponName = weapon.Name; // "Axe" + var weaponDamage = weapon.Damage; // 5 + } + ``` + +=== "Dart" + + ```dart + var unionType = monster.equippedType.value; + + if (unionType == myGame.EquipmentTypeId.Weapon.value) { + myGame.Weapon weapon = mon.equipped as myGame.Weapon; + + var weaponName = weapon.name; // "Axe" + var weaponDamage = weapon.damage; // 5 + } + ``` + +=== "Go" + + ```go + // We need a `flatbuffers.Table` to capture the output of the + // `monster.Equipped()` function. + unionTable := new(flatbuffers.Table) + + if monster.Equipped(unionTable) { + unionType := monster.EquippedType() + + if unionType == sample.EquipmentWeapon { + // Create a `sample.Weapon` object that can be initialized with the + // contents of the `flatbuffers.Table` (`unionTable`), which was + // populated by `monster.Equipped()`. + unionWeapon = new(sample.Weapon) + unionWeapon.Init(unionTable.Bytes, unionTable.Pos) + + weaponName = unionWeapon.Name() + weaponDamage = unionWeapon.Damage() + } + } + ``` + +=== "Java" + + ```java + int unionType = monster.EquippedType(); + + if (unionType == Equipment.Weapon) { + // Requires an explicit cast to `Weapon`. + Weapon weapon = (Weapon)monster.equipped(new Weapon()); + + String weaponName = weapon.name(); // "Axe" + short weaponDamage = weapon.damage(); // 5 + } + ``` + +=== "JavaScript" + + ```javascript + var unionType = monster.equippedType(); + + if (unionType == MyGame.Sample.Equipment.Weapon) { + // 'Axe' + var weaponName = monster.equipped(new MyGame.Sample.Weapon()).name(); + // 5 + var weaponDamage = + monster.equipped(new MyGame.Sample.Weapon()).damage(); + } + ``` + +=== "Kotlin" + + ```kotlin + val unionType = monster.EquippedType + + if (unionType == Equipment.Weapon) { + // Requires an explicit cast to `Weapon`. + val weapon = monster.equipped(Weapon()) as Weapon + + val weaponName = weapon.name // "Axe" + val weaponDamage = weapon.damage // 5 + } + ``` + +=== "Lobster" + + ```lobster + union_type = monster.equipped_type + + if union_type == MyGame_Sample_Equipment_Weapon: + // `monster.equipped_as_Weapon` returns a FlatBuffer handle much like + // normal table fields, but this is only valid to call if we already + // know it is the correct type. + let union_weapon = monster.equipped_as_Weapon + + let weapon_name = union_weapon.name // "Axe" + let weapon_damage = union_weapon.damage // 5 + ``` + +=== "Lua" + + ```lua + local unionType = mon:EquippedType() + + if unionType == equipment.Weapon then + local unionWeapon = weapon.New() + unionWeapon:Init(mon:Equipped().bytes, mon:Equipped().pos) + + local weaponName = unionWeapon:Name() -- 'Axe' + local weaponDamage = unionWeapon:Damage() -- 5 + end + ``` + +=== "PHP" + + ```php + $union_type = $monster->getEquippedType(); + + if ($union_type == \MyGame\Sample\Equipment::Weapon) { + // "Axe" + $weapon_name = + $monster->getEquipped(new \MyGame\Sample\Weapon())->getName(); + // 5 + $weapon_damage = + $monster->getEquipped(new \MyGame\Sample\Weapon())->getDamage(); + } + ``` + +=== "Python" + + ```py + union_type = monster.EquippedType() + + if union_type == MyGame.Sample.Equipment.Equipment().Weapon: + # `monster.Equipped()` returns a `flatbuffers.Table`, which can be used + # to initialize a `MyGame.Sample.Weapon.Weapon()`. + union_weapon = MyGame.Sample.Weapon.Weapon() + union_weapon.Init(monster.Equipped().Bytes, monster.Equipped().Pos) + + weapon_name = union_weapon.Name() // 'Axe' + weapon_damage = union_weapon.Damage() // 5 + ``` + +=== "Rust" + + ```rust + // Get and test the `Equipment` union (`equipped` field). + // `equipped_as_weapon` returns a FlatBuffer handle much like normal table + // fields, but this will return `None` if the union is not actually of that + // type. + if monster.equipped_type() == Equipment::Weapon { + let equipped = monster.equipped_as_weapon().unwrap(); + let weapon_name = equipped.name(); + let weapon_damage = equipped.damage(); + ``` + +=== "Swift" + + ```swift + // Get and check if the monster has an equipped item + if monster.equippedType == .weapon { + let _weapon = monster.equipped(type: Weapon.self) + let name = _weapon.name // should return "Axe" + let dmg = _weapon.damage // should return 5 + } + ``` + +=== "TypeScript" + + ```ts + let unionType = monster.equippedType(); + + if (unionType == MyGame.Sample.Equipment.Weapon) { + // 'Axe' + let weaponName = monster.equipped(new MyGame.Sample.Weapon()).name(); + // 5 + let weaponDamage = monster.equipped(new MyGame.Sample.Weapon()).damage(); + } + ``` diff --git a/third_party/flatbuffers/docs/source/white_paper.md b/third_party/flatbuffers/docs/source/white_paper.md new file mode 100644 index 00000000000..dbad2cb35a0 --- /dev/null +++ b/third_party/flatbuffers/docs/source/white_paper.md @@ -0,0 +1,128 @@ +FlatBuffers white paper {#flatbuffers_white_paper} +======================= + +This document tries to shed some light on to the "why" of FlatBuffers, a +new serialization library. + +## Motivation + +Back in the good old days, performance was all about instructions and +cycles. Nowadays, processing units have run so far ahead of the memory +subsystem, that making an efficient application should start and finish +with thinking about memory. How much you use of it. How you lay it out +and access it. How you allocate it. When you copy it. + +Serialization is a pervasive activity in a lot programs, and a common +source of memory inefficiency, with lots of temporary data structures +needed to parse and represent data, and inefficient allocation patterns +and locality. + +If it would be possible to do serialization with no temporary objects, +no additional allocation, no copying, and good locality, this could be +of great value. The reason serialization systems usually don't manage +this is because it goes counter to forwards/backwards compatibility, and +platform specifics like endianness and alignment. + +FlatBuffers is what you get if you try anyway. + +In particular, FlatBuffers focus is on mobile hardware (where memory +size and memory bandwidth is even more constrained than on desktop +hardware), and applications that have the highest performance needs: +games. + +## FlatBuffers + +*This is a summary of FlatBuffers functionality, with some rationale. +A more detailed description can be found in the FlatBuffers +documentation.* + +### Summary + +A FlatBuffer is a binary buffer containing nested objects (structs, +tables, vectors,..) organized using offsets so that the data can be +traversed in-place just like any pointer-based data structure. Unlike +most in-memory data structures however, it uses strict rules of +alignment and endianness (always little) to ensure these buffers are +cross platform. Additionally, for objects that are tables, FlatBuffers +provides forwards/backwards compatibility and general optionality of +fields, to support most forms of format evolution. + +You define your object types in a schema, which can then be compiled to +C++ or Java for low to zero overhead reading & writing. +Optionally, JSON data can be dynamically parsed into buffers. + +### Tables + +Tables are the cornerstone of FlatBuffers, since format evolution is +essential for most applications of serialization. Typically, dealing +with format changes is something that can be done transparently during +the parsing process of most serialization solutions out there. +But a FlatBuffer isn't parsed before it is accessed. + +Tables get around this by using an extra indirection to access fields, +through a *vtable*. Each table comes with a vtable (which may be shared +between multiple tables with the same layout), and contains information +where fields for this particular kind of instance of vtable are stored. +The vtable may also indicate that the field is not present (because this +FlatBuffer was written with an older version of the software, or simply +because the information was not necessary for this instance, or deemed +deprecated), in which case a default value is returned. + +Tables have a low overhead in memory (since vtables are small and +shared) and in access cost (an extra indirection), but provide great +flexibility. Tables may even cost less memory than the equivalent +struct, since fields do not need to be stored when they are equal to +their default. + +FlatBuffers additionally offers "naked" structs, which do not offer +forwards/backwards compatibility, but can be even smaller (useful for +very small objects that are unlikely to change, like e.g. a coordinate +pair or a RGBA color). + +### Schemas + +While schemas reduce some generality (you can't just read any data +without having its schema), they have a lot of upsides: + +- Most information about the format can be factored into the generated + code, reducing memory needed to store data, and time to access it. + +- The strong typing of the data definitions means less error + checking/handling at runtime (less can go wrong). + +- A schema enables us to access a buffer without parsing. + +FlatBuffer schemas are fairly similar to those of the incumbent, +Protocol Buffers, and generally should be readable to those familiar +with the C family of languages. We chose to improve upon the features +offered by .proto files in the following ways: + +- Deprecation of fields instead of manual field id assignment. + Extending an object in a .proto means hunting for a free slot among + the numbers (preferring lower numbers since they have a more compact + representation). Besides being inconvenient, it also makes removing + fields problematic: you either have to keep them, not making it + obvious that this field shouldn't be read/written anymore, and still + generating accessors. Or you remove it, but now you risk that + there's still old data around that uses that field by the time + someone reuses that field id, with nasty consequences. + +- Differentiating between tables and structs (see above). Effectively + all table fields are `optional`, and all struct fields are + `required`. + +- Having a native vector type instead of `repeated`. This gives you a + length without having to collect all items, and in the case of + scalars provides for a more compact representation, and one that + guarantees adjacency. + +- Having a native `union` type instead of using a series of `optional` + fields, all of which must be checked individually. + +- Being able to define defaults for all scalars, instead of having to + deal with their optionality at each access. + +- A parser that can deal with both schemas and data definitions (JSON + compatible) uniformly. + +
diff --git a/third_party/flatbuffers/examples/go-echo/README.md b/third_party/flatbuffers/examples/go-echo/README.md new file mode 100644 index 00000000000..acecee7e42e --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/README.md @@ -0,0 +1,27 @@ +# Go Echo Example + +A simple example demonstrating how to send flatbuffers over the network in Go. + +## Generate flatbuffer code + +``` +flatc -g --gen-object-api --go-module-name echo hero.fbs net.fbs +``` + +## Running example + +1. Run go mod tidy to get dependencies +``` +go mod tidy +``` + +2. Start a server +``` +go run server/server.go +``` + +3. Run the client in another terminal +``` +go run client/client.go +``` + diff --git a/third_party/flatbuffers/examples/go-echo/client/client.go b/third_party/flatbuffers/examples/go-echo/client/client.go new file mode 100644 index 00000000000..be8fd7e8524 --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/client/client.go @@ -0,0 +1,51 @@ +package main + +import ( + "bytes" + "fmt" + "io/ioutil" + "net/http" + + "echo/hero" + "echo/net" + + flatbuffers "github.com/google/flatbuffers/go" +) + +func RequestBody() *bytes.Reader { + b := flatbuffers.NewBuilder(0) + r := net.RequestT{Player: &hero.WarriorT{Name: "Krull", Hp: 100}} + b.Finish(r.Pack(b)) + return bytes.NewReader(b.FinishedBytes()) +} + +func ReadResponse(r *http.Response) { + body, err := ioutil.ReadAll(r.Body) + if err != nil { + fmt.Printf("Unable to read request body: %v\n", err) + return + } + + res := net.GetRootAsResponse(body, 0) + player := res.Player(nil) + + fmt.Printf("Got response (name: %v, hp: %v)\n", string(player.Name()), player.Hp()) +} + +func main() { + body := RequestBody() + req, err := http.NewRequest("POST", "http://localhost:8080/echo", body) + if err != nil { + fmt.Println(err) + return + } + + client := http.DefaultClient + resp, err := client.Do(req) + if err != nil { + fmt.Println(err) + return + } + + ReadResponse(resp) +} diff --git a/third_party/flatbuffers/examples/go-echo/go.mod b/third_party/flatbuffers/examples/go-echo/go.mod new file mode 100644 index 00000000000..81abc9b5b39 --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/go.mod @@ -0,0 +1,5 @@ +module echo + +go 1.19 + +require github.com/google/flatbuffers v22.10.26+incompatible diff --git a/third_party/flatbuffers/examples/go-echo/hero.fbs b/third_party/flatbuffers/examples/go-echo/hero.fbs new file mode 100644 index 00000000000..91b9dcaaf46 --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/hero.fbs @@ -0,0 +1,6 @@ +namespace hero; + +table Warrior { + name: string; + hp: uint32; +} diff --git a/third_party/flatbuffers/examples/go-echo/hero/Warrior.go b/third_party/flatbuffers/examples/go-echo/hero/Warrior.go new file mode 100644 index 00000000000..0e9802c189a --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/hero/Warrior.go @@ -0,0 +1,100 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package hero + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type WarriorT struct { + Name string `json:"name"` + Hp uint32 `json:"hp"` +} + +func (t *WarriorT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + nameOffset := flatbuffers.UOffsetT(0) + if t.Name != "" { + nameOffset = builder.CreateString(t.Name) + } + WarriorStart(builder) + WarriorAddName(builder, nameOffset) + WarriorAddHp(builder, t.Hp) + return WarriorEnd(builder) +} + +func (rcv *Warrior) UnPackTo(t *WarriorT) { + t.Name = string(rcv.Name()) + t.Hp = rcv.Hp() +} + +func (rcv *Warrior) UnPack() *WarriorT { + if rcv == nil { + return nil + } + t := &WarriorT{} + rcv.UnPackTo(t) + return t +} + +type Warrior struct { + _tab flatbuffers.Table +} + +func GetRootAsWarrior(buf []byte, offset flatbuffers.UOffsetT) *Warrior { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Warrior{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsWarrior(buf []byte, offset flatbuffers.UOffsetT) *Warrior { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Warrior{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *Warrior) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Warrior) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Warrior) Name() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Warrior) Hp() uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + return rcv._tab.GetUint32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Warrior) MutateHp(n uint32) bool { + return rcv._tab.MutateUint32Slot(6, n) +} + +func WarriorStart(builder *flatbuffers.Builder) { + builder.StartObject(2) +} +func WarriorAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(name), 0) +} +func WarriorAddHp(builder *flatbuffers.Builder, hp uint32) { + builder.PrependUint32Slot(1, hp, 0) +} +func WarriorEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/examples/go-echo/net.fbs b/third_party/flatbuffers/examples/go-echo/net.fbs new file mode 100644 index 00000000000..7293bb699d1 --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/net.fbs @@ -0,0 +1,11 @@ +include "hero.fbs"; + +namespace net; + +table Request { + player: hero.Warrior; +} + +table Response { + player: hero.Warrior; +} diff --git a/third_party/flatbuffers/examples/go-echo/net/Request.go b/third_party/flatbuffers/examples/go-echo/net/Request.go new file mode 100644 index 00000000000..4c833626540 --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/net/Request.go @@ -0,0 +1,86 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package net + +import ( + flatbuffers "github.com/google/flatbuffers/go" + + hero "echo/hero" +) + +type RequestT struct { + Player *hero.WarriorT `json:"player"` +} + +func (t *RequestT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + playerOffset := t.Player.Pack(builder) + RequestStart(builder) + RequestAddPlayer(builder, playerOffset) + return RequestEnd(builder) +} + +func (rcv *Request) UnPackTo(t *RequestT) { + t.Player = rcv.Player(nil).UnPack() +} + +func (rcv *Request) UnPack() *RequestT { + if rcv == nil { + return nil + } + t := &RequestT{} + rcv.UnPackTo(t) + return t +} + +type Request struct { + _tab flatbuffers.Table +} + +func GetRootAsRequest(buf []byte, offset flatbuffers.UOffsetT) *Request { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Request{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsRequest(buf []byte, offset flatbuffers.UOffsetT) *Request { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Request{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *Request) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Request) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Request) Player(obj *hero.Warrior) *hero.Warrior { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(hero.Warrior) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func RequestStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func RequestAddPlayer(builder *flatbuffers.Builder, player flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(player), 0) +} +func RequestEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/examples/go-echo/net/Response.go b/third_party/flatbuffers/examples/go-echo/net/Response.go new file mode 100644 index 00000000000..a9d1f43783e --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/net/Response.go @@ -0,0 +1,86 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package net + +import ( + flatbuffers "github.com/google/flatbuffers/go" + + hero "echo/hero" +) + +type ResponseT struct { + Player *hero.WarriorT `json:"player"` +} + +func (t *ResponseT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + playerOffset := t.Player.Pack(builder) + ResponseStart(builder) + ResponseAddPlayer(builder, playerOffset) + return ResponseEnd(builder) +} + +func (rcv *Response) UnPackTo(t *ResponseT) { + t.Player = rcv.Player(nil).UnPack() +} + +func (rcv *Response) UnPack() *ResponseT { + if rcv == nil { + return nil + } + t := &ResponseT{} + rcv.UnPackTo(t) + return t +} + +type Response struct { + _tab flatbuffers.Table +} + +func GetRootAsResponse(buf []byte, offset flatbuffers.UOffsetT) *Response { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Response{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsResponse(buf []byte, offset flatbuffers.UOffsetT) *Response { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Response{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *Response) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Response) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Response) Player(obj *hero.Warrior) *hero.Warrior { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(hero.Warrior) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func ResponseStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func ResponseAddPlayer(builder *flatbuffers.Builder, player flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(player), 0) +} +func ResponseEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/examples/go-echo/server/server.go b/third_party/flatbuffers/examples/go-echo/server/server.go new file mode 100644 index 00000000000..c9885b899d3 --- /dev/null +++ b/third_party/flatbuffers/examples/go-echo/server/server.go @@ -0,0 +1,29 @@ +package main + +import ( + "echo/net" + "fmt" + "io/ioutil" + "net/http" +) + +func echo(w http.ResponseWriter, r *http.Request) { + body, err := ioutil.ReadAll(r.Body) + if err != nil { + fmt.Printf("Unable to read request body: %v\n", err) + return + } + + req := net.GetRootAsRequest(body, 0) + player := req.Player(nil) + + fmt.Printf("Got request (name: %v, hp: %v)\n", string(player.Name()), player.Hp()) + w.Write(body) +} + +func main() { + http.HandleFunc("/echo", echo) + + fmt.Println("Listening on port :8080") + http.ListenAndServe(":8080", nil) +} diff --git a/third_party/flatbuffers/extensions.bzl b/third_party/flatbuffers/extensions.bzl new file mode 100644 index 00000000000..c5865af2909 --- /dev/null +++ b/third_party/flatbuffers/extensions.bzl @@ -0,0 +1,19 @@ +"""Bzlmod extensions""" + +load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file") + +def _non_module_dependencies_impl(_ctx): + """Non module dependencies""" + http_file( + name = "bazel_linux_x86_64", + downloaded_file_path = "bazel", + executable = True, + sha256 = "e78fc3394deae5408d6f49a15c7b1e615901969ecf6e50d55ef899996b0b8458", + urls = [ + "https://github.com/bazelbuild/bazel/releases/download/6.3.2/bazel-6.3.2-linux-x86_64", + ], + ) + +non_module_dependencies = module_extension( + implementation = _non_module_dependencies_impl, +) diff --git a/third_party/flatbuffers/go/BUILD.bazel b/third_party/flatbuffers/go/BUILD.bazel new file mode 100644 index 00000000000..78bd8d81ada --- /dev/null +++ b/third_party/flatbuffers/go/BUILD.bazel @@ -0,0 +1,23 @@ +load("@io_bazel_rules_go//go:def.bzl", "go_library") + +alias( + name = "go_default_library", + actual = ":go", + visibility = ["//visibility:public"], +) + +go_library( + name = "go", + srcs = [ + "builder.go", + "doc.go", + "encode.go", + "grpc.go", + "lib.go", + "sizes.go", + "struct.go", + "table.go", + ], + importpath = "github.com/google/flatbuffers/go", + visibility = ["//visibility:public"], +) diff --git a/third_party/flatbuffers/go/builder.go b/third_party/flatbuffers/go/builder.go new file mode 100644 index 00000000000..5d90e8ef982 --- /dev/null +++ b/third_party/flatbuffers/go/builder.go @@ -0,0 +1,856 @@ +package flatbuffers + +import "sort" + +// Builder is a state machine for creating FlatBuffer objects. +// Use a Builder to construct object(s) starting from leaf nodes. +// +// A Builder constructs byte buffers in a last-first manner for simplicity and +// performance. +type Builder struct { + // `Bytes` gives raw access to the buffer. Most users will want to use + // FinishedBytes() instead. + Bytes []byte + + minalign int + vtable []UOffsetT + objectEnd UOffsetT + vtables []UOffsetT + head UOffsetT + nested bool + finished bool + + sharedStrings map[string]UOffsetT +} + +const fileIdentifierLength = 4 +const sizePrefixLength = 4 + +// NewBuilder initializes a Builder of size `initial_size`. +// The internal buffer is grown as needed. +func NewBuilder(initialSize int) *Builder { + if initialSize <= 0 { + initialSize = 0 + } + + b := &Builder{} + b.Bytes = make([]byte, initialSize) + b.head = UOffsetT(initialSize) + b.minalign = 1 + b.vtables = make([]UOffsetT, 0, 16) // sensible default capacity + return b +} + +// Reset truncates the underlying Builder buffer, facilitating alloc-free +// reuse of a Builder. It also resets bookkeeping data. +func (b *Builder) Reset() { + if b.Bytes != nil { + b.Bytes = b.Bytes[:cap(b.Bytes)] + } + + if b.vtables != nil { + b.vtables = b.vtables[:0] + } + + if b.vtable != nil { + b.vtable = b.vtable[:0] + } + + if b.sharedStrings != nil { + for key := range b.sharedStrings { + delete(b.sharedStrings, key) + } + } + + b.head = UOffsetT(len(b.Bytes)) + b.minalign = 1 + b.nested = false + b.finished = false +} + +// FinishedBytes returns a pointer to the written data in the byte buffer. +// Panics if the builder is not in a finished state (which is caused by calling +// `Finish()`). +func (b *Builder) FinishedBytes() []byte { + b.assertFinished() + return b.Bytes[b.Head():] +} + +// StartObject initializes bookkeeping for writing a new object. +func (b *Builder) StartObject(numfields int) { + b.assertNotNested() + b.nested = true + + // use 32-bit offsets so that arithmetic doesn't overflow. + if cap(b.vtable) < numfields || b.vtable == nil { + b.vtable = make([]UOffsetT, numfields) + } else { + b.vtable = b.vtable[:numfields] + for i := 0; i < len(b.vtable); i++ { + b.vtable[i] = 0 + } + } + + b.objectEnd = b.Offset() +} + +// WriteVtable serializes the vtable for the current object, if applicable. +// +// Before writing out the vtable, this checks pre-existing vtables for equality +// to this one. If an equal vtable is found, point the object to the existing +// vtable and return. +// +// Because vtable values are sensitive to alignment of object data, not all +// logically-equal vtables will be deduplicated. +// +// A vtable has the following format: +// +// +// * N, where N is the number of fields in +// the schema for this type. Includes deprecated fields. +// Thus, a vtable is made of 2 + N elements, each SizeVOffsetT bytes wide. +// +// An object has the following format: +// +// + +func (b *Builder) WriteVtable() (n UOffsetT) { + // Prepend a zero scalar to the object. Later in this function we'll + // write an offset here that points to the object's vtable: + b.PrependSOffsetT(0) + + objectOffset := b.Offset() + existingVtable := UOffsetT(0) + + // Trim vtable of trailing zeroes. + i := len(b.vtable) - 1 + for ; i >= 0 && b.vtable[i] == 0; i-- { + } + b.vtable = b.vtable[:i+1] + + // Search backwards through existing vtables, because similar vtables + // are likely to have been recently appended. See + // BenchmarkVtableDeduplication for a case in which this heuristic + // saves about 30% of the time used in writing objects with duplicate + // tables. + for i := len(b.vtables) - 1; i >= 0; i-- { + // Find the other vtable, which is associated with `i`: + vt2Offset := b.vtables[i] + vt2Start := len(b.Bytes) - int(vt2Offset) + vt2Len := GetVOffsetT(b.Bytes[vt2Start:]) + + metadata := VtableMetadataFields * SizeVOffsetT + vt2End := vt2Start + int(vt2Len) + vt2 := b.Bytes[vt2Start+metadata : vt2End] + + // Compare the other vtable to the one under consideration. + // If they are equal, store the offset and break: + if vtableEqual(b.vtable, objectOffset, vt2) { + existingVtable = vt2Offset + break + } + } + + if existingVtable == 0 { + // Did not find a vtable, so write this one to the buffer. + + // Write out the current vtable in reverse , because + // serialization occurs in last-first order: + for i := len(b.vtable) - 1; i >= 0; i-- { + var off UOffsetT + if b.vtable[i] != 0 { + // Forward reference to field; + // use 32bit number to assert no overflow: + off = objectOffset - b.vtable[i] + } + + b.PrependVOffsetT(VOffsetT(off)) + } + + // The two metadata fields are written last. + + // First, store the object bytesize: + objectSize := objectOffset - b.objectEnd + b.PrependVOffsetT(VOffsetT(objectSize)) + + // Second, store the vtable bytesize: + vBytes := (len(b.vtable) + VtableMetadataFields) * SizeVOffsetT + b.PrependVOffsetT(VOffsetT(vBytes)) + + // Next, write the offset to the new vtable in the + // already-allocated SOffsetT at the beginning of this object: + objectStart := SOffsetT(len(b.Bytes)) - SOffsetT(objectOffset) + WriteSOffsetT(b.Bytes[objectStart:], + SOffsetT(b.Offset())-SOffsetT(objectOffset)) + + // Finally, store this vtable in memory for future + // deduplication: + b.vtables = append(b.vtables, b.Offset()) + } else { + // Found a duplicate vtable. + + objectStart := SOffsetT(len(b.Bytes)) - SOffsetT(objectOffset) + b.head = UOffsetT(objectStart) + + // Write the offset to the found vtable in the + // already-allocated SOffsetT at the beginning of this object: + WriteSOffsetT(b.Bytes[b.head:], + SOffsetT(existingVtable)-SOffsetT(objectOffset)) + } + + b.vtable = b.vtable[:0] + return objectOffset +} + +// EndObject writes data necessary to finish object construction. +func (b *Builder) EndObject() UOffsetT { + b.assertNested() + n := b.WriteVtable() + b.nested = false + return n +} + +// Doubles the size of the byteslice, and copies the old data towards the +// end of the new byteslice (since we build the buffer backwards). +func (b *Builder) growByteBuffer() { + if (int64(len(b.Bytes)) & int64(0xC0000000)) != 0 { + panic("cannot grow buffer beyond 2 gigabytes") + } + newLen := len(b.Bytes) * 2 + if newLen == 0 { + newLen = 1 + } + + if cap(b.Bytes) >= newLen { + b.Bytes = b.Bytes[:newLen] + } else { + extension := make([]byte, newLen-len(b.Bytes)) + b.Bytes = append(b.Bytes, extension...) + } + + middle := newLen / 2 + copy(b.Bytes[middle:], b.Bytes[:middle]) +} + +// Head gives the start of useful data in the underlying byte buffer. +// Note: unlike other functions, this value is interpreted as from the left. +func (b *Builder) Head() UOffsetT { + return b.head +} + +// Offset relative to the end of the buffer. +func (b *Builder) Offset() UOffsetT { + return UOffsetT(len(b.Bytes)) - b.head +} + +// Pad places zeros at the current offset. +func (b *Builder) Pad(n int) { + for i := 0; i < n; i++ { + b.PlaceByte(0) + } +} + +// Prep prepares to write an element of `size` after `additional_bytes` +// have been written, e.g. if you write a string, you need to align such +// the int length field is aligned to SizeInt32, and the string data follows it +// directly. +// If all you need to do is align, `additionalBytes` will be 0. +func (b *Builder) Prep(size, additionalBytes int) { + // Track the biggest thing we've ever aligned to. + if size > b.minalign { + b.minalign = size + } + // Find the amount of alignment needed such that `size` is properly + // aligned after `additionalBytes`: + alignSize := (^(len(b.Bytes) - int(b.Head()) + additionalBytes)) + 1 + alignSize &= (size - 1) + + // Reallocate the buffer if needed: + for int(b.head) <= alignSize+size+additionalBytes { + oldBufSize := len(b.Bytes) + b.growByteBuffer() + b.head += UOffsetT(len(b.Bytes) - oldBufSize) + } + b.Pad(alignSize) +} + +// PrependSOffsetT prepends an SOffsetT, relative to where it will be written. +func (b *Builder) PrependSOffsetT(off SOffsetT) { + b.Prep(SizeSOffsetT, 0) // Ensure alignment is already done. + if !(UOffsetT(off) <= b.Offset()) { + panic("unreachable: off <= b.Offset()") + } + off2 := SOffsetT(b.Offset()) - off + SOffsetT(SizeSOffsetT) + b.PlaceSOffsetT(off2) +} + +// PrependUOffsetT prepends an UOffsetT, relative to where it will be written. +func (b *Builder) PrependUOffsetT(off UOffsetT) { + b.Prep(SizeUOffsetT, 0) // Ensure alignment is already done. + if !(off <= b.Offset()) { + panic("unreachable: off <= b.Offset()") + } + off2 := b.Offset() - off + UOffsetT(SizeUOffsetT) + b.PlaceUOffsetT(off2) +} + +// StartVector initializes bookkeeping for writing a new vector. +// +// A vector has the following format: +// +// +, where T is the type of elements of this vector. +func (b *Builder) StartVector(elemSize, numElems, alignment int) UOffsetT { + b.assertNotNested() + b.nested = true + b.Prep(SizeUint32, elemSize*numElems) + b.Prep(alignment, elemSize*numElems) // Just in case alignment > int. + return b.Offset() +} + +// EndVector writes data necessary to finish vector construction. +func (b *Builder) EndVector(vectorNumElems int) UOffsetT { + b.assertNested() + + // we already made space for this, so write without PrependUint32 + b.PlaceUOffsetT(UOffsetT(vectorNumElems)) + + b.nested = false + return b.Offset() +} + +// CreateVectorOfTables serializes slice of table offsets into a vector. +func (b *Builder) CreateVectorOfTables(offsets []UOffsetT) UOffsetT { + b.assertNotNested() + b.StartVector(4, len(offsets), 4) + for i := len(offsets) - 1; i >= 0; i-- { + b.PrependUOffsetT(offsets[i]) + } + return b.EndVector(len(offsets)) +} + +type KeyCompare func(o1, o2 UOffsetT, buf []byte) bool + +func (b *Builder) CreateVectorOfSortedTables(offsets []UOffsetT, keyCompare KeyCompare) UOffsetT { + sort.Slice(offsets, func(i, j int) bool { + return keyCompare(offsets[i], offsets[j], b.Bytes) + }) + return b.CreateVectorOfTables(offsets) +} + +// CreateSharedString Checks if the string is already written +// to the buffer before calling CreateString +func (b *Builder) CreateSharedString(s string) UOffsetT { + if b.sharedStrings == nil { + b.sharedStrings = make(map[string]UOffsetT) + } + if v, ok := b.sharedStrings[s]; ok { + return v + } + off := b.CreateString(s) + b.sharedStrings[s] = off + return off +} + +// CreateString writes a null-terminated string as a vector. +func (b *Builder) CreateString(s string) UOffsetT { + b.assertNotNested() + b.nested = true + + b.Prep(int(SizeUOffsetT), (len(s)+1)*SizeByte) + b.PlaceByte(0) + + l := UOffsetT(len(s)) + + b.head -= l + copy(b.Bytes[b.head:b.head+l], s) + + return b.EndVector(len(s)) +} + +// CreateByteString writes a byte slice as a string (null-terminated). +func (b *Builder) CreateByteString(s []byte) UOffsetT { + b.assertNotNested() + b.nested = true + + b.Prep(int(SizeUOffsetT), (len(s)+1)*SizeByte) + b.PlaceByte(0) + + l := UOffsetT(len(s)) + + b.head -= l + copy(b.Bytes[b.head:b.head+l], s) + + return b.EndVector(len(s)) +} + +// CreateByteVector writes a ubyte vector +func (b *Builder) CreateByteVector(v []byte) UOffsetT { + b.assertNotNested() + b.nested = true + + b.Prep(int(SizeUOffsetT), len(v)*SizeByte) + + l := UOffsetT(len(v)) + + b.head -= l + copy(b.Bytes[b.head:b.head+l], v) + + return b.EndVector(len(v)) +} + +func (b *Builder) assertNested() { + // If you get this assert, you're in an object while trying to write + // data that belongs outside of an object. + // To fix this, write non-inline data (like vectors) before creating + // objects. + if !b.nested { + panic("Incorrect creation order: must be inside object.") + } +} + +func (b *Builder) assertNotNested() { + // If you hit this, you're trying to construct a Table/Vector/String + // during the construction of its parent table (between the MyTableBuilder + // and builder.Finish()). + // Move the creation of these sub-objects to above the MyTableBuilder to + // not get this assert. + // Ignoring this assert may appear to work in simple cases, but the reason + // it is here is that storing objects in-line may cause vtable offsets + // to not fit anymore. It also leads to vtable duplication. + if b.nested { + panic("Incorrect creation order: object must not be nested.") + } +} + +func (b *Builder) assertFinished() { + // If you get this assert, you're attempting to get access a buffer + // which hasn't been finished yet. Be sure to call builder.Finish() + // with your root table. + // If you really need to access an unfinished buffer, use the Bytes + // buffer directly. + if !b.finished { + panic("Incorrect use of FinishedBytes(): must call 'Finish' first.") + } +} + +// PrependBoolSlot prepends a bool onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependBoolSlot(o int, x, d bool) { + val := byte(0) + if x { + val = 1 + } + def := byte(0) + if d { + def = 1 + } + b.PrependByteSlot(o, val, def) +} + +// PrependByteSlot prepends a byte onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependByteSlot(o int, x, d byte) { + if x != d { + b.PrependByte(x) + b.Slot(o) + } +} + +// PrependUint8Slot prepends a uint8 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependUint8Slot(o int, x, d uint8) { + if x != d { + b.PrependUint8(x) + b.Slot(o) + } +} + +// PrependUint16Slot prepends a uint16 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependUint16Slot(o int, x, d uint16) { + if x != d { + b.PrependUint16(x) + b.Slot(o) + } +} + +// PrependUint32Slot prepends a uint32 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependUint32Slot(o int, x, d uint32) { + if x != d { + b.PrependUint32(x) + b.Slot(o) + } +} + +// PrependUint64Slot prepends a uint64 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependUint64Slot(o int, x, d uint64) { + if x != d { + b.PrependUint64(x) + b.Slot(o) + } +} + +// PrependInt8Slot prepends a int8 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependInt8Slot(o int, x, d int8) { + if x != d { + b.PrependInt8(x) + b.Slot(o) + } +} + +// PrependInt16Slot prepends a int16 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependInt16Slot(o int, x, d int16) { + if x != d { + b.PrependInt16(x) + b.Slot(o) + } +} + +// PrependInt32Slot prepends a int32 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependInt32Slot(o int, x, d int32) { + if x != d { + b.PrependInt32(x) + b.Slot(o) + } +} + +// PrependInt64Slot prepends a int64 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependInt64Slot(o int, x, d int64) { + if x != d { + b.PrependInt64(x) + b.Slot(o) + } +} + +// PrependFloat32Slot prepends a float32 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependFloat32Slot(o int, x, d float32) { + if x != d { + b.PrependFloat32(x) + b.Slot(o) + } +} + +// PrependFloat64Slot prepends a float64 onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependFloat64Slot(o int, x, d float64) { + if x != d { + b.PrependFloat64(x) + b.Slot(o) + } +} + +// PrependUOffsetTSlot prepends an UOffsetT onto the object at vtable slot `o`. +// If value `x` equals default `d`, then the slot will be set to zero and no +// other data will be written. +func (b *Builder) PrependUOffsetTSlot(o int, x, d UOffsetT) { + if x != d { + b.PrependUOffsetT(x) + b.Slot(o) + } +} + +// PrependStructSlot prepends a struct onto the object at vtable slot `o`. +// Structs are stored inline, so nothing additional is being added. +// In generated code, `d` is always 0. +func (b *Builder) PrependStructSlot(voffset int, x, d UOffsetT) { + if x != d { + b.assertNested() + if x != b.Offset() { + panic("inline data write outside of object") + } + b.Slot(voffset) + } +} + +// Slot sets the vtable key `voffset` to the current location in the buffer. +func (b *Builder) Slot(slotnum int) { + b.vtable[slotnum] = UOffsetT(b.Offset()) +} + +// FinishWithFileIdentifier finalizes a buffer, pointing to the given `rootTable`. +// as well as applys a file identifier +func (b *Builder) FinishWithFileIdentifier(rootTable UOffsetT, fid []byte) { + if fid == nil || len(fid) != fileIdentifierLength { + panic("incorrect file identifier length") + } + // In order to add a file identifier to the flatbuffer message, we need + // to prepare an alignment and file identifier length + b.Prep(b.minalign, SizeInt32+fileIdentifierLength) + for i := fileIdentifierLength - 1; i >= 0; i-- { + // place the file identifier + b.PlaceByte(fid[i]) + } + // finish + b.Finish(rootTable) +} + +// FinishSizePrefixed finalizes a buffer, pointing to the given `rootTable`. +// The buffer is prefixed with the size of the buffer, excluding the size +// of the prefix itself. +func (b *Builder) FinishSizePrefixed(rootTable UOffsetT) { + b.finish(rootTable, true) +} + +// FinishSizePrefixedWithFileIdentifier finalizes a buffer, pointing to the given `rootTable` +// and applies a file identifier. The buffer is prefixed with the size of the buffer, +// excluding the size of the prefix itself. +func (b *Builder) FinishSizePrefixedWithFileIdentifier(rootTable UOffsetT, fid []byte) { + if fid == nil || len(fid) != fileIdentifierLength { + panic("incorrect file identifier length") + } + // In order to add a file identifier and size prefix to the flatbuffer message, + // we need to prepare an alignment, a size prefix length, and file identifier length + b.Prep(b.minalign, SizeInt32+fileIdentifierLength+sizePrefixLength) + for i := fileIdentifierLength - 1; i >= 0; i-- { + // place the file identifier + b.PlaceByte(fid[i]) + } + // finish + b.finish(rootTable, true) +} + +// Finish finalizes a buffer, pointing to the given `rootTable`. +func (b *Builder) Finish(rootTable UOffsetT) { + b.finish(rootTable, false) +} + +// finish finalizes a buffer, pointing to the given `rootTable` +// with an optional size prefix. +func (b *Builder) finish(rootTable UOffsetT, sizePrefix bool) { + b.assertNotNested() + + if sizePrefix { + b.Prep(b.minalign, SizeUOffsetT+sizePrefixLength) + } else { + b.Prep(b.minalign, SizeUOffsetT) + } + + b.PrependUOffsetT(rootTable) + + if sizePrefix { + b.PlaceUint32(uint32(b.Offset())) + } + + b.finished = true +} + +// vtableEqual compares an unwritten vtable to a written vtable. +func vtableEqual(a []UOffsetT, objectStart UOffsetT, b []byte) bool { + if len(a)*SizeVOffsetT != len(b) { + return false + } + + for i := 0; i < len(a); i++ { + x := GetVOffsetT(b[i*SizeVOffsetT : (i+1)*SizeVOffsetT]) + + // Skip vtable entries that indicate a default value. + if x == 0 && a[i] == 0 { + continue + } + + y := SOffsetT(objectStart) - SOffsetT(a[i]) + if SOffsetT(x) != y { + return false + } + } + return true +} + +// PrependBool prepends a bool to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependBool(x bool) { + b.Prep(SizeBool, 0) + b.PlaceBool(x) +} + +// PrependUint8 prepends a uint8 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependUint8(x uint8) { + b.Prep(SizeUint8, 0) + b.PlaceUint8(x) +} + +// PrependUint16 prepends a uint16 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependUint16(x uint16) { + b.Prep(SizeUint16, 0) + b.PlaceUint16(x) +} + +// PrependUint32 prepends a uint32 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependUint32(x uint32) { + b.Prep(SizeUint32, 0) + b.PlaceUint32(x) +} + +// PrependUint64 prepends a uint64 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependUint64(x uint64) { + b.Prep(SizeUint64, 0) + b.PlaceUint64(x) +} + +// PrependInt8 prepends a int8 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependInt8(x int8) { + b.Prep(SizeInt8, 0) + b.PlaceInt8(x) +} + +// PrependInt16 prepends a int16 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependInt16(x int16) { + b.Prep(SizeInt16, 0) + b.PlaceInt16(x) +} + +// PrependInt32 prepends a int32 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependInt32(x int32) { + b.Prep(SizeInt32, 0) + b.PlaceInt32(x) +} + +// PrependInt64 prepends a int64 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependInt64(x int64) { + b.Prep(SizeInt64, 0) + b.PlaceInt64(x) +} + +// PrependFloat32 prepends a float32 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependFloat32(x float32) { + b.Prep(SizeFloat32, 0) + b.PlaceFloat32(x) +} + +// PrependFloat64 prepends a float64 to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependFloat64(x float64) { + b.Prep(SizeFloat64, 0) + b.PlaceFloat64(x) +} + +// PrependByte prepends a byte to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependByte(x byte) { + b.Prep(SizeByte, 0) + b.PlaceByte(x) +} + +// PrependVOffsetT prepends a VOffsetT to the Builder buffer. +// Aligns and checks for space. +func (b *Builder) PrependVOffsetT(x VOffsetT) { + b.Prep(SizeVOffsetT, 0) + b.PlaceVOffsetT(x) +} + +// PlaceBool prepends a bool to the Builder, without checking for space. +func (b *Builder) PlaceBool(x bool) { + b.head -= UOffsetT(SizeBool) + WriteBool(b.Bytes[b.head:], x) +} + +// PlaceUint8 prepends a uint8 to the Builder, without checking for space. +func (b *Builder) PlaceUint8(x uint8) { + b.head -= UOffsetT(SizeUint8) + WriteUint8(b.Bytes[b.head:], x) +} + +// PlaceUint16 prepends a uint16 to the Builder, without checking for space. +func (b *Builder) PlaceUint16(x uint16) { + b.head -= UOffsetT(SizeUint16) + WriteUint16(b.Bytes[b.head:], x) +} + +// PlaceUint32 prepends a uint32 to the Builder, without checking for space. +func (b *Builder) PlaceUint32(x uint32) { + b.head -= UOffsetT(SizeUint32) + WriteUint32(b.Bytes[b.head:], x) +} + +// PlaceUint64 prepends a uint64 to the Builder, without checking for space. +func (b *Builder) PlaceUint64(x uint64) { + b.head -= UOffsetT(SizeUint64) + WriteUint64(b.Bytes[b.head:], x) +} + +// PlaceInt8 prepends a int8 to the Builder, without checking for space. +func (b *Builder) PlaceInt8(x int8) { + b.head -= UOffsetT(SizeInt8) + WriteInt8(b.Bytes[b.head:], x) +} + +// PlaceInt16 prepends a int16 to the Builder, without checking for space. +func (b *Builder) PlaceInt16(x int16) { + b.head -= UOffsetT(SizeInt16) + WriteInt16(b.Bytes[b.head:], x) +} + +// PlaceInt32 prepends a int32 to the Builder, without checking for space. +func (b *Builder) PlaceInt32(x int32) { + b.head -= UOffsetT(SizeInt32) + WriteInt32(b.Bytes[b.head:], x) +} + +// PlaceInt64 prepends a int64 to the Builder, without checking for space. +func (b *Builder) PlaceInt64(x int64) { + b.head -= UOffsetT(SizeInt64) + WriteInt64(b.Bytes[b.head:], x) +} + +// PlaceFloat32 prepends a float32 to the Builder, without checking for space. +func (b *Builder) PlaceFloat32(x float32) { + b.head -= UOffsetT(SizeFloat32) + WriteFloat32(b.Bytes[b.head:], x) +} + +// PlaceFloat64 prepends a float64 to the Builder, without checking for space. +func (b *Builder) PlaceFloat64(x float64) { + b.head -= UOffsetT(SizeFloat64) + WriteFloat64(b.Bytes[b.head:], x) +} + +// PlaceByte prepends a byte to the Builder, without checking for space. +func (b *Builder) PlaceByte(x byte) { + b.head -= UOffsetT(SizeByte) + WriteByte(b.Bytes[b.head:], x) +} + +// PlaceVOffsetT prepends a VOffsetT to the Builder, without checking for space. +func (b *Builder) PlaceVOffsetT(x VOffsetT) { + b.head -= UOffsetT(SizeVOffsetT) + WriteVOffsetT(b.Bytes[b.head:], x) +} + +// PlaceSOffsetT prepends a SOffsetT to the Builder, without checking for space. +func (b *Builder) PlaceSOffsetT(x SOffsetT) { + b.head -= UOffsetT(SizeSOffsetT) + WriteSOffsetT(b.Bytes[b.head:], x) +} + +// PlaceUOffsetT prepends a UOffsetT to the Builder, without checking for space. +func (b *Builder) PlaceUOffsetT(x UOffsetT) { + b.head -= UOffsetT(SizeUOffsetT) + WriteUOffsetT(b.Bytes[b.head:], x) +} diff --git a/third_party/flatbuffers/go/doc.go b/third_party/flatbuffers/go/doc.go new file mode 100644 index 00000000000..694edc763d8 --- /dev/null +++ b/third_party/flatbuffers/go/doc.go @@ -0,0 +1,3 @@ +// Package flatbuffers provides facilities to read and write flatbuffers +// objects. +package flatbuffers diff --git a/third_party/flatbuffers/go/encode.go b/third_party/flatbuffers/go/encode.go new file mode 100644 index 00000000000..a2a57981255 --- /dev/null +++ b/third_party/flatbuffers/go/encode.go @@ -0,0 +1,238 @@ +package flatbuffers + +import ( + "math" +) + +type ( + // A SOffsetT stores a signed offset into arbitrary data. + SOffsetT int32 + // A UOffsetT stores an unsigned offset into vector data. + UOffsetT uint32 + // A VOffsetT stores an unsigned offset in a vtable. + VOffsetT uint16 +) + +const ( + // VtableMetadataFields is the count of metadata fields in each vtable. + VtableMetadataFields = 2 +) + +// GetByte decodes a little-endian byte from a byte slice. +func GetByte(buf []byte) byte { + return byte(GetUint8(buf)) +} + +// GetBool decodes a little-endian bool from a byte slice. +func GetBool(buf []byte) bool { + return buf[0] == 1 +} + +// GetUint8 decodes a little-endian uint8 from a byte slice. +func GetUint8(buf []byte) (n uint8) { + n = uint8(buf[0]) + return +} + +// GetUint16 decodes a little-endian uint16 from a byte slice. +func GetUint16(buf []byte) (n uint16) { + _ = buf[1] // Force one bounds check. See: golang.org/issue/14808 + n |= uint16(buf[0]) + n |= uint16(buf[1]) << 8 + return +} + +// GetUint32 decodes a little-endian uint32 from a byte slice. +func GetUint32(buf []byte) (n uint32) { + _ = buf[3] // Force one bounds check. See: golang.org/issue/14808 + n |= uint32(buf[0]) + n |= uint32(buf[1]) << 8 + n |= uint32(buf[2]) << 16 + n |= uint32(buf[3]) << 24 + return +} + +// GetUint64 decodes a little-endian uint64 from a byte slice. +func GetUint64(buf []byte) (n uint64) { + _ = buf[7] // Force one bounds check. See: golang.org/issue/14808 + n |= uint64(buf[0]) + n |= uint64(buf[1]) << 8 + n |= uint64(buf[2]) << 16 + n |= uint64(buf[3]) << 24 + n |= uint64(buf[4]) << 32 + n |= uint64(buf[5]) << 40 + n |= uint64(buf[6]) << 48 + n |= uint64(buf[7]) << 56 + return +} + +// GetInt8 decodes a little-endian int8 from a byte slice. +func GetInt8(buf []byte) (n int8) { + n = int8(buf[0]) + return +} + +// GetInt16 decodes a little-endian int16 from a byte slice. +func GetInt16(buf []byte) (n int16) { + _ = buf[1] // Force one bounds check. See: golang.org/issue/14808 + n |= int16(buf[0]) + n |= int16(buf[1]) << 8 + return +} + +// GetInt32 decodes a little-endian int32 from a byte slice. +func GetInt32(buf []byte) (n int32) { + _ = buf[3] // Force one bounds check. See: golang.org/issue/14808 + n |= int32(buf[0]) + n |= int32(buf[1]) << 8 + n |= int32(buf[2]) << 16 + n |= int32(buf[3]) << 24 + return +} + +// GetInt64 decodes a little-endian int64 from a byte slice. +func GetInt64(buf []byte) (n int64) { + _ = buf[7] // Force one bounds check. See: golang.org/issue/14808 + n |= int64(buf[0]) + n |= int64(buf[1]) << 8 + n |= int64(buf[2]) << 16 + n |= int64(buf[3]) << 24 + n |= int64(buf[4]) << 32 + n |= int64(buf[5]) << 40 + n |= int64(buf[6]) << 48 + n |= int64(buf[7]) << 56 + return +} + +// GetFloat32 decodes a little-endian float32 from a byte slice. +func GetFloat32(buf []byte) float32 { + x := GetUint32(buf) + return math.Float32frombits(x) +} + +// GetFloat64 decodes a little-endian float64 from a byte slice. +func GetFloat64(buf []byte) float64 { + x := GetUint64(buf) + return math.Float64frombits(x) +} + +// GetUOffsetT decodes a little-endian UOffsetT from a byte slice. +func GetUOffsetT(buf []byte) UOffsetT { + return UOffsetT(GetUint32(buf)) +} + +// GetSOffsetT decodes a little-endian SOffsetT from a byte slice. +func GetSOffsetT(buf []byte) SOffsetT { + return SOffsetT(GetInt32(buf)) +} + +// GetVOffsetT decodes a little-endian VOffsetT from a byte slice. +func GetVOffsetT(buf []byte) VOffsetT { + return VOffsetT(GetUint16(buf)) +} + +// WriteByte encodes a little-endian uint8 into a byte slice. +func WriteByte(buf []byte, n byte) { + WriteUint8(buf, uint8(n)) +} + +// WriteBool encodes a little-endian bool into a byte slice. +func WriteBool(buf []byte, b bool) { + buf[0] = 0 + if b { + buf[0] = 1 + } +} + +// WriteUint8 encodes a little-endian uint8 into a byte slice. +func WriteUint8(buf []byte, n uint8) { + buf[0] = byte(n) +} + +// WriteUint16 encodes a little-endian uint16 into a byte slice. +func WriteUint16(buf []byte, n uint16) { + _ = buf[1] // Force one bounds check. See: golang.org/issue/14808 + buf[0] = byte(n) + buf[1] = byte(n >> 8) +} + +// WriteUint32 encodes a little-endian uint32 into a byte slice. +func WriteUint32(buf []byte, n uint32) { + _ = buf[3] // Force one bounds check. See: golang.org/issue/14808 + buf[0] = byte(n) + buf[1] = byte(n >> 8) + buf[2] = byte(n >> 16) + buf[3] = byte(n >> 24) +} + +// WriteUint64 encodes a little-endian uint64 into a byte slice. +func WriteUint64(buf []byte, n uint64) { + _ = buf[7] // Force one bounds check. See: golang.org/issue/14808 + buf[0] = byte(n) + buf[1] = byte(n >> 8) + buf[2] = byte(n >> 16) + buf[3] = byte(n >> 24) + buf[4] = byte(n >> 32) + buf[5] = byte(n >> 40) + buf[6] = byte(n >> 48) + buf[7] = byte(n >> 56) +} + +// WriteInt8 encodes a little-endian int8 into a byte slice. +func WriteInt8(buf []byte, n int8) { + buf[0] = byte(n) +} + +// WriteInt16 encodes a little-endian int16 into a byte slice. +func WriteInt16(buf []byte, n int16) { + _ = buf[1] // Force one bounds check. See: golang.org/issue/14808 + buf[0] = byte(n) + buf[1] = byte(n >> 8) +} + +// WriteInt32 encodes a little-endian int32 into a byte slice. +func WriteInt32(buf []byte, n int32) { + _ = buf[3] // Force one bounds check. See: golang.org/issue/14808 + buf[0] = byte(n) + buf[1] = byte(n >> 8) + buf[2] = byte(n >> 16) + buf[3] = byte(n >> 24) +} + +// WriteInt64 encodes a little-endian int64 into a byte slice. +func WriteInt64(buf []byte, n int64) { + _ = buf[7] // Force one bounds check. See: golang.org/issue/14808 + buf[0] = byte(n) + buf[1] = byte(n >> 8) + buf[2] = byte(n >> 16) + buf[3] = byte(n >> 24) + buf[4] = byte(n >> 32) + buf[5] = byte(n >> 40) + buf[6] = byte(n >> 48) + buf[7] = byte(n >> 56) +} + +// WriteFloat32 encodes a little-endian float32 into a byte slice. +func WriteFloat32(buf []byte, n float32) { + WriteUint32(buf, math.Float32bits(n)) +} + +// WriteFloat64 encodes a little-endian float64 into a byte slice. +func WriteFloat64(buf []byte, n float64) { + WriteUint64(buf, math.Float64bits(n)) +} + +// WriteVOffsetT encodes a little-endian VOffsetT into a byte slice. +func WriteVOffsetT(buf []byte, n VOffsetT) { + WriteUint16(buf, uint16(n)) +} + +// WriteSOffsetT encodes a little-endian SOffsetT into a byte slice. +func WriteSOffsetT(buf []byte, n SOffsetT) { + WriteInt32(buf, int32(n)) +} + +// WriteUOffsetT encodes a little-endian UOffsetT into a byte slice. +func WriteUOffsetT(buf []byte, n UOffsetT) { + WriteUint32(buf, uint32(n)) +} diff --git a/third_party/flatbuffers/go/grpc.go b/third_party/flatbuffers/go/grpc.go new file mode 100644 index 00000000000..15f1a510d3b --- /dev/null +++ b/third_party/flatbuffers/go/grpc.go @@ -0,0 +1,38 @@ +package flatbuffers + +// Codec implements gRPC-go Codec which is used to encode and decode messages. +var Codec = "flatbuffers" + +// FlatbuffersCodec defines the interface gRPC uses to encode and decode messages. Note +// that implementations of this interface must be thread safe; a Codec's +// methods can be called from concurrent goroutines. +type FlatbuffersCodec struct{} + +// Marshal returns the wire format of v. +func (FlatbuffersCodec) Marshal(v interface{}) ([]byte, error) { + return v.(*Builder).FinishedBytes(), nil +} + +// Unmarshal parses the wire format into v. +func (FlatbuffersCodec) Unmarshal(data []byte, v interface{}) error { + v.(flatbuffersInit).Init(data, GetUOffsetT(data)) + return nil +} + +// String old gRPC Codec interface func +func (FlatbuffersCodec) String() string { + return Codec +} + +// Name returns the name of the Codec implementation. The returned string +// will be used as part of content type in transmission. The result must be +// static; the result cannot change between calls. +// +// add Name() for ForceCodec interface +func (FlatbuffersCodec) Name() string { + return Codec +} + +type flatbuffersInit interface { + Init(data []byte, i UOffsetT) +} diff --git a/third_party/flatbuffers/go/lib.go b/third_party/flatbuffers/go/lib.go new file mode 100644 index 00000000000..a4e99de1019 --- /dev/null +++ b/third_party/flatbuffers/go/lib.go @@ -0,0 +1,50 @@ +package flatbuffers + +// FlatBuffer is the interface that represents a flatbuffer. +type FlatBuffer interface { + Table() Table + Init(buf []byte, i UOffsetT) +} + +// GetRootAs is a generic helper to initialize a FlatBuffer with the provided buffer bytes and its data offset. +func GetRootAs(buf []byte, offset UOffsetT, fb FlatBuffer) { + n := GetUOffsetT(buf[offset:]) + fb.Init(buf, n+offset) +} + +// GetSizePrefixedRootAs is a generic helper to initialize a FlatBuffer with the provided size-prefixed buffer +// bytes and its data offset +func GetSizePrefixedRootAs(buf []byte, offset UOffsetT, fb FlatBuffer) { + n := GetUOffsetT(buf[offset+sizePrefixLength:]) + fb.Init(buf, n+offset+sizePrefixLength) +} + +// GetSizePrefix reads the size from a size-prefixed flatbuffer +func GetSizePrefix(buf []byte, offset UOffsetT) uint32 { + return GetUint32(buf[offset:]) +} + +// GetIndirectOffset retrives the relative offset in the provided buffer stored at `offset`. +func GetIndirectOffset(buf []byte, offset UOffsetT) UOffsetT { + return offset + GetUOffsetT(buf[offset:]) +} + +// GetBufferIdentifier returns the file identifier as string +func GetBufferIdentifier(buf []byte) string { + return string(buf[SizeUOffsetT:][:fileIdentifierLength]) +} + +// GetBufferIdentifier returns the file identifier as string for a size-prefixed buffer +func GetSizePrefixedBufferIdentifier(buf []byte) string { + return string(buf[SizeUOffsetT+sizePrefixLength:][:fileIdentifierLength]) +} + +// BufferHasIdentifier checks if the identifier in a buffer has the expected value +func BufferHasIdentifier(buf []byte, identifier string) bool { + return GetBufferIdentifier(buf) == identifier +} + +// BufferHasIdentifier checks if the identifier in a buffer has the expected value for a size-prefixed buffer +func SizePrefixedBufferHasIdentifier(buf []byte, identifier string) bool { + return GetSizePrefixedBufferIdentifier(buf) == identifier +} diff --git a/third_party/flatbuffers/go/sizes.go b/third_party/flatbuffers/go/sizes.go new file mode 100644 index 00000000000..ba221698455 --- /dev/null +++ b/third_party/flatbuffers/go/sizes.go @@ -0,0 +1,55 @@ +package flatbuffers + +import ( + "unsafe" +) + +const ( + // See http://golang.org/ref/spec#Numeric_types + + // SizeUint8 is the byte size of a uint8. + SizeUint8 = 1 + // SizeUint16 is the byte size of a uint16. + SizeUint16 = 2 + // SizeUint32 is the byte size of a uint32. + SizeUint32 = 4 + // SizeUint64 is the byte size of a uint64. + SizeUint64 = 8 + + // SizeInt8 is the byte size of a int8. + SizeInt8 = 1 + // SizeInt16 is the byte size of a int16. + SizeInt16 = 2 + // SizeInt32 is the byte size of a int32. + SizeInt32 = 4 + // SizeInt64 is the byte size of a int64. + SizeInt64 = 8 + + // SizeFloat32 is the byte size of a float32. + SizeFloat32 = 4 + // SizeFloat64 is the byte size of a float64. + SizeFloat64 = 8 + + // SizeByte is the byte size of a byte. + // The `byte` type is aliased (by Go definition) to uint8. + SizeByte = 1 + + // SizeBool is the byte size of a bool. + // The `bool` type is aliased (by flatbuffers convention) to uint8. + SizeBool = 1 + + // SizeSOffsetT is the byte size of an SOffsetT. + // The `SOffsetT` type is aliased (by flatbuffers convention) to int32. + SizeSOffsetT = 4 + // SizeUOffsetT is the byte size of an UOffsetT. + // The `UOffsetT` type is aliased (by flatbuffers convention) to uint32. + SizeUOffsetT = 4 + // SizeVOffsetT is the byte size of an VOffsetT. + // The `VOffsetT` type is aliased (by flatbuffers convention) to uint16. + SizeVOffsetT = 2 +) + +// byteSliceToString converts a []byte to string without a heap allocation. +func byteSliceToString(b []byte) string { + return *(*string)(unsafe.Pointer(&b)) +} diff --git a/third_party/flatbuffers/go/struct.go b/third_party/flatbuffers/go/struct.go new file mode 100644 index 00000000000..11258f715d4 --- /dev/null +++ b/third_party/flatbuffers/go/struct.go @@ -0,0 +1,8 @@ +package flatbuffers + +// Struct wraps a byte slice and provides read access to its data. +// +// Structs do not have a vtable. +type Struct struct { + Table +} diff --git a/third_party/flatbuffers/go/table.go b/third_party/flatbuffers/go/table.go new file mode 100644 index 00000000000..b273146fad4 --- /dev/null +++ b/third_party/flatbuffers/go/table.go @@ -0,0 +1,505 @@ +package flatbuffers + +// Table wraps a byte slice and provides read access to its data. +// +// The variable `Pos` indicates the root of the FlatBuffers object therein. +type Table struct { + Bytes []byte + Pos UOffsetT // Always < 1<<31. +} + +// Offset provides access into the Table's vtable. +// +// Fields which are deprecated are ignored by checking against the vtable's length. +func (t *Table) Offset(vtableOffset VOffsetT) VOffsetT { + vtable := UOffsetT(SOffsetT(t.Pos) - t.GetSOffsetT(t.Pos)) + if vtableOffset < t.GetVOffsetT(vtable) { + return t.GetVOffsetT(vtable + UOffsetT(vtableOffset)) + } + return 0 +} + +// Indirect retrieves the relative offset stored at `offset`. +func (t *Table) Indirect(off UOffsetT) UOffsetT { + return off + GetUOffsetT(t.Bytes[off:]) +} + +// String gets a string from data stored inside the flatbuffer. +func (t *Table) String(off UOffsetT) string { + b := t.ByteVector(off) + return byteSliceToString(b) +} + +// ByteVector gets a byte slice from data stored inside the flatbuffer. +func (t *Table) ByteVector(off UOffsetT) []byte { + off += GetUOffsetT(t.Bytes[off:]) + start := off + UOffsetT(SizeUOffsetT) + length := GetUOffsetT(t.Bytes[off:]) + return t.Bytes[start : start+length] +} + +// VectorLen retrieves the length of the vector whose offset is stored at +// "off" in this object. +func (t *Table) VectorLen(off UOffsetT) int { + off += t.Pos + off += GetUOffsetT(t.Bytes[off:]) + return int(GetUOffsetT(t.Bytes[off:])) +} + +// Vector retrieves the start of data of the vector whose offset is stored +// at "off" in this object. +func (t *Table) Vector(off UOffsetT) UOffsetT { + off += t.Pos + x := off + GetUOffsetT(t.Bytes[off:]) + // data starts after metadata containing the vector length + x += UOffsetT(SizeUOffsetT) + return x +} + +// Union initializes any Table-derived type to point to the union at the given +// offset. +func (t *Table) Union(t2 *Table, off UOffsetT) { + off += t.Pos + t2.Pos = off + t.GetUOffsetT(off) + t2.Bytes = t.Bytes +} + +// GetBool retrieves a bool at the given offset. +func (t *Table) GetBool(off UOffsetT) bool { + return GetBool(t.Bytes[off:]) +} + +// GetByte retrieves a byte at the given offset. +func (t *Table) GetByte(off UOffsetT) byte { + return GetByte(t.Bytes[off:]) +} + +// GetUint8 retrieves a uint8 at the given offset. +func (t *Table) GetUint8(off UOffsetT) uint8 { + return GetUint8(t.Bytes[off:]) +} + +// GetUint16 retrieves a uint16 at the given offset. +func (t *Table) GetUint16(off UOffsetT) uint16 { + return GetUint16(t.Bytes[off:]) +} + +// GetUint32 retrieves a uint32 at the given offset. +func (t *Table) GetUint32(off UOffsetT) uint32 { + return GetUint32(t.Bytes[off:]) +} + +// GetUint64 retrieves a uint64 at the given offset. +func (t *Table) GetUint64(off UOffsetT) uint64 { + return GetUint64(t.Bytes[off:]) +} + +// GetInt8 retrieves a int8 at the given offset. +func (t *Table) GetInt8(off UOffsetT) int8 { + return GetInt8(t.Bytes[off:]) +} + +// GetInt16 retrieves a int16 at the given offset. +func (t *Table) GetInt16(off UOffsetT) int16 { + return GetInt16(t.Bytes[off:]) +} + +// GetInt32 retrieves a int32 at the given offset. +func (t *Table) GetInt32(off UOffsetT) int32 { + return GetInt32(t.Bytes[off:]) +} + +// GetInt64 retrieves a int64 at the given offset. +func (t *Table) GetInt64(off UOffsetT) int64 { + return GetInt64(t.Bytes[off:]) +} + +// GetFloat32 retrieves a float32 at the given offset. +func (t *Table) GetFloat32(off UOffsetT) float32 { + return GetFloat32(t.Bytes[off:]) +} + +// GetFloat64 retrieves a float64 at the given offset. +func (t *Table) GetFloat64(off UOffsetT) float64 { + return GetFloat64(t.Bytes[off:]) +} + +// GetUOffsetT retrieves a UOffsetT at the given offset. +func (t *Table) GetUOffsetT(off UOffsetT) UOffsetT { + return GetUOffsetT(t.Bytes[off:]) +} + +// GetVOffsetT retrieves a VOffsetT at the given offset. +func (t *Table) GetVOffsetT(off UOffsetT) VOffsetT { + return GetVOffsetT(t.Bytes[off:]) +} + +// GetSOffsetT retrieves a SOffsetT at the given offset. +func (t *Table) GetSOffsetT(off UOffsetT) SOffsetT { + return GetSOffsetT(t.Bytes[off:]) +} + +// GetBoolSlot retrieves the bool that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetBoolSlot(slot VOffsetT, d bool) bool { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetBool(t.Pos + UOffsetT(off)) +} + +// GetByteSlot retrieves the byte that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetByteSlot(slot VOffsetT, d byte) byte { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetByte(t.Pos + UOffsetT(off)) +} + +// GetInt8Slot retrieves the int8 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetInt8Slot(slot VOffsetT, d int8) int8 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetInt8(t.Pos + UOffsetT(off)) +} + +// GetUint8Slot retrieves the uint8 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetUint8Slot(slot VOffsetT, d uint8) uint8 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetUint8(t.Pos + UOffsetT(off)) +} + +// GetInt16Slot retrieves the int16 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetInt16Slot(slot VOffsetT, d int16) int16 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetInt16(t.Pos + UOffsetT(off)) +} + +// GetUint16Slot retrieves the uint16 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetUint16Slot(slot VOffsetT, d uint16) uint16 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetUint16(t.Pos + UOffsetT(off)) +} + +// GetInt32Slot retrieves the int32 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetInt32Slot(slot VOffsetT, d int32) int32 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetInt32(t.Pos + UOffsetT(off)) +} + +// GetUint32Slot retrieves the uint32 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetUint32Slot(slot VOffsetT, d uint32) uint32 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetUint32(t.Pos + UOffsetT(off)) +} + +// GetInt64Slot retrieves the int64 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetInt64Slot(slot VOffsetT, d int64) int64 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetInt64(t.Pos + UOffsetT(off)) +} + +// GetUint64Slot retrieves the uint64 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetUint64Slot(slot VOffsetT, d uint64) uint64 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetUint64(t.Pos + UOffsetT(off)) +} + +// GetFloat32Slot retrieves the float32 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetFloat32Slot(slot VOffsetT, d float32) float32 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetFloat32(t.Pos + UOffsetT(off)) +} + +// GetFloat64Slot retrieves the float64 that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetFloat64Slot(slot VOffsetT, d float64) float64 { + off := t.Offset(slot) + if off == 0 { + return d + } + + return t.GetFloat64(t.Pos + UOffsetT(off)) +} + +// GetVOffsetTSlot retrieves the VOffsetT that the given vtable location +// points to. If the vtable value is zero, the default value `d` +// will be returned. +func (t *Table) GetVOffsetTSlot(slot VOffsetT, d VOffsetT) VOffsetT { + off := t.Offset(slot) + if off == 0 { + return d + } + return VOffsetT(off) +} + +// MutateBool updates a bool at the given offset. +func (t *Table) MutateBool(off UOffsetT, n bool) bool { + WriteBool(t.Bytes[off:], n) + return true +} + +// MutateByte updates a Byte at the given offset. +func (t *Table) MutateByte(off UOffsetT, n byte) bool { + WriteByte(t.Bytes[off:], n) + return true +} + +// MutateUint8 updates a Uint8 at the given offset. +func (t *Table) MutateUint8(off UOffsetT, n uint8) bool { + WriteUint8(t.Bytes[off:], n) + return true +} + +// MutateUint16 updates a Uint16 at the given offset. +func (t *Table) MutateUint16(off UOffsetT, n uint16) bool { + WriteUint16(t.Bytes[off:], n) + return true +} + +// MutateUint32 updates a Uint32 at the given offset. +func (t *Table) MutateUint32(off UOffsetT, n uint32) bool { + WriteUint32(t.Bytes[off:], n) + return true +} + +// MutateUint64 updates a Uint64 at the given offset. +func (t *Table) MutateUint64(off UOffsetT, n uint64) bool { + WriteUint64(t.Bytes[off:], n) + return true +} + +// MutateInt8 updates a Int8 at the given offset. +func (t *Table) MutateInt8(off UOffsetT, n int8) bool { + WriteInt8(t.Bytes[off:], n) + return true +} + +// MutateInt16 updates a Int16 at the given offset. +func (t *Table) MutateInt16(off UOffsetT, n int16) bool { + WriteInt16(t.Bytes[off:], n) + return true +} + +// MutateInt32 updates a Int32 at the given offset. +func (t *Table) MutateInt32(off UOffsetT, n int32) bool { + WriteInt32(t.Bytes[off:], n) + return true +} + +// MutateInt64 updates a Int64 at the given offset. +func (t *Table) MutateInt64(off UOffsetT, n int64) bool { + WriteInt64(t.Bytes[off:], n) + return true +} + +// MutateFloat32 updates a Float32 at the given offset. +func (t *Table) MutateFloat32(off UOffsetT, n float32) bool { + WriteFloat32(t.Bytes[off:], n) + return true +} + +// MutateFloat64 updates a Float64 at the given offset. +func (t *Table) MutateFloat64(off UOffsetT, n float64) bool { + WriteFloat64(t.Bytes[off:], n) + return true +} + +// MutateUOffsetT updates a UOffsetT at the given offset. +func (t *Table) MutateUOffsetT(off UOffsetT, n UOffsetT) bool { + WriteUOffsetT(t.Bytes[off:], n) + return true +} + +// MutateVOffsetT updates a VOffsetT at the given offset. +func (t *Table) MutateVOffsetT(off UOffsetT, n VOffsetT) bool { + WriteVOffsetT(t.Bytes[off:], n) + return true +} + +// MutateSOffsetT updates a SOffsetT at the given offset. +func (t *Table) MutateSOffsetT(off UOffsetT, n SOffsetT) bool { + WriteSOffsetT(t.Bytes[off:], n) + return true +} + +// MutateBoolSlot updates the bool at given vtable location +func (t *Table) MutateBoolSlot(slot VOffsetT, n bool) bool { + if off := t.Offset(slot); off != 0 { + t.MutateBool(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateByteSlot updates the byte at given vtable location +func (t *Table) MutateByteSlot(slot VOffsetT, n byte) bool { + if off := t.Offset(slot); off != 0 { + t.MutateByte(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateInt8Slot updates the int8 at given vtable location +func (t *Table) MutateInt8Slot(slot VOffsetT, n int8) bool { + if off := t.Offset(slot); off != 0 { + t.MutateInt8(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateUint8Slot updates the uint8 at given vtable location +func (t *Table) MutateUint8Slot(slot VOffsetT, n uint8) bool { + if off := t.Offset(slot); off != 0 { + t.MutateUint8(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateInt16Slot updates the int16 at given vtable location +func (t *Table) MutateInt16Slot(slot VOffsetT, n int16) bool { + if off := t.Offset(slot); off != 0 { + t.MutateInt16(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateUint16Slot updates the uint16 at given vtable location +func (t *Table) MutateUint16Slot(slot VOffsetT, n uint16) bool { + if off := t.Offset(slot); off != 0 { + t.MutateUint16(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateInt32Slot updates the int32 at given vtable location +func (t *Table) MutateInt32Slot(slot VOffsetT, n int32) bool { + if off := t.Offset(slot); off != 0 { + t.MutateInt32(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateUint32Slot updates the uint32 at given vtable location +func (t *Table) MutateUint32Slot(slot VOffsetT, n uint32) bool { + if off := t.Offset(slot); off != 0 { + t.MutateUint32(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateInt64Slot updates the int64 at given vtable location +func (t *Table) MutateInt64Slot(slot VOffsetT, n int64) bool { + if off := t.Offset(slot); off != 0 { + t.MutateInt64(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateUint64Slot updates the uint64 at given vtable location +func (t *Table) MutateUint64Slot(slot VOffsetT, n uint64) bool { + if off := t.Offset(slot); off != 0 { + t.MutateUint64(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateFloat32Slot updates the float32 at given vtable location +func (t *Table) MutateFloat32Slot(slot VOffsetT, n float32) bool { + if off := t.Offset(slot); off != 0 { + t.MutateFloat32(t.Pos+UOffsetT(off), n) + return true + } + + return false +} + +// MutateFloat64Slot updates the float64 at given vtable location +func (t *Table) MutateFloat64Slot(slot VOffsetT, n float64) bool { + if off := t.Offset(slot); off != 0 { + t.MutateFloat64(t.Pos+UOffsetT(off), n) + return true + } + + return false +} diff --git a/third_party/flatbuffers/goldens/README.md b/third_party/flatbuffers/goldens/README.md new file mode 100644 index 00000000000..00bbdc01186 --- /dev/null +++ b/third_party/flatbuffers/goldens/README.md @@ -0,0 +1,26 @@ +# Golden Generated Files + +This directory is a repository for the generated files of `flatc`. + +We check in the generated code so we can see, during a PR review, how the +changes affect the generated output. Its also useful as a reference to point too +as how things work across various languages. + +These files are **NOT** intended to be depended on by any code, such as tests or +or compiled examples. + +## Languages Specifics + +Each language should keep their generated code in their respective directories. +However, the parent schemas can, and should, be shared so we have a consistent +view of things across languages. These are kept in the `schema/` directory. + +Some languages may not support every generation feature, so each language is +required to specify the `flatc` arguments individually. + +* Try to avoid includes and nested directories, preferring it as flat as +possible. + +## Updating + +Just run the `generate_goldens.py` script and it should generate them all. diff --git a/third_party/flatbuffers/goldens/cpp/basic_generated.h b/third_party/flatbuffers/goldens/cpp/basic_generated.h new file mode 100644 index 00000000000..f4600d71124 --- /dev/null +++ b/third_party/flatbuffers/goldens/cpp/basic_generated.h @@ -0,0 +1,163 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_BASIC_FLATBUFFERS_GOLDENS_H_ +#define FLATBUFFERS_GENERATED_BASIC_FLATBUFFERS_GOLDENS_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace flatbuffers { +namespace goldens { + +struct Galaxy; +struct GalaxyBuilder; + +struct Universe; +struct UniverseBuilder; + +struct Galaxy FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef GalaxyBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_NUM_STARS = 4 + }; + int64_t num_stars() const { + return GetField(VT_NUM_STARS, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_NUM_STARS, 8) && + verifier.EndTable(); + } +}; + +struct GalaxyBuilder { + typedef Galaxy Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_num_stars(int64_t num_stars) { + fbb_.AddElement(Galaxy::VT_NUM_STARS, num_stars, 0); + } + explicit GalaxyBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateGalaxy( + ::flatbuffers::FlatBufferBuilder &_fbb, + int64_t num_stars = 0) { + GalaxyBuilder builder_(_fbb); + builder_.add_num_stars(num_stars); + return builder_.Finish(); +} + +struct Universe FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef UniverseBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_AGE = 4, + VT_GALAXIES = 6 + }; + double age() const { + return GetField(VT_AGE, 0.0); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *galaxies() const { + return GetPointer> *>(VT_GALAXIES); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_AGE, 8) && + VerifyOffset(verifier, VT_GALAXIES) && + verifier.VerifyVector(galaxies()) && + verifier.VerifyVectorOfTables(galaxies()) && + verifier.EndTable(); + } +}; + +struct UniverseBuilder { + typedef Universe Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_age(double age) { + fbb_.AddElement(Universe::VT_AGE, age, 0.0); + } + void add_galaxies(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> galaxies) { + fbb_.AddOffset(Universe::VT_GALAXIES, galaxies); + } + explicit UniverseBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateUniverse( + ::flatbuffers::FlatBufferBuilder &_fbb, + double age = 0.0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> galaxies = 0) { + UniverseBuilder builder_(_fbb); + builder_.add_age(age); + builder_.add_galaxies(galaxies); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateUniverseDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + double age = 0.0, + const std::vector<::flatbuffers::Offset> *galaxies = nullptr) { + auto galaxies__ = galaxies ? _fbb.CreateVector<::flatbuffers::Offset>(*galaxies) : 0; + return flatbuffers::goldens::CreateUniverse( + _fbb, + age, + galaxies__); +} + +inline const flatbuffers::goldens::Universe *GetUniverse(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const flatbuffers::goldens::Universe *GetSizePrefixedUniverse(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline bool VerifyUniverseBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedUniverseBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishUniverseBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedUniverseBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +} // namespace goldens +} // namespace flatbuffers + +#endif // FLATBUFFERS_GENERATED_BASIC_FLATBUFFERS_GOLDENS_H_ diff --git a/third_party/flatbuffers/goldens/cpp/generate.py b/third_party/flatbuffers/goldens/cpp/generate.py new file mode 100644 index 00000000000..cdc7e8c37b5 --- /dev/null +++ b/third_party/flatbuffers/goldens/cpp/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with C++ specifics + flatc_golden(options=["--cpp"] + options, schema=schema, prefix="cpp") + + +def GenerateCpp(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/csharp/flatbuffers/goldens/Galaxy.cs b/third_party/flatbuffers/goldens/csharp/flatbuffers/goldens/Galaxy.cs new file mode 100644 index 00000000000..f947a1a7af2 --- /dev/null +++ b/third_party/flatbuffers/goldens/csharp/flatbuffers/goldens/Galaxy.cs @@ -0,0 +1,50 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace flatbuffers.goldens +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Galaxy : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Galaxy GetRootAsGalaxy(ByteBuffer _bb) { return GetRootAsGalaxy(_bb, new Galaxy()); } + public static Galaxy GetRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Galaxy __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public long NumStars { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } } + + public static Offset CreateGalaxy(FlatBufferBuilder builder, + long num_stars = 0) { + builder.StartTable(1); + Galaxy.AddNumStars(builder, num_stars); + return Galaxy.EndGalaxy(builder); + } + + public static void StartGalaxy(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddNumStars(FlatBufferBuilder builder, long numStars) { builder.AddLong(0, numStars, 0); } + public static Offset EndGalaxy(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } +} + + +static public class GalaxyVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*NumStars*/, 8 /*long*/, 8, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/goldens/csharp/flatbuffers/goldens/Universe.cs b/third_party/flatbuffers/goldens/csharp/flatbuffers/goldens/Universe.cs new file mode 100644 index 00000000000..7e8b80291c1 --- /dev/null +++ b/third_party/flatbuffers/goldens/csharp/flatbuffers/goldens/Universe.cs @@ -0,0 +1,64 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace flatbuffers.goldens +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Universe : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Universe GetRootAsUniverse(ByteBuffer _bb) { return GetRootAsUniverse(_bb, new Universe()); } + public static Universe GetRootAsUniverse(ByteBuffer _bb, Universe obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool VerifyUniverse(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("", false, UniverseVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Universe __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public double Age { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)0.0; } } + public flatbuffers.goldens.Galaxy? Galaxies(int j) { int o = __p.__offset(6); return o != 0 ? (flatbuffers.goldens.Galaxy?)(new flatbuffers.goldens.Galaxy()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; } + public int GalaxiesLength { get { int o = __p.__offset(6); return o != 0 ? __p.__vector_len(o) : 0; } } + + public static Offset CreateUniverse(FlatBufferBuilder builder, + double age = 0.0, + VectorOffset galaxiesOffset = default(VectorOffset)) { + builder.StartTable(2); + Universe.AddAge(builder, age); + Universe.AddGalaxies(builder, galaxiesOffset); + return Universe.EndUniverse(builder); + } + + public static void StartUniverse(FlatBufferBuilder builder) { builder.StartTable(2); } + public static void AddAge(FlatBufferBuilder builder, double age) { builder.AddDouble(0, age, 0.0); } + public static void AddGalaxies(FlatBufferBuilder builder, VectorOffset galaxiesOffset) { builder.AddOffset(1, galaxiesOffset.Value, 0); } + public static VectorOffset CreateGalaxiesVector(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateGalaxiesVectorBlock(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateGalaxiesVectorBlock(FlatBufferBuilder builder, ArraySegment> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateGalaxiesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add>(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartGalaxiesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static Offset EndUniverse(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishUniverseBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value); } + public static void FinishSizePrefixedUniverseBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value); } +} + + +static public class UniverseVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Age*/, 8 /*double*/, 8, false) + && verifier.VerifyVectorOfTables(tablePos, 6 /*Galaxies*/, flatbuffers.goldens.GalaxyVerify.Verify, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/goldens/csharp/generate.py b/third_party/flatbuffers/goldens/csharp/generate.py new file mode 100644 index 00000000000..86a3a80f5ad --- /dev/null +++ b/third_party/flatbuffers/goldens/csharp/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with C# specifics + flatc_golden(options=["--csharp"] + options, schema=schema, prefix="csharp") + + +def GenerateCSharp(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/dart/basic_flatbuffers.goldens_generated.dart b/third_party/flatbuffers/goldens/dart/basic_flatbuffers.goldens_generated.dart new file mode 100644 index 00000000000..0f6c6087ca0 --- /dev/null +++ b/third_party/flatbuffers/goldens/dart/basic_flatbuffers.goldens_generated.dart @@ -0,0 +1,162 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library flatbuffers.goldens; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +class Galaxy { + Galaxy._(this._bc, this._bcOffset); + factory Galaxy(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _GalaxyReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get numStars => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 4, 0); + + @override + String toString() { + return 'Galaxy{numStars: ${numStars}}'; + } +} + +class _GalaxyReader extends fb.TableReader { + const _GalaxyReader(); + + @override + Galaxy createObject(fb.BufferContext bc, int offset) => + Galaxy._(bc, offset); +} + +class GalaxyBuilder { + GalaxyBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addNumStars(int? numStars) { + fbBuilder.addInt64(0, numStars); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class GalaxyObjectBuilder extends fb.ObjectBuilder { + final int? _numStars; + + GalaxyObjectBuilder({ + int? numStars, + }) + : _numStars = numStars; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addInt64(0, _numStars); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Universe { + Universe._(this._bc, this._bcOffset); + factory Universe(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _UniverseReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + double get age => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 4, 0.0); + List? get galaxies => const fb.ListReader(Galaxy.reader).vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'Universe{age: ${age}, galaxies: ${galaxies}}'; + } +} + +class _UniverseReader extends fb.TableReader { + const _UniverseReader(); + + @override + Universe createObject(fb.BufferContext bc, int offset) => + Universe._(bc, offset); +} + +class UniverseBuilder { + UniverseBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addAge(double? age) { + fbBuilder.addFloat64(0, age); + return fbBuilder.offset; + } + int addGalaxiesOffset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class UniverseObjectBuilder extends fb.ObjectBuilder { + final double? _age; + final List? _galaxies; + + UniverseObjectBuilder({ + double? age, + List? galaxies, + }) + : _age = age, + _galaxies = galaxies; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? galaxiesOffset = _galaxies == null ? null + : fbBuilder.writeList(_galaxies!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + fbBuilder.startTable(2); + fbBuilder.addFloat64(0, _age); + fbBuilder.addOffset(1, galaxiesOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/goldens/dart/generate.py b/third_party/flatbuffers/goldens/dart/generate.py new file mode 100644 index 00000000000..a92070c2653 --- /dev/null +++ b/third_party/flatbuffers/goldens/dart/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Dart specifics + flatc_golden(options=["--dart"] + options, schema=schema, prefix="dart") + + +def GenerateDart(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/generate_goldens.py b/third_party/flatbuffers/goldens/generate_goldens.py new file mode 100755 index 00000000000..d521b812dc6 --- /dev/null +++ b/third_party/flatbuffers/goldens/generate_goldens.py @@ -0,0 +1,32 @@ +#!/usr/bin/env python3 + +from cpp.generate import GenerateCpp +from csharp.generate import GenerateCSharp +from dart.generate import GenerateDart +from go.generate import GenerateGo +from java.generate import GenerateJava +from kotlin.generate import GenerateKotlin +from lobster.generate import GenerateLobster +from lua.generate import GenerateLua +from nim.generate import GenerateNim +from php.generate import GeneratePhp +from py.generate import GeneratePython +from rust.generate import GenerateRust +from swift.generate import GenerateSwift +from ts.generate import GenerateTs + +# Run each language generation logic +GenerateCpp() +GenerateCSharp() +GenerateDart() +GenerateGo() +GenerateJava() +GenerateKotlin() +GenerateLobster() +GenerateLua() +GenerateNim() +GeneratePhp() +GeneratePython() +GenerateRust() +GenerateSwift() +GenerateTs() diff --git a/third_party/flatbuffers/goldens/go/flatbuffers/goldens/Galaxy.go b/third_party/flatbuffers/goldens/go/flatbuffers/goldens/Galaxy.go new file mode 100644 index 00000000000..a0cd0ae719f --- /dev/null +++ b/third_party/flatbuffers/goldens/go/flatbuffers/goldens/Galaxy.go @@ -0,0 +1,64 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package goldens + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type Galaxy struct { + _tab flatbuffers.Table +} + +func GetRootAsGalaxy(buf []byte, offset flatbuffers.UOffsetT) *Galaxy { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Galaxy{} + x.Init(buf, n+offset) + return x +} + +func FinishGalaxyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsGalaxy(buf []byte, offset flatbuffers.UOffsetT) *Galaxy { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Galaxy{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedGalaxyBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *Galaxy) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Galaxy) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Galaxy) NumStars() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Galaxy) MutateNumStars(n int64) bool { + return rcv._tab.MutateInt64Slot(4, n) +} + +func GalaxyStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func GalaxyAddNumStars(builder *flatbuffers.Builder, numStars int64) { + builder.PrependInt64Slot(0, numStars, 0) +} +func GalaxyEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/goldens/go/flatbuffers/goldens/Universe.go b/third_party/flatbuffers/goldens/go/flatbuffers/goldens/Universe.go new file mode 100644 index 00000000000..d8fd83327af --- /dev/null +++ b/third_party/flatbuffers/goldens/go/flatbuffers/goldens/Universe.go @@ -0,0 +1,90 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package goldens + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type Universe struct { + _tab flatbuffers.Table +} + +func GetRootAsUniverse(buf []byte, offset flatbuffers.UOffsetT) *Universe { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Universe{} + x.Init(buf, n+offset) + return x +} + +func FinishUniverseBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsUniverse(buf []byte, offset flatbuffers.UOffsetT) *Universe { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Universe{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedUniverseBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *Universe) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Universe) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Universe) Age() float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetFloat64(o + rcv._tab.Pos) + } + return 0.0 +} + +func (rcv *Universe) MutateAge(n float64) bool { + return rcv._tab.MutateFloat64Slot(4, n) +} + +func (rcv *Universe) Galaxies(obj *Galaxy, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + x = rcv._tab.Indirect(x) + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Universe) GalaxiesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func UniverseStart(builder *flatbuffers.Builder) { + builder.StartObject(2) +} +func UniverseAddAge(builder *flatbuffers.Builder, age float64) { + builder.PrependFloat64Slot(0, age, 0.0) +} +func UniverseAddGalaxies(builder *flatbuffers.Builder, galaxies flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(galaxies), 0) +} +func UniverseStartGalaxiesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func UniverseEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/goldens/go/generate.py b/third_party/flatbuffers/goldens/go/generate.py new file mode 100644 index 00000000000..358c42c30bb --- /dev/null +++ b/third_party/flatbuffers/goldens/go/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Go specifics + flatc_golden(options=["--go"] + options, schema=schema, prefix="go") + + +def GenerateGo(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/golden_utils.py b/third_party/flatbuffers/goldens/golden_utils.py new file mode 100644 index 00000000000..d2aab1330b6 --- /dev/null +++ b/third_party/flatbuffers/goldens/golden_utils.py @@ -0,0 +1,30 @@ +import sys +from pathlib import Path + +# Get the path where this script is located so we can invoke the script from +# any directory and have the paths work correctly. +script_path = Path(__file__).parent.resolve() + +# Get the root path as an absolute path, so all derived paths are absolute. +root_path = script_path.parent.absolute() + +# Get the location of the schema +schema_path = Path(script_path, "schema") + +# Too add the util package in /scripts/util.py +sys.path.append(str(root_path.absolute())) + +from scripts.util import flatc + + +def flatc_golden(options, schema, prefix): + # wrap the generic flatc call with specifis for these goldens. + flatc( + options=options, + # where the files are generated, typically the language (e.g. "cpp"). + prefix=prefix, + # The schema are relative to the schema directory. + schema=str(Path(schema_path, schema)), + # Run flatc from this location. + cwd=script_path, + ) diff --git a/third_party/flatbuffers/goldens/java/flatbuffers/goldens/Galaxy.java b/third_party/flatbuffers/goldens/java/flatbuffers/goldens/Galaxy.java new file mode 100644 index 00000000000..ef90810ea2f --- /dev/null +++ b/third_party/flatbuffers/goldens/java/flatbuffers/goldens/Galaxy.java @@ -0,0 +1,53 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package flatbuffers.goldens; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Galaxy extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Galaxy getRootAsGalaxy(ByteBuffer _bb) { return getRootAsGalaxy(_bb, new Galaxy()); } + public static Galaxy getRootAsGalaxy(ByteBuffer _bb, Galaxy obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Galaxy __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public long numStars() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + + public static int createGalaxy(FlatBufferBuilder builder, + long numStars) { + builder.startTable(1); + Galaxy.addNumStars(builder, numStars); + return Galaxy.endGalaxy(builder); + } + + public static void startGalaxy(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addNumStars(FlatBufferBuilder builder, long numStars) { builder.addLong(0, numStars, 0L); } + public static int endGalaxy(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Galaxy get(int j) { return get(new Galaxy(), j); } + public Galaxy get(Galaxy obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } +} + diff --git a/third_party/flatbuffers/goldens/java/flatbuffers/goldens/Universe.java b/third_party/flatbuffers/goldens/java/flatbuffers/goldens/Universe.java new file mode 100644 index 00000000000..e8b46098860 --- /dev/null +++ b/third_party/flatbuffers/goldens/java/flatbuffers/goldens/Universe.java @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package flatbuffers.goldens; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Universe extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Universe getRootAsUniverse(ByteBuffer _bb) { return getRootAsUniverse(_bb, new Universe()); } + public static Universe getRootAsUniverse(ByteBuffer _bb, Universe obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Universe __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public double age() { int o = __offset(4); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; } + public flatbuffers.goldens.Galaxy galaxies(int j) { return galaxies(new flatbuffers.goldens.Galaxy(), j); } + public flatbuffers.goldens.Galaxy galaxies(flatbuffers.goldens.Galaxy obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int galaxiesLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } + public flatbuffers.goldens.Galaxy.Vector galaxiesVector() { return galaxiesVector(new flatbuffers.goldens.Galaxy.Vector()); } + public flatbuffers.goldens.Galaxy.Vector galaxiesVector(flatbuffers.goldens.Galaxy.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createUniverse(FlatBufferBuilder builder, + double age, + int galaxiesOffset) { + builder.startTable(2); + Universe.addAge(builder, age); + Universe.addGalaxies(builder, galaxiesOffset); + return Universe.endUniverse(builder); + } + + public static void startUniverse(FlatBufferBuilder builder) { builder.startTable(2); } + public static void addAge(FlatBufferBuilder builder, double age) { builder.addDouble(0, age, 0.0); } + public static void addGalaxies(FlatBufferBuilder builder, int galaxiesOffset) { builder.addOffset(1, galaxiesOffset, 0); } + public static int createGalaxiesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startGalaxiesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endUniverse(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + public static void finishUniverseBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); } + public static void finishSizePrefixedUniverseBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Universe get(int j) { return get(new Universe(), j); } + public Universe get(Universe obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } +} + diff --git a/third_party/flatbuffers/goldens/java/generate.py b/third_party/flatbuffers/goldens/java/generate.py new file mode 100644 index 00000000000..cc1a8b29457 --- /dev/null +++ b/third_party/flatbuffers/goldens/java/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Java specifics + flatc_golden(options=["--java"] + options, schema=schema, prefix="java") + + +def GenerateJava(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/kotlin/flatbuffers/goldens/Galaxy.kt b/third_party/flatbuffers/goldens/kotlin/flatbuffers/goldens/Galaxy.kt new file mode 100644 index 00000000000..4307151cd88 --- /dev/null +++ b/third_party/flatbuffers/goldens/kotlin/flatbuffers/goldens/Galaxy.kt @@ -0,0 +1,55 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package flatbuffers.goldens + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Galaxy : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Galaxy { + __init(_i, _bb) + return this + } + val numStars : Long + get() { + val o = __offset(4) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsGalaxy(_bb: ByteBuffer): Galaxy = getRootAsGalaxy(_bb, Galaxy()) + fun getRootAsGalaxy(_bb: ByteBuffer, obj: Galaxy): Galaxy { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createGalaxy(builder: FlatBufferBuilder, numStars: Long) : Int { + builder.startTable(1) + addNumStars(builder, numStars) + return endGalaxy(builder) + } + fun startGalaxy(builder: FlatBufferBuilder) = builder.startTable(1) + fun addNumStars(builder: FlatBufferBuilder, numStars: Long) = builder.addLong(0, numStars, 0L) + fun endGalaxy(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/goldens/kotlin/flatbuffers/goldens/Universe.kt b/third_party/flatbuffers/goldens/kotlin/flatbuffers/goldens/Universe.kt new file mode 100644 index 00000000000..b413b0e440c --- /dev/null +++ b/third_party/flatbuffers/goldens/kotlin/flatbuffers/goldens/Universe.kt @@ -0,0 +1,80 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package flatbuffers.goldens + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Universe : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Universe { + __init(_i, _bb) + return this + } + val age : Double + get() { + val o = __offset(4) + return if(o != 0) bb.getDouble(o + bb_pos) else 0.0 + } + fun galaxies(j: Int) : flatbuffers.goldens.Galaxy? = galaxies(flatbuffers.goldens.Galaxy(), j) + fun galaxies(obj: flatbuffers.goldens.Galaxy, j: Int) : flatbuffers.goldens.Galaxy? { + val o = __offset(6) + return if (o != 0) { + obj.__assign(__indirect(__vector(o) + j * 4), bb) + } else { + null + } + } + val galaxiesLength : Int + get() { + val o = __offset(6); return if (o != 0) __vector_len(o) else 0 + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsUniverse(_bb: ByteBuffer): Universe = getRootAsUniverse(_bb, Universe()) + fun getRootAsUniverse(_bb: ByteBuffer, obj: Universe): Universe { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createUniverse(builder: FlatBufferBuilder, age: Double, galaxiesOffset: Int) : Int { + builder.startTable(2) + addAge(builder, age) + addGalaxies(builder, galaxiesOffset) + return endUniverse(builder) + } + fun startUniverse(builder: FlatBufferBuilder) = builder.startTable(2) + fun addAge(builder: FlatBufferBuilder, age: Double) = builder.addDouble(0, age, 0.0) + fun addGalaxies(builder: FlatBufferBuilder, galaxies: Int) = builder.addOffset(1, galaxies, 0) + fun createGalaxiesVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startGalaxiesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun endUniverse(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun finishUniverseBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset) + fun finishSizePrefixedUniverseBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset) + } +} diff --git a/third_party/flatbuffers/goldens/kotlin/generate.py b/third_party/flatbuffers/goldens/kotlin/generate.py new file mode 100644 index 00000000000..ac8b551743d --- /dev/null +++ b/third_party/flatbuffers/goldens/kotlin/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Kotlin specifics + flatc_golden(options=["--kotlin"] + options, schema=schema, prefix="kotlin") + + +def GenerateKotlin(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/lobster/basic_generated.lobster b/third_party/flatbuffers/goldens/lobster/basic_generated.lobster new file mode 100644 index 00000000000..ade4b824d49 --- /dev/null +++ b/third_party/flatbuffers/goldens/lobster/basic_generated.lobster @@ -0,0 +1,57 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import flatbuffers + +namespace flatbuffers.goldens + +class Galaxy + +class Universe + +class Galaxy : flatbuffers.handle + def num_stars() -> int: + return flatbuffers.field_int64(buf_, pos_, 4, 0) + +def GetRootAsGalaxy(buf:string): return Galaxy { buf, flatbuffers.indirect(buf, 0) } + +struct GalaxyBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(1) + return this + def add_num_stars(num_stars:int): + b_.PrependInt64Slot(0, num_stars, 0) + return this + def end(): + return b_.EndObject() + +class Universe : flatbuffers.handle + def age() -> float: + return flatbuffers.field_float64(buf_, pos_, 4, 0.0) + def galaxies(i:int) -> flatbuffers.goldens.Galaxy: + return flatbuffers.goldens.Galaxy { buf_, flatbuffers.indirect(buf_, flatbuffers.field_vector(buf_, pos_, 6) + i * 4) } + def galaxies_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 6) + +def GetRootAsUniverse(buf:string): return Universe { buf, flatbuffers.indirect(buf, 0) } + +struct UniverseBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(2) + return this + def add_age(age:float): + b_.PrependFloat64Slot(0, age, 0.0) + return this + def add_galaxies(galaxies:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(1, galaxies) + return this + def end(): + return b_.EndObject() + +def UniverseStartGalaxiesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def UniverseCreateGalaxiesVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + diff --git a/third_party/flatbuffers/goldens/lobster/generate.py b/third_party/flatbuffers/goldens/lobster/generate.py new file mode 100644 index 00000000000..cb75fda4b7a --- /dev/null +++ b/third_party/flatbuffers/goldens/lobster/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Lobster specifics + flatc_golden(options=["--lobster"] + options, schema=schema, prefix="lobster") + + +def GenerateLobster(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/lua/Galaxy.lua b/third_party/flatbuffers/goldens/lua/Galaxy.lua new file mode 100644 index 00000000000..fd346081921 --- /dev/null +++ b/third_party/flatbuffers/goldens/lua/Galaxy.lua @@ -0,0 +1,48 @@ +--[[ Galaxy + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 23.5.26 + + Declared by : //basic.fbs + Rooting type : Universe (//basic.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Galaxy = {} +local mt = {} + +function Galaxy.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:NumStars() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int64, self.view.pos + o) + end + return 0 +end + +function Galaxy.Start(builder) + builder:StartObject(1) +end + +function Galaxy.AddNumStars(builder, numStars) + builder:PrependInt64Slot(0, numStars, 0) +end + +function Galaxy.End(builder) + return builder:EndObject() +end + +return Galaxy \ No newline at end of file diff --git a/third_party/flatbuffers/goldens/lua/Universe.lua b/third_party/flatbuffers/goldens/lua/Universe.lua new file mode 100644 index 00000000000..74a7761e0fd --- /dev/null +++ b/third_party/flatbuffers/goldens/lua/Universe.lua @@ -0,0 +1,88 @@ +--[[ Universe + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 23.5.26 + + Declared by : //basic.fbs + Rooting type : Universe (//basic.fbs) + +--]] + +local __Galaxy = require('Galaxy') +local flatbuffers = require('flatbuffers') + +local Universe = {} +local mt = {} + +function Universe.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function Universe.GetRootAsUniverse(buf, offset) + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + + local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) + local o = Universe.New() + o:Init(buf, n + offset) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:Age() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float64, self.view.pos + o) + end + return 0.0 +end + +function mt:Galaxies(j) + local o = self.view:Offset(6) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + x = self.view:Indirect(x) + local obj = __Galaxy.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:GalaxiesLength() + local o = self.view:Offset(6) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function Universe.Start(builder) + builder:StartObject(2) +end + +function Universe.AddAge(builder, age) + builder:PrependFloat64Slot(0, age, 0.0) +end + +function Universe.AddGalaxies(builder, galaxies) + builder:PrependUOffsetTRelativeSlot(1, galaxies, 0) +end + +function Universe.StartGalaxiesVector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Universe.End(builder) + return builder:EndObject() +end + +return Universe \ No newline at end of file diff --git a/third_party/flatbuffers/goldens/lua/generate.py b/third_party/flatbuffers/goldens/lua/generate.py new file mode 100644 index 00000000000..d099118a803 --- /dev/null +++ b/third_party/flatbuffers/goldens/lua/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Lua specifics + flatc_golden(options=["--lua"] + options, schema=schema, prefix="lua") + + +def GenerateLua(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/nim/Galaxy.nim b/third_party/flatbuffers/goldens/nim/Galaxy.nim new file mode 100644 index 00000000000..76b1e4a2e03 --- /dev/null +++ b/third_party/flatbuffers/goldens/nim/Galaxy.nim @@ -0,0 +1,26 @@ +#[ Galaxy + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 23.5.26 + + Declared by : //basic.fbs + Rooting type : Universe (//basic.fbs) +]# + +import flatbuffers + +type Galaxy* = object of FlatObj +func numStars*(self: Galaxy): int64 = + let o = self.tab.Offset(4) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 0 +func `numStars=`*(self: var Galaxy, n: int64): bool = + return self.tab.MutateSlot(4, n) +proc GalaxyStart*(builder: var Builder) = + builder.StartObject(1) +proc GalaxyAddnumStars*(builder: var Builder, numStars: int64) = + builder.PrependSlot(0, numStars, default(int64)) +proc GalaxyEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/goldens/nim/Universe.nim b/third_party/flatbuffers/goldens/nim/Universe.nim new file mode 100644 index 00000000000..a3e8a9114f8 --- /dev/null +++ b/third_party/flatbuffers/goldens/nim/Universe.nim @@ -0,0 +1,46 @@ +#[ Universe + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 23.5.26 + + Declared by : //basic.fbs + Rooting type : Universe (//basic.fbs) +]# + +import Galaxy as Galaxy +import flatbuffers +import std/options + +type Universe* = object of FlatObj +func age*(self: Universe): float64 = + let o = self.tab.Offset(4) + if o != 0: + return Get[float64](self.tab, self.tab.Pos + o) + return 0.0 +func `age=`*(self: var Universe, n: float64): bool = + return self.tab.MutateSlot(4, n) +func galaxiesLength*(self: Universe): int = + let o = self.tab.Offset(6) + if o != 0: + return self.tab.VectorLen(o) +func galaxies*(self: Universe, j: int): Galaxy.Galaxy = + let o = self.tab.Offset(6) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return Galaxy.Galaxy(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func galaxies*(self: Universe): seq[Galaxy.Galaxy] = + let len = self.galaxiesLength + for i in countup(0, len - 1): + result.add(self.galaxies(i)) +proc UniverseStart*(builder: var Builder) = + builder.StartObject(2) +proc UniverseAddage*(builder: var Builder, age: float64) = + builder.PrependSlot(0, age, default(float64)) +proc UniverseAddgalaxies*(builder: var Builder, galaxies: uoffset) = + builder.PrependSlot(1, galaxies, default(uoffset)) +proc UniverseStartgalaxiesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc UniverseEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/goldens/nim/generate.py b/third_party/flatbuffers/goldens/nim/generate.py new file mode 100644 index 00000000000..16c0d3bcdb4 --- /dev/null +++ b/third_party/flatbuffers/goldens/nim/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Nim specifics + flatc_golden(options=["--nim"] + options, schema=schema, prefix="nim") + + +def GenerateNim(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/php/flatbuffers/goldens/Galaxy.php b/third_party/flatbuffers/goldens/php/flatbuffers/goldens/Galaxy.php new file mode 100644 index 00000000000..d29a09a7665 --- /dev/null +++ b/third_party/flatbuffers/goldens/php/flatbuffers/goldens/Galaxy.php @@ -0,0 +1,84 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Galaxy + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return long + */ + public function getNumStars() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getLong($o + $this->bb_pos) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startGalaxy(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return Galaxy + */ + public static function createGalaxy(FlatBufferBuilder $builder, $num_stars) + { + $builder->startObject(1); + self::addNumStars($builder, $num_stars); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param long + * @return void + */ + public static function addNumStars(FlatBufferBuilder $builder, $numStars) + { + $builder->addLongX(0, $numStars, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endGalaxy(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/goldens/php/flatbuffers/goldens/Universe.php b/third_party/flatbuffers/goldens/php/flatbuffers/goldens/Universe.php new file mode 100644 index 00000000000..9d705614e91 --- /dev/null +++ b/third_party/flatbuffers/goldens/php/flatbuffers/goldens/Universe.php @@ -0,0 +1,143 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Universe + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return double + */ + public function getAge() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getDouble($o + $this->bb_pos) : 0.0; + } + + /** + * @returnVectorOffset + */ + public function getGalaxies($j) + { + $o = $this->__offset(6); + $obj = new Galaxy(); + return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null; + } + + /** + * @return int + */ + public function getGalaxiesLength() + { + $o = $this->__offset(6); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startUniverse(FlatBufferBuilder $builder) + { + $builder->StartObject(2); + } + + /** + * @param FlatBufferBuilder $builder + * @return Universe + */ + public static function createUniverse(FlatBufferBuilder $builder, $age, $galaxies) + { + $builder->startObject(2); + self::addAge($builder, $age); + self::addGalaxies($builder, $galaxies); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param double + * @return void + */ + public static function addAge(FlatBufferBuilder $builder, $age) + { + $builder->addDoubleX(0, $age, 0.0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addGalaxies(FlatBufferBuilder $builder, $galaxies) + { + $builder->addOffsetX(1, $galaxies, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createGalaxiesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startGalaxiesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endUniverse(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } + + public static function finishUniverseBuffer(FlatBufferBuilder $builder, $offset) + { + $builder->finish($offset); + } +} diff --git a/third_party/flatbuffers/goldens/php/generate.py b/third_party/flatbuffers/goldens/php/generate.py new file mode 100644 index 00000000000..6e9144c675d --- /dev/null +++ b/third_party/flatbuffers/goldens/php/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with PHP specifics + flatc_golden(options=["--php"] + options, schema=schema, prefix="php") + + +def GeneratePhp(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/py/__init__.py b/third_party/flatbuffers/goldens/py/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/goldens/py/flatbuffers/__init__.py b/third_party/flatbuffers/goldens/py/flatbuffers/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/goldens/py/flatbuffers/goldens/Galaxy.py b/third_party/flatbuffers/goldens/py/flatbuffers/goldens/Galaxy.py new file mode 100644 index 00000000000..5f3fb0f6eb9 --- /dev/null +++ b/third_party/flatbuffers/goldens/py/flatbuffers/goldens/Galaxy.py @@ -0,0 +1,50 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: goldens + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Galaxy(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Galaxy() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsGalaxy(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # Galaxy + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Galaxy + def NumStars(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + +def GalaxyStart(builder): + builder.StartObject(1) + +def Start(builder): + GalaxyStart(builder) + +def GalaxyAddNumStars(builder, numStars): + builder.PrependInt64Slot(0, numStars, 0) + +def AddNumStars(builder, numStars): + GalaxyAddNumStars(builder, numStars) + +def GalaxyEnd(builder): + return builder.EndObject() + +def End(builder): + return GalaxyEnd(builder) diff --git a/third_party/flatbuffers/goldens/py/flatbuffers/goldens/Universe.py b/third_party/flatbuffers/goldens/py/flatbuffers/goldens/Universe.py new file mode 100644 index 00000000000..feec6d96c06 --- /dev/null +++ b/third_party/flatbuffers/goldens/py/flatbuffers/goldens/Universe.py @@ -0,0 +1,87 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: goldens + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Universe(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Universe() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsUniverse(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # Universe + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Universe + def Age(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # Universe + def Galaxies(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from flatbuffers.goldens.Galaxy import Galaxy + obj = Galaxy() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Universe + def GalaxiesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Universe + def GalaxiesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + return o == 0 + +def UniverseStart(builder): + builder.StartObject(2) + +def Start(builder): + UniverseStart(builder) + +def UniverseAddAge(builder, age): + builder.PrependFloat64Slot(0, age, 0.0) + +def AddAge(builder, age): + UniverseAddAge(builder, age) + +def UniverseAddGalaxies(builder, galaxies): + builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(galaxies), 0) + +def AddGalaxies(builder, galaxies): + UniverseAddGalaxies(builder, galaxies) + +def UniverseStartGalaxiesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartGalaxiesVector(builder, numElems): + return UniverseStartGalaxiesVector(builder, numElems) + +def UniverseEnd(builder): + return builder.EndObject() + +def End(builder): + return UniverseEnd(builder) diff --git a/third_party/flatbuffers/goldens/py/flatbuffers/goldens/__init__.py b/third_party/flatbuffers/goldens/py/flatbuffers/goldens/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/goldens/py/generate.py b/third_party/flatbuffers/goldens/py/generate.py new file mode 100644 index 00000000000..ceff5d2d6b7 --- /dev/null +++ b/third_party/flatbuffers/goldens/py/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Python specifics + flatc_golden(options=["--python"] + options, schema=schema, prefix="py") + + +def GeneratePython(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/rust/basic_generated.rs b/third_party/flatbuffers/goldens/rust/basic_generated.rs new file mode 100644 index 00000000000..0e83305c854 --- /dev/null +++ b/third_party/flatbuffers/goldens/rust/basic_generated.rs @@ -0,0 +1,313 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +// @generated + +use core::mem; +use core::cmp::Ordering; + +extern crate flatbuffers; +use self::flatbuffers::{EndianScalar, Follow}; + +#[allow(unused_imports, dead_code)] +pub mod flatbuffers { + + use core::mem; + use core::cmp::Ordering; + + extern crate flatbuffers; + use self::flatbuffers::{EndianScalar, Follow}; +#[allow(unused_imports, dead_code)] +pub mod goldens { + + use core::mem; + use core::cmp::Ordering; + + extern crate flatbuffers; + use self::flatbuffers::{EndianScalar, Follow}; + +pub enum GalaxyOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Galaxy<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Galaxy<'a> { + type Inner = Galaxy<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Galaxy<'a> { + pub const VT_NUM_STARS: flatbuffers::VOffsetT = 4; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Galaxy { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args GalaxyArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = GalaxyBuilder::new(_fbb); + builder.add_num_stars(args.num_stars); + builder.finish() + } + + + #[inline] + pub fn num_stars(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Galaxy::VT_NUM_STARS, Some(0)).unwrap()} + } +} + +impl flatbuffers::Verifiable for Galaxy<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("num_stars", Self::VT_NUM_STARS, false)? + .finish(); + Ok(()) + } +} +pub struct GalaxyArgs { + pub num_stars: i64, +} +impl<'a> Default for GalaxyArgs { + #[inline] + fn default() -> Self { + GalaxyArgs { + num_stars: 0, + } + } +} + +pub struct GalaxyBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GalaxyBuilder<'a, 'b, A> { + #[inline] + pub fn add_num_stars(&mut self, num_stars: i64) { + self.fbb_.push_slot::(Galaxy::VT_NUM_STARS, num_stars, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> GalaxyBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + GalaxyBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Galaxy<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Galaxy"); + ds.field("num_stars", &self.num_stars()); + ds.finish() + } +} +pub enum UniverseOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Universe<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Universe<'a> { + type Inner = Universe<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Universe<'a> { + pub const VT_AGE: flatbuffers::VOffsetT = 4; + pub const VT_GALAXIES: flatbuffers::VOffsetT = 6; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Universe { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args UniverseArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = UniverseBuilder::new(_fbb); + builder.add_age(args.age); + if let Some(x) = args.galaxies { builder.add_galaxies(x); } + builder.finish() + } + + + #[inline] + pub fn age(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Universe::VT_AGE, Some(0.0)).unwrap()} + } + #[inline] + pub fn galaxies(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Universe::VT_GALAXIES, None)} + } +} + +impl flatbuffers::Verifiable for Universe<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("age", Self::VT_AGE, false)? + .visit_field::>>>("galaxies", Self::VT_GALAXIES, false)? + .finish(); + Ok(()) + } +} +pub struct UniverseArgs<'a> { + pub age: f64, + pub galaxies: Option>>>>, +} +impl<'a> Default for UniverseArgs<'a> { + #[inline] + fn default() -> Self { + UniverseArgs { + age: 0.0, + galaxies: None, + } + } +} + +pub struct UniverseBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> UniverseBuilder<'a, 'b, A> { + #[inline] + pub fn add_age(&mut self, age: f64) { + self.fbb_.push_slot::(Universe::VT_AGE, age, 0.0); + } + #[inline] + pub fn add_galaxies(&mut self, galaxies: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Universe::VT_GALAXIES, galaxies); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> UniverseBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + UniverseBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Universe<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Universe"); + ds.field("age", &self.age()); + ds.field("galaxies", &self.galaxies()); + ds.finish() + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `Universe` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_universe_unchecked`. +pub fn root_as_universe(buf: &[u8]) -> Result { + flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `Universe` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_universe_unchecked`. +pub fn size_prefixed_root_as_universe(buf: &[u8]) -> Result { + flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `Universe` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_universe_unchecked`. +pub fn root_as_universe_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `Universe` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_universe_unchecked`. +pub fn size_prefixed_root_as_universe_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a Universe and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `Universe`. +pub unsafe fn root_as_universe_unchecked(buf: &[u8]) -> Universe { + flatbuffers::root_unchecked::(buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed Universe and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `Universe`. +pub unsafe fn size_prefixed_root_as_universe_unchecked(buf: &[u8]) -> Universe { + flatbuffers::size_prefixed_root_unchecked::(buf) +} +#[inline] +pub fn finish_universe_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( + fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + root: flatbuffers::WIPOffset>) { + fbb.finish(root, None); +} + +#[inline] +pub fn finish_size_prefixed_universe_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, None); +} +} // pub mod goldens +} // pub mod flatbuffers + diff --git a/third_party/flatbuffers/goldens/rust/generate.py b/third_party/flatbuffers/goldens/rust/generate.py new file mode 100644 index 00000000000..f3a568fef89 --- /dev/null +++ b/third_party/flatbuffers/goldens/rust/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Rust specifics + flatc_golden(options=["--rust"] + options, schema=schema, prefix="rust") + + +def GenerateRust(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/schema/basic.fbs b/third_party/flatbuffers/goldens/schema/basic.fbs new file mode 100644 index 00000000000..b4574a1c1f3 --- /dev/null +++ b/third_party/flatbuffers/goldens/schema/basic.fbs @@ -0,0 +1,15 @@ +// This file should contain the basics of flatbuffers that all languages should +// support. + +namespace flatbuffers.goldens; + +table Galaxy { + num_stars:long; +} + +table Universe { + age:double; + galaxies:[Galaxy]; +} + +root_type Universe; \ No newline at end of file diff --git a/third_party/flatbuffers/goldens/swift/__init__.py b/third_party/flatbuffers/goldens/swift/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/goldens/swift/basic_generated.swift b/third_party/flatbuffers/goldens/swift/basic_generated.swift new file mode 100644 index 00000000000..16ef66363b4 --- /dev/null +++ b/third_party/flatbuffers/goldens/swift/basic_generated.swift @@ -0,0 +1,84 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public struct flatbuffers_goldens_Galaxy: FlatBufferObject, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case numStars = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var numStars: Int64 { let o = _accessor.offset(VTOFFSET.numStars.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + public static func startGalaxy(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(numStars: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: numStars, def: 0, at: VTOFFSET.numStars.p) } + public static func endGalaxy(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createGalaxy( + _ fbb: inout FlatBufferBuilder, + numStars: Int64 = 0 + ) -> Offset { + let __start = flatbuffers_goldens_Galaxy.startGalaxy(&fbb) + flatbuffers_goldens_Galaxy.add(numStars: numStars, &fbb) + return flatbuffers_goldens_Galaxy.endGalaxy(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.numStars.p, fieldName: "numStars", required: false, type: Int64.self) + _v.finish() + } +} + +public struct flatbuffers_goldens_Universe: FlatBufferObject, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case age = 4 + case galaxies = 6 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var age: Double { let o = _accessor.offset(VTOFFSET.age.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var hasGalaxies: Bool { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? false : true } + public var galaxiesCount: Int32 { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func galaxies(at index: Int32) -> flatbuffers_goldens_Galaxy? { let o = _accessor.offset(VTOFFSET.galaxies.v); return o == 0 ? nil : flatbuffers_goldens_Galaxy(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public static func startUniverse(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 2) } + public static func add(age: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: age, def: 0.0, at: VTOFFSET.age.p) } + public static func addVectorOf(galaxies: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: galaxies, at: VTOFFSET.galaxies.p) } + public static func endUniverse(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createUniverse( + _ fbb: inout FlatBufferBuilder, + age: Double = 0.0, + galaxiesVectorOffset galaxies: Offset = Offset() + ) -> Offset { + let __start = flatbuffers_goldens_Universe.startUniverse(&fbb) + flatbuffers_goldens_Universe.add(age: age, &fbb) + flatbuffers_goldens_Universe.addVectorOf(galaxies: galaxies, &fbb) + return flatbuffers_goldens_Universe.endUniverse(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.age.p, fieldName: "age", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.galaxies.p, fieldName: "galaxies", required: false, type: ForwardOffset, flatbuffers_goldens_Galaxy>>.self) + _v.finish() + } +} + diff --git a/third_party/flatbuffers/goldens/swift/generate.py b/third_party/flatbuffers/goldens/swift/generate.py new file mode 100644 index 00000000000..ccdb97e7758 --- /dev/null +++ b/third_party/flatbuffers/goldens/swift/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Swift specifics + flatc_golden(options=["--swift"] + options, schema=schema, prefix="swift") + + +def GenerateSwift(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/goldens/ts/basic.ts b/third_party/flatbuffers/goldens/ts/basic.ts new file mode 100644 index 00000000000..bf563a0b8d8 --- /dev/null +++ b/third_party/flatbuffers/goldens/ts/basic.ts @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Galaxy } from './galaxy.js'; +export { Universe } from './universe.js'; diff --git a/third_party/flatbuffers/goldens/ts/flatbuffers/goldens.ts b/third_party/flatbuffers/goldens/ts/flatbuffers/goldens.ts new file mode 100644 index 00000000000..0d2097f7816 --- /dev/null +++ b/third_party/flatbuffers/goldens/ts/flatbuffers/goldens.ts @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Galaxy } from './goldens/galaxy.js'; +export { Universe } from './goldens/universe.js'; diff --git a/third_party/flatbuffers/goldens/ts/flatbuffers/goldens/galaxy.ts b/third_party/flatbuffers/goldens/ts/flatbuffers/goldens/galaxy.ts new file mode 100644 index 00000000000..1d3c50d68bd --- /dev/null +++ b/third_party/flatbuffers/goldens/ts/flatbuffers/goldens/galaxy.ts @@ -0,0 +1,48 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +export class Galaxy { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Galaxy { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsGalaxy(bb:flatbuffers.ByteBuffer, obj?:Galaxy):Galaxy { + return (obj || new Galaxy()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsGalaxy(bb:flatbuffers.ByteBuffer, obj?:Galaxy):Galaxy { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Galaxy()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +numStars():bigint { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +static startGalaxy(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addNumStars(builder:flatbuffers.Builder, numStars:bigint) { + builder.addFieldInt64(0, numStars, BigInt('0')); +} + +static endGalaxy(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createGalaxy(builder:flatbuffers.Builder, numStars:bigint):flatbuffers.Offset { + Galaxy.startGalaxy(builder); + Galaxy.addNumStars(builder, numStars); + return Galaxy.endGalaxy(builder); +} +} diff --git a/third_party/flatbuffers/goldens/ts/flatbuffers/goldens/universe.ts b/third_party/flatbuffers/goldens/ts/flatbuffers/goldens/universe.ts new file mode 100644 index 00000000000..5634d78314a --- /dev/null +++ b/third_party/flatbuffers/goldens/ts/flatbuffers/goldens/universe.ts @@ -0,0 +1,86 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Galaxy } from '../../flatbuffers/goldens/galaxy.js'; + + +export class Universe { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Universe { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsUniverse(bb:flatbuffers.ByteBuffer, obj?:Universe):Universe { + return (obj || new Universe()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsUniverse(bb:flatbuffers.ByteBuffer, obj?:Universe):Universe { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Universe()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +age():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0; +} + +galaxies(index: number, obj?:Galaxy):Galaxy|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new Galaxy()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +galaxiesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static startUniverse(builder:flatbuffers.Builder) { + builder.startObject(2); +} + +static addAge(builder:flatbuffers.Builder, age:number) { + builder.addFieldFloat64(0, age, 0.0); +} + +static addGalaxies(builder:flatbuffers.Builder, galaxiesOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, galaxiesOffset, 0); +} + +static createGalaxiesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startGalaxiesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endUniverse(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static finishUniverseBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset); +} + +static finishSizePrefixedUniverseBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, undefined, true); +} + +static createUniverse(builder:flatbuffers.Builder, age:number, galaxiesOffset:flatbuffers.Offset):flatbuffers.Offset { + Universe.startUniverse(builder); + Universe.addAge(builder, age); + Universe.addGalaxies(builder, galaxiesOffset); + return Universe.endUniverse(builder); +} +} diff --git a/third_party/flatbuffers/goldens/ts/generate.py b/third_party/flatbuffers/goldens/ts/generate.py new file mode 100644 index 00000000000..ee072fdd637 --- /dev/null +++ b/third_party/flatbuffers/goldens/ts/generate.py @@ -0,0 +1,10 @@ +from golden_utils import flatc_golden + + +def flatc(options, schema): + # Wrap the golden flatc generator with Swift specifics + flatc_golden(options=["--ts"] + options, schema=schema, prefix="ts") + + +def GenerateTs(): + flatc([], "basic.fbs") diff --git a/third_party/flatbuffers/grpc/boringssl.patch b/third_party/flatbuffers/grpc/boringssl.patch index 632499e2804..a8768927ac1 100644 --- a/third_party/flatbuffers/grpc/boringssl.patch +++ b/third_party/flatbuffers/grpc/boringssl.patch @@ -11,3 +11,31 @@ index 1645a264a..12f8ca999 100644 add_executable( bssl +diff --git a/src/crypto/x509/t_x509.c b/src/crypto/x509/t_x509.c +index 7c32a8798..6e50d040e 100644 +--- a/src/crypto/x509/t_x509.c ++++ b/src/crypto/x509/t_x509.c +@@ -318,9 +318,7 @@ int X509_signature_print(BIO *bp, const X509_ALGOR *sigalg, + int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase) + { + char *s, *c, *b; +- int ret = 0, l, i; +- +- l = 80 - 2 - obase; ++ int ret = 0, i; + + b = X509_NAME_oneline(name, NULL, 0); + if (!b) +@@ -347,12 +345,10 @@ int X509_NAME_print(BIO *bp, const X509_NAME *name, int obase) + if (BIO_write(bp, ", ", 2) != 2) + goto err; + } +- l--; + } + if (*s == '\0') + break; + s++; +- l--; + } + + ret = 1; diff --git a/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch b/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch index 38cdfe9931b..b5900af5b34 100644 --- a/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch +++ b/third_party/flatbuffers/grpc/build_grpc_with_cxx14.patch @@ -2,9 +2,12 @@ diff --git a/bazel/copts.bzl b/bazel/copts.bzl index 10be944f25..879518b92f 100644 --- a/bazel/copts.bzl +++ b/bazel/copts.bzl -@@ -59,4 +59,4 @@ GRPC_LLVM_WARNING_FLAGS = [ +@@ -59,4 +59,7 @@ GRPC_LLVM_WARNING_FLAGS = [ GRPC_DEFAULT_COPTS = select({ "//:use_strict_warning": GRPC_LLVM_WARNING_FLAGS + ["-DUSE_STRICT_WARNING=1"], "//conditions:default": [], -}) -+}) + ["-std=c++14"] ++}) + select({ ++ "@bazel_tools//src/conditions:windows": ["/std:c++14"], ++ "//conditions:default": ["-std=c++14"], ++}) diff --git a/third_party/flatbuffers/grpc/examples/python/greeter/greeter_grpc.fb.py b/third_party/flatbuffers/grpc/examples/python/greeter/greeter_grpc.fb.py new file mode 100644 index 00000000000..7d1fec44f8f --- /dev/null +++ b/third_party/flatbuffers/grpc/examples/python/greeter/greeter_grpc.fb.py @@ -0,0 +1,54 @@ +# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT! + +import flatbuffers +import grpc + +from models.HelloReply import HelloReply +from models.HelloRequest import HelloRequest + + +class GreeterStub(object): + '''Interface exported by the server.''' + + def __init__(self, channel): + '''Constructor. + + Args: + channel: A grpc.Channel. + ''' + + self.SayHello = channel.unary_unary( + method='/models.Greeter/SayHello') + + self.SayManyHellos = channel.unary_stream( + method='/models.Greeter/SayManyHellos') + + +class GreeterServicer(object): + '''Interface exported by the server.''' + + def SayHello(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def SayManyHellos(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_GreeterServicer_to_server(servicer, server): + rpc_method_handlers = { + 'SayHello': grpc.unary_unary_rpc_method_handler( + servicer.SayHello), + 'SayManyHellos': grpc.unary_stream_rpc_method_handler( + servicer.SayManyHellos), + } + + generic_handler = grpc.method_handlers_generic_handler( + 'models.Greeter', rpc_method_handlers) + + server.add_generic_rpc_handlers((generic_handler,)) + + diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift index 5e6fb68cde3..392c2798df4 100644 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift +++ b/third_party/flatbuffers/grpc/examples/swift/Greeter/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.1 +// swift-tools-version:5.9 /* * Copyright 2020 Google Inc. All rights reserved. * diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift index 81ffe48f857..5339272510d 100644 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift +++ b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/Model/greeter_generated.swift @@ -6,7 +6,7 @@ import FlatBuffers public struct models_HelloReply: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_24_3_25() } + static func validateVersion() { FlatBuffersVersion_25_2_10() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table @@ -53,7 +53,7 @@ extension models_HelloReply: Encodable { public struct models_HelloRequest: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_24_3_25() } + static func validateVersion() { FlatBuffersVersion_25_2_10() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift index a4b2a675c70..e7065ac9c40 100644 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift +++ b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/client/main.swift @@ -1,5 +1,5 @@ /* - * Copyright 2023 Google Inc. All rights reserved. + * Copyright 2024 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift index 62286c4759f..60deb544a1b 100644 --- a/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift +++ b/third_party/flatbuffers/grpc/examples/swift/Greeter/Sources/server/main.swift @@ -1,5 +1,5 @@ /* - * Copyright 2023 Google Inc. All rights reserved. + * Copyright 2024 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml b/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml index f7d41763747..dee931344d4 100644 --- a/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml +++ b/third_party/flatbuffers/grpc/flatbuffers-java-grpc/pom.xml @@ -24,7 +24,7 @@ - 1.36.0 + 1.67.1 diff --git a/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel b/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel index 0efa9560c2d..a73a79ba45d 100644 --- a/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel +++ b/third_party/flatbuffers/grpc/src/compiler/BUILD.bazel @@ -95,6 +95,8 @@ cc_library( visibility = ["//visibility:private"], deps = [ "//:flatbuffers", + "//include/codegen:namer", + "//include/codegen:python", ], ) diff --git a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc b/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc index fd635f2fa5e..21a94acf545 100644 --- a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc +++ b/third_party/flatbuffers/grpc/src/compiler/cpp_generator.cc @@ -8,8 +8,6 @@ namespace grpc_cpp_generator { namespace { -static grpc::string service_header_ext() { return ".grpc.fb.h"; } - template static grpc::string as_string(T x) { std::ostringstream out; @@ -1137,7 +1135,7 @@ grpc::string GetSourcePrologue(grpc_generator::File *file, vars["filename"] = file->filename(); vars["filename_base"] = file->filename_without_ext(); vars["message_header_ext"] = params.message_header_extension; - vars["service_header_ext"] = service_header_ext(); + vars["service_header_ext"] = params.service_header_extension; printer->Print(vars, "// Generated by the gRPC C++ plugin.\n"); printer->Print(vars, @@ -1557,7 +1555,7 @@ grpc::string GetMockPrologue(grpc_generator::File *file, vars["filename"] = file->filename(); vars["filename_base"] = file->filename_without_ext(); vars["message_header_ext"] = params.message_header_extension; - vars["service_header_ext"] = service_header_ext(); + vars["service_header_ext"] = params.service_header_extension; printer->Print(vars, "// Generated by the gRPC C++ plugin.\n"); printer->Print(vars, diff --git a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h b/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h index a9af1a6794f..98e37df97ad 100644 --- a/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h +++ b/third_party/flatbuffers/grpc/src/compiler/cpp_generator.h @@ -35,6 +35,8 @@ struct Parameters { bool generate_mock_code; // By default, use "_generated.h" std::string message_header_extension; + // Default: ".grpc.fb.h" + std::string service_header_extension; }; // Return the prologue of the generated header file. diff --git a/third_party/flatbuffers/grpc/src/compiler/python_generator.cc b/third_party/flatbuffers/grpc/src/compiler/python_generator.cc index d5f69e20e71..91203a28024 100644 --- a/third_party/flatbuffers/grpc/src/compiler/python_generator.cc +++ b/third_party/flatbuffers/grpc/src/compiler/python_generator.cc @@ -16,136 +16,365 @@ * */ +#include "src/compiler/python_generator.h" + +#include +#include #include +#include #include +#include +#include "codegen/idl_namer.h" +#include "codegen/namer.h" +#include "codegen/python.h" +#include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include "src/compiler/python_generator.h" -namespace grpc_python_generator { +namespace flatbuffers { +namespace python { +namespace grpc { namespace { +bool ClientStreaming(const RPCCall *method) { + const Value *val = method->attributes.Lookup("streaming"); + return val != nullptr && (val->constant == "client" || val->constant == "bidi"); +} -static grpc::string GenerateMethodType(const grpc_generator::Method *method) { +bool ServerStreaming(const RPCCall *method) { + const Value *val = method->attributes.Lookup("streaming"); + return val != nullptr && (val->constant == "server" || val->constant == "bidi"); +} - if (method->NoStreaming()) - return "unary_unary"; +void FormatImports(std::stringstream &ss, const Imports &imports) { + std::set modules; + std::map> names_by_module; + for (const Import &import : imports.imports) { + if (import.IsLocal()) continue; // skip all local imports + if (import.name == "") { + modules.insert(import.module); + } else { + names_by_module[import.module].insert(import.name); + } + } - if (method->ServerStreaming()) - return "unary_stream"; + for (const std::string &module : modules) { + ss << "import " << module << '\n'; + } + ss << '\n'; + for (const auto &import : names_by_module) { + ss << "from " << import.first << " import "; + size_t i = 0; + for (const std::string &name : import.second) { + if (i > 0) ss << ", "; + ss << name; + ++i; + } + ss << '\n'; + } + ss << "\n\n"; +} - if (method->ClientStreaming()) - return "stream_unary"; +bool SaveStub(const std::string &filename, const Imports &imports, + const std::string &content) { + std::stringstream ss; + ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n" + << '\n' + << "from __future__ import annotations\n" + << '\n'; + FormatImports(ss, imports); + ss << content << '\n'; - return "stream_stream"; + EnsureDirExists(StripFileName(filename)); + return flatbuffers::SaveFile(filename.c_str(), ss.str(), false); } -grpc::string GenerateMethodInput(const grpc_generator::Method *method) { - - if (method->NoStreaming() || method->ServerStreaming()) - return "self, request, context"; +bool SaveService(const std::string &filename, const Imports &imports, + const std::string &content) { + std::stringstream ss; + ss << "# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT!\n" << '\n'; + FormatImports(ss, imports); + ss << content << '\n'; - return "self, request_iterator, context"; + EnsureDirExists(StripFileName(filename)); + return flatbuffers::SaveFile(filename.c_str(), ss.str(), false); } -void GenerateStub(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "class $ServiceName$Stub(object):\n"); - printer->Indent(); - printer->Print("\"\"\" Interface exported by the server. \"\"\""); - printer->Print("\n\n"); - printer->Print("def __init__(self, channel):\n"); - printer->Indent(); - printer->Print("\"\"\" Constructor. \n\n"); - printer->Print("Args: \n"); - printer->Print("channel: A grpc.Channel. \n"); - printer->Print("\"\"\"\n\n"); - - for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); - vars["MethodName"] = method->name(); - vars["MethodType"] = GenerateMethodType(&*method); - printer->Print(vars, "self.$MethodName$ = channel.$MethodType$(\n"); - printer->Indent(); - printer->Print(vars, "\"/$PATH$$ServiceName$/$MethodName$\"\n"); - printer->Print(")\n"); - printer->Outdent(); - printer->Print("\n"); +class BaseGenerator { + protected: + BaseGenerator(const Parser &parser, const Namer::Config &config, + const std::string &path, const Version &version) + : parser_{parser}, + namer_{WithFlagOptions(config, parser.opts, path), Keywords(version)}, + version_{version} {} + + protected: + std::string ModuleForFile(const std::string &file) const { + std::string module = parser_.opts.include_prefix + StripExtension(file) + + parser_.opts.filename_suffix; + std::replace(module.begin(), module.end(), '/', '.'); + return module; } - printer->Outdent(); - printer->Outdent(); - printer->Print("\n"); -} -void GenerateServicer(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "class $ServiceName$Servicer(object):\n"); - printer->Indent(); - printer->Print("\"\"\" Interface exported by the server. \"\"\""); - printer->Print("\n\n"); - - for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); - vars["MethodName"] = method->name(); - vars["MethodInput"] = GenerateMethodInput(&*method); - printer->Print(vars, "def $MethodName$($MethodInput$):\n"); - printer->Indent(); - printer->Print("context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n"); - printer->Print("context.set_details('Method not implemented!')\n"); - printer->Print("raise NotImplementedError('Method not implemented!')\n"); - printer->Outdent(); - printer->Print("\n\n"); + template + std::string ModuleFor(const T *def) const { + if (parser_.opts.one_file) return ModuleForFile(def->file); + return namer_.NamespacedType(*def); } - printer->Outdent(); - printer->Print("\n"); -} + const Parser &parser_; + const IdlNamer namer_; + const Version version_; +}; + +class StubGenerator : public BaseGenerator { + public: + StubGenerator(const Parser &parser, const std::string &path, + const Version &version) + : BaseGenerator(parser, kStubConfig, path, version) {} + + bool Generate() { + Imports imports; + std::stringstream stub; + for (const ServiceDef *service : parser_.services_.vec) { + Generate(stub, service, &imports); + } + + std::string filename = + namer_.config_.output_path + + StripPath(StripExtension(parser_.file_being_parsed_)) + "_grpc" + + parser_.opts.grpc_filename_suffix + namer_.config_.filename_extension; + + return SaveStub(filename, imports, stub.str()); + } + + private: + void Generate(std::stringstream &ss, const ServiceDef *service, + Imports *imports) { + imports->Import("grpc"); + + ss << "class " << service->name << "Stub(object):\n" + << " def __init__(self, channel: grpc.Channel) -> None: ...\n"; + + for (const RPCCall *method : service->calls.vec) { + std::string request = "bytes"; + std::string response = "bytes"; + + if (parser_.opts.grpc_python_typed_handlers) { + request = namer_.Type(*method->request); + response = namer_.Type(*method->response); + + imports->Import(ModuleFor(method->request), request); + imports->Import(ModuleFor(method->response), response); + } + + ss << " def " << method->name << "(self, "; + if (ClientStreaming(method)) { + imports->Import("typing"); + ss << "request_iterator: typing.Iterator[" << request << "]"; + } else { + ss << "request: " << request; + } + ss << ") -> "; + if (ServerStreaming(method)) { + imports->Import("typing"); + ss << "typing.Iterator[" << response << "]"; + } else { + ss << response; + } + ss << ": ...\n"; + } + + ss << "\n\n"; + ss << "class " << service->name << "Servicer(object):\n"; + + for (const RPCCall *method : service->calls.vec) { + std::string request = "bytes"; + std::string response = "bytes"; + + if (parser_.opts.grpc_python_typed_handlers) { + request = namer_.Type(*method->request); + response = namer_.Type(*method->response); + + imports->Import(ModuleFor(method->request), request); + imports->Import(ModuleFor(method->response), response); + } + + ss << " def " << method->name << "(self, "; + if (ClientStreaming(method)) { + imports->Import("typing"); + ss << "request_iterator: typing.Iterator[" << request << "]"; + } else { + ss << "request: " << request; + } + ss << ", context: grpc.ServicerContext) -> "; + if (ServerStreaming(method)) { + imports->Import("typing"); + ss << "typing.Iterator[" << response << "]"; + } else { + ss << response; + } + ss << ": ...\n"; + } -void GenerateRegister(const grpc_generator::Service *service, - grpc_generator::Printer *printer, - std::map *dictonary) { - auto vars = *dictonary; - printer->Print(vars, "def add_$ServiceName$Servicer_to_server(servicer, server):\n"); - printer->Indent(); - printer->Print("rpc_method_handlers = {\n"); - printer->Indent(); - for (int j = 0; j < service->method_count(); j++) { - auto method = service->method(j); - vars["MethodName"] = method->name(); - vars["MethodType"] = GenerateMethodType(&*method); - printer->Print(vars, "'$MethodName$': grpc.$MethodType$_rpc_method_handler(\n"); - printer->Indent(); - printer->Print(vars, "servicer.$MethodName$\n"); - printer->Outdent(); - printer->Print("),\n"); + ss << '\n' + << '\n' + << "def add_" << service->name + << "Servicer_to_server(servicer: " << service->name + << "Servicer, server: grpc.Server) -> None: ...\n"; } - printer->Outdent(); - printer->Print("}\n"); - printer->Print(vars, "generic_handler = grpc.method_handlers_generic_handler(\n"); - printer->Indent(); - printer->Print(vars, "'$PATH$$ServiceName$', rpc_method_handlers)\n"); - printer->Outdent(); - printer->Print("server.add_generic_rpc_handlers((generic_handler,))"); - printer->Outdent(); - printer->Print("\n"); +}; + +class ServiceGenerator : public BaseGenerator { + public: + ServiceGenerator(const Parser &parser, const std::string &path, + const Version &version) + : BaseGenerator(parser, kConfig, path, version) {} + + bool Generate() { + Imports imports; + std::stringstream ss; + + imports.Import("flatbuffers"); + + if (parser_.opts.grpc_python_typed_handlers) { + ss << "def _serialize_to_bytes(table):\n" + << " buf = table._tab.Bytes\n" + << " n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, 0)\n" + << " if table._tab.Pos != n:\n" + << " raise ValueError('must be a top-level table')\n" + << " return bytes(buf)\n" + << '\n' + << '\n'; + } + + for (const ServiceDef *service : parser_.services_.vec) { + GenerateStub(ss, service, &imports); + GenerateServicer(ss, service, &imports); + GenerateRegister(ss, service, &imports); + } + + std::string filename = + namer_.config_.output_path + + StripPath(StripExtension(parser_.file_being_parsed_)) + "_grpc" + + parser_.opts.grpc_filename_suffix + namer_.config_.filename_extension; + + return SaveService(filename, imports, ss.str()); + } + + private: + void GenerateStub(std::stringstream &ss, const ServiceDef *service, + Imports *imports) { + ss << "class " << service->name << "Stub"; + if (version_.major != 3) ss << "(object)"; + ss << ":\n" + << " '''Interface exported by the server.'''\n" + << '\n' + << " def __init__(self, channel):\n" + << " '''Constructor.\n" + << '\n' + << " Args:\n" + << " channel: A grpc.Channel.\n" + << " '''\n" + << '\n'; + + for (const RPCCall *method : service->calls.vec) { + std::string response = namer_.Type(*method->response); + + imports->Import(ModuleFor(method->response), response); + + ss << " self." << method->name << " = channel." + << (ClientStreaming(method) ? "stream" : "unary") << "_" + << (ServerStreaming(method) ? "stream" : "unary") << "(\n" + << " method='/" + << service->defined_namespace->GetFullyQualifiedName(service->name) + << "/" << method->name << "'"; + + if (parser_.opts.grpc_python_typed_handlers) { + ss << ",\n" + << " request_serializer=_serialize_to_bytes,\n" + << " response_deserializer=" << response << ".GetRootAs"; + } + ss << ")\n\n"; + } + + ss << '\n'; + } + + void GenerateServicer(std::stringstream &ss, const ServiceDef *service, + Imports *imports) { + imports->Import("grpc"); + + ss << "class " << service->name << "Servicer"; + if (version_.major != 3) ss << "(object)"; + ss << ":\n" + << " '''Interface exported by the server.'''\n" + << '\n'; + + for (const RPCCall *method : service->calls.vec) { + const std::string request_param = + ClientStreaming(method) ? "request_iterator" : "request"; + ss << " def " << method->name << "(self, " << request_param + << ", context):\n" + << " context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n" + << " context.set_details('Method not implemented!')\n" + << " raise NotImplementedError('Method not implemented!')\n" + << '\n'; + } + + ss << '\n'; + } + + void GenerateRegister(std::stringstream &ss, const ServiceDef *service, + Imports *imports) { + imports->Import("grpc"); + + ss << "def add_" << service->name + << "Servicer_to_server(servicer, server):\n" + << " rpc_method_handlers = {\n"; + + for (const RPCCall *method : service->calls.vec) { + std::string request = namer_.Type(*method->request); + + imports->Import(ModuleFor(method->request), request); + + ss << " '" << method->name << "': grpc." + << (ClientStreaming(method) ? "stream" : "unary") << "_" + << (ServerStreaming(method) ? "stream" : "unary") + << "_rpc_method_handler(\n" + << " servicer." << method->name; + + if (parser_.opts.grpc_python_typed_handlers) { + ss << ",\n" + << " request_deserializer=" << request << ".GetRootAs,\n" + << " response_serializer=_serialize_to_bytes"; + } + ss << "),\n"; + } + ss << " }\n" + << '\n' + << " generic_handler = grpc.method_handlers_generic_handler(\n" + << " '" + << service->defined_namespace->GetFullyQualifiedName(service->name) + << "', rpc_method_handlers)\n" + << '\n' + << " server.add_generic_rpc_handlers((generic_handler,))\n" + << '\n'; + } +}; +} // namespace + +bool Generate(const Parser &parser, const std::string &path, + const Version &version) { + ServiceGenerator generator{parser, path, version}; + return generator.Generate(); } -} // namespace - -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service) { - grpc::string output; - std::map vars; - vars["PATH"] = file->package(); - if (!file->package().empty()) { vars["PATH"].append("."); } - vars["ServiceName"] = service->name(); - auto printer = file->CreatePrinter(&output); - GenerateStub(service, &*printer, &vars); - GenerateServicer(service, &*printer, &vars); - GenerateRegister(service, &*printer, &vars); - return output; + +bool GenerateStub(const Parser &parser, const std::string &path, + const Version &version) { + StubGenerator generator{parser, path, version}; + return generator.Generate(); } -} // namespace grpc_python_generator +} // namespace grpc +} // namespace python +} // namespace flatbuffers diff --git a/third_party/flatbuffers/grpc/src/compiler/python_generator.h b/third_party/flatbuffers/grpc/src/compiler/python_generator.h index 40d29aada55..6335ecc9fbe 100644 --- a/third_party/flatbuffers/grpc/src/compiler/python_generator.h +++ b/third_party/flatbuffers/grpc/src/compiler/python_generator.h @@ -19,14 +19,21 @@ #ifndef GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H #define GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H -#include +#include -#include "src/compiler/schema_interface.h" +#include "codegen/python.h" +#include "flatbuffers/idl.h" -namespace grpc_python_generator { +namespace flatbuffers { +namespace python { +namespace grpc { +bool Generate(const Parser &parser, const std::string &path, + const Version &version); -grpc::string Generate(grpc_generator::File *file, - const grpc_generator::Service *service); -} // namespace grpc_python_generator +bool GenerateStub(const Parser &parser, const std::string &path, + const Version &version); +} // namespace grpc +} // namespace python +} // namespace flatbuffers #endif // GRPC_INTERNAL_COMPILER_PYTHON_GENERATOR_H diff --git a/third_party/flatbuffers/grpc/tests/BUILD b/third_party/flatbuffers/grpc/tests/BUILD index 5d4023ec752..ec7b8c14647 100644 --- a/third_party/flatbuffers/grpc/tests/BUILD +++ b/third_party/flatbuffers/grpc/tests/BUILD @@ -1,3 +1,5 @@ +load("@rules_cc//cc:defs.bzl", "cc_test") + cc_test( name = "grpc_test", srcs = [ diff --git a/third_party/flatbuffers/include/codegen/BUILD.bazel b/third_party/flatbuffers/include/codegen/BUILD.bazel new file mode 100644 index 00000000000..196181b411b --- /dev/null +++ b/third_party/flatbuffers/include/codegen/BUILD.bazel @@ -0,0 +1,39 @@ +load("@rules_cc//cc:defs.bzl", "cc_library") + +package( + default_visibility = ["//visibility:private"], +) + +filegroup( + name = "distribution", + srcs = [ + "BUILD.bazel", + ] + glob([ + "*.cc", + "*.h", + ]), + visibility = ["//visibility:public"], +) + +cc_library( + name = "namer", + hdrs = [ + "idl_namer.h", + "namer.h", + ], + strip_include_prefix = "/include", + visibility = ["//:__subpackages__"], + deps = ["//:runtime_cc"], +) + +cc_library( + name = "python", + srcs = ["python.cc"], + hdrs = ["python.h"], + strip_include_prefix = "/include", + visibility = [ + "//grpc:__subpackages__", + "//src:__subpackages__", + ], + deps = [":namer"], +) diff --git a/third_party/flatbuffers/include/codegen/idl_namer.h b/third_party/flatbuffers/include/codegen/idl_namer.h new file mode 100644 index 00000000000..dd2fe3b8afe --- /dev/null +++ b/third_party/flatbuffers/include/codegen/idl_namer.h @@ -0,0 +1,179 @@ +#ifndef FLATBUFFERS_INCLUDE_CODEGEN_IDL_NAMER_H_ +#define FLATBUFFERS_INCLUDE_CODEGEN_IDL_NAMER_H_ + +#include "codegen/namer.h" +#include "flatbuffers/idl.h" + +namespace flatbuffers { + +// Provides Namer capabilities to types defined in the flatbuffers IDL. +class IdlNamer : public Namer { + public: + explicit IdlNamer(Config config, std::set keywords) + : Namer(config, std::move(keywords)) {} + + using Namer::Constant; + using Namer::Directories; + using Namer::Field; + using Namer::File; + using Namer::Function; + using Namer::Method; + using Namer::Namespace; + using Namer::NamespacedType; + using Namer::ObjectType; + using Namer::Type; + using Namer::Variable; + using Namer::Variant; + + std::string Constant(const FieldDef &d) const { return Constant(d.name); } + + // Types are always structs or enums so we can only expose these two + // overloads. + std::string Type(const StructDef &d) const { return Type(d.name); } + std::string Type(const EnumDef &d) const { return Type(d.name); } + + std::string Function(const Definition &s) const { return Function(s.name); } + std::string Function(const std::string& prefix, const Definition &s) const { + return Function(prefix + s.name); + } + + std::string Field(const FieldDef &s) const { return Field(s.name); } + std::string Field(const FieldDef &d, const std::string &s) const { + return Field(d.name + "_" + s); + } + + std::string Variable(const FieldDef &s) const { return Variable(s.name); } + + std::string Variable(const StructDef &s) const { return Variable(s.name); } + + std::string Variant(const EnumVal &s) const { return Variant(s.name); } + + std::string EnumVariant(const EnumDef &e, const EnumVal &v) const { + return Type(e) + config_.enum_variant_seperator + Variant(v); + } + + std::string ObjectType(const StructDef &d) const { + return ObjectType(d.name); + } + std::string ObjectType(const EnumDef &d) const { return ObjectType(d.name); } + + std::string Method(const FieldDef &d, const std::string &suffix) const { + return Method(d.name, suffix); + } + std::string Method(const std::string &prefix, const StructDef &d) const { + return Method(prefix, d.name); + } + std::string Method(const std::string &prefix, const FieldDef &d) const { + return Method(prefix, d.name); + } + std::string Method(const std::string &prefix, const FieldDef &d, + const std::string &suffix) const { + return Method(prefix, d.name, suffix); + } + + std::string Namespace(const struct Namespace &ns) const { + return Namespace(ns.components); + } + + std::string NamespacedEnumVariant(const EnumDef &e, const EnumVal &v) const { + return NamespacedString(e.defined_namespace, EnumVariant(e, v)); + } + + std::string NamespacedType(const Definition &def) const { + return NamespacedString(def.defined_namespace, Type(def.name)); + } + + std::string NamespacedObjectType(const Definition &def) const { + return NamespacedString(def.defined_namespace, ObjectType(def.name)); + } + + std::string Directories(const struct Namespace &ns, + SkipDir skips = SkipDir::None, + Case input_case = Case::kUpperCamel) const { + return Directories(ns.components, skips, input_case); + } + + // Legacy fields do not really follow the usual config and should be + // considered for deprecation. + + std::string LegacyRustNativeVariant(const EnumVal &v) const { + return ConvertCase(EscapeKeyword(v.name), Case::kUpperCamel); + } + + std::string LegacyRustFieldOffsetName(const FieldDef &field) const { + return "VT_" + ConvertCase(EscapeKeyword(field.name), Case::kAllUpper); + } + std::string LegacyRustUnionTypeOffsetName(const FieldDef &field) const { + return "VT_" + ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper); + } + + + std::string LegacySwiftVariant(const EnumVal &ev) const { + auto name = ev.name; + if (isupper(name.front())) { + std::transform(name.begin(), name.end(), name.begin(), CharToLower); + } + return EscapeKeyword(ConvertCase(name, Case::kLowerCamel)); + } + + // Also used by Kotlin, lol. + std::string LegacyJavaMethod2(const std::string &prefix, const StructDef &sd, + const std::string &suffix) const { + return prefix + sd.name + suffix; + } + + std::string LegacyKotlinVariant(EnumVal &ev) const { + // Namer assumes the input case is snake case which is wrong... + return ConvertCase(EscapeKeyword(ev.name), Case::kLowerCamel); + } + // Kotlin methods escapes keywords after case conversion but before + // prefixing and suffixing. + std::string LegacyKotlinMethod(const std::string &prefix, const FieldDef &d, + const std::string &suffix) const { + return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) + + suffix; + } + std::string LegacyKotlinMethod(const std::string &prefix, const StructDef &d, + const std::string &suffix) const { + return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) + + suffix; + } + + // This is a mix of snake case and keep casing, when Ts should be using + // lower camel case. + std::string LegacyTsMutateMethod(const FieldDef& d) { + return "mutate_" + d.name; + } + + std::string LegacyRustUnionTypeMethod(const FieldDef &d) { + // assert d is a union + // d should convert case but not escape keywords due to historical reasons + return ConvertCase(d.name, config_.fields, Case::kLowerCamel) + "_type"; + } + + private: + std::string NamespacedString(const struct Namespace *ns, + const std::string &str) const { + std::string ret; + if (ns != nullptr) { ret += Namespace(ns->components); } + if (!ret.empty()) ret += config_.namespace_seperator; + return ret + str; + } +}; + +// This is a temporary helper function for code generators to call until all +// flag-overriding logic into flatc.cpp +inline Namer::Config WithFlagOptions(const Namer::Config &input, + const IDLOptions &opts, + const std::string &path) { + Namer::Config result = input; + result.object_prefix = opts.object_prefix; + result.object_suffix = opts.object_suffix; + result.output_path = path; + result.filename_suffix = opts.filename_suffix; + return result; +} + +} // namespace flatbuffers + +#endif // FLATBUFFERS_INCLUDE_CODEGEN_IDL_NAMER_H_ diff --git a/third_party/flatbuffers/include/codegen/namer.h b/third_party/flatbuffers/include/codegen/namer.h new file mode 100644 index 00000000000..e8b4286307b --- /dev/null +++ b/third_party/flatbuffers/include/codegen/namer.h @@ -0,0 +1,270 @@ +#ifndef FLATBUFFERS_INCLUDE_CODEGEN_NAMER_H_ +#define FLATBUFFERS_INCLUDE_CODEGEN_NAMER_H_ + +#include "flatbuffers/util.h" + +namespace flatbuffers { + +// Options for Namer::File. +enum class SkipFile { + None = 0, + Suffix = 1, + Extension = 2, + SuffixAndExtension = 3, +}; +inline SkipFile operator&(SkipFile a, SkipFile b) { + return static_cast(static_cast(a) & static_cast(b)); +} +// Options for Namer::Directories +enum class SkipDir { + None = 0, + // Skip prefixing the -o $output_path. + OutputPath = 1, + // Skip trailing path seperator. + TrailingPathSeperator = 2, + OutputPathAndTrailingPathSeparator = 3, +}; +inline SkipDir operator&(SkipDir a, SkipDir b) { + return static_cast(static_cast(a) & static_cast(b)); +} + +// `Namer` applies style configuration to symbols in generated code. It manages +// casing, escapes keywords, and object API naming. +// TODO: Refactor all code generators to use this. +class Namer { + public: + struct Config { + // Symbols in code. + + // Case style for flatbuffers-defined types. + // e.g. `class TableA {}` + Case types; + // Case style for flatbuffers-defined constants. + // e.g. `uint64_t ENUM_A_MAX`; + Case constants; + // Case style for flatbuffers-defined methods. + // e.g. `class TableA { int field_a(); }` + Case methods; + // Case style for flatbuffers-defined functions. + // e.g. `TableA* get_table_a_root()`; + Case functions; + // Case style for flatbuffers-defined fields. + // e.g. `struct Struct { int my_field; }` + Case fields; + // Case style for flatbuffers-defined variables. + // e.g. `int my_variable = 2` + Case variables; + // Case style for flatbuffers-defined variants. + // e.g. `enum class Enum { MyVariant, }` + Case variants; + // Seperator for qualified enum names. + // e.g. `Enum::MyVariant` uses `::`. + std::string enum_variant_seperator; + + // Configures, when formatting code, whether symbols are checked against + // keywords and escaped before or after case conversion. It does not make + // sense to do so before, but its legacy behavior. :shrug: + // TODO(caspern): Deprecate. + enum class Escape { + BeforeConvertingCase, + AfterConvertingCase, + }; + Escape escape_keywords; + + // Namespaces + + // e.g. `namespace my_namespace {}` + Case namespaces; + // The seperator between namespaces in a namespace path. + std::string namespace_seperator; + + // Object API. + // Native versions flatbuffers types have this prefix. + // e.g. "" (it's usually empty string) + std::string object_prefix; + // Native versions flatbuffers types have this suffix. + // e.g. "T" + std::string object_suffix; + + // Keywords. + // Prefix used to escape keywords. It is usually empty string. + std::string keyword_prefix; + // Suffix used to escape keywords. It is usually "_". + std::string keyword_suffix; + + // Files. + + // Case style for filenames. e.g. `foo_bar_generated.rs` + Case filenames; + // Case style for directories, e.g. `output_files/foo_bar/baz/` + Case directories; + // The directory within which we will generate files. + std::string output_path; + // Suffix for generated file names, e.g. "_generated". + std::string filename_suffix; + // Extension for generated files, e.g. ".cpp" or ".rs". + std::string filename_extension; + }; + Namer(Config config, std::set keywords) + : config_(config), keywords_(std::move(keywords)) {} + + virtual ~Namer() {} + + template std::string Method(const T &s) const { + return Method(s.name); + } + + virtual std::string Method(const std::string &pre, + const std::string &mid, + const std::string &suf) const { + return Format(pre + "_" + mid + "_" + suf, config_.methods); + } + virtual std::string Method(const std::string &pre, + const std::string &suf) const { + return Format(pre + "_" + suf, config_.methods); + } + virtual std::string Method(const std::string &s) const { + return Format(s, config_.methods); + } + + virtual std::string Constant(const std::string &s) const { + return Format(s, config_.constants); + } + + virtual std::string Function(const std::string &s) const { + return Format(s, config_.functions); + } + + virtual std::string Variable(const std::string &s) const { + return Format(s, config_.variables); + } + + template + std::string Variable(const std::string &p, const T &s) const { + return Format(p + "_" + s.name, config_.variables); + } + virtual std::string Variable(const std::string &p, + const std::string &s) const { + return Format(p + "_" + s, config_.variables); + } + + virtual std::string Namespace(const std::string &s) const { + return Format(s, config_.namespaces); + } + + virtual std::string Namespace(const std::vector &ns) const { + std::string result; + for (auto it = ns.begin(); it != ns.end(); it++) { + if (it != ns.begin()) result += config_.namespace_seperator; + result += Namespace(*it); + } + return result; + } + + virtual std::string NamespacedType(const std::vector &ns, + const std::string &s) const { + return (ns.empty() ? "" : (Namespace(ns) + config_.namespace_seperator)) + + Type(s); + } + + // Returns `filename` with the right casing, suffix, and extension. + virtual std::string File(const std::string &filename, + SkipFile skips = SkipFile::None) const { + const bool skip_suffix = (skips & SkipFile::Suffix) != SkipFile::None; + const bool skip_ext = (skips & SkipFile::Extension) != SkipFile::None; + return ConvertCase(filename, config_.filenames, Case::kUpperCamel) + + (skip_suffix ? "" : config_.filename_suffix) + + (skip_ext ? "" : config_.filename_extension); + } + template + std::string File(const T &f, SkipFile skips = SkipFile::None) const { + return File(f.name, skips); + } + + // Formats `directories` prefixed with the output_path and joined with the + // right seperator. Output path prefixing and the trailing separator may be + // skiped using `skips`. + // Callers may want to use `EnsureDirExists` with the result. + // input_case is used to tell how to modify namespace. e.g. kUpperCamel will + // add a underscode between case changes, so MyGame turns into My_Game + // (depending also on the output_case). + virtual std::string Directories(const std::vector &directories, + SkipDir skips = SkipDir::None, + Case input_case = Case::kUpperCamel) const { + const bool skip_output_path = + (skips & SkipDir::OutputPath) != SkipDir::None; + const bool skip_trailing_seperator = + (skips & SkipDir::TrailingPathSeperator) != SkipDir::None; + std::string result = skip_output_path ? "" : config_.output_path; + for (auto d = directories.begin(); d != directories.end(); d++) { + result += ConvertCase(*d, config_.directories, input_case); + result.push_back(kPathSeparator); + } + if (skip_trailing_seperator && !result.empty()) result.pop_back(); + return result; + } + + virtual std::string EscapeKeyword(const std::string &name) const { + if (keywords_.find(name) == keywords_.end()) { + return name; + } else { + return config_.keyword_prefix + name + config_.keyword_suffix; + } + } + + virtual std::string Type(const std::string &s) const { + return Format(s, config_.types); + } + virtual std::string Type(const std::string &t, const std::string &s) const { + return Format(t + "_" + s, config_.types); + } + + virtual std::string ObjectType(const std::string &s) const { + return config_.object_prefix + Type(s) + config_.object_suffix; + } + + virtual std::string Field(const std::string &s) const { + return Format(s, config_.fields); + } + + virtual std::string Variant(const std::string &s) const { + return Format(s, config_.variants); + } + + virtual std::string Format(const std::string &s, Case casing) const { + if (config_.escape_keywords == Config::Escape::BeforeConvertingCase) { + return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel); + } else { + return EscapeKeyword(ConvertCase(s, casing, Case::kLowerCamel)); + } + } + + // Denamespaces a string (e.g. The.Quick.Brown.Fox) by returning the last part + // after the `delimiter` (Fox) and placing the rest in `namespace_prefix` + // (The.Quick.Brown). + virtual std::string Denamespace(const std::string &s, + std::string &namespace_prefix, + const char delimiter = '.') const { + const size_t pos = s.find_last_of(delimiter); + if (pos == std::string::npos) { + namespace_prefix = ""; + return s; + } + namespace_prefix = s.substr(0, pos); + return s.substr(pos + 1); + } + + // Same as above, but disregards the prefix. + virtual std::string Denamespace(const std::string &s, + const char delimiter = '.') const { + std::string prefix; + return Denamespace(s, prefix, delimiter); + } + + const Config config_; + const std::set keywords_; +}; + +} // namespace flatbuffers + +#endif // FLATBUFFERS_INCLUDE_CODEGEN_NAMER_H_ diff --git a/third_party/flatbuffers/include/codegen/python.cc b/third_party/flatbuffers/include/codegen/python.cc new file mode 100644 index 00000000000..cea95889193 --- /dev/null +++ b/third_party/flatbuffers/include/codegen/python.cc @@ -0,0 +1,63 @@ +#include "codegen/python.h" + +#include +#include +#include +#include + +namespace flatbuffers { +namespace python { +Version::Version(const std::string &version) { + std::stringstream ss(version); + char dot; + ss >> major >> dot >> minor >> dot >> micro; +} + +bool Version::IsValid() const { + return (major == 0 || major == 2 || major == 3) && minor >= 0 && micro >= 0; +} + +std::set Keywords(const Version &version) { + switch (version.major) { + case 2: + // https://docs.python.org/2/reference/lexical_analysis.html#keywords + return { + "and", "as", "assert", "break", "class", "continue", "def", + "del", "elif", "else", "except", "exec", "finally", "for", + "from", "global", "if", "import", "in", "is", "lambda", + "not", "or", "pass", "print", "raise", "return", "try", + "while", "with", "yield", + }; + case 0: + case 3: + // https://docs.python.org/3/reference/lexical_analysis.html#keywords + return { + "and", "as", "assert", "async", "await", "break", + "class", "continue", "def", "del", "elif", "else", + "except", "False", "finally", "for", "from", "global", + "if", "import", "in", "is", "lambda", "None", + "nonlocal", "not", "or", "pass", "raise", "return", + "True", "try", "while", "with", "yield", + }; + default: + return {}; + } +} + +const python::Import &python::Imports::Import(const std::string &module) { + python::Import import; + import.module = module; + imports.push_back(std::move(import)); + return imports.back(); +} + +const python::Import &python::Imports::Import(const std::string &module, + const std::string &name) { + python::Import import; + import.module = module; + import.name = name; + imports.push_back(std::move(import)); + return imports.back(); +} +} // namespace python +} // namespace flatbuffers diff --git a/third_party/flatbuffers/include/codegen/python.h b/third_party/flatbuffers/include/codegen/python.h new file mode 100644 index 00000000000..778eacfc4e5 --- /dev/null +++ b/third_party/flatbuffers/include/codegen/python.h @@ -0,0 +1,93 @@ +#ifndef FLATBUFFERS_INCLUDE_CODEGEN_PYTHON_H_ +#define FLATBUFFERS_INCLUDE_CODEGEN_PYTHON_H_ + +#include +#include +#include +#include + +#include "codegen/namer.h" + +namespace flatbuffers { +namespace python { +static const Namer::Config kConfig = { + /*types=*/Case::kKeep, + /*constants=*/Case::kScreamingSnake, + /*methods=*/Case::kUpperCamel, + /*functions=*/Case::kUpperCamel, + /*fields=*/Case::kLowerCamel, + /*variable=*/Case::kLowerCamel, + /*variants=*/Case::kKeep, + /*enum_variant_seperator=*/".", + /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase, + /*namespaces=*/Case::kKeep, // Packages in python. + /*namespace_seperator=*/".", + /*object_prefix=*/"", + /*object_suffix=*/"T", + /*keyword_prefix=*/"", + /*keyword_suffix=*/"_", + /*filenames=*/Case::kKeep, + /*directories=*/Case::kKeep, + /*output_path=*/"", + /*filename_suffix=*/"", + /*filename_extension=*/".py", +}; + +static const Namer::Config kStubConfig = { + /*types=*/Case::kKeep, + /*constants=*/Case::kScreamingSnake, + /*methods=*/Case::kUpperCamel, + /*functions=*/Case::kUpperCamel, + /*fields=*/Case::kLowerCamel, + /*variables=*/Case::kLowerCamel, + /*variants=*/Case::kKeep, + /*enum_variant_seperator=*/".", + /*escape_keywords=*/Namer::Config::Escape::AfterConvertingCase, + /*namespaces=*/Case::kKeep, // Packages in python. + /*namespace_seperator=*/".", + /*object_prefix=*/"", + /*object_suffix=*/"T", + /*keyword_prefix=*/"", + /*keyword_suffix=*/"_", + /*filenames=*/Case::kKeep, + /*directories=*/Case::kKeep, + /*output_path=*/"", + /*filename_suffix=*/"", + /*filename_extension=*/".pyi", +}; + +// `Version` represent a Python version. +// +// The zero value (i.e. `Version{}`) represents both Python2 and Python3. +// +// https://docs.python.org/3/faq/general.html#how-does-the-python-version-numbering-scheme-work +struct Version { + explicit Version(const std::string &version); + + bool IsValid() const; + + int16_t major = 0; + int16_t minor = 0; + int16_t micro = 0; +}; + +std::set Keywords(const Version &version); + +struct Import { + bool IsLocal() const { return module == "."; } + + std::string module; + std::string name; +}; + +struct Imports { + const python::Import &Import(const std::string &module); + const python::Import &Import(const std::string &module, + const std::string &name); + + std::vector imports; +}; +} // namespace python +} // namespace flatbuffers + +#endif // FLATBUFFERS_INCLUDE_CODEGEN_PYTHON_H_ diff --git a/third_party/flatbuffers/include/flatbuffers/base.h b/third_party/flatbuffers/include/flatbuffers/base.h index 1c19dde98f3..84cb0a7d16d 100644 --- a/third_party/flatbuffers/include/flatbuffers/base.h +++ b/third_party/flatbuffers/include/flatbuffers/base.h @@ -139,9 +139,9 @@ #endif #endif // !defined(FLATBUFFERS_LITTLEENDIAN) -#define FLATBUFFERS_VERSION_MAJOR 24 -#define FLATBUFFERS_VERSION_MINOR 3 -#define FLATBUFFERS_VERSION_REVISION 25 +#define FLATBUFFERS_VERSION_MAJOR 25 +#define FLATBUFFERS_VERSION_MINOR 2 +#define FLATBUFFERS_VERSION_REVISION 10 #define FLATBUFFERS_STRING_EXPAND(X) #X #define FLATBUFFERS_STRING(X) FLATBUFFERS_STRING_EXPAND(X) namespace flatbuffers { @@ -339,15 +339,15 @@ typedef uint16_t voffset_t; typedef uintmax_t largest_scalar_t; // In 32bits, this evaluates to 2GB - 1 -#define FLATBUFFERS_MAX_BUFFER_SIZE std::numeric_limits<::flatbuffers::soffset_t>::max() -#define FLATBUFFERS_MAX_64_BUFFER_SIZE std::numeric_limits<::flatbuffers::soffset64_t>::max() +#define FLATBUFFERS_MAX_BUFFER_SIZE (std::numeric_limits<::flatbuffers::soffset_t>::max)() +#define FLATBUFFERS_MAX_64_BUFFER_SIZE (std::numeric_limits<::flatbuffers::soffset64_t>::max)() // The minimum size buffer that can be a valid flatbuffer. // Includes the offset to the root table (uoffset_t), the offset to the vtable // of the root table (soffset_t), the size of the vtable (uint16_t), and the // size of the referring table (uint16_t). -#define FLATBUFFERS_MIN_BUFFER_SIZE sizeof(uoffset_t) + sizeof(soffset_t) + \ - sizeof(uint16_t) + sizeof(uint16_t) +#define FLATBUFFERS_MIN_BUFFER_SIZE sizeof(::flatbuffers::uoffset_t) + \ + sizeof(::flatbuffers::soffset_t) + sizeof(uint16_t) + sizeof(uint16_t) // We support aligning the contents of buffers up to this size. #ifndef FLATBUFFERS_MAX_ALIGNMENT @@ -459,10 +459,17 @@ inline size_t PaddingBytes(size_t buf_size, size_t scalar_size) { return ((~buf_size) + 1) & (scalar_size - 1); } +#if !defined(_MSC_VER) + #pragma GCC diagnostic push + #pragma GCC diagnostic ignored "-Wfloat-equal" +#endif // Generic 'operator==' with conditional specialisations. // T e - new value of a scalar field. // T def - default of scalar (is known at compile-time). template inline bool IsTheSameAs(T e, T def) { return e == def; } +#if !defined(_MSC_VER) + #pragma GCC diagnostic pop +#endif #if defined(FLATBUFFERS_NAN_DEFAULTS) && \ defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) diff --git a/third_party/flatbuffers/include/flatbuffers/detached_buffer.h b/third_party/flatbuffers/include/flatbuffers/detached_buffer.h index 5e900baeb57..36d3f6d6deb 100644 --- a/third_party/flatbuffers/include/flatbuffers/detached_buffer.h +++ b/third_party/flatbuffers/include/flatbuffers/detached_buffer.h @@ -80,6 +80,11 @@ class DetachedBuffer { size_t size() const { return size_; } + uint8_t *begin() { return data(); } + const uint8_t *begin() const { return data(); } + uint8_t *end() { return data() + size(); } + const uint8_t *end() const { return data() + size(); } + // These may change access mode, leave these at end of public section FLATBUFFERS_DELETE_FUNC(DetachedBuffer(const DetachedBuffer &other)); FLATBUFFERS_DELETE_FUNC( diff --git a/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h b/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h index 9a2d62541bd..9ceca8207b6 100644 --- a/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h +++ b/third_party/flatbuffers/include/flatbuffers/flatbuffer_builder.h @@ -47,7 +47,8 @@ inline voffset_t FieldIndexToOffset(voffset_t field_id) { 2 * sizeof(voffset_t); // Vtable size and Object Size. size_t offset = fixed_fields + field_id * sizeof(voffset_t); FLATBUFFERS_ASSERT(offset < std::numeric_limits::max()); - return static_cast(offset);} + return static_cast(offset); +} template> const T *data(const std::vector &v) { @@ -241,7 +242,7 @@ template class FlatBufferBuilderImpl { /// called. uint8_t *ReleaseRaw(size_t &size, size_t &offset) { Finished(); - uint8_t* raw = buf_.release_raw(size, offset); + uint8_t *raw = buf_.release_raw(size, offset); Clear(); return raw; } @@ -561,7 +562,7 @@ template class FlatBufferBuilderImpl { return CreateString(str.c_str(), str.length()); } -// clang-format off + // clang-format off #ifdef FLATBUFFERS_HAS_STRING_VIEW /// @brief Store a string in the buffer, which can contain any binary data. /// @param[in] str A const string_view to copy in to the buffer. @@ -743,7 +744,7 @@ template class FlatBufferBuilderImpl { AssertScalarT(); StartVector(len); if (len > 0) { -// clang-format off + // clang-format off #if FLATBUFFERS_LITTLEENDIAN PushBytes(reinterpret_cast(v), len * sizeof(T)); #else @@ -1470,7 +1471,8 @@ T *GetMutableTemporaryPointer(FlatBufferBuilder &fbb, Offset offset) { template const T *GetTemporaryPointer(const FlatBufferBuilder &fbb, Offset offset) { - return GetMutableTemporaryPointer(fbb, offset); + return reinterpret_cast(fbb.GetCurrentBufferPointer() + + fbb.GetSize() - offset.o); } } // namespace flatbuffers diff --git a/third_party/flatbuffers/include/flatbuffers/flexbuffers.h b/third_party/flatbuffers/include/flatbuffers/flexbuffers.h index f262558e4cb..c4bbbbc54a1 100644 --- a/third_party/flatbuffers/include/flatbuffers/flexbuffers.h +++ b/third_party/flatbuffers/include/flatbuffers/flexbuffers.h @@ -367,7 +367,8 @@ inline void IndentString(std::string &s, int indent, template void AppendToString(std::string &s, T &&v, bool keys_quoted, bool indented, - int cur_indent, const char *indent_string) { + int cur_indent, const char *indent_string, + bool natural_utf8) { s += "["; s += indented ? "\n" : " "; for (size_t i = 0; i < v.size(); i++) { @@ -377,7 +378,7 @@ void AppendToString(std::string &s, T &&v, bool keys_quoted, bool indented, } if (indented) IndentString(s, cur_indent, indent_string); v[i].ToString(true, keys_quoted, s, indented, cur_indent, - indent_string); + indent_string, natural_utf8); } if (indented) { s += "\n"; @@ -567,23 +568,24 @@ class Reference { // string values at the top level receive "" quotes (inside other values // they always do). keys_quoted determines if keys are quoted, at any level. void ToString(bool strings_quoted, bool keys_quoted, std::string &s) const { - ToString(strings_quoted, keys_quoted, s, false, 0, ""); + ToString(strings_quoted, keys_quoted, s, false, 0, "", false); } // This version additionally allow you to specify if you want indentation. void ToString(bool strings_quoted, bool keys_quoted, std::string &s, - bool indented, int cur_indent, const char *indent_string) const { + bool indented, int cur_indent, const char *indent_string, + bool natural_utf8 = false) const { if (type_ == FBT_STRING) { String str(Indirect(), byte_width_); if (strings_quoted) { - flatbuffers::EscapeString(str.c_str(), str.length(), &s, true, false); + flatbuffers::EscapeString(str.c_str(), str.length(), &s, true, natural_utf8); } else { s.append(str.c_str(), str.length()); } } else if (IsKey()) { auto str = AsKey(); if (keys_quoted) { - flatbuffers::EscapeString(str, strlen(str), &s, true, false); + flatbuffers::EscapeString(str, strlen(str), &s, true, natural_utf8); } else { s += str; } @@ -623,7 +625,8 @@ class Reference { if (indented) IndentString(s, cur_indent + 1, indent_string); keys[i].ToString(true, kq, s); s += ": "; - vals[i].ToString(true, keys_quoted, s, indented, cur_indent + 1, indent_string); + vals[i].ToString(true, keys_quoted, s, indented, cur_indent + 1, indent_string, + natural_utf8); if (i < keys.size() - 1) { s += ","; if (!indented) s += " "; @@ -635,13 +638,15 @@ class Reference { s += "}"; } else if (IsVector()) { AppendToString(s, AsVector(), keys_quoted, indented, - cur_indent + 1, indent_string); + cur_indent + 1, indent_string, natural_utf8); } else if (IsTypedVector()) { AppendToString(s, AsTypedVector(), keys_quoted, indented, - cur_indent + 1, indent_string); + cur_indent + 1, indent_string, + natural_utf8); } else if (IsFixedTypedVector()) { AppendToString(s, AsFixedTypedVector(), keys_quoted, - indented, cur_indent + 1, indent_string); + indented, cur_indent + 1, indent_string, + natural_utf8); } else if (IsBlob()) { auto blob = AsBlob(); flatbuffers::EscapeString(reinterpret_cast(blob.data()), diff --git a/third_party/flatbuffers/include/flatbuffers/idl.h b/third_party/flatbuffers/include/flatbuffers/idl.h index a08db9bb658..c84999a5485 100644 --- a/third_party/flatbuffers/include/flatbuffers/idl.h +++ b/third_party/flatbuffers/include/flatbuffers/idl.h @@ -22,6 +22,7 @@ #include #include #include +#include #include "flatbuffers/base.h" #include "flatbuffers/flatbuffers.h" @@ -705,8 +706,26 @@ struct IDLOptions { bool no_leak_private_annotations; bool require_json_eof; bool keep_proto_id; + + /********************************** Python **********************************/ bool python_no_type_prefix_suffix; bool python_typing; + + // The target Python version. Can be one of the following: + // - "0" + // - "2" + // - "3" + // - "2." + // - "3." + // - "2.." + // - "3.." + // + // https://docs.python.org/3/faq/general.html#how-does-the-python-version-numbering-scheme-work + std::string python_version; + + // Whether to generate numpy helpers. + bool python_gen_numpy; + bool ts_omit_entrypoint; ProtoIdGapAction proto_id_gap_action; @@ -759,6 +778,15 @@ struct IDLOptions { // make the flatbuffer more compact. bool set_empty_vectors_to_null; + /*********************************** gRPC ***********************************/ + std::string grpc_filename_suffix; + bool grpc_use_system_headers; + std::string grpc_search_path; + std::vector grpc_additional_headers; + + /******************************* Python gRPC ********************************/ + bool grpc_python_typed_handlers; + IDLOptions() : gen_jvmstatic(false), use_flexbuffers(false), @@ -821,6 +849,7 @@ struct IDLOptions { keep_proto_id(false), python_no_type_prefix_suffix(false), python_typing(false), + python_gen_numpy(true), ts_omit_entrypoint(false), proto_id_gap_action(ProtoIdGapAction::WARNING), mini_reflect(IDLOptions::kNone), @@ -829,7 +858,10 @@ struct IDLOptions { rust_module_root_file(false), lang_to_generate(0), set_empty_strings_to_null(true), - set_empty_vectors_to_null(true) {} + set_empty_vectors_to_null(true), + grpc_filename_suffix(".fb"), + grpc_use_system_headers(true), + grpc_python_typed_handlers(false) {} }; // This encapsulates where the parser is in the current source file. diff --git a/third_party/flatbuffers/include/flatbuffers/reflection_generated.h b/third_party/flatbuffers/include/flatbuffers/reflection_generated.h index 3e865ec15bc..ca673b1b6b6 100644 --- a/third_party/flatbuffers/include/flatbuffers/reflection_generated.h +++ b/third_party/flatbuffers/include/flatbuffers/reflection_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); namespace reflection { diff --git a/third_party/flatbuffers/include/flatbuffers/stl_emulation.h b/third_party/flatbuffers/include/flatbuffers/stl_emulation.h index 5f19eaf8d41..67c6768cbf2 100644 --- a/third_party/flatbuffers/include/flatbuffers/stl_emulation.h +++ b/third_party/flatbuffers/include/flatbuffers/stl_emulation.h @@ -273,7 +273,7 @@ template FLATBUFFERS_CONSTEXPR_CPP11 bool operator==(const Optional& lhs, const Optional& rhs) FLATBUFFERS_NOEXCEPT { return static_cast(lhs) != static_cast(rhs) ? false - : !static_cast(lhs) ? false : (*lhs == *rhs); + : !static_cast(lhs) ? true : (*lhs == *rhs); } #endif // FLATBUFFERS_USE_STD_OPTIONAL diff --git a/third_party/flatbuffers/include/flatbuffers/vector.h b/third_party/flatbuffers/include/flatbuffers/vector.h index ae52b9382c2..021b3c3fe54 100644 --- a/third_party/flatbuffers/include/flatbuffers/vector.h +++ b/third_party/flatbuffers/include/flatbuffers/vector.h @@ -56,12 +56,24 @@ struct VectorIterator { return data_ == other.data_; } + bool operator!=(const VectorIterator &other) const { + return data_ != other.data_; + } + bool operator<(const VectorIterator &other) const { return data_ < other.data_; } - bool operator!=(const VectorIterator &other) const { - return data_ != other.data_; + bool operator>(const VectorIterator &other) const { + return data_ > other.data_; + } + + bool operator<=(const VectorIterator &other) const { + return !(data_ > other.data_); + } + + bool operator>=(const VectorIterator &other) const { + return !(data_ < other.data_); } difference_type operator-(const VectorIterator &other) const { @@ -163,6 +175,11 @@ template class Vector { SizeT size() const { return EndianScalar(length_); } + // Returns true if the vector is empty. + // + // This just provides another standardized method that is expected of vectors. + bool empty() const { return size() == 0; } + // Deprecated: use size(). Here for backwards compatibility. FLATBUFFERS_ATTRIBUTE([[deprecated("use size() instead")]]) SizeT Length() const { return size(); } diff --git a/third_party/flatbuffers/include/flatbuffers/verifier.h b/third_party/flatbuffers/include/flatbuffers/verifier.h index de1146be92e..6df923be45c 100644 --- a/third_party/flatbuffers/include/flatbuffers/verifier.h +++ b/third_party/flatbuffers/include/flatbuffers/verifier.h @@ -23,7 +23,8 @@ namespace flatbuffers { // Helper class to verify the integrity of a FlatBuffer -class Verifier FLATBUFFERS_FINAL_CLASS { +template +class VerifierTemplate FLATBUFFERS_FINAL_CLASS { public: struct Options { // The maximum nesting of tables and vectors before we call it invalid. @@ -40,17 +41,18 @@ class Verifier FLATBUFFERS_FINAL_CLASS { bool assert = false; }; - explicit Verifier(const uint8_t *const buf, const size_t buf_len, - const Options &opts) + explicit VerifierTemplate(const uint8_t *const buf, const size_t buf_len, + const Options &opts) : buf_(buf), size_(buf_len), opts_(opts) { FLATBUFFERS_ASSERT(size_ < opts.max_size); } - // Deprecated API, please construct with Verifier::Options. - Verifier(const uint8_t *const buf, const size_t buf_len, - const uoffset_t max_depth = 64, const uoffset_t max_tables = 1000000, - const bool check_alignment = true) - : Verifier(buf, buf_len, [&] { + // Deprecated API, please construct with VerifierTemplate::Options. + VerifierTemplate(const uint8_t *const buf, const size_t buf_len, + const uoffset_t max_depth = 64, + const uoffset_t max_tables = 1000000, + const bool check_alignment = true) + : VerifierTemplate(buf, buf_len, [&] { Options opts; opts.max_depth = max_depth; opts.max_tables = max_tables; @@ -62,25 +64,25 @@ class Verifier FLATBUFFERS_FINAL_CLASS { bool Check(const bool ok) const { // clang-format off #ifdef FLATBUFFERS_DEBUG_VERIFICATION_FAILURE - if (opts_.assert) { FLATBUFFERS_ASSERT(ok); } - #endif - #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE - if (!ok) - upper_bound_ = 0; + if (opts_.assert) { FLATBUFFERS_ASSERT(ok); } #endif // clang-format on + if (TrackVerifierBufferSize) { + if (!ok) { + upper_bound_ = 0; + } + } return ok; } // Verify any range within the buffer. bool Verify(const size_t elem, const size_t elem_len) const { - // clang-format off - #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE + if (TrackVerifierBufferSize) { auto upper_bound = elem + elem_len; - if (upper_bound_ < upper_bound) + if (upper_bound_ < upper_bound) { upper_bound_ = upper_bound; - #endif - // clang-format on + } + } return Check(elem_len < size_ && elem <= size_ - elem_len); } @@ -210,14 +212,14 @@ class Verifier FLATBUFFERS_FINAL_CLASS { // Call T::Verify, which must be in the generated code for this type. const auto o = VerifyOffset(start); - return Check(o != 0) && - reinterpret_cast(buf_ + start + o)->Verify(*this) - // clang-format off - #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE - && GetComputedSize() - #endif - ; - // clang-format on + if (!Check(o != 0)) return false; + if (!(reinterpret_cast(buf_ + start + o)->Verify(*this))) { + return false; + } + if (TrackVerifierBufferSize) { + if (GetComputedSize() == 0) return false; + } + return true; } template @@ -232,7 +234,8 @@ class Verifier FLATBUFFERS_FINAL_CLASS { // If there is a nested buffer, it must be greater than the min size. if (!Check(buf->size() >= FLATBUFFERS_MIN_BUFFER_SIZE)) return false; - Verifier nested_verifier(buf->data(), buf->size(), opts_); + VerifierTemplate nested_verifier( + buf->data(), buf->size(), opts_); return nested_verifier.VerifyBuffer(identifier); } @@ -286,21 +289,27 @@ class Verifier FLATBUFFERS_FINAL_CLASS { return true; } - // Returns the message size in bytes + // Returns the message size in bytes. + // + // This should only be called after first calling VerifyBuffer or + // VerifySizePrefixedBuffer. + // + // This method should only be called for VerifierTemplate instances + // where the TrackVerifierBufferSize template parameter is true, + // i.e. for SizeVerifier. For instances where TrackVerifierBufferSize + // is false, this fails at runtime or returns zero. size_t GetComputedSize() const { - // clang-format off - #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE + if (TrackVerifierBufferSize) { uintptr_t size = upper_bound_; // Align the size to uoffset_t size = (size - 1 + sizeof(uoffset_t)) & ~(sizeof(uoffset_t) - 1); return (size > size_) ? 0 : size; - #else - // Must turn on FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE for this to work. - (void)upper_bound_; - FLATBUFFERS_ASSERT(false); - return 0; - #endif - // clang-format on + } + // Must use SizeVerifier, or (deprecated) turn on + // FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE, for this to work. + (void)upper_bound_; + FLATBUFFERS_ASSERT(false); + return 0; } std::vector *GetFlexReuseTracker() { return flex_reuse_tracker_; } @@ -323,10 +332,33 @@ class Verifier FLATBUFFERS_FINAL_CLASS { // Specialization for 64-bit offsets. template<> -inline size_t Verifier::VerifyOffset(const size_t start) const { +template<> +inline size_t VerifierTemplate::VerifyOffset( + const size_t start) const { + return VerifyOffset(start); +} +template<> +template<> +inline size_t VerifierTemplate::VerifyOffset( + const size_t start) const { return VerifyOffset(start); } +// Instance of VerifierTemplate that supports GetComputedSize(). +using SizeVerifier = VerifierTemplate; + +// The FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE build configuration macro is +// deprecated, and should not be defined, since it is easy to misuse in ways +// that result in ODR violations. Rather than using Verifier and defining +// FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE, please use SizeVerifier instead. +#ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE // Deprecated, see above. +using Verifier = SizeVerifier; +#else +// Instance of VerifierTemplate that is slightly faster, but does not +// support GetComputedSize(). +using Verifier = VerifierTemplate; +#endif + } // namespace flatbuffers #endif // FLATBUFFERS_VERIFIER_H_ diff --git a/third_party/flatbuffers/java/pom.xml b/third_party/flatbuffers/java/pom.xml new file mode 100644 index 00000000000..48c6e20d8ec --- /dev/null +++ b/third_party/flatbuffers/java/pom.xml @@ -0,0 +1,197 @@ + + + 4.0.0 + com.google.flatbuffers + flatbuffers-java + 25.2.10 + bundle + FlatBuffers Java API + + Memory Efficient Serialization Library + + + + Wouter van Oortmerssen + + + Derek Bailey + dbaileychess@gmail.com + + + + UTF-8 + + https://github.com/google/flatbuffers + + + Apache License V2.0 + https://raw.githubusercontent.com/google/flatbuffers/master/LICENSE + repo + + + + https://github.com/google/flatbuffers + + scm:git:https://github.com/google/flatbuffers.git + + HEAD + + + + junit + junit + 4.13.1 + test + + + com.google.truth + truth + 1.1.3 + test + + + + + ossrh + https://oss.sonatype.org/content/repositories/snapshots + + + + + + maven-surefire-plugin + + + **/*Test.java + + + 2.22.2 + + + org.apache.maven.plugins + maven-source-plugin + 3.2.1 + + + attach-sources + + jar + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 3.3.0 + + -Xdoclint:none + -Xdoclint:none + + + + attach-javadocs + + jar + + + + + + org.apache.felix + maven-bundle-plugin + 5.1.2 + true + + + org.sonatype.plugins + nexus-staging-maven-plugin + 1.6.8 + true + + ossrh + https://oss.sonatype.org/ + true + + + + org.apache.maven.plugins + maven-gpg-plugin + 3.0.1 + + + sign-artifacts + verify + + sign + + + + --pinentry-mode + loopback + + + + + + + org.apache.maven.plugins + maven-release-plugin + 2.5.3 + + true + false + release + deploy + + + + + + + jdk9 + + [1.9,) + + + + + maven-compiler-plugin + + 8 + + MyGame/Example/MonsterStorageGrpc.java + MyGame/OtherNameSpace/TableBT.java + + + 3.8.1 + + + + + + jdk8 + + 1.8 + + + 8 + 8 + + + + + maven-compiler-plugin + + + MyGame/Example/MonsterStorageGrpc.java + MyGame/OtherNameSpace/TableBT.java + + + 3.8.1 + + + + + + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ArrayReadWriteBuf.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ArrayReadWriteBuf.java new file mode 100644 index 00000000000..b7573d6e10c --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ArrayReadWriteBuf.java @@ -0,0 +1,252 @@ +package com.google.flatbuffers; + +import java.util.Arrays; + +/** + * Implements {@code ReadBuf} using an array of bytes + * as a backing storage. Using array of bytes are + * usually faster than {@code ByteBuffer}. + * + * This class is not thread-safe, meaning that + * it must operate on a single thread. Operating from + * multiple thread leads into a undefined behavior + */ +public class ArrayReadWriteBuf implements ReadWriteBuf { + + private byte[] buffer; + private int writePos; + + public ArrayReadWriteBuf() { + this(10); + } + + public ArrayReadWriteBuf(int initialCapacity) { + this(new byte[initialCapacity]); + } + + public ArrayReadWriteBuf(byte[] buffer) { + this.buffer = buffer; + this.writePos = 0; + } + + public ArrayReadWriteBuf(byte[] buffer, int startPos) { + this.buffer = buffer; + this.writePos = startPos; + } + + @Override + public void clear() { + this.writePos = 0; + } + + @Override + public boolean getBoolean(int index) { + return buffer[index] != 0; + } + + @Override + public byte get(int index) { + return buffer[index]; + } + + @Override + public short getShort(int index) { + return (short) ((buffer[index+ 1] << 8) | (buffer[index] & 0xff)); + } + + @Override + public int getInt(int index) { + return (((buffer[index + 3]) << 24) | + ((buffer[index + 2] & 0xff) << 16) | + ((buffer[index + 1] & 0xff) << 8) | + ((buffer[index] & 0xff))); + } + + @Override + public long getLong(int index) { + return ((((long) buffer[index++] & 0xff)) | + (((long) buffer[index++] & 0xff) << 8) | + (((long) buffer[index++] & 0xff) << 16) | + (((long) buffer[index++] & 0xff) << 24) | + (((long) buffer[index++] & 0xff) << 32) | + (((long) buffer[index++] & 0xff) << 40) | + (((long) buffer[index++] & 0xff) << 48) | + (((long) buffer[index]) << 56)); + } + + @Override + public float getFloat(int index) { + return Float.intBitsToFloat(getInt(index)); + } + + @Override + public double getDouble(int index) { + return Double.longBitsToDouble(getLong(index)); + } + + @Override + public String getString(int start, int size) { + return Utf8Safe.decodeUtf8Array(buffer, start, size); + } + + @Override + public byte[] data() { + return buffer; + } + + + @Override + public void putBoolean(boolean value) { + setBoolean(writePos, value); + writePos++; + } + + @Override + public void put(byte[] value, int start, int length) { + set(writePos, value, start, length); + writePos+=length; + } + + @Override + public void put(byte value) { + set(writePos, value); + writePos++; + } + + @Override + public void putShort(short value) { + setShort(writePos, value); + writePos +=2; + } + + @Override + public void putInt(int value) { + setInt(writePos, value); + writePos +=4; + } + + @Override + public void putLong(long value) { + setLong(writePos, value); + writePos +=8; + } + + @Override + public void putFloat(float value) { + setFloat(writePos, value); + writePos +=4; + } + + @Override + public void putDouble(double value) { + setDouble(writePos, value); + writePos +=8; + } + + @Override + public void setBoolean(int index, boolean value) { + set(index, value ? (byte)1 : (byte)0); + } + + @Override + public void set(int index, byte value) { + requestCapacity(index + 1); + buffer[index] = value; + } + + @Override + public void set(int index, byte[] toCopy, int start, int length) { + requestCapacity(index + (length - start)); + System.arraycopy(toCopy, start, buffer, index, length); + } + + @Override + public void setShort(int index, short value) { + requestCapacity(index + 2); + + buffer[index++] = (byte) ((value) & 0xff); + buffer[index ] = (byte) ((value >> 8) & 0xff); + } + + @Override + public void setInt(int index, int value) { + requestCapacity(index + 4); + + buffer[index++] = (byte) ((value) & 0xff); + buffer[index++] = (byte) ((value >> 8) & 0xff); + buffer[index++] = (byte) ((value >> 16) & 0xff); + buffer[index ] = (byte) ((value >> 24) & 0xff); + } + + @Override + public void setLong(int index, long value) { + requestCapacity(index + 8); + + int i = (int) value; + buffer[index++] = (byte) ((i) & 0xff); + buffer[index++] = (byte) ((i >> 8) & 0xff); + buffer[index++] = (byte) ((i >> 16) & 0xff); + buffer[index++] = (byte) ((i >> 24) & 0xff); + i = (int) (value >> 32); + buffer[index++] = (byte) ((i) & 0xff); + buffer[index++] = (byte) ((i >> 8) & 0xff); + buffer[index++] = (byte) ((i >> 16) & 0xff); + buffer[index ] = (byte) ((i >> 24) & 0xff); + } + + @Override + public void setFloat(int index, float value) { + requestCapacity(index + 4); + + int iValue = Float.floatToRawIntBits(value); + buffer[index++] = (byte) ((iValue) & 0xff); + buffer[index++] = (byte) ((iValue >> 8) & 0xff); + buffer[index++] = (byte) ((iValue >> 16) & 0xff); + buffer[index ] = (byte) ((iValue >> 24) & 0xff); + } + + @Override + public void setDouble(int index, double value) { + requestCapacity(index + 8); + + long lValue = Double.doubleToRawLongBits(value); + int i = (int) lValue; + buffer[index++] = (byte) ((i) & 0xff); + buffer[index++] = (byte) ((i >> 8) & 0xff); + buffer[index++] = (byte) ((i >> 16) & 0xff); + buffer[index++] = (byte) ((i >> 24) & 0xff); + i = (int) (lValue >> 32); + buffer[index++] = (byte) ((i) & 0xff); + buffer[index++] = (byte) ((i >> 8) & 0xff); + buffer[index++] = (byte) ((i >> 16) & 0xff); + buffer[index ] = (byte) ((i >> 24) & 0xff); + } + + @Override + public int limit() { + return writePos; + } + + @Override + public int writePosition() { + return writePos; + } + + @Override + public boolean requestCapacity(int capacity) { + if (capacity < 0) { + throw new IllegalArgumentException("Capacity may not be negative (likely a previous int overflow)"); + } + if (buffer.length >= capacity) { + return true; + } + // implemented in the same growing fashion as ArrayList + int oldCapacity = buffer.length; + int newCapacity = oldCapacity + (oldCapacity >> 1); + if (newCapacity < capacity) { // Note: this also catches newCapacity int overflow + newCapacity = capacity; + } + buffer = Arrays.copyOf(buffer, newCapacity); + return true; + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/BaseVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/BaseVector.java new file mode 100644 index 00000000000..9230da79d0b --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/BaseVector.java @@ -0,0 +1,96 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import java.nio.ByteBuffer; + +/// @cond FLATBUFFERS_INTERNAL + +/** + * All vector access objects derive from this class, and add their own accessors. + */ +public class BaseVector { + /** Used to hold the vector data position. */ + private int vector; + /** Used to hold the vector size. */ + private int length; + /** Used to hold the vector element size in table. */ + private int element_size; + /** The underlying ByteBuffer to hold the data of the vector. */ + protected ByteBuffer bb; + + /** + * Get the start data of a vector. + * + * @return Returns the start of the vector data. + */ + protected int __vector() { + return vector; + } + + /** + * Gets the element position in vector's ByteBuffer. + * + * @param j An `int` index of element into a vector. + * @return Returns the position of the vector element in a ByteBuffer. + */ + protected int __element(int j) { + return vector + j * element_size; + } + + /** + * Re-init the internal state with an external buffer {@code ByteBuffer}, an offset within and + * element size. + * + * This method exists primarily to allow recycling vector instances without risking memory leaks + * due to {@code ByteBuffer} references. + */ + protected void __reset(int _vector, int _element_size, ByteBuffer _bb) { + bb = _bb; + if (bb != null) { + vector = _vector; + length = bb.getInt(_vector - Constants.SIZEOF_INT); + element_size = _element_size; + } else { + vector = 0; + length = 0; + element_size = 0; + } + } + + /** + * Resets the internal state with a null {@code ByteBuffer} and a zero position. + * + * This method exists primarily to allow recycling vector instances without risking memory leaks + * due to {@code ByteBuffer} references. The instance will be unusable until it is assigned + * again to a {@code ByteBuffer}. + */ + public void reset() { + __reset(0, 0, null); + } + + /** + * Get the length of a vector. + * + * @return Returns the length of the vector. + */ + public int length() { + return length; + } +} + +/// @endcond diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/BooleanVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/BooleanVector.java new file mode 100644 index 00000000000..1c2a4cda35e --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/BooleanVector.java @@ -0,0 +1,49 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of booleans. + */ +public final class BooleanVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public BooleanVector __assign(int _vector, ByteBuffer _bb) { + __reset(_vector, Constants.SIZEOF_BYTE, _bb); return this; + } + + /** + * Reads the boolean at the given index. + * + * @param j The index from which the boolean will be read. + * @return the boolean value at the given index. + */ + public boolean get(int j) { + return 0 != bb.get(__element(j)); + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteBufferReadWriteBuf.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteBufferReadWriteBuf.java new file mode 100644 index 00000000000..aaf72fe8192 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteBufferReadWriteBuf.java @@ -0,0 +1,170 @@ +package com.google.flatbuffers; + +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class ByteBufferReadWriteBuf implements ReadWriteBuf { + + private final ByteBuffer buffer; + + public ByteBufferReadWriteBuf(ByteBuffer bb) { + this.buffer = bb; + this.buffer.order(ByteOrder.LITTLE_ENDIAN); + } + + @Override + public void clear() { + buffer.clear(); + } + + @Override + public boolean getBoolean(int index) { + return get(index) != 0; + } + + @Override + public byte get(int index) { + return buffer.get(index); + } + + @Override + public short getShort(int index) { + return buffer.getShort(index); + } + + @Override + public int getInt(int index) { + return buffer.getInt(index); + } + + @Override + public long getLong(int index) { + return buffer.getLong(index); + } + + @Override + public float getFloat(int index) { + return buffer.getFloat(index); + } + + @Override + public double getDouble(int index) { + return buffer.getDouble(index); + } + + @Override + public String getString(int start, int size) { + return Utf8Safe.decodeUtf8Buffer(buffer, start, size); + } + + @Override + public byte[] data() { + return buffer.array(); + } + + @Override + public void putBoolean(boolean value) { + buffer.put(value ? (byte)1 : (byte)0); + } + + @Override + public void put(byte[] value, int start, int length) { + buffer.put(value, start, length); + } + + @Override + public void put(byte value) { + buffer.put(value); + } + + @Override + public void putShort(short value) { + buffer.putShort(value); + } + + @Override + public void putInt(int value) { + buffer.putInt(value); + } + + @Override + public void putLong(long value) { + buffer.putLong(value); + } + + @Override + public void putFloat(float value) { + buffer.putFloat(value); + } + + @Override + public void putDouble(double value) { + buffer.putDouble(value); + } + + @Override + public void setBoolean(int index, boolean value) { + set(index, value ? (byte)1 : (byte)0); + } + + @Override + public void set(int index, byte value) { + requestCapacity(index + 1); + buffer.put(index, value); + } + + @Override + public void set(int index, byte[] value, int start, int length) { + requestCapacity(index + (length - start)); + int curPos = buffer.position(); + buffer.position(index); + buffer.put(value, start, length); + buffer.position(curPos); + } + + @Override + public void setShort(int index, short value) { + requestCapacity(index + 2); + buffer.putShort(index, value); + } + + @Override + public void setInt(int index, int value) { + requestCapacity(index + 4); + buffer.putInt(index, value); + } + + @Override + public void setLong(int index, long value) { + requestCapacity(index + 8); + buffer.putLong(index, value); + } + + @Override + public void setFloat(int index, float value) { + requestCapacity(index + 4); + buffer.putFloat(index, value); + } + + @Override + public void setDouble(int index, double value) { + requestCapacity(index + 8); + buffer.putDouble(index, value); + } + + @Override + public int writePosition() { + return buffer.position(); + } + + @Override + public int limit() { + return buffer.limit(); + } + + @Override + public boolean requestCapacity(int capacity) { + return capacity <= buffer.limit(); + } + +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteBufferUtil.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteBufferUtil.java new file mode 100644 index 00000000000..624dc4e2f7c --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteBufferUtil.java @@ -0,0 +1,58 @@ +/* + * Copyright 2017 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; + +import java.nio.ByteBuffer; + +/// @file +/// @addtogroup flatbuffers_java_api +/// @{ + +/** + * Class that collects utility functions around `ByteBuffer`. + */ +public class ByteBufferUtil { + + /** + * Extract the size prefix from a `ByteBuffer`. + * + * @param bb a size-prefixed buffer + * @return the size prefix + */ + public static int getSizePrefix(ByteBuffer bb) { + return bb.getInt(bb.position()); + } + + /** + * Create a duplicate of a size-prefixed `ByteBuffer` that has its position + * advanced just past the size prefix. + * + * @param bb a size-prefixed buffer + * @return a new buffer on the same underlying data that has skipped the + * size prefix + */ + public static ByteBuffer removeSizePrefix(ByteBuffer bb) { + ByteBuffer s = bb.duplicate(); + s.position(s.position() + SIZE_PREFIX_LENGTH); + return s; + } + +} + +/// @} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteVector.java new file mode 100644 index 00000000000..8bc715b3c02 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ByteVector.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of signed or unsigned 8-bit values. + */ +public final class ByteVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param vector Start data of a vector. + * @param bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public ByteVector __assign(int vector, ByteBuffer bb) { + __reset(vector, Constants.SIZEOF_BYTE, bb); return this; + } + + /** + * Reads the byte at the given index. + * + * @param j The index from which the byte will be read. + * @return the 8-bit value at the given index. + */ + public byte get(int j) { + return bb.get(__element(j)); + } + + /** + * Reads the byte at the given index, zero-extends it to type int, and returns the result, + * which is therefore in the range 0 through 255. + * + * @param j The index from which the byte will be read. + * @return the unsigned 8-bit at the given index. + */ + public int getAsUnsigned(int j) { + return (int) get(j) & 0xFF; + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Constants.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Constants.java new file mode 100644 index 00000000000..cb505f4e28f --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Constants.java @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +/// @cond FLATBUFFERS_INTERNAL + +/** + * Class that holds shared constants + */ +public class Constants { + // Java doesn't seem to have these. + /** The number of bytes in an `byte`. */ + static final int SIZEOF_BYTE = 1; + /** The number of bytes in a `short`. */ + static final int SIZEOF_SHORT = 2; + /** The number of bytes in an `int`. */ + static final int SIZEOF_INT = 4; + /** The number of bytes in an `float`. */ + static final int SIZEOF_FLOAT = 4; + /** The number of bytes in an `long`. */ + static final int SIZEOF_LONG = 8; + /** The number of bytes in an `double`. */ + static final int SIZEOF_DOUBLE = 8; + /** The number of bytes in a file identifier. */ + static final int FILE_IDENTIFIER_LENGTH = 4; + /** The number of bytes in a size prefix. */ + public static final int SIZE_PREFIX_LENGTH = 4; + /** A version identifier to force a compile error if someone + accidentally tries to build generated code with a runtime of + two mismatched version. Versions need to always match, as + the runtime and generated code are modified in sync. + Changes to the Java implementation need to be sure to change + the version here and in the code generator on every possible + incompatible change */ + public static void FLATBUFFERS_25_2_10() {} +} + +/// @endcond diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/DoubleVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/DoubleVector.java new file mode 100644 index 00000000000..fd4a3a48a7a --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/DoubleVector.java @@ -0,0 +1,49 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of double values. + */ +public final class DoubleVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public DoubleVector __assign(int _vector, ByteBuffer _bb) { + __reset(_vector, Constants.SIZEOF_DOUBLE, _bb); return this; + } + + /** + * Reads the double value at the given index. + * + * @param j The index from which the double value will be read. + * @return the double value at the given index. + */ + public double get(int j) { + return bb.getDouble(__element(j)); + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlatBufferBuilder.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlatBufferBuilder.java new file mode 100644 index 00000000000..a954d9fbbd4 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlatBufferBuilder.java @@ -0,0 +1,1120 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; + +import java.io.IOException; +import java.io.InputStream; +import java.nio.*; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import java.lang.Integer; + +/// @file +/// @addtogroup flatbuffers_java_api +/// @{ + +/** + * Class that helps you build a FlatBuffer. See the section + * "Use in Java/C#" in the main FlatBuffers documentation. + */ +public class FlatBufferBuilder { + /// @cond FLATBUFFERS_INTERNAL + ByteBuffer bb; // Where we construct the FlatBuffer. + int space; // Remaining space in the ByteBuffer. + int minalign = 1; // Minimum alignment encountered so far. + int[] vtable = null; // The vtable for the current table. + int vtable_in_use = 0; // The amount of fields we're actually using. + boolean nested = false; // Whether we are currently serializing a table. + boolean finished = false; // Whether the buffer is finished. + int object_start; // Starting offset of the current struct/table. + int[] vtables = new int[16]; // List of offsets of all vtables. + int num_vtables = 0; // Number of entries in `vtables` in use. + int vector_num_elems = 0; // For the current vector being built. + boolean force_defaults = false; // False omits default values from the serialized data. + ByteBufferFactory bb_factory; // Factory for allocating the internal buffer + final Utf8 utf8; // UTF-8 encoder to use + Map string_pool; // map used to cache shared strings. + /// @endcond + + + /** + * Maximum size of buffer to allocate. If we're allocating arrays on the heap, + * the header size of the array counts towards its maximum size. + */ + private static final int MAX_BUFFER_SIZE = Integer.MAX_VALUE - 8; + + /** + * Default buffer size that is allocated if an initial size is not given, or is + * non positive. + */ + private static final int DEFAULT_BUFFER_SIZE = 1024; + + /** + * Start with a buffer of size `initial_size`, then grow as required. + * + * @param initial_size The initial size of the internal buffer to use. + * @param bb_factory The factory to be used for allocating the internal buffer + */ + public FlatBufferBuilder(int initial_size, ByteBufferFactory bb_factory) { + this(initial_size, bb_factory, null, Utf8.getDefault()); + } + + /** + * Start with a buffer of size `initial_size`, then grow as required. + * + * @param initial_size The initial size of the internal buffer to use. + * @param bb_factory The factory to be used for allocating the internal buffer + * @param existing_bb The byte buffer to reuse. + * @param utf8 The Utf8 codec + */ + public FlatBufferBuilder(int initial_size, ByteBufferFactory bb_factory, + ByteBuffer existing_bb, Utf8 utf8) { + if (initial_size <= 0) { + initial_size = DEFAULT_BUFFER_SIZE; + } + this.bb_factory = bb_factory; + if (existing_bb != null) { + bb = existing_bb; + bb.clear(); + bb.order(ByteOrder.LITTLE_ENDIAN); + } else { + bb = bb_factory.newByteBuffer(initial_size); + } + this.utf8 = utf8; + space = bb.capacity(); + } + + /** + * Start with a buffer of size `initial_size`, then grow as required. + * + * @param initial_size The initial size of the internal buffer to use. + */ + public FlatBufferBuilder(int initial_size) { + this(initial_size, HeapByteBufferFactory.INSTANCE, null, Utf8.getDefault()); + } + + /** + * Start with a buffer of 1KiB, then grow as required. + */ + public FlatBufferBuilder() { + this(DEFAULT_BUFFER_SIZE); + } + + /** + * Alternative constructor allowing reuse of {@link ByteBuffer}s. The builder + * can still grow the buffer as necessary. User classes should make sure + * to call {@link #dataBuffer()} to obtain the resulting encoded message. + * + * @param existing_bb The byte buffer to reuse. + * @param bb_factory The factory to be used for allocating a new internal buffer if + * the existing buffer needs to grow + */ + public FlatBufferBuilder(ByteBuffer existing_bb, ByteBufferFactory bb_factory) { + this(existing_bb.capacity(), bb_factory, existing_bb, Utf8.getDefault()); + } + + /** + * Alternative constructor allowing reuse of {@link ByteBuffer}s. The builder + * can still grow the buffer as necessary. User classes should make sure + * to call {@link #dataBuffer()} to obtain the resulting encoded message. + * + * @param existing_bb The byte buffer to reuse. + */ + public FlatBufferBuilder(ByteBuffer existing_bb) { + this(existing_bb, new HeapByteBufferFactory()); + } + + /** + * Alternative initializer that allows reusing this object on an existing + * `ByteBuffer`. This method resets the builder's internal state, but keeps + * objects that have been allocated for temporary storage. + * + * @param existing_bb The byte buffer to reuse. + * @param bb_factory The factory to be used for allocating a new internal buffer if + * the existing buffer needs to grow + * @return Returns `this`. + */ + public FlatBufferBuilder init(ByteBuffer existing_bb, ByteBufferFactory bb_factory){ + this.bb_factory = bb_factory; + bb = existing_bb; + bb.clear(); + bb.order(ByteOrder.LITTLE_ENDIAN); + minalign = 1; + space = bb.capacity(); + vtable_in_use = 0; + nested = false; + finished = false; + object_start = 0; + num_vtables = 0; + vector_num_elems = 0; + if (string_pool != null) { + string_pool.clear(); + } + return this; + } + + /** + * An interface that provides a user of the FlatBufferBuilder class the ability to specify + * the method in which the internal buffer gets allocated. This allows for alternatives + * to the default behavior, which is to allocate memory for a new byte-array + * backed `ByteBuffer` array inside the JVM. + * + * The FlatBufferBuilder class contains the HeapByteBufferFactory class to + * preserve the default behavior in the event that the user does not provide + * their own implementation of this interface. + */ + public static abstract class ByteBufferFactory { + /** + * Create a `ByteBuffer` with a given capacity. + * The returned ByteBuf must have a ByteOrder.LITTLE_ENDIAN ByteOrder. + * + * @param capacity The size of the `ByteBuffer` to allocate. + * @return Returns the new `ByteBuffer` that was allocated. + */ + public abstract ByteBuffer newByteBuffer(int capacity); + + /** + * Release a ByteBuffer. Current {@link FlatBufferBuilder} + * released any reference to it, so it is safe to dispose the buffer + * or return it to a pool. + * It is not guaranteed that the buffer has been created + * with {@link #newByteBuffer(int) }. + * + * @param bb the buffer to release + */ + public void releaseByteBuffer(ByteBuffer bb) { + } + } + + /** + * An implementation of the ByteBufferFactory interface that is used when + * one is not provided by the user. + * + * Allocate memory for a new byte-array backed `ByteBuffer` array inside the JVM. + */ + public static final class HeapByteBufferFactory extends ByteBufferFactory { + + public static final HeapByteBufferFactory INSTANCE = new HeapByteBufferFactory(); + + @Override + public ByteBuffer newByteBuffer(int capacity) { + return ByteBuffer.allocate(capacity).order(ByteOrder.LITTLE_ENDIAN); + } + } + + /** + * Helper function to test if a field is present in the table + * + * @param table Flatbuffer table + * @param offset virtual table offset + * @return true if the filed is present + */ + public static boolean isFieldPresent(Table table, int offset) { + return table.__offset(offset) != 0; + } + + /** + * Reset the FlatBufferBuilder by purging all data that it holds. + */ + public void clear(){ + space = bb.capacity(); + bb.clear(); + minalign = 1; + while(vtable_in_use > 0) vtable[--vtable_in_use] = 0; + vtable_in_use = 0; + nested = false; + finished = false; + object_start = 0; + num_vtables = 0; + vector_num_elems = 0; + if (string_pool != null) { + string_pool.clear(); + } + } + + /** + * Doubles the size of the backing {@link ByteBuffer} and copies the old data towards the + * end of the new buffer (since we build the buffer backwards). + * + * @param bb The current buffer with the existing data. + * @param bb_factory The factory to be used for allocating the new internal buffer + * @return A new byte buffer with the old data copied copied to it. The data is + * located at the end of the buffer. + */ + static ByteBuffer growByteBuffer(ByteBuffer bb, ByteBufferFactory bb_factory) { + int old_buf_size = bb.capacity(); + + int new_buf_size; + + if (old_buf_size == 0) { + new_buf_size = DEFAULT_BUFFER_SIZE; + } + else { + if (old_buf_size == MAX_BUFFER_SIZE) { // Ensure we don't grow beyond what fits in an int. + throw new AssertionError("FlatBuffers: cannot grow buffer beyond 2 gigabytes."); + } + new_buf_size = (old_buf_size & 0xC0000000) != 0 ? MAX_BUFFER_SIZE : old_buf_size << 1; + } + + bb.position(0); + ByteBuffer nbb = bb_factory.newByteBuffer(new_buf_size); + new_buf_size = nbb.clear().capacity(); // Ensure the returned buffer is treated as empty + nbb.position(new_buf_size - old_buf_size); + nbb.put(bb); + return nbb; + } + + /** + * Offset relative to the end of the buffer. + * + * @return Offset relative to the end of the buffer. + */ + public int offset() { + return bb.capacity() - space; + } + + /** + * Add zero valued bytes to prepare a new entry to be added. + * + * @param byte_size Number of bytes to add. + */ + public void pad(int byte_size) { + for (int i = 0; i < byte_size; i++) bb.put(--space, (byte)0); + } + + /** + * Prepare to write an element of `size` after `additional_bytes` + * have been written, e.g. if you write a string, you need to align such + * the int length field is aligned to {@link com.google.flatbuffers.Constants#SIZEOF_INT}, and + * the string data follows it directly. If all you need to do is alignment, `additional_bytes` + * will be 0. + * + * @param size This is the of the new element to write. + * @param additional_bytes The padding size. + */ + public void prep(int size, int additional_bytes) { + // Track the biggest thing we've ever aligned to. + if (size > minalign) minalign = size; + // Find the amount of alignment needed such that `size` is properly + // aligned after `additional_bytes` + int align_size = ((~(bb.capacity() - space + additional_bytes)) + 1) & (size - 1); + // Reallocate the buffer if needed. + while (space < align_size + size + additional_bytes) { + int old_buf_size = bb.capacity(); + ByteBuffer old = bb; + bb = growByteBuffer(old, bb_factory); + if (old != bb) { + bb_factory.releaseByteBuffer(old); + } + space += bb.capacity() - old_buf_size; + } + pad(align_size); + } + + /** + * Add a `boolean` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `boolean` to put into the buffer. + */ + public void putBoolean(boolean x) { bb.put (space -= Constants.SIZEOF_BYTE, (byte)(x ? 1 : 0)); } + + /** + * Add a `byte` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `byte` to put into the buffer. + */ + public void putByte (byte x) { bb.put (space -= Constants.SIZEOF_BYTE, x); } + + /** + * Add a `short` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `short` to put into the buffer. + */ + public void putShort (short x) { bb.putShort (space -= Constants.SIZEOF_SHORT, x); } + + /** + * Add an `int` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x An `int` to put into the buffer. + */ + public void putInt (int x) { bb.putInt (space -= Constants.SIZEOF_INT, x); } + + /** + * Add a `long` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `long` to put into the buffer. + */ + public void putLong (long x) { bb.putLong (space -= Constants.SIZEOF_LONG, x); } + + /** + * Add a `float` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `float` to put into the buffer. + */ + public void putFloat (float x) { bb.putFloat (space -= Constants.SIZEOF_FLOAT, x); } + + /** + * Add a `double` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `double` to put into the buffer. + */ + public void putDouble (double x) { bb.putDouble(space -= Constants.SIZEOF_DOUBLE, x); } + /// @endcond + + /** + * Add a `boolean` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `boolean` to put into the buffer. + */ + public void addBoolean(boolean x) { prep(Constants.SIZEOF_BYTE, 0); putBoolean(x); } + + /** + * Add a `byte` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `byte` to put into the buffer. + */ + public void addByte (byte x) { prep(Constants.SIZEOF_BYTE, 0); putByte (x); } + + /** + * Add a `short` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `short` to put into the buffer. + */ + public void addShort (short x) { prep(Constants.SIZEOF_SHORT, 0); putShort (x); } + + /** + * Add an `int` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x An `int` to put into the buffer. + */ + public void addInt (int x) { prep(Constants.SIZEOF_INT, 0); putInt (x); } + + /** + * Add a `long` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `long` to put into the buffer. + */ + public void addLong (long x) { prep(Constants.SIZEOF_LONG, 0); putLong (x); } + + /** + * Add a `float` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `float` to put into the buffer. + */ + public void addFloat (float x) { prep(Constants.SIZEOF_FLOAT, 0); putFloat (x); } + + /** + * Add a `double` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `double` to put into the buffer. + */ + public void addDouble (double x) { prep(Constants.SIZEOF_DOUBLE, 0); putDouble (x); } + + /** + * Adds on offset, relative to where it will be written. + * + * @param off The offset to add. + */ + public void addOffset(int off) { + prep(SIZEOF_INT, 0); // Ensure alignment is already done. + assert off <= offset(); + off = offset() - off + SIZEOF_INT; + putInt(off); + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * Start a new array/vector of objects. Users usually will not call + * this directly. The `FlatBuffers` compiler will create a start/end + * method for vector types in generated code. + *

+ * The expected sequence of calls is: + *

    + *
  1. Start the array using this method.
  2. + *
  3. Call {@link #addOffset(int)} `num_elems` number of times to set + * the offset of each element in the array.
  4. + *
  5. Call {@link #endVector()} to retrieve the offset of the array.
  6. + *
+ *

+ * For example, to create an array of strings, do: + *

{@code
+    * // Need 10 strings
+    * FlatBufferBuilder builder = new FlatBufferBuilder(existingBuffer);
+    * int[] offsets = new int[10];
+    *
+    * for (int i = 0; i < 10; i++) {
+    *   offsets[i] = fbb.createString(" " + i);
+    * }
+    *
+    * // Have the strings in the buffer, but don't have a vector.
+    * // Add a vector that references the newly created strings:
+    * builder.startVector(4, offsets.length, 4);
+    *
+    * // Add each string to the newly created vector
+    * // The strings are added in reverse order since the buffer
+    * // is filled in back to front
+    * for (int i = offsets.length - 1; i >= 0; i--) {
+    *   builder.addOffset(offsets[i]);
+    * }
+    *
+    * // Finish off the vector
+    * int offsetOfTheVector = fbb.endVector();
+    * }
+ * + * @param elem_size The size of each element in the array. + * @param num_elems The number of elements in the array. + * @param alignment The alignment of the array. + */ + public void startVector(int elem_size, int num_elems, int alignment) { + notNested(); + vector_num_elems = num_elems; + prep(SIZEOF_INT, elem_size * num_elems); + prep(alignment, elem_size * num_elems); // Just in case alignment > int. + nested = true; + } + + /** + * Finish off the creation of an array and all its elements. The array + * must be created with {@link #startVector(int, int, int)}. + * + * @return The offset at which the newly created array starts. + * @see #startVector(int, int, int) + */ + public int endVector() { + if (!nested) + throw new AssertionError("FlatBuffers: endVector called without startVector"); + nested = false; + putInt(vector_num_elems); + return offset(); + } + /// @endcond + + /** + * Create a new array/vector and return a ByteBuffer to be filled later. + * Call {@link #endVector} after this method to get an offset to the beginning + * of vector. + * + * @param elem_size the size of each element in bytes. + * @param num_elems number of elements in the vector. + * @param alignment byte alignment. + * @return ByteBuffer with position and limit set to the space allocated for the array. + */ + public ByteBuffer createUnintializedVector(int elem_size, int num_elems, int alignment) { + int length = elem_size * num_elems; + startVector(elem_size, num_elems, alignment); + + bb.position(space -= length); + + // Slice and limit the copy vector to point to the 'array' + ByteBuffer copy = bb.slice().order(ByteOrder.LITTLE_ENDIAN); + copy.limit(length); + return copy; + } + + /** + * Create a vector of tables. + * + * @param offsets Offsets of the tables. + * @return Returns offset of the vector. + */ + public int createVectorOfTables(int[] offsets) { + notNested(); + startVector(Constants.SIZEOF_INT, offsets.length, Constants.SIZEOF_INT); + for(int i = offsets.length - 1; i >= 0; i--) addOffset(offsets[i]); + return endVector(); + } + + /** + * Create a vector of sorted by the key tables. + * + * @param obj Instance of the table subclass. + * @param offsets Offsets of the tables. + * @return Returns offset of the sorted vector. + */ + public int createSortedVectorOfTables(T obj, int[] offsets) { + obj.sortTables(offsets, bb); + return createVectorOfTables(offsets); + } + + /** + * Encode the String `s` in the buffer using UTF-8. If a String with + * this exact contents has already been serialized using this method, + * instead simply returns the offset of the existing String. + * + * Usage of the method will incur into additional allocations, + * so it is advisable to use it only when it is known upfront that + * your message will have several repeated strings. + * + * @param s The String to encode. + * @return The offset in the buffer where the encoded String starts. + */ + public int createSharedString(String s) { + + if (string_pool == null) { + string_pool = new HashMap<>(); + int offset = createString(s); + string_pool.put(s, offset); + return offset; + + } + + Integer offset = string_pool.get(s); + + if(offset == null) { + offset = createString(s); + string_pool.put(s, offset); + } + return offset; + } + + /** + * Encode the string `s` in the buffer using UTF-8. If {@code s} is + * already a {@link CharBuffer}, this method is allocation free. + * + * @param s The string to encode. + * @return The offset in the buffer where the encoded string starts. + */ + public int createString(CharSequence s) { + int length = utf8.encodedLength(s); + addByte((byte)0); + startVector(1, length, 1); + bb.position(space -= length); + utf8.encodeUtf8(s, bb); + return endVector(); + } + + /** + * Create a string in the buffer from an already encoded UTF-8 string in a ByteBuffer. + * + * @param s An already encoded UTF-8 string as a `ByteBuffer`. + * @return The offset in the buffer where the encoded string starts. + */ + public int createString(ByteBuffer s) { + int length = s.remaining(); + addByte((byte)0); + startVector(1, length, 1); + bb.position(space -= length); + bb.put(s); + return endVector(); + } + + /** + * Create a byte array in the buffer. + * + * @param arr A source array with data + * @return The offset in the buffer where the encoded array starts. + */ + public int createByteVector(byte[] arr) { + int length = arr.length; + startVector(1, length, 1); + bb.position(space -= length); + bb.put(arr); + return endVector(); + } + + /** + * Create a byte array in the buffer. + * + * @param arr a source array with data. + * @param offset the offset in the source array to start copying from. + * @param length the number of bytes to copy from the source array. + * @return The offset in the buffer where the encoded array starts. + */ + public int createByteVector(byte[] arr, int offset, int length) { + startVector(1, length, 1); + bb.position(space -= length); + bb.put(arr, offset, length); + return endVector(); + } + + /** + * Create a byte array in the buffer. + * + * The source {@link ByteBuffer} position is advanced by {@link ByteBuffer#remaining()} places + * after this call. + * + * @param byteBuffer A source {@link ByteBuffer} with data. + * @return The offset in the buffer where the encoded array starts. + */ + public int createByteVector(ByteBuffer byteBuffer) { + int length = byteBuffer.remaining(); + startVector(1, length, 1); + bb.position(space -= length); + bb.put(byteBuffer); + return endVector(); + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * Should not be accessing the final buffer before it is finished. + */ + public void finished() { + if (!finished) + throw new AssertionError( + "FlatBuffers: you can only access the serialized buffer after it has been" + + " finished by FlatBufferBuilder.finish()."); + } + + /** + * Should not be creating any other object, string or vector + * while an object is being constructed. + */ + public void notNested() { + if (nested) + throw new AssertionError("FlatBuffers: object serialization must not be nested."); + } + + /** + * Structures are always stored inline, they need to be created right + * where they're used. You'll get this assertion failure if you + * created it elsewhere. + * + * @param obj The offset of the created object. + */ + public void Nested(int obj) { + if (obj != offset()) + throw new AssertionError("FlatBuffers: struct must be serialized inline."); + } + + /** + * Start encoding a new object in the buffer. Users will not usually need to + * call this directly. The `FlatBuffers` compiler will generate helper methods + * that call this method internally. + *

+ * For example, using the "Monster" code found on the "landing page". An + * object of type `Monster` can be created using the following code: + * + *

{@code
+    * int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] {
+    *   fbb.createString("test1"),
+    *   fbb.createString("test2")
+    * });
+    *
+    * Monster.startMonster(fbb);
+    * Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
+    *   Color.Green, (short)5, (byte)6));
+    * Monster.addHp(fbb, (short)80);
+    * Monster.addName(fbb, str);
+    * Monster.addInventory(fbb, inv);
+    * Monster.addTestType(fbb, (byte)Any.Monster);
+    * Monster.addTest(fbb, mon2);
+    * Monster.addTest4(fbb, test4);
+    * Monster.addTestarrayofstring(fbb, testArrayOfString);
+    * int mon = Monster.endMonster(fbb);
+    * }
+ *

+ * Here: + *

    + *
  • The call to `Monster#startMonster(FlatBufferBuilder)` will call this + * method with the right number of fields set.
  • + *
  • `Monster#endMonster(FlatBufferBuilder)` will ensure {@link #endObject()} is called.
  • + *
+ *

+ * It's not recommended to call this method directly. If it's called manually, you must ensure + * to audit all calls to it whenever fields are added or removed from your schema. This is + * automatically done by the code generated by the `FlatBuffers` compiler. + * + * @param numfields The number of fields found in this object. + */ + public void startTable(int numfields) { + notNested(); + if (vtable == null || vtable.length < numfields) vtable = new int[numfields]; + vtable_in_use = numfields; + Arrays.fill(vtable, 0, vtable_in_use, 0); + nested = true; + object_start = offset(); + } + + /** + * Add a `boolean` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x A `boolean` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d A `boolean` default value to compare against when `force_defaults` is `false`. + */ + public void addBoolean(int o, boolean x, boolean d) { if(force_defaults || x != d) { addBoolean(x); slot(o); } } + + /** + * Add a `byte` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x A `byte` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d A `byte` default value to compare against when `force_defaults` is `false`. + */ + public void addByte (int o, byte x, int d) { if(force_defaults || x != d) { addByte (x); slot(o); } } + + /** + * Add a `short` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x A `short` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d A `short` default value to compare against when `force_defaults` is `false`. + */ + public void addShort (int o, short x, int d) { if(force_defaults || x != d) { addShort (x); slot(o); } } + + /** + * Add an `int` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x An `int` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d An `int` default value to compare against when `force_defaults` is `false`. + */ + public void addInt (int o, int x, int d) { if(force_defaults || x != d) { addInt (x); slot(o); } } + + /** + * Add a `long` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x A `long` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d A `long` default value to compare against when `force_defaults` is `false`. + */ + public void addLong (int o, long x, long d) { if(force_defaults || x != d) { addLong (x); slot(o); } } + + /** + * Add a `float` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x A `float` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d A `float` default value to compare against when `force_defaults` is `false`. + */ + public void addFloat (int o, float x, double d) { if(force_defaults || x != d) { addFloat (x); slot(o); } } + + /** + * Add a `double` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x A `double` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d A `double` default value to compare against when `force_defaults` is `false`. + */ + public void addDouble (int o, double x, double d) { if(force_defaults || x != d) { addDouble (x); slot(o); } } + + /** + * Add an `offset` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x An `offset` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d An `offset` default value to compare against when `force_defaults` is `false`. + */ + public void addOffset (int o, int x, int d) { if(force_defaults || x != d) { addOffset (x); slot(o); } } + + /** + * Add a struct to the table. Structs are stored inline, so nothing additional is being added. + * + * @param voffset The index into the vtable. + * @param x The offset of the created struct. + * @param d The default value is always `0`. + */ + public void addStruct(int voffset, int x, int d) { + if(x != d) { + Nested(x); + slot(voffset); + } + } + + /** + * Set the current vtable at `voffset` to the current location in the buffer. + * + * @param voffset The index into the vtable to store the offset relative to the end of the + * buffer. + */ + public void slot(int voffset) { + vtable[voffset] = offset(); + } + + /** + * Finish off writing the object that is under construction. + * + * @return The offset to the object inside {@link #dataBuffer()}. + * @see #startTable(int) + */ + public int endTable() { + if (vtable == null || !nested) + throw new AssertionError("FlatBuffers: endTable called without startTable"); + addInt(0); + int vtableloc = offset(); + // Write out the current vtable. + int i = vtable_in_use - 1; + // Trim trailing zeroes. + for (; i >= 0 && vtable[i] == 0; i--) {} + int trimmed_size = i + 1; + for (; i >= 0 ; i--) { + // Offset relative to the start of the table. + short off = (short)(vtable[i] != 0 ? vtableloc - vtable[i] : 0); + addShort(off); + } + + final int standard_fields = 2; // The fields below: + addShort((short)(vtableloc - object_start)); + addShort((short)((trimmed_size + standard_fields) * SIZEOF_SHORT)); + + // Search for an existing vtable that matches the current one. + int existing_vtable = 0; + outer_loop: + for (i = 0; i < num_vtables; i++) { + int vt1 = bb.capacity() - vtables[i]; + int vt2 = space; + short len = bb.getShort(vt1); + if (len == bb.getShort(vt2)) { + for (int j = SIZEOF_SHORT; j < len; j += SIZEOF_SHORT) { + if (bb.getShort(vt1 + j) != bb.getShort(vt2 + j)) { + continue outer_loop; + } + } + existing_vtable = vtables[i]; + break outer_loop; + } + } + + if (existing_vtable != 0) { + // Found a match: + // Remove the current vtable. + space = bb.capacity() - vtableloc; + // Point table to existing vtable. + bb.putInt(space, existing_vtable - vtableloc); + } else { + // No match: + // Add the location of the current vtable to the list of vtables. + if (num_vtables == vtables.length) vtables = Arrays.copyOf(vtables, num_vtables * 2); + vtables[num_vtables++] = offset(); + // Point table to current vtable. + bb.putInt(bb.capacity() - vtableloc, offset() - vtableloc); + } + + nested = false; + return vtableloc; + } + + /** + * Checks that a required field has been set in a given table that has + * just been constructed. + * + * @param table The offset to the start of the table from the `ByteBuffer` capacity. + * @param field The offset to the field in the vtable. + */ + public void required(int table, int field) { + int table_start = bb.capacity() - table; + int vtable_start = table_start - bb.getInt(table_start); + boolean ok = bb.getShort(vtable_start + field) != 0; + // If this fails, the caller will show what field needs to be set. + if (!ok) + throw new AssertionError("FlatBuffers: field " + field + " must be set"); + } + /// @endcond + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param root_table An offset to be added to the buffer. + * @param size_prefix Whether to prefix the size to the buffer. + */ + protected void finish(int root_table, boolean size_prefix) { + prep(minalign, SIZEOF_INT + (size_prefix ? SIZEOF_INT : 0)); + addOffset(root_table); + if (size_prefix) { + addInt(bb.capacity() - space); + } + bb.position(space); + finished = true; + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param root_table An offset to be added to the buffer. + */ + public void finish(int root_table) { + finish(root_table, false); + } + + /** + * Finalize a buffer, pointing to the given `root_table`, with the size prefixed. + * + * @param root_table An offset to be added to the buffer. + */ + public void finishSizePrefixed(int root_table) { + finish(root_table, true); + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param root_table An offset to be added to the buffer. + * @param file_identifier A FlatBuffer file identifier to be added to the buffer before + * `root_table`. + * @param size_prefix Whether to prefix the size to the buffer. + */ + protected void finish(int root_table, String file_identifier, boolean size_prefix) { + prep(minalign, SIZEOF_INT + FILE_IDENTIFIER_LENGTH + (size_prefix ? SIZEOF_INT : 0)); + if (file_identifier.length() != FILE_IDENTIFIER_LENGTH) + throw new AssertionError("FlatBuffers: file identifier must be length " + + FILE_IDENTIFIER_LENGTH); + for (int i = FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) { + addByte((byte)file_identifier.charAt(i)); + } + finish(root_table, size_prefix); + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param root_table An offset to be added to the buffer. + * @param file_identifier A FlatBuffer file identifier to be added to the buffer before + * `root_table`. + */ + public void finish(int root_table, String file_identifier) { + finish(root_table, file_identifier, false); + } + + /** + * Finalize a buffer, pointing to the given `root_table`, with the size prefixed. + * + * @param root_table An offset to be added to the buffer. + * @param file_identifier A FlatBuffer file identifier to be added to the buffer before + * `root_table`. + */ + public void finishSizePrefixed(int root_table, String file_identifier) { + finish(root_table, file_identifier, true); + } + + /** + * In order to save space, fields that are set to their default value + * don't get serialized into the buffer. Forcing defaults provides a + * way to manually disable this optimization. + * + * @param forceDefaults When set to `true`, always serializes default values. + * @return Returns `this`. + */ + public FlatBufferBuilder forceDefaults(boolean forceDefaults){ + this.force_defaults = forceDefaults; + return this; + } + + /** + * Get the ByteBuffer representing the FlatBuffer. Only call this after you've + * called `finish()`. The actual data starts at the ByteBuffer's current position, + * not necessarily at `0`. + * + * @return The {@link ByteBuffer} representing the FlatBuffer + */ + public ByteBuffer dataBuffer() { + finished(); + return bb; + } + + /** + * The FlatBuffer data doesn't start at offset 0 in the {@link ByteBuffer}, but + * now the {@code ByteBuffer}'s position is set to that location upon {@link #finish(int)}. + * + * @return The {@link ByteBuffer#position() position} the data starts in {@link #dataBuffer()} + * @deprecated This method should not be needed anymore, but is left + * here for the moment to document this API change. It will be removed in the future. + */ + @Deprecated + private int dataStart() { + finished(); + return space; + } + + /** + * A utility function to copy and return the ByteBuffer data from `start` to + * `start` + `length` as a `byte[]`. + * + * @param start Start copying at this offset. + * @param length How many bytes to copy. + * @return A range copy of the {@link #dataBuffer() data buffer}. + * @throws IndexOutOfBoundsException If the range of bytes is ouf of bound. + */ + public byte[] sizedByteArray(int start, int length){ + finished(); + byte[] array = new byte[length]; + bb.position(start); + bb.get(array); + return array; + } + + /** + * A utility function to copy and return the ByteBuffer data as a `byte[]`. + * + * @return A full copy of the {@link #dataBuffer() data buffer}. + */ + public byte[] sizedByteArray() { + return sizedByteArray(space, bb.capacity() - space); + } + + /** + * A utility function to return an InputStream to the ByteBuffer data + * + * @return An InputStream that starts at the beginning of the ByteBuffer data + * and can read to the end of it. + */ + public InputStream sizedInputStream() { + finished(); + ByteBuffer duplicate = bb.duplicate(); + duplicate.position(space); + duplicate.limit(bb.capacity()); + return new ByteBufferBackedInputStream(duplicate); + } + + /** + * A class that allows a user to create an InputStream from a ByteBuffer. + */ + static class ByteBufferBackedInputStream extends InputStream { + + ByteBuffer buf; + + public ByteBufferBackedInputStream(ByteBuffer buf) { + this.buf = buf; + } + + public int read() throws IOException { + try { + return buf.get() & 0xFF; + } catch(BufferUnderflowException e) { + return -1; + } + } + } + +} + +/// @} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlexBuffers.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlexBuffers.java new file mode 100644 index 00000000000..75a0595f67a --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlexBuffers.java @@ -0,0 +1,1221 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + + +import static com.google.flatbuffers.FlexBuffers.Unsigned.byteToUnsignedInt; +import static com.google.flatbuffers.FlexBuffers.Unsigned.intToUnsignedLong; +import static com.google.flatbuffers.FlexBuffers.Unsigned.shortToUnsignedInt; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.charset.StandardCharsets; + +/// @file +/// @addtogroup flatbuffers_java_api +/// @{ + +/** + * This class can be used to parse FlexBuffer messages. + *

+ * For generating FlexBuffer messages, use {@link FlexBuffersBuilder}. + *

+ * Example of usage: + *

+ * ReadBuf bb = ... // load message from file or network
+ * FlexBuffers.Reference r = FlexBuffers.getRoot(bb); // Reads the root element
+ * FlexBuffers.Map map = r.asMap(); // We assumed root object is a map
+ * System.out.println(map.get("name").asString()); // prints element with key "name"
+ * 
+ */ +public class FlexBuffers { + + // These are used as the upper 6 bits of a type field to indicate the actual + // type. + /** Represent a null type */ + public static final int FBT_NULL = 0; + /** Represent a signed integer type */ + public static final int FBT_INT = 1; + /** Represent a unsigned type */ + public static final int FBT_UINT = 2; + /** Represent a float type */ + public static final int FBT_FLOAT = 3; // Types above stored inline, types below store an offset. + /** Represent a key to a map type */ + public static final int FBT_KEY = 4; + /** Represent a string type */ + public static final int FBT_STRING = 5; + /** Represent a indirect signed integer type */ + public static final int FBT_INDIRECT_INT = 6; + /** Represent a indirect unsigned integer type */ + public static final int FBT_INDIRECT_UINT = 7; + /** Represent a indirect float type */ + public static final int FBT_INDIRECT_FLOAT = 8; + /** Represent a map type */ + public static final int FBT_MAP = 9; + /** Represent a vector type */ + public static final int FBT_VECTOR = 10; // Untyped. + /** Represent a vector of signed integers type */ + public static final int FBT_VECTOR_INT = 11; // Typed any size = stores no type table). + /** Represent a vector of unsigned integers type */ + public static final int FBT_VECTOR_UINT = 12; + /** Represent a vector of floats type */ + public static final int FBT_VECTOR_FLOAT = 13; + /** Represent a vector of keys type */ + public static final int FBT_VECTOR_KEY = 14; + /** Represent a vector of strings type */ + // DEPRECATED, use FBT_VECTOR or FBT_VECTOR_KEY instead. + // more info on thttps://github.com/google/flatbuffers/issues/5627. + public static final int FBT_VECTOR_STRING_DEPRECATED = 15; + + /// @cond FLATBUFFERS_INTERNAL + public static final int FBT_VECTOR_INT2 = 16; // Typed tuple = no type table; no size field). + public static final int FBT_VECTOR_UINT2 = 17; + public static final int FBT_VECTOR_FLOAT2 = 18; + public static final int FBT_VECTOR_INT3 = 19; // Typed triple = no type table; no size field). + public static final int FBT_VECTOR_UINT3 = 20; + public static final int FBT_VECTOR_FLOAT3 = 21; + public static final int FBT_VECTOR_INT4 = 22; // Typed quad = no type table; no size field). + public static final int FBT_VECTOR_UINT4 = 23; + public static final int FBT_VECTOR_FLOAT4 = 24; + /// @endcond FLATBUFFERS_INTERNAL + + /** Represent a blob type */ + public static final int FBT_BLOB = 25; + /** Represent a boolean type */ + public static final int FBT_BOOL = 26; + /** Represent a vector of booleans type */ + public static final int FBT_VECTOR_BOOL = 36; // To Allow the same type of conversion of type to vector type + + private static final ReadBuf EMPTY_BB = new ArrayReadWriteBuf(new byte[] {0}, 1); + + /** + * Checks where a type is a typed vector + * + * @param type type to be checked + * @return true if typed vector + */ + static boolean isTypedVector(int type) { + return (type >= FBT_VECTOR_INT && type <= FBT_VECTOR_STRING_DEPRECATED) || type == FBT_VECTOR_BOOL; + } + + /** + * Check whether you can access type directly (no indirection) or not. + * + * @param type type to be checked + * @return true if inline type + */ + static boolean isTypeInline(int type) { + return type <= FBT_FLOAT || type == FBT_BOOL; + } + + static int toTypedVectorElementType(int original_type) { + return original_type - FBT_VECTOR_INT + FBT_INT; + } + + /** + * Return a vector type our of a original element type + * + * @param type element type + * @param fixedLength size of element + * @return typed vector type + */ + static int toTypedVector(int type, int fixedLength) { + assert (isTypedVectorElementType(type)); + switch (fixedLength) { + case 0: return type - FBT_INT + FBT_VECTOR_INT; + case 2: return type - FBT_INT + FBT_VECTOR_INT2; + case 3: return type - FBT_INT + FBT_VECTOR_INT3; + case 4: return type - FBT_INT + FBT_VECTOR_INT4; + default: + assert (false); + return FBT_NULL; + } + } + + static boolean isTypedVectorElementType(int type) { + return (type >= FBT_INT && type <= FBT_KEY) || type == FBT_BOOL; + } + + // return position of the element that the offset is pointing to + private static int indirect(ReadBuf bb, int offset, int byteWidth) { + // we assume all offset fits on a int, since ReadBuf operates with that assumption + return (int) (offset - readUInt(bb, offset, byteWidth)); + } + + // read unsigned int with size byteWidth and return as a 64-bit integer + private static long readUInt(ReadBuf buff, int end, int byteWidth) { + switch (byteWidth) { + case 1: return byteToUnsignedInt(buff.get(end)); + case 2: return shortToUnsignedInt(buff.getShort(end)); + case 4: return intToUnsignedLong(buff.getInt(end)); + case 8: return buff.getLong(end); // We are passing signed long here. Losing information (user should know) + default: return -1; // we should never reach here + } + } + + // read signed int of size byteWidth and return as 32-bit int + private static int readInt(ReadBuf buff, int end, int byteWidth) { + return (int) readLong(buff, end, byteWidth); + } + + // read signed int of size byteWidth and return as 64-bit int + private static long readLong(ReadBuf buff, int end, int byteWidth) { + switch (byteWidth) { + case 1: return buff.get(end); + case 2: return buff.getShort(end); + case 4: return buff.getInt(end); + case 8: return buff.getLong(end); + default: return -1; // we should never reach here + } + } + + private static double readDouble(ReadBuf buff, int end, int byteWidth) { + switch (byteWidth) { + case 4: return buff.getFloat(end); + case 8: return buff.getDouble(end); + default: return -1; // we should never reach here + } + } + + /** + * Reads a FlexBuffer message in ReadBuf and returns {@link Reference} to + * the root element. + * @param buffer ReadBuf containing FlexBuffer message + * @return {@link Reference} to the root object + */ + @Deprecated + public static Reference getRoot(ByteBuffer buffer) { + return getRoot( buffer.hasArray() ? new ArrayReadWriteBuf(buffer.array(), buffer.limit()) : new ByteBufferReadWriteBuf(buffer)); + } + + /** + * Reads a FlexBuffer message in ReadBuf and returns {@link Reference} to + * the root element. + * @param buffer ReadBuf containing FlexBuffer message + * @return {@link Reference} to the root object + */ + public static Reference getRoot(ReadBuf buffer) { + // See Finish() below for the serialization counterpart of this. + // The root ends at the end of the buffer, so we parse backwards from there. + int end = buffer.limit(); + int byteWidth = buffer.get(--end); + int packetType = byteToUnsignedInt(buffer.get(--end)); + end -= byteWidth; // The root data item. + return new Reference(buffer, end, byteWidth, packetType); + } + + /** + * Represents an generic element in the buffer. + */ + public static class Reference { + + private static final Reference NULL_REFERENCE = new Reference(EMPTY_BB, 0, 1, 0); + private ReadBuf bb; + private int end; + private int parentWidth; + private int byteWidth; + private int type; + + Reference(ReadBuf bb, int end, int parentWidth, int packedType) { + this(bb, end, parentWidth, (1 << (packedType & 3)), packedType >> 2); + } + + Reference(ReadBuf bb, int end, int parentWidth, int byteWidth, int type) { + this.bb = bb; + this.end = end; + this.parentWidth = parentWidth; + this.byteWidth = byteWidth; + this.type = type; + } + + /** + * Return element type + * @return element type as integer + */ + public int getType() { + return type; + } + + /** + * Checks whether the element is null type + * @return true if null type + */ + public boolean isNull() { + return type == FBT_NULL; + } + + /** + * Checks whether the element is boolean type + * @return true if boolean type + */ + public boolean isBoolean() { + return type == FBT_BOOL; + } + + /** + * Checks whether the element type is numeric (signed/unsigned integers and floats) + * @return true if numeric type + */ + public boolean isNumeric() { + return isIntOrUInt() || isFloat(); + } + + /** + * Checks whether the element type is signed or unsigned integers + * @return true if an integer type + */ + public boolean isIntOrUInt() { + return isInt() || isUInt(); + } + + /** + * Checks whether the element type is float + * @return true if a float type + */ + public boolean isFloat() { + return type == FBT_FLOAT || type == FBT_INDIRECT_FLOAT; + } + + /** + * Checks whether the element type is signed integer + * @return true if a signed integer type + */ + public boolean isInt() { + return type == FBT_INT || type == FBT_INDIRECT_INT; + } + + /** + * Checks whether the element type is signed integer + * @return true if a signed integer type + */ + public boolean isUInt() { + return type == FBT_UINT || type == FBT_INDIRECT_UINT; + } + + /** + * Checks whether the element type is string + * @return true if a string type + */ + public boolean isString() { + return type == FBT_STRING; + } + + /** + * Checks whether the element type is key + * @return true if a key type + */ + public boolean isKey() { + return type == FBT_KEY; + } + + /** + * Checks whether the element type is vector + * @return true if a vector type + */ + public boolean isVector() { + return type == FBT_VECTOR || type == FBT_MAP; + } + + /** + * Checks whether the element type is typed vector + * @return true if a typed vector type + */ + public boolean isTypedVector() { + return FlexBuffers.isTypedVector(type); + } + + /** + * Checks whether the element type is a map + * @return true if a map type + */ + public boolean isMap() { + return type == FBT_MAP; + } + + /** + * Checks whether the element type is a blob + * @return true if a blob type + */ + public boolean isBlob() { + return type == FBT_BLOB; + } + + /** + * Returns element as 32-bit integer. + *

For vector element, it will return size of the vector

+ *

For String element, it will type to be parsed as integer

+ *

Unsigned elements will become negative

+ *

Float elements will be casted to integer

+ * @return 32-bit integer or 0 if fail to convert element to integer. + */ + public int asInt() { + if (type == FBT_INT) { + // A fast path for the common case. + return readInt(bb, end, parentWidth); + } else + switch (type) { + case FBT_INDIRECT_INT: return readInt(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_UINT: return (int) readUInt(bb, end, parentWidth); + case FBT_INDIRECT_UINT: return (int) readUInt(bb, indirect(bb, end, parentWidth), parentWidth); + case FBT_FLOAT: return (int) readDouble(bb, end, parentWidth); + case FBT_INDIRECT_FLOAT: return (int) readDouble(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_NULL: return 0; + case FBT_STRING: return Integer.parseInt(asString()); + case FBT_VECTOR: return asVector().size(); + case FBT_BOOL: return readInt(bb, end, parentWidth); + default: + // Convert other things to int. + return 0; + } + } + + /** + * Returns element as unsigned 64-bit integer. + *

For vector element, it will return size of the vector

+ *

For String element, it will type to be parsed as integer

+ *

Negative signed elements will become unsigned counterpart

+ *

Float elements will be casted to integer

+ * @return 64-bit integer or 0 if fail to convert element to integer. + */ + public long asUInt() { + if (type == FBT_UINT) { + // A fast path for the common case. + return readUInt(bb, end, parentWidth); + } else + switch (type) { + case FBT_INDIRECT_UINT: return readUInt(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_INT: return readLong(bb, end, parentWidth); + case FBT_INDIRECT_INT: return readLong(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_FLOAT: return (long) readDouble(bb, end, parentWidth); + case FBT_INDIRECT_FLOAT: return (long) readDouble(bb, indirect(bb, end, parentWidth), parentWidth); + case FBT_NULL: return 0; + case FBT_STRING: return Long.parseLong(asString()); + case FBT_VECTOR: return asVector().size(); + case FBT_BOOL: return readInt(bb, end, parentWidth); + default: + // Convert other things to uint. + return 0; + } + } + + /** + * Returns element as 64-bit integer. + *

For vector element, it will return size of the vector

+ *

For String element, it will type to be parsed as integer

+ *

Unsigned elements will become negative

+ *

Float elements will be casted to integer

+ * @return 64-bit integer or 0 if fail to convert element to long. + */ + public long asLong() { + if (type == FBT_INT) { + // A fast path for the common case. + return readLong(bb, end, parentWidth); + } else + switch (type) { + case FBT_INDIRECT_INT: return readLong(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_UINT: return readUInt(bb, end, parentWidth); + case FBT_INDIRECT_UINT: return readUInt(bb, indirect(bb, end, parentWidth), parentWidth); + case FBT_FLOAT: return (long) readDouble(bb, end, parentWidth); + case FBT_INDIRECT_FLOAT: return (long) readDouble(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_NULL: return 0; + case FBT_STRING: { + try { + return Long.parseLong(asString()); + } catch (NumberFormatException nfe) { + return 0; //same as C++ implementation + } + } + case FBT_VECTOR: return asVector().size(); + case FBT_BOOL: return readInt(bb, end, parentWidth); + default: + // Convert other things to int. + return 0; + } + } + + /** + * Returns element as 64-bit integer. + *

For vector element, it will return size of the vector

+ *

For String element, it will type to be parsed as integer

+ * @return 64-bit integer or 0 if fail to convert element to long. + */ + public double asFloat() { + if (type == FBT_FLOAT) { + // A fast path for the common case. + return readDouble(bb, end, parentWidth); + } else + switch (type) { + case FBT_INDIRECT_FLOAT: return readDouble(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_INT: return readInt(bb, end, parentWidth); + case FBT_UINT: + case FBT_BOOL: + return readUInt(bb, end, parentWidth); + case FBT_INDIRECT_INT: return readInt(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_INDIRECT_UINT: return readUInt(bb, indirect(bb, end, parentWidth), byteWidth); + case FBT_NULL: return 0.0; + case FBT_STRING: return Double.parseDouble(asString()); + case FBT_VECTOR: return asVector().size(); + default: + // Convert strings and other things to float. + return 0; + } + } + + /** + * Returns element as a {@link Key} + * @return key or {@link Key#empty()} if element is not a key + */ + public Key asKey() { + if (isKey()) { + return new Key(bb, indirect(bb, end, parentWidth), byteWidth); + } else { + return Key.empty(); + } + } + + /** + * Returns element as a `String` + * @return element as `String` or empty `String` if fail + */ + public String asString() { + if (isString()) { + int start = indirect(bb, end, parentWidth); + int size = (int) readUInt(bb, start - byteWidth, byteWidth); + return bb.getString(start, size); + } + else if (isKey()){ + int start = indirect(bb, end, byteWidth); + for (int i = start; ; i++) { + if (bb.get(i) == 0) { + return bb.getString(start, i - start); + } + } + } else { + return ""; + } + } + + /** + * Returns element as a {@link Map} + * @return element as {@link Map} or empty {@link Map} if fail + */ + public Map asMap() { + if (isMap()) { + return new Map(bb, indirect(bb, end, parentWidth), byteWidth); + } else { + return Map.empty(); + } + } + + /** + * Returns element as a {@link Vector} + * @return element as {@link Vector} or empty {@link Vector} if fail + */ + public Vector asVector() { + if (isVector()) { + return new Vector(bb, indirect(bb, end, parentWidth), byteWidth); + } else if(type == FlexBuffers.FBT_VECTOR_STRING_DEPRECATED) { + // deprecated. Should be treated as key vector + return new TypedVector(bb, indirect(bb, end, parentWidth), byteWidth, FlexBuffers.FBT_KEY); + } else if (FlexBuffers.isTypedVector(type)) { + return new TypedVector(bb, indirect(bb, end, parentWidth), byteWidth, FlexBuffers.toTypedVectorElementType(type)); + } else { + return Vector.empty(); + } + } + + /** + * Returns element as a {@link Blob} + * @return element as {@link Blob} or empty {@link Blob} if fail + */ + public Blob asBlob() { + if (isBlob() || isString()) { + return new Blob(bb, indirect(bb, end, parentWidth), byteWidth); + } else { + return Blob.empty(); + } + } + + /** + * Returns element as a boolean + *

If element type is not boolean, it will be casted to integer and compared against 0

+ * @return element as boolean + */ + public boolean asBoolean() { + if (isBoolean()) { + return bb.get(end) != 0; + } + return asUInt() != 0; + } + + /** + * Returns text representation of the element (JSON) + * @return String containing text representation of the element + */ + @Override + public String toString() { + return toString(new StringBuilder(128)).toString(); + } + + /** + * Appends a text(JSON) representation to a `StringBuilder` + */ + StringBuilder toString(StringBuilder sb) { + //TODO: Original C++ implementation escape strings. + // probably we should do it as well. + switch (type) { + case FBT_NULL: + return sb.append("null"); + case FBT_INT: + case FBT_INDIRECT_INT: + return sb.append(asLong()); + case FBT_UINT: + case FBT_INDIRECT_UINT: + return sb.append(asUInt()); + case FBT_INDIRECT_FLOAT: + case FBT_FLOAT: + return sb.append(asFloat()); + case FBT_KEY: + return asKey().toString(sb.append('"')).append('"'); + case FBT_STRING: + return sb.append('"').append(asString()).append('"'); + case FBT_MAP: + return asMap().toString(sb); + case FBT_VECTOR: + return asVector().toString(sb); + case FBT_BLOB: + return asBlob().toString(sb); + case FBT_BOOL: + return sb.append(asBoolean()); + case FBT_VECTOR_INT: + case FBT_VECTOR_UINT: + case FBT_VECTOR_FLOAT: + case FBT_VECTOR_KEY: + case FBT_VECTOR_STRING_DEPRECATED: + case FBT_VECTOR_BOOL: + return sb.append(asVector()); + case FBT_VECTOR_INT2: + case FBT_VECTOR_UINT2: + case FBT_VECTOR_FLOAT2: + case FBT_VECTOR_INT3: + case FBT_VECTOR_UINT3: + case FBT_VECTOR_FLOAT3: + case FBT_VECTOR_INT4: + case FBT_VECTOR_UINT4: + case FBT_VECTOR_FLOAT4: + + throw new FlexBufferException("not_implemented:" + type); + default: + return sb; + } + } + } + + /** + * Base class of all types below. + * Points into the data buffer and allows access to one type. + */ + private static abstract class Object { + ReadBuf bb; + int end; + int byteWidth; + + Object(ReadBuf buff, int end, int byteWidth) { + this.bb = buff; + this.end = end; + this.byteWidth = byteWidth; + } + + @Override + public String toString() { + return toString(new StringBuilder(128)).toString(); + } + + public abstract StringBuilder toString(StringBuilder sb); + } + + // Stores size in `byte_width_` bytes before end position. + private static abstract class Sized extends Object { + + protected final int size; + + Sized(ReadBuf buff, int end, int byteWidth) { + super(buff, end, byteWidth); + size = (int) readUInt(bb, end - byteWidth, byteWidth); + } + + public int size() { + return size; + } + } + + /** + * Represents a array of bytes element in the buffer + * + *

It can be converted to `ReadBuf` using {@link data()}, + * copied into a byte[] using {@link getBytes()} or + * have individual bytes accessed individually using {@link get(int)}

+ */ + public static class Blob extends Sized { + static final Blob EMPTY = new Blob(EMPTY_BB, 1, 1); + + Blob(ReadBuf buff, int end, int byteWidth) { + super(buff, end, byteWidth); + } + + /** Return an empty {@link Blob} */ + public static Blob empty() { + return EMPTY; + } + + /** + * Return {@link Blob} as `ReadBuf` + * @return blob as `ReadBuf` + */ + public ByteBuffer data() { + ByteBuffer dup = ByteBuffer.wrap(bb.data()); + dup.position(end); + dup.limit(end + size()); + return dup.asReadOnlyBuffer().slice(); + } + + /** + * Copy blob into a byte[] + * @return blob as a byte[] + */ + public byte[] getBytes() { + int size = size(); + byte[] result = new byte[size]; + for (int i = 0; i < size; i++) { + result[i] = bb.get(end + i); + } + return result; + } + + /** + * Return individual byte at a given position + * @param pos position of the byte to be read + */ + public byte get(int pos) { + assert pos >=0 && pos <= size(); + return bb.get(end + pos); + } + + /** + * Returns a text(JSON) representation of the {@link Blob} + */ + @Override + public String toString() { + return bb.getString(end, size()); + } + + /** + * Append a text(JSON) representation of the {@link Blob} into a `StringBuilder` + */ + @Override + public StringBuilder toString(StringBuilder sb) { + sb.append('"'); + sb.append(bb.getString(end, size())); + return sb.append('"'); + } + } + + /** + * Represents a key element in the buffer. Keys are + * used to reference objects in a {@link Map} + */ + public static class Key extends Object { + + private static final Key EMPTY = new Key(EMPTY_BB, 0, 0); + + Key(ReadBuf buff, int end, int byteWidth) { + super(buff, end, byteWidth); + } + + /** + * Return an empty {@link Key} + * @return empty {@link Key} + * */ + public static Key empty() { + return Key.EMPTY; + } + + /** + * Appends a text(JSON) representation to a `StringBuilder` + */ + @Override + public StringBuilder toString(StringBuilder sb) { + return sb.append(toString()); + } + + @Override + public String toString() { + int size; + for (int i = end; ; i++) { + if (bb.get(i) == 0) { + size = i - end; + break; + } + } + return bb.getString(end, size); + } + + int compareTo(byte[] other) { + int ia = end; + int io = 0; + byte c1, c2; + do { + c1 = bb.get(ia); + c2 = other[io]; + if (c1 == '\0') + return c1 - c2; + ia++; + io++; + if (io == other.length) { + // in our buffer we have an additional \0 byte + // but this does not exist in regular Java strings, so we return now + int cmp = c1 - c2; + if (cmp != 0 || bb.get(ia) == '\0') { + return cmp; + } else { + return 1; + } + } + } + while (c1 == c2); + return c1 - c2; + } + + /** + * Compare keys + * @param obj other key to compare + * @return true if keys are the same + */ + @Override + public boolean equals(java.lang.Object obj) { + if (!(obj instanceof Key)) + return false; + + return ((Key) obj).end == end && ((Key) obj).byteWidth == byteWidth; + } + + public int hashCode() { + return end ^ byteWidth; + } + } + + /** + * Map object representing a set of key-value pairs. + */ + public static class Map extends Vector { + private static final Map EMPTY_MAP = new Map(EMPTY_BB, 1, 1); + // cache for converting UTF-8 codepoints into + // Java chars. Used to speed up String comparison + private final byte[] comparisonBuffer = new byte[4]; + + Map(ReadBuf bb, int end, int byteWidth) { + super(bb, end, byteWidth); + } + + /** + * Returns an empty {@link Map} + * @return an empty {@link Map} + */ + public static Map empty() { + return EMPTY_MAP; + } + + /** + * @param key access key to element on map + * @return reference to value in map + */ + public Reference get(String key) { + int index = binarySearch(key); + if (index >= 0 && index < size) { + return get(index); + } + return Reference.NULL_REFERENCE; + } + + /** + * @param key access key to element on map. Keys are assumed to be encoded in UTF-8 + * @return reference to value in map + */ + public Reference get(byte[] key) { + int index = binarySearch(key); + if (index >= 0 && index < size) { + return get(index); + } + return Reference.NULL_REFERENCE; + } + + /** + * Get a vector or keys in the map + * + * @return vector of keys + */ + public KeyVector keys() { + final int num_prefixed_fields = 3; + int keysOffset = end - (byteWidth * num_prefixed_fields); + return new KeyVector(new TypedVector(bb, + indirect(bb, keysOffset, byteWidth), + readInt(bb, keysOffset + byteWidth, byteWidth), + FBT_KEY)); + } + + /** + * @return {@code Vector} of values from map + */ + public Vector values() { + return new Vector(bb, end, byteWidth); + } + + /** + * Writes text (json) representation of map in a {@code StringBuilder}. + * + * @param builder {@code StringBuilder} to be appended to + * @return Same {@code StringBuilder} with appended text + */ + public StringBuilder toString(StringBuilder builder) { + builder.append("{ "); + KeyVector keys = keys(); + int size = size(); + Vector vals = values(); + for (int i = 0; i < size; i++) { + builder.append('"') + .append(keys.get(i).toString()) + .append("\" : "); + builder.append(vals.get(i).toString()); + if (i != size - 1) + builder.append(", "); + } + builder.append(" }"); + return builder; + } + + // Performs a binary search on a key vector and return index of the key in key vector + private int binarySearch(CharSequence searchedKey) { + int low = 0; + int high = size - 1; + final int num_prefixed_fields = 3; + int keysOffset = end - (byteWidth * num_prefixed_fields); + int keysStart = indirect(bb, keysOffset, byteWidth); + int keyByteWidth = readInt(bb, keysOffset + byteWidth, byteWidth); + while (low <= high) { + int mid = (low + high) >>> 1; + int keyPos = indirect(bb, keysStart + mid * keyByteWidth, keyByteWidth); + int cmp = compareCharSequence(keyPos, searchedKey); + if (cmp < 0) + low = mid + 1; + else if (cmp > 0) + high = mid - 1; + else + return mid; // key found + } + return -(low + 1); // key not found + } + + private int binarySearch(byte[] searchedKey) { + int low = 0; + int high = size - 1; + final int num_prefixed_fields = 3; + int keysOffset = end - (byteWidth * num_prefixed_fields); + int keysStart = indirect(bb, keysOffset, byteWidth); + int keyByteWidth = readInt(bb, keysOffset + byteWidth, byteWidth); + + while (low <= high) { + int mid = (low + high) >>> 1; + int keyPos = indirect(bb, keysStart + mid * keyByteWidth, keyByteWidth); + int cmp = compareBytes(bb, keyPos, searchedKey); + if (cmp < 0) + low = mid + 1; + else if (cmp > 0) + high = mid - 1; + else + return mid; // key found + } + return -(low + 1); // key not found + } + + // compares a byte[] against a FBT_KEY + private int compareBytes(ReadBuf bb, int start, byte[] other) { + int l1 = start; + int l2 = 0; + byte c1, c2; + do { + c1 = bb.get(l1); + c2 = other[l2]; + if (c1 == '\0') + return c1 - c2; + l1++; + l2++; + if (l2 == other.length) { + // in our buffer we have an additional \0 byte + // but this does not exist in regular Java strings, so we return now + int cmp = c1 - c2; + if (cmp != 0 || bb.get(l1) == '\0') { + return cmp; + } else { + return 1; + } + } + } + while (c1 == c2); + return c1 - c2; + } + + // compares a CharSequence against a FBT_KEY + private int compareCharSequence(int start, CharSequence other) { + int bufferPos = start; + int otherPos = 0; + int limit = bb.limit(); + int otherLimit = other.length(); + + // special loop for ASCII characters. Most of keys should be ASCII only, so this + // loop should be optimized for that. + // breaks if a multi-byte character is found + while (otherPos < otherLimit) { + char c2 = other.charAt(otherPos); + + if (c2 >= 0x80) { + // not a single byte codepoint + break; + } + + byte b = bb.get(bufferPos); + + if (b == 0) { + return -c2; + } else if (b < 0) { + break; + } else if ((char) b != c2) { + return b - c2; + } + ++bufferPos; + ++otherPos; + } + + while (bufferPos < limit) { + + int sizeInBuff = Utf8.encodeUtf8CodePoint(other, otherPos, comparisonBuffer); + + if (sizeInBuff == 0) { + // That means we finish with other and there are not more chars to + // compare. String in the buffer is bigger. + return bb.get(bufferPos); + } + + for (int i = 0; i < sizeInBuff; i++) { + byte bufferByte = bb.get(bufferPos++); + byte otherByte = comparisonBuffer[i]; + if (bufferByte == 0) { + // Our key is finished, so other is bigger + return -otherByte; + } else if (bufferByte != otherByte) { + return bufferByte - otherByte; + } + } + + otherPos += sizeInBuff == 4 ? 2 : 1; + } + return 0; + } + } + + /** + * Object that represents a set of elements in the buffer + */ + public static class Vector extends Sized { + + private static final Vector EMPTY_VECTOR = new Vector(EMPTY_BB, 1, 1); + + Vector(ReadBuf bb, int end, int byteWidth) { + super(bb, end, byteWidth); + } + + /** + * Returns an empty {@link Map} + * @return an empty {@link Map} + */ + public static Vector empty() { + return EMPTY_VECTOR; + } + + /** + * Checks if the vector is empty + * @return true if vector is empty + */ + public boolean isEmpty() { + return this == EMPTY_VECTOR; + } + + /** + * Appends a text(JSON) representation to a `StringBuilder` + */ + @Override + public StringBuilder toString(StringBuilder sb) { + sb.append("[ "); + int size = size(); + for (int i = 0; i < size; i++) { + get(i).toString(sb); + if (i != size - 1) { + sb.append(", "); + } + } + sb.append(" ]"); + return sb; + } + + /** + * Get a element in a vector by index + * + * @param index position of the element + * @return {@code Reference} to the element + */ + public Reference get(int index) { + long len = size(); + if (index >= len) { + return Reference.NULL_REFERENCE; + } + int packedType = byteToUnsignedInt(bb.get((int) (end + (len * byteWidth) + index))); + int obj_end = end + index * byteWidth; + return new Reference(bb, obj_end, byteWidth, packedType); + } + } + + /** + * Object that represents a set of elements with the same type + */ + public static class TypedVector extends Vector { + + private static final TypedVector EMPTY_VECTOR = new TypedVector(EMPTY_BB, 1, 1, FBT_INT); + + private final int elemType; + + TypedVector(ReadBuf bb, int end, int byteWidth, int elemType) { + super(bb, end, byteWidth); + this.elemType = elemType; + } + + public static TypedVector empty() { + return EMPTY_VECTOR; + } + + /** + * Returns whether the vector is empty + * + * @return true if empty + */ + public boolean isEmptyVector() { + return this == EMPTY_VECTOR; + } + + /** + * Return element type for all elements in the vector + * + * @return element type + */ + public int getElemType() { + return elemType; + } + + /** + * Get reference to an object in the {@code Vector} + * + * @param pos position of the object in {@code Vector} + * @return reference to element + */ + @Override + public Reference get(int pos) { + int len = size(); + if (pos >= len) return Reference.NULL_REFERENCE; + int childPos = end + pos * byteWidth; + return new Reference(bb, childPos, byteWidth, 1, elemType); + } + } + + /** + * Represent a vector of keys in a map + */ + public static class KeyVector { + + private final TypedVector vec; + + KeyVector(TypedVector vec) { + this.vec = vec; + } + + /** + * Return key + * + * @param pos position of the key in key vector + * @return key + */ + public Key get(int pos) { + int len = size(); + if (pos >= len) return Key.EMPTY; + int childPos = vec.end + pos * vec.byteWidth; + return new Key(vec.bb, indirect(vec.bb, childPos, vec.byteWidth), 1); + } + + /** + * Returns size of key vector + * + * @return size + */ + public int size() { + return vec.size(); + } + + /** + * Returns a text(JSON) representation + */ + public String toString() { + StringBuilder b = new StringBuilder(); + b.append('['); + for (int i = 0; i < vec.size(); i++) { + vec.get(i).toString(b); + if (i != vec.size() - 1) { + b.append(", "); + } + } + return b.append("]").toString(); + } + } + + public static class FlexBufferException extends RuntimeException { + FlexBufferException(String msg) { + super(msg); + } + } + + static class Unsigned { + + static int byteToUnsignedInt(byte x) { + return ((int) x) & 0xff; + } + + static int shortToUnsignedInt(short x) { + return ((int) x) & 0xffff; + } + + static long intToUnsignedLong(int x) { + return ((long) x) & 0xffffffffL; + } + } +} +/// @} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlexBuffersBuilder.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlexBuffersBuilder.java new file mode 100644 index 00000000000..60ab5355ab1 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FlexBuffersBuilder.java @@ -0,0 +1,802 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import java.math.BigInteger; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.StandardCharsets; +import java.util.ArrayList; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; + +import static com.google.flatbuffers.FlexBuffers.*; +import static com.google.flatbuffers.FlexBuffers.Unsigned.byteToUnsignedInt; +import static com.google.flatbuffers.FlexBuffers.Unsigned.intToUnsignedLong; +import static com.google.flatbuffers.FlexBuffers.Unsigned.shortToUnsignedInt; + +/// @file +/// @addtogroup flatbuffers_java_api +/// @{ + +/** + * Helper class that builds FlexBuffers + *

This class presents all necessary APIs to create FlexBuffers. A `ByteBuffer` will be used to store the + * data. It can be created internally, or passed down in the constructor.

+ * + *

There are some limitations when compared to original implementation in C++. Most notably: + *

    + *
  • No support for mutations (might change in the future).

  • + *
  • Buffer size limited to {@link Integer#MAX_VALUE}

  • + *
  • Since Java does not support unsigned type, all unsigned operations accepts an immediate higher representation + * of similar type.

  • + *
+ *

+ */ +public class FlexBuffersBuilder { + + /** + * No keys or strings will be shared + */ + public static final int BUILDER_FLAG_NONE = 0; + /** + * Keys will be shared between elements. Identical keys will only be serialized once, thus possibly saving space. + * But serialization performance might be slower and consumes more memory. + */ + public static final int BUILDER_FLAG_SHARE_KEYS = 1; + /** + * Strings will be shared between elements. Identical strings will only be serialized once, thus possibly saving space. + * But serialization performance might be slower and consumes more memory. This is ideal if you expect many repeated + * strings on the message. + */ + public static final int BUILDER_FLAG_SHARE_STRINGS = 2; + /** + * Strings and keys will be shared between elements. + */ + public static final int BUILDER_FLAG_SHARE_KEYS_AND_STRINGS = 3; + /** + * Reserved for the future. + */ + public static final int BUILDER_FLAG_SHARE_KEY_VECTORS = 4; + /** + * Reserved for the future. + */ + public static final int BUILDER_FLAG_SHARE_ALL = 7; + + /// @cond FLATBUFFERS_INTERNAL + private static final int WIDTH_8 = 0; + private static final int WIDTH_16 = 1; + private static final int WIDTH_32 = 2; + private static final int WIDTH_64 = 3; + private final ReadWriteBuf bb; + private final ArrayList stack = new ArrayList<>(); + private final HashMap keyPool = new HashMap<>(); + private final HashMap stringPool = new HashMap<>(); + private final int flags; + private boolean finished = false; + + // A lambda to sort map keys + private Comparator keyComparator = new Comparator() { + @Override + public int compare(Value o1, Value o2) { + int ia = o1.key; + int io = o2.key; + byte c1, c2; + do { + c1 = bb.get(ia); + c2 = bb.get(io); + if (c1 == 0) + return c1 - c2; + ia++; + io++; + } + while (c1 == c2); + return c1 - c2; + } + }; + /// @endcond + + /** + * Constructs a newly allocated {@code FlexBuffersBuilder} with {@link #BUILDER_FLAG_SHARE_KEYS} set. + * @param bufSize size of buffer in bytes. + */ + public FlexBuffersBuilder(int bufSize) { + this(new ArrayReadWriteBuf(bufSize), BUILDER_FLAG_SHARE_KEYS); + } + + /** + * Constructs a newly allocated {@code FlexBuffersBuilder} with {@link #BUILDER_FLAG_SHARE_KEYS} set. + */ + public FlexBuffersBuilder() { + this(256); + } + + /** + * Constructs a newly allocated {@code FlexBuffersBuilder}. + * + * @param bb `ByteBuffer` that will hold the message + * @param flags Share flags + */ + @Deprecated + public FlexBuffersBuilder(ByteBuffer bb, int flags) { + this(new ArrayReadWriteBuf(bb.array()), flags); + } + + public FlexBuffersBuilder(ReadWriteBuf bb, int flags) { + this.bb = bb; + this.flags = flags; + } + + /** + * Constructs a newly allocated {@code FlexBuffersBuilder}. + * By default same keys will be serialized only once + * @param bb `ByteBuffer` that will hold the message + */ + public FlexBuffersBuilder(ByteBuffer bb) { + this(bb, BUILDER_FLAG_SHARE_KEYS); + } + + /** + * Reset the FlexBuffersBuilder by purging all data that it holds. + */ + public void clear(){ + bb.clear(); + stack.clear(); + keyPool.clear(); + stringPool.clear(); + finished = false; + } + + /** + * Return `ByteBuffer` containing FlexBuffer message. {@code #finish()} must be called before calling this + * function otherwise an assert will trigger. + * + * @return `ByteBuffer` with finished message + */ + public ReadWriteBuf getBuffer() { + assert (finished); + return bb; + } + + /** + * Insert a null value into the buffer + */ + public void putNull() { + putNull(null); + } + + /** + * Insert a null value into the buffer + * @param key key used to store element in map + */ + public void putNull(String key) { + stack.add(Value.nullValue(putKey(key))); + } + + /** + * Insert a single boolean into the buffer + * @param val true or false + */ + public void putBoolean(boolean val) { + putBoolean(null, val); + } + + /** + * Insert a single boolean into the buffer + * @param key key used to store element in map + * @param val true or false + */ + public void putBoolean(String key, boolean val) { + stack.add(Value.bool(putKey(key), val)); + } + + private int putKey(String key) { + if (key == null) { + return -1; + } + int pos = bb.writePosition(); + if ((flags & BUILDER_FLAG_SHARE_KEYS) != 0) { + Integer keyFromPool = keyPool.get(key); + if (keyFromPool == null) { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + bb.put(keyBytes, 0, keyBytes.length); + bb.put((byte) 0); + keyPool.put(key, pos); + } else { + pos = keyFromPool; + } + } else { + byte[] keyBytes = key.getBytes(StandardCharsets.UTF_8); + bb.put(keyBytes, 0, keyBytes.length); + bb.put((byte) 0); + keyPool.put(key, pos); + } + return pos; + } + + /** + * Adds a integer into the buff + * @param val integer + */ + public void putInt(int val) { + putInt(null, val); + } + + /** + * Adds a integer into the buff + * @param key key used to store element in map + * @param val integer + */ + public void putInt(String key, int val) { + putInt(key, (long) val); + } + + /** + * Adds a integer into the buff + * @param key key used to store element in map + * @param val 64-bit integer + */ + public void putInt(String key, long val) { + int iKey = putKey(key); + if (Byte.MIN_VALUE <= val && val <= Byte.MAX_VALUE) { + stack.add(Value.int8(iKey, (int) val)); + } else if (Short.MIN_VALUE <= val && val <= Short.MAX_VALUE) { + stack.add(Value.int16(iKey, (int) val)); + } else if (Integer.MIN_VALUE <= val && val <= Integer.MAX_VALUE) { + stack.add(Value.int32(iKey, (int) val)); + } else { + stack.add(Value.int64(iKey, val)); + } + } + + /** + * Adds a 64-bit integer into the buff + * @param value integer + */ + public void putInt(long value) { + putInt(null, value); + } + + /** + * Adds a unsigned integer into the buff. + * @param value integer representing unsigned value + */ + public void putUInt(int value) { + putUInt(null, (long) value); + } + + /** + * Adds a unsigned integer (stored in a signed 64-bit integer) into the buff. + * @param value integer representing unsigned value + */ + public void putUInt(long value) { + putUInt(null, value); + } + + /** + * Adds a 64-bit unsigned integer (stored as {@link BigInteger}) into the buff. + * Warning: This operation might be very slow. + * @param value integer representing unsigned value + */ + public void putUInt64(BigInteger value) { + putUInt64(null, value.longValue()); + } + + private void putUInt64(String key, long value) { + stack.add(Value.uInt64(putKey(key), value)); + } + + private void putUInt(String key, long value) { + int iKey = putKey(key); + Value vVal; + + int width = widthUInBits(value); + + if (width == WIDTH_8) { + vVal = Value.uInt8(iKey, (int)value); + } else if (width == WIDTH_16) { + vVal = Value.uInt16(iKey, (int)value); + } else if (width == WIDTH_32) { + vVal = Value.uInt32(iKey, (int)value); + } else { + vVal = Value.uInt64(iKey, value); + } + stack.add(vVal); + } + + /** + * Adds a 32-bit float into the buff. + * @param value float representing value + */ + public void putFloat(float value) { + putFloat(null, value); + } + + /** + * Adds a 32-bit float into the buff. + * @param key key used to store element in map + * @param value float representing value + */ + public void putFloat(String key, float val) { + stack.add(Value.float32(putKey(key), val)); + } + + /** + * Adds a 64-bit float into the buff. + * @param value float representing value + */ + public void putFloat(double value) { + putFloat(null, value); + } + + /** + * Adds a 64-bit float into the buff. + * @param key key used to store element in map + * @param value float representing value + */ + public void putFloat(String key, double val) { + stack.add(Value.float64(putKey(key), val)); + } + + /** + * Adds a String into the buffer + * @param value string + * @return start position of string in the buffer + */ + public int putString(String value) { + return putString(null, value); + } + + /** + * Adds a String into the buffer + * @param key key used to store element in map + * @param value string + * @return start position of string in the buffer + */ + public int putString(String key, String val) { + int iKey = putKey(key); + if ((flags & FlexBuffersBuilder.BUILDER_FLAG_SHARE_STRINGS) != 0) { + Integer i = stringPool.get(val); + if (i == null) { + Value value = writeString(iKey, val); + stringPool.put(val, (int) value.iValue); + stack.add(value); + return (int) value.iValue; + } else { + int bitWidth = widthUInBits(val.length()); + stack.add(Value.blob(iKey, i, FBT_STRING, bitWidth)); + return i; + } + } else { + Value value = writeString(iKey, val); + stack.add(value); + return (int) value.iValue; + } + } + + private Value writeString(int key, String s) { + return writeBlob(key, s.getBytes(StandardCharsets.UTF_8), FBT_STRING, true); + } + + // in bits to fit a unsigned int + static int widthUInBits(long len) { + if (len <= byteToUnsignedInt((byte)0xff)) return WIDTH_8; + if (len <= shortToUnsignedInt((short)0xffff)) return WIDTH_16; + if (len <= intToUnsignedLong(0xffff_ffff)) return WIDTH_32; + return WIDTH_64; + } + + private Value writeBlob(int key, byte[] blob, int type, boolean trailing) { + int bitWidth = widthUInBits(blob.length); + int byteWidth = align(bitWidth); + writeInt(blob.length, byteWidth); + int sloc = bb.writePosition(); + bb.put(blob, 0, blob.length); + if (trailing) { + bb.put((byte) 0); + } + return Value.blob(key, sloc, type, bitWidth); + } + + // Align to prepare for writing a scalar with a certain size. + private int align(int alignment) { + int byteWidth = 1 << alignment; + int padBytes = Value.paddingBytes(bb.writePosition(), byteWidth); + while (padBytes-- != 0) { + bb.put((byte) 0); + } + return byteWidth; + } + + private void writeInt(long value, int byteWidth) { + switch (byteWidth) { + case 1: bb.put((byte) value); break; + case 2: bb.putShort((short) value); break; + case 4: bb.putInt((int) value); break; + case 8: bb.putLong(value); break; + } + } + + /** + * Adds a byte array into the message + * @param value byte array + * @return position in buffer as the start of byte array + */ + public int putBlob(byte[] value) { + return putBlob(null, value); + } + + /** + * Adds a byte array into the message + * @param key key used to store element in map + * @param value byte array + * @return position in buffer as the start of byte array + */ + public int putBlob(String key, byte[] val) { + int iKey = putKey(key); + Value value = writeBlob(iKey, val, FBT_BLOB, false); + stack.add(value); + return (int) value.iValue; + } + + /** + * Start a new vector in the buffer. + * @return a reference indicating position of the vector in buffer. This + * reference must be passed along when the vector is finished using endVector() + */ + public int startVector() { + return stack.size(); + } + + /** + * Finishes a vector, but writing the information in the buffer + * @param key key used to store element in map + * @param start reference for beginning of the vector. Returned by {@link startVector()} + * @param typed boolean indicating whether vector is typed + * @param fixed boolean indicating whether vector is fixed + * @return Reference to the vector + */ + public int endVector(String key, int start, boolean typed, boolean fixed) { + int iKey = putKey(key); + Value vec = createVector(iKey, start, stack.size() - start, typed, fixed, null); + // Remove temp elements and return vector. + while (stack.size() > start) { + stack.remove(stack.size() - 1); + } + stack.add(vec); + return (int) vec.iValue; + } + + /** + * Finish writing the message into the buffer. After that no other element must + * be inserted into the buffer. Also, you must call this function before start using the + * FlexBuffer message + * @return `ByteBuffer` containing the FlexBuffer message + */ + public ByteBuffer finish() { + // If you hit this assert, you likely have objects that were never included + // in a parent. You need to have exactly one root to finish a buffer. + // Check your Start/End calls are matched, and all objects are inside + // some other object. + assert (stack.size() == 1); + // Write root value. + int byteWidth = align(stack.get(0).elemWidth(bb.writePosition(), 0)); + writeAny(stack.get(0), byteWidth); + // Write root type. + bb.put(stack.get(0).storedPackedType()); + // Write root size. Normally determined by parent, but root has no parent :) + bb.put((byte) byteWidth); + this.finished = true; + return ByteBuffer.wrap(bb.data(), 0, bb.writePosition()); + } + + /* + * Create a vector based on the elements stored in the stack + * + * @param key reference to its key + * @param start element in the stack + * @param length size of the vector + * @param typed whether is TypedVector or not + * @param fixed whether is Fixed vector or not + * @param keys Value representing key vector + * @return Value representing the created vector + */ + private Value createVector(int key, int start, int length, boolean typed, boolean fixed, Value keys) { + if (fixed & !typed) + throw new UnsupportedOperationException("Untyped fixed vector is not supported"); + + // Figure out smallest bit width we can store this vector with. + int bitWidth = Math.max(WIDTH_8, widthUInBits(length)); + int prefixElems = 1; + if (keys != null) { + // If this vector is part of a map, we will pre-fix an offset to the keys + // to this vector. + bitWidth = Math.max(bitWidth, keys.elemWidth(bb.writePosition(), 0)); + prefixElems += 2; + } + int vectorType = FBT_KEY; + // Check bit widths and types for all elements. + for (int i = start; i < stack.size(); i++) { + int elemWidth = stack.get(i).elemWidth(bb.writePosition(), i + prefixElems); + bitWidth = Math.max(bitWidth, elemWidth); + if (typed) { + if (i == start) { + vectorType = stack.get(i).type; + if (!FlexBuffers.isTypedVectorElementType(vectorType)) { + throw new FlexBufferException("TypedVector does not support this element type"); + } + } else { + // If you get this assert, you are writing a typed vector with + // elements that are not all the same type. + assert (vectorType == stack.get(i).type); + } + } + } + // If you get this assert, your fixed types are not one of: + // Int / UInt / Float / Key. + assert (!fixed || FlexBuffers.isTypedVectorElementType(vectorType)); + + int byteWidth = align(bitWidth); + // Write vector. First the keys width/offset if available, and size. + if (keys != null) { + writeOffset(keys.iValue, byteWidth); + writeInt(1L << keys.minBitWidth, byteWidth); + } + if (!fixed) { + writeInt(length, byteWidth); + } + // Then the actual data. + int vloc = bb.writePosition(); + for (int i = start; i < stack.size(); i++) { + writeAny(stack.get(i), byteWidth); + } + // Then the types. + if (!typed) { + for (int i = start; i < stack.size(); i++) { + bb.put(stack.get(i).storedPackedType(bitWidth)); + } + } + return new Value(key, keys != null ? FBT_MAP + : (typed ? FlexBuffers.toTypedVector(vectorType, fixed ? length : 0) + : FBT_VECTOR), bitWidth, vloc); + } + + private void writeOffset(long val, int byteWidth) { + int reloff = (int) (bb.writePosition() - val); + assert (byteWidth == 8 || reloff < 1L << (byteWidth * 8)); + writeInt(reloff, byteWidth); + } + + private void writeAny(final Value val, int byteWidth) { + switch (val.type) { + case FBT_NULL: + case FBT_BOOL: + case FBT_INT: + case FBT_UINT: + writeInt(val.iValue, byteWidth); + break; + case FBT_FLOAT: + writeDouble(val.dValue, byteWidth); + break; + default: + writeOffset(val.iValue, byteWidth); + break; + } + } + + private void writeDouble(double val, int byteWidth) { + if (byteWidth == 4) { + bb.putFloat((float) val); + } else if (byteWidth == 8) { + bb.putDouble(val); + } + } + + /** + * Start a new map in the buffer. + * @return a reference indicating position of the map in buffer. This + * reference must be passed along when the map is finished using endMap() + */ + public int startMap() { + return stack.size(); + } + + /** + * Finishes a map, but writing the information in the buffer + * @param key key used to store element in map + * @param start reference for beginning of the map. Returned by {@link startMap()} + * @return Reference to the map + */ + public int endMap(String key, int start) { + int iKey = putKey(key); + + Collections.sort(stack.subList(start, stack.size()), keyComparator); + + Value keys = createKeyVector(start, stack.size() - start); + Value vec = createVector(iKey, start, stack.size() - start, false, false, keys); + // Remove temp elements and return map. + while (stack.size() > start) { + stack.remove(stack.size() - 1); + } + stack.add(vec); + return (int) vec.iValue; + } + + private Value createKeyVector(int start, int length) { + // Figure out smallest bit width we can store this vector with. + int bitWidth = Math.max(WIDTH_8, widthUInBits(length)); + int prefixElems = 1; + // Check bit widths and types for all elements. + for (int i = start; i < stack.size(); i++) { + int elemWidth = Value.elemWidth(FBT_KEY, WIDTH_8, stack.get(i).key, bb.writePosition(), i + prefixElems); + bitWidth = Math.max(bitWidth, elemWidth); + } + + int byteWidth = align(bitWidth); + // Write vector. First the keys width/offset if available, and size. + writeInt(length, byteWidth); + // Then the actual data. + int vloc = bb.writePosition(); + for (int i = start; i < stack.size(); i++) { + int pos = stack.get(i).key; + assert(pos != -1); + writeOffset(stack.get(i).key, byteWidth); + } + // Then the types. + return new Value(-1, FlexBuffers.toTypedVector(FBT_KEY,0), bitWidth, vloc); + } + + private static class Value { + final int type; + // for scalars, represents scalar size in bytes + // for vectors, represents the size + // for string, length + final int minBitWidth; + // float value + final double dValue; + // integer value + long iValue; + // position of the key associated with this value in buffer + int key; + + Value(int key, int type, int bitWidth, long iValue) { + this.key = key; + this.type = type; + this.minBitWidth = bitWidth; + this.iValue = iValue; + this.dValue = Double.MIN_VALUE; + } + + Value(int key, int type, int bitWidth, double dValue) { + this.key = key; + this.type = type; + this.minBitWidth = bitWidth; + this.dValue = dValue; + this.iValue = Long.MIN_VALUE; + } + + static Value nullValue(int key) { + return new Value(key, FBT_NULL, WIDTH_8, 0); + } + + static Value bool(int key, boolean b) { + return new Value(key, FBT_BOOL, WIDTH_8, b ? 1 : 0); + } + + static Value blob(int key, int position, int type, int bitWidth) { + return new Value(key, type, bitWidth, position); + } + + static Value int8(int key, int value) { + return new Value(key, FBT_INT, WIDTH_8, value); + } + + static Value int16(int key, int value) { + return new Value(key, FBT_INT, WIDTH_16, value); + } + + static Value int32(int key, int value) { + return new Value(key, FBT_INT, WIDTH_32, value); + } + + static Value int64(int key, long value) { + return new Value(key, FBT_INT, WIDTH_64, value); + } + + static Value uInt8(int key, int value) { + return new Value(key, FBT_UINT, WIDTH_8, value); + } + + static Value uInt16(int key, int value) { + return new Value(key, FBT_UINT, WIDTH_16, value); + } + + static Value uInt32(int key, int value) { + return new Value(key, FBT_UINT, WIDTH_32, value); + } + + static Value uInt64(int key, long value) { + return new Value(key, FBT_UINT, WIDTH_64, value); + } + + static Value float32(int key, float value) { + return new Value(key, FBT_FLOAT, WIDTH_32, value); + } + + static Value float64(int key, double value) { + return new Value(key, FBT_FLOAT, WIDTH_64, value); + } + + private byte storedPackedType() { + return storedPackedType(WIDTH_8); + } + + private byte storedPackedType(int parentBitWidth) { + return packedType(storedWidth(parentBitWidth), type); + } + + private static byte packedType(int bitWidth, int type) { + return (byte) (bitWidth | (type << 2)); + } + + private int storedWidth(int parentBitWidth) { + if (FlexBuffers.isTypeInline(type)) { + return Math.max(minBitWidth, parentBitWidth); + } else { + return minBitWidth; + } + } + + private int elemWidth(int bufSize, int elemIndex) { + return elemWidth(type, minBitWidth, iValue, bufSize, elemIndex); + } + + private static int elemWidth(int type, int minBitWidth, long iValue, int bufSize, int elemIndex) { + if (FlexBuffers.isTypeInline(type)) { + return minBitWidth; + } else { + // We have an absolute offset, but want to store a relative offset + // elem_index elements beyond the current buffer end. Since whether + // the relative offset fits in a certain byte_width depends on + // the size of the elements before it (and their alignment), we have + // to test for each size in turn. + + // Original implementation checks for largest scalar + // which is long unsigned int + for (int byteWidth = 1; byteWidth <= 32; byteWidth *= 2) { + // Where are we going to write this offset? + int offsetLoc = bufSize + paddingBytes(bufSize, byteWidth) + (elemIndex * byteWidth); + // Compute relative offset. + long offset = offsetLoc - iValue; + // Does it fit? + int bitWidth = widthUInBits(offset); + if (((1L) << bitWidth) == byteWidth) + return bitWidth; + } + assert (false); // Must match one of the sizes above. + return WIDTH_64; + } + } + + private static int paddingBytes(int bufSize, int scalarSize) { + return ((~bufSize) + 1) & (scalarSize - 1); + } + } +} + +/// @} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FloatVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FloatVector.java new file mode 100644 index 00000000000..5c505ba82ca --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/FloatVector.java @@ -0,0 +1,49 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of float values. + */ +public final class FloatVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public FloatVector __assign(int _vector, ByteBuffer _bb) { + __reset(_vector, Constants.SIZEOF_FLOAT, _bb); return this; + } + + /** + * Reads the float value at the given index. + * + * @param j The index from which the float value will be read. + * @return the float value at the given index. + */ + public float get(int j) { + return bb.getFloat(__element(j)); + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/IntVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/IntVector.java new file mode 100644 index 00000000000..85549f4171b --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/IntVector.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of signed or unsigned 32-bit values. + */ +public final class IntVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public IntVector __assign(int _vector, ByteBuffer _bb) { + __reset(_vector, Constants.SIZEOF_INT, _bb); return this; + } + + /** + * Reads the integer at the given index. + * + * @param j The index from which the integer will be read. + * @return the 32-bit value at the given index. + */ + public int get(int j) { + return bb.getInt(__element(j)); + } + + /** + * Reads the integer at the given index, zero-extends it to type long, and returns the result, + * which is therefore in the range 0 through 4294967295. + * + * @param j The index from which the integer will be read. + * @return the unsigned 32-bit at the given index. + */ + public long getAsUnsigned(int j) { + return (long) get(j) & 0xFFFFFFFFL; + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/LongVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/LongVector.java new file mode 100644 index 00000000000..0ca5ab82e5a --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/LongVector.java @@ -0,0 +1,49 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of long values. + */ +public final class LongVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public LongVector __assign(int _vector, ByteBuffer _bb) { + __reset(_vector, Constants.SIZEOF_LONG, _bb); return this; + } + + /** + * Reads the long value at the given index. + * + * @param j The index from which the long value will be read. + * @return the signed 64-bit value at the given index. + */ + public long get(int j) { + return bb.getLong(__element(j)); + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ReadBuf.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ReadBuf.java new file mode 100644 index 00000000000..751361fa25b --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ReadBuf.java @@ -0,0 +1,81 @@ +package com.google.flatbuffers; + +/** + * Represent a chunk of data, where FlexBuffers will read from. + */ +public interface ReadBuf { + + /** + * Read boolean from data. Booleans as stored as single byte + * @param index position of the element in ReadBuf + * @return boolean element + */ + boolean getBoolean(int index); + + /** + * Read a byte from data. + * @param index position of the element in ReadBuf + * @return a byte + */ + byte get(int index); + + /** + * Read a short from data. + * @param index position of the element in ReadBuf + * @return a short + */ + short getShort(int index); + + /** + * Read a 32-bit int from data. + * @param index position of the element in ReadBuf + * @return an int + */ + int getInt(int index); + + /** + * Read a 64-bit long from data. + * @param index position of the element in ReadBuf + * @return a long + */ + long getLong(int index); + + /** + * Read a 32-bit float from data. + * @param index position of the element in ReadBuf + * @return a float + */ + float getFloat(int index); + + /** + * Read a 64-bit float from data. + * @param index position of the element in ReadBuf + * @return a double + */ + double getDouble(int index); + + /** + * Read an UTF-8 string from data. + * @param start initial element of the string + * @param size size of the string in bytes. + * @return a {@code String} + */ + String getString(int start, int size); + + /** + * Expose ReadBuf as an array of bytes. + * This method is meant to be as efficient as possible, so for a array-backed ReadBuf, it should + * return its own internal data. In case access to internal data is not possible, + * a copy of the data into an array of bytes might occur. + * @return ReadBuf as an array of bytes + */ + byte[] data(); + + /** + * Defines the size of the message in the buffer. It also determines last position that buffer + * can be read. Last byte to be accessed is in position {@code limit() -1}. + * @return indicate last position + */ + int limit(); + +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ReadWriteBuf.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ReadWriteBuf.java new file mode 100644 index 00000000000..6eb43bd5d30 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ReadWriteBuf.java @@ -0,0 +1,142 @@ +package com.google.flatbuffers; + +/** + * Interface to represent a read-write buffer. This interface will be used to access and write + * FlexBuffers message. + */ +public interface ReadWriteBuf extends ReadBuf { + + /** + * Clears (resets) the buffer so that it can be reused. Write position will be set to the + * start. + */ + void clear(); + + /** + * Put a boolean into the buffer at {@code writePosition()} . Booleans as stored as single + * byte. Write position will be incremented. + * @return boolean element + */ + void putBoolean(boolean value); + + /** + * Put an array of bytes into the buffer at {@code writePosition()}. Write position will be + * incremented. + * @param value the data to be copied + * @param start initial position on value to be copied + * @param length amount of bytes to be copied + */ + void put (byte[] value, int start, int length); + + /** + * Write a byte into the buffer at {@code writePosition()}. Write position will be + * incremented. + */ + void put(byte value); + + /** + * Write a 16-bit into in the buffer at {@code writePosition()}. Write position will be + * incremented. + */ + void putShort(short value); + + /** + * Write a 32-bit into in the buffer at {@code writePosition()}. Write position will be + * incremented. + */ + void putInt(int value); + + /** + * Write a 64-bit into in the buffer at {@code writePosition()}. Write position will be + * incremented. + */ + void putLong(long value); + + /** + * Write a 32-bit float into the buffer at {@code writePosition()}. Write position will be + * incremented. + */ + void putFloat(float value); + + /** + * Write a 64-bit float into the buffer at {@code writePosition()}. Write position will be + * incremented. + */ + void putDouble(double value); + + /** + * Write boolean into a given position on the buffer. Booleans as stored as single byte. + * @param index position of the element in buffer + */ + void setBoolean(int index, boolean value); + + /** + * Read a byte from data. + * @param index position of the element in the buffer + * @return a byte + */ + void set(int index, byte value); + + /** + * Write an array of bytes into the buffer. + * @param index initial position of the buffer to be written + * @param value the data to be copied + * @param start initial position on value to be copied + * @param length amount of bytes to be copied + */ + void set(int index, byte[] value, int start, int length); + + /** + * Read a short from data. + * @param index position of the element in ReadBuf + * @return a short + */ + void setShort(int index, short value); + + /** + * Read a 32-bit int from data. + * @param index position of the element in ReadBuf + * @return an int + */ + void setInt(int index, int value); + + /** + * Read a 64-bit long from data. + * @param index position of the element in ReadBuf + * @return a long + */ + void setLong(int index, long value); + + /** + * Read a 32-bit float from data. + * @param index position of the element in ReadBuf + * @return a float + */ + void setFloat(int index, float value); + + /** + * Read a 64-bit float from data. + * @param index position of the element in ReadBuf + * @return a double + */ + void setDouble(int index, double value); + + + int writePosition(); + /** + * Defines the size of the message in the buffer. It also determines last position that buffer + * can be read or write. Last byte to be accessed is in position {@code limit() -1}. + * @return indicate last position + */ + int limit(); + + /** + * Request capacity of the buffer. In case buffer is already larger + * than the requested, this method will just return true. Otherwise + * It might try to resize the buffer. + * + * @return true if buffer is able to offer + * the requested capacity + */ + boolean requestCapacity(int capacity); +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ShortVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ShortVector.java new file mode 100644 index 00000000000..b02ac3e490b --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/ShortVector.java @@ -0,0 +1,60 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of signed or unsigned 16-bit values. + */ +public final class ShortVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public ShortVector __assign(int _vector, ByteBuffer _bb) { + __reset(_vector, Constants.SIZEOF_SHORT, _bb); return this; + } + + /** + * Reads the short value at the given index. + * + * @param j The index from which the short value will be read. + * @return the 16-bit value at the given index. + */ + public short get(int j) { + return bb.getShort(__element(j)); + } + + /** + * Reads the short at the given index, zero-extends it to type int, and returns the result, + * which is therefore in the range 0 through 65535. + * + * @param j The index from which the short value will be read. + * @return the unsigned 16-bit at the given index. + */ + public int getAsUnsigned(int j) { + return (int) get(j) & 0xFFFF; + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/StringVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/StringVector.java new file mode 100644 index 00000000000..6c20775c317 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/StringVector.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of String. + */ +public final class StringVector extends BaseVector { + private Utf8 utf8 = Utf8.getDefault(); + + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _element_size Size of a vector element. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public StringVector __assign(int _vector, int _element_size, ByteBuffer _bb) { + __reset(_vector, _element_size, _bb); return this; + } + + /** + * Reads the String at the given index. + * + * @param j The index from which the String value will be read. + * @return the String at the given index. + */ + public String get(int j) { + return Table.__string(__element(j), bb, utf8); + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Struct.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Struct.java new file mode 100644 index 00000000000..c92164ff822 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Struct.java @@ -0,0 +1,61 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import java.nio.ByteBuffer; + +/// @cond FLATBUFFERS_INTERNAL + +/** + * All structs in the generated code derive from this class, and add their own accessors. + */ +public class Struct { + /** Used to hold the position of the `bb` buffer. */ + protected int bb_pos; + /** The underlying ByteBuffer to hold the data of the Struct. */ + protected ByteBuffer bb; + + /** + * Re-init the internal state with an external buffer {@code ByteBuffer} and an offset within. + * + * This method exists primarily to allow recycling Table instances without risking memory leaks + * due to {@code ByteBuffer} references. + */ + protected void __reset(int _i, ByteBuffer _bb) { + bb = _bb; + if (bb != null) { + bb_pos = _i; + } else { + bb_pos = 0; + } + } + + /** + * Resets internal state with a null {@code ByteBuffer} and a zero position. + * + * This method exists primarily to allow recycling Struct instances without risking memory leaks + * due to {@code ByteBuffer} references. The instance will be unusable until it is assigned + * again to a {@code ByteBuffer}. + * + * @param struct the instance to reset to initial state + */ + public void __reset() { + __reset(0, null); + } +} + +/// @endcond diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Table.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Table.java new file mode 100644 index 00000000000..7f416396e30 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Table.java @@ -0,0 +1,322 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/// @cond FLATBUFFERS_INTERNAL + +/** + * All tables in the generated code derive from this class, and add their own accessors. + */ +public class Table { + /** Used to hold the position of the `bb` buffer. */ + protected int bb_pos; + /** The underlying ByteBuffer to hold the data of the Table. */ + protected ByteBuffer bb; + /** Used to hold the vtable position. */ + private int vtable_start; + /** Used to hold the vtable size. */ + private int vtable_size; + Utf8 utf8 = Utf8.getDefault(); + + /** + * Get the underlying ByteBuffer. + * + * @return Returns the Table's ByteBuffer. + */ + public ByteBuffer getByteBuffer() { return bb; } + + /** + * Look up a field in the vtable. + * + * @param vtable_offset An `int` offset to the vtable in the Table's ByteBuffer. + * @return Returns an offset into the object, or `0` if the field is not present. + */ + protected int __offset(int vtable_offset) { + return vtable_offset < vtable_size ? bb.getShort(vtable_start + vtable_offset) : 0; + } + + protected static int __offset(int vtable_offset, int offset, ByteBuffer bb) { + int vtable = bb.capacity() - offset; + return bb.getShort(vtable + vtable_offset - bb.getInt(vtable)) + vtable; + } + + /** + * Retrieve a relative offset. + * + * @param offset An `int` index into the Table's ByteBuffer containing the relative offset. + * @return Returns the relative offset stored at `offset`. + */ + protected int __indirect(int offset) { + return offset + bb.getInt(offset); + } + + /** + * Retrieve a relative offset. + * + * @param offset An `int` index into a ByteBuffer containing the relative offset. + * @param bb from which the relative offset will be retrieved. + * @return Returns the relative offset stored at `offset`. + */ + protected static int __indirect(int offset, ByteBuffer bb) { + return offset + bb.getInt(offset); + } + + /** + * Create a Java `String` from UTF-8 data stored inside the FlatBuffer. + * + * This allocates a new string and converts to wide chars upon each access, + * which is not very efficient. Instead, each FlatBuffer string also comes with an + * accessor based on __vector_as_bytebuffer below, which is much more efficient, + * assuming your Java program can handle UTF-8 data directly. + * + * @param offset An `int` index into the Table's ByteBuffer. + * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`. + */ + protected String __string(int offset) { + return __string(offset, bb, utf8); + } + + /** + * Create a Java `String` from UTF-8 data stored inside the FlatBuffer. + * + * This allocates a new string and converts to wide chars upon each access, + * which is not very efficient. Instead, each FlatBuffer string also comes with an + * accessor based on __vector_as_bytebuffer below, which is much more efficient, + * assuming your Java program can handle UTF-8 data directly. + * + * @param offset An `int` index into the Table's ByteBuffer. + * @param bb Table ByteBuffer used to read a string at given offset. + * @param utf8 decoder that creates a Java `String` from UTF-8 characters. + * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`. + */ + protected static String __string(int offset, ByteBuffer bb, Utf8 utf8) { + offset += bb.getInt(offset); + int length = bb.getInt(offset); + return utf8.decodeUtf8(bb, offset + SIZEOF_INT, length); + } + + /** + * Get the length of a vector. + * + * @param offset An `int` index into the Table's ByteBuffer. + * @return Returns the length of the vector whose offset is stored at `offset`. + */ + protected int __vector_len(int offset) { + offset += bb_pos; + offset += bb.getInt(offset); + return bb.getInt(offset); + } + + /** + * Get the start data of a vector. + * + * @param offset An `int` index into the Table's ByteBuffer. + * @return Returns the start of the vector data whose offset is stored at `offset`. + */ + protected int __vector(int offset) { + offset += bb_pos; + return offset + bb.getInt(offset) + SIZEOF_INT; // data starts after the length + } + + /** + * Get a whole vector as a ByteBuffer. + * + * This is efficient, since it only allocates a new {@link ByteBuffer} object, + * but does not actually copy the data, it still refers to the same bytes + * as the original ByteBuffer. Also useful with nested FlatBuffers, etc. + * + * @param vector_offset The position of the vector in the byte buffer + * @param elem_size The size of each element in the array + * @return The {@link ByteBuffer} for the array + */ + protected ByteBuffer __vector_as_bytebuffer(int vector_offset, int elem_size) { + int o = __offset(vector_offset); + if (o == 0) return null; + ByteBuffer bb = this.bb.duplicate().order(ByteOrder.LITTLE_ENDIAN); + int vectorstart = __vector(o); + bb.position(vectorstart); + bb.limit(vectorstart + __vector_len(o) * elem_size); + return bb; + } + + /** + * Initialize vector as a ByteBuffer. + * + * This is more efficient than using duplicate, since it doesn't copy the data + * nor allocattes a new {@link ByteBuffer}, creating no garbage to be collected. + * + * @param bb The {@link ByteBuffer} for the array + * @param vector_offset The position of the vector in the byte buffer + * @param elem_size The size of each element in the array + * @return The {@link ByteBuffer} for the array + */ + protected ByteBuffer __vector_in_bytebuffer(ByteBuffer bb, int vector_offset, int elem_size) { + int o = this.__offset(vector_offset); + if (o == 0) return null; + int vectorstart = __vector(o); + bb.rewind(); + bb.limit(vectorstart + __vector_len(o) * elem_size); + bb.position(vectorstart); + return bb; + } + + /** + * Initialize any Table-derived type to point to the union at the given `offset`. + * + * @param t A `Table`-derived type that should point to the union at `offset`. + * @param offset An `int` index into the Table's ByteBuffer. + * @return Returns the Table that points to the union at `offset`. + */ + protected Table __union(Table t, int offset) { + return __union(t, offset, bb); + } + + /** + * Initialize any Table-derived type to point to the union at the given `offset`. + * + * @param t A `Table`-derived type that should point to the union at `offset`. + * @param offset An `int` index into the Table's ByteBuffer. + * @param bb Table ByteBuffer used to initialize the object Table-derived type. + * @return Returns the Table that points to the union at `offset`. + */ + protected static Table __union(Table t, int offset, ByteBuffer bb) { + t.__reset(__indirect(offset, bb), bb); + return t; + } + + /** + * Check if a {@link ByteBuffer} contains a file identifier. + * + * @param bb A {@code ByteBuffer} to check if it contains the identifier + * `ident`. + * @param ident A `String` identifier of the FlatBuffer file. + * @return True if the buffer contains the file identifier + */ + protected static boolean __has_identifier(ByteBuffer bb, String ident) { + if (ident.length() != FILE_IDENTIFIER_LENGTH) + throw new AssertionError("FlatBuffers: file identifier must be length " + + FILE_IDENTIFIER_LENGTH); + for (int i = 0; i < FILE_IDENTIFIER_LENGTH; i++) { + if (ident.charAt(i) != (char)bb.get(bb.position() + SIZEOF_INT + i)) return false; + } + return true; + } + + /** + * Sort tables by the key. + * + * @param offsets An 'int' indexes of the tables into the bb. + * @param bb A {@code ByteBuffer} to get the tables. + */ + protected void sortTables(int[] offsets, final ByteBuffer bb) { + Integer[] off = new Integer[offsets.length]; + for (int i = 0; i < offsets.length; i++) off[i] = offsets[i]; + java.util.Arrays.sort(off, new java.util.Comparator() { + public int compare(Integer o1, Integer o2) { + return keysCompare(o1, o2, bb); + } + }); + for (int i = 0; i < offsets.length; i++) offsets[i] = off[i]; + } + + /** + * Compare two tables by the key. + * + * @param o1 An 'Integer' index of the first key into the bb. + * @param o2 An 'Integer' index of the second key into the bb. + * @param bb A {@code ByteBuffer} to get the keys. + */ + protected int keysCompare(Integer o1, Integer o2, ByteBuffer bb) { return 0; } + + /** + * Compare two strings in the buffer. + * + * @param offset_1 An 'int' index of the first string into the bb. + * @param offset_2 An 'int' index of the second string into the bb. + * @param bb A {@code ByteBuffer} to get the strings. + */ + protected static int compareStrings(int offset_1, int offset_2, ByteBuffer bb) { + offset_1 += bb.getInt(offset_1); + offset_2 += bb.getInt(offset_2); + int len_1 = bb.getInt(offset_1); + int len_2 = bb.getInt(offset_2); + int startPos_1 = offset_1 + SIZEOF_INT; + int startPos_2 = offset_2 + SIZEOF_INT; + int len = Math.min(len_1, len_2); + for(int i = 0; i < len; i++) { + if (bb.get(i + startPos_1) != bb.get(i + startPos_2)) + return bb.get(i + startPos_1) - bb.get(i + startPos_2); + } + return len_1 - len_2; + } + + /** + * Compare string from the buffer with the 'String' object. + * + * @param offset_1 An 'int' index of the first string into the bb. + * @param key Second string as a byte array. + * @param bb A {@code ByteBuffer} to get the first string. + */ + protected static int compareStrings(int offset_1, byte[] key, ByteBuffer bb) { + offset_1 += bb.getInt(offset_1); + int len_1 = bb.getInt(offset_1); + int len_2 = key.length; + int startPos_1 = offset_1 + Constants.SIZEOF_INT; + int len = Math.min(len_1, len_2); + for (int i = 0; i < len; i++) { + if (bb.get(i + startPos_1) != key[i]) + return bb.get(i + startPos_1) - key[i]; + } + return len_1 - len_2; + } + + /** + * Re-init the internal state with an external buffer {@code ByteBuffer} and an offset within. + * + * This method exists primarily to allow recycling Table instances without risking memory leaks + * due to {@code ByteBuffer} references. + */ + protected void __reset(int _i, ByteBuffer _bb) { + bb = _bb; + if (bb != null) { + bb_pos = _i; + vtable_start = bb_pos - bb.getInt(bb_pos); + vtable_size = bb.getShort(vtable_start); + } else { + bb_pos = 0; + vtable_start = 0; + vtable_size = 0; + } + } + + /** + * Resets the internal state with a null {@code ByteBuffer} and a zero position. + * + * This method exists primarily to allow recycling Table instances without risking memory leaks + * due to {@code ByteBuffer} references. The instance will be unusable until it is assigned + * again to a {@code ByteBuffer}. + */ + public void __reset() { + __reset(0, null); + } +} + +/// @endcond diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/UnionVector.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/UnionVector.java new file mode 100644 index 00000000000..986cfea4000 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/UnionVector.java @@ -0,0 +1,52 @@ +/* + * Copyright 2019 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import static com.google.flatbuffers.Constants.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.charset.Charset; + +/** + * Helper type for accessing vector of unions. + */ +public final class UnionVector extends BaseVector { + /** + * Assigns vector access object to vector data. + * + * @param _vector Start data of a vector. + * @param _element_size Size of a vector element. + * @param _bb Table's ByteBuffer. + * @return Returns current vector access object assigned to vector data whose offset is stored at + * `vector`. + */ + public UnionVector __assign(int _vector, int _element_size, ByteBuffer _bb) { + __reset(_vector, _element_size, _bb); return this; + } + + + /** + * Initialize any Table-derived type to point to the union at the given `index`. + * + * @param obj A `Table`-derived type that should point to the union at `index`. + * @param j An `int` index into the union vector. + * @return Returns the Table that points to the union at `index`. + */ + public Table get(Table obj, int j) { + return Table.__union(obj, __element(j), bb); + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8.java new file mode 100644 index 00000000000..e8af8ad6c7f --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8.java @@ -0,0 +1,247 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import java.nio.ByteBuffer; + +import static java.lang.Character.MAX_SURROGATE; +import static java.lang.Character.MIN_SURROGATE; +import static java.lang.Character.MIN_HIGH_SURROGATE; +import static java.lang.Character.MIN_LOW_SURROGATE; +import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; +import static java.lang.Character.isSurrogatePair; +import static java.lang.Character.toCodePoint; + +public abstract class Utf8 { + + /** + * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, + * this method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in + * both time and space. + * + * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired + * surrogates) + */ + public abstract int encodedLength(CharSequence sequence); + + /** + * Encodes the given characters to the target {@link ByteBuffer} using UTF-8 encoding. + * + *

Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) + * and the capabilities of the platform. + * + * @param in the source string to be encoded + * @param out the target buffer to receive the encoded string. + */ + public abstract void encodeUtf8(CharSequence in, ByteBuffer out); + + /** + * Decodes the given UTF-8 portion of the {@link ByteBuffer} into a {@link String}. + * + * @throws IllegalArgumentException if the input is not valid UTF-8. + */ + public abstract String decodeUtf8(ByteBuffer buffer, int offset, int length); + + private static Utf8 DEFAULT; + + /** + * Get the default UTF-8 processor. + * @return the default processor + */ + public static Utf8 getDefault() { + if (DEFAULT == null) { + DEFAULT = new Utf8Safe(); + } + return DEFAULT; + } + + /** + * Set the default instance of the UTF-8 processor. + * @param instance the new instance to use + */ + public static void setDefault(Utf8 instance) { + DEFAULT = instance; + } + + /** + * Encode a Java's CharSequence UTF8 codepoint into a byte array. + * @param in CharSequence to be encoded + * @param start start position of the first char in the codepoint + * @param out byte array of 4 bytes to be filled + * @return return the amount of bytes occupied by the codepoint + */ + public static int encodeUtf8CodePoint(CharSequence in, int start, byte[] out) { + // utf8 codepoint needs at least 4 bytes + assert out.length >= 4; + + final int inLength = in.length(); + if (start >= inLength) { + return 0; + } + + char c = in.charAt(start); + if (c < 0x80) { + // One byte (0xxx xxxx) + out[0] = (byte) c; + return 1; + } else if (c < 0x800) { + // Two bytes (110x xxxx 10xx xxxx) + out[0] = (byte) (0xC0 | (c >>> 6)); + out[1] = (byte) (0x80 | (0x3F & c)); + return 2; + } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx) + // Maximum single-char code point is 0xFFFF, 16 bits. + out[0] = (byte) (0xE0 | (c >>> 12)); + out[1] =(byte) (0x80 | (0x3F & (c >>> 6))); + out[2] = (byte) (0x80 | (0x3F & c)); + return 3; + } else { + // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx) + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 + // bytes + final char low; + if (start + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(start+1)))) { + throw new UnpairedSurrogateException(start, inLength); + } + int codePoint = toCodePoint(c, low); + out[0] = (byte) ((0xF << 4) | (codePoint >>> 18)); + out[1] = (byte) (0x80 | (0x3F & (codePoint >>> 12))); + out[2] = (byte) (0x80 | (0x3F & (codePoint >>> 6))); + out[3] = (byte) (0x80 | (0x3F & codePoint)); + return 4; + } + } + + /** + * Utility methods for decoding bytes into {@link String}. Callers are responsible for extracting + * bytes (possibly using Unsafe methods), and checking remaining bytes. All other UTF-8 validity + * checks and codepoint conversion happen in this class. + */ + static class DecodeUtil { + + /** + * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. + */ + static boolean isOneByte(byte b) { + return b >= 0; + } + + /** + * Returns whether this is a two-byte codepoint with the form '10XXXXXX'. + */ + static boolean isTwoBytes(byte b) { + return b < (byte) 0xE0; + } + + /** + * Returns whether this is a three-byte codepoint with the form '110XXXXX'. + */ + static boolean isThreeBytes(byte b) { + return b < (byte) 0xF0; + } + + static void handleOneByte(byte byte1, char[] resultArr, int resultPos) { + resultArr[resultPos] = (char) byte1; + } + + static void handleTwoBytes( + byte byte1, byte byte2, char[] resultArr, int resultPos) + throws IllegalArgumentException { + // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and + // overlong 2-byte, '11000001'. + if (byte1 < (byte) 0xC2) { + throw new IllegalArgumentException("Invalid UTF-8: Illegal leading byte in 2 bytes utf"); + } + if (isNotTrailingByte(byte2)) { + throw new IllegalArgumentException("Invalid UTF-8: Illegal trailing byte in 2 bytes utf"); + } + resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); + } + + static void handleThreeBytes( + byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos) + throws IllegalArgumentException { + if (isNotTrailingByte(byte2) + // overlong? 5 most significant bits must not all be zero + || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) + // check for illegal surrogate codepoints + || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) + || isNotTrailingByte(byte3)) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + resultArr[resultPos] = (char) + (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); + } + + static void handleFourBytes( + byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) + throws IllegalArgumentException{ + if (isNotTrailingByte(byte2) + // Check that 1 <= plane <= 16. Tricky optimized form of: + // valid 4-byte leading byte? + // if (byte1 > (byte) 0xF4 || + // overlong? 4 most significant bits must not all be zero + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // codepoint larger than the highest code point (U+10FFFF)? + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 + || isNotTrailingByte(byte3) + || isNotTrailingByte(byte4)) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + int codepoint = ((byte1 & 0x07) << 18) + | (trailingByteValue(byte2) << 12) + | (trailingByteValue(byte3) << 6) + | trailingByteValue(byte4); + resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); + resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); + } + + /** + * Returns whether the byte is not a valid continuation of the form '10XXXXXX'. + */ + private static boolean isNotTrailingByte(byte b) { + return b > (byte) 0xBF; + } + + /** + * Returns the actual value of the trailing byte (removes the prefix '10') for composition. + */ + private static int trailingByteValue(byte b) { + return b & 0x3F; + } + + private static char highSurrogate(int codePoint) { + return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + + (codePoint >>> 10)); + } + + private static char lowSurrogate(int codePoint) { + return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff)); + } + } + + // These UTF-8 handling methods are copied from Guava's Utf8Unsafe class with a modification to throw + // a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can + // fallback to more lenient behavior. + static class UnpairedSurrogateException extends IllegalArgumentException { + UnpairedSurrogateException(int index, int length) { + super("Unpaired surrogate at index " + index + " of " + length); + } + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8Old.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8Old.java new file mode 100644 index 00000000000..c568105a01c --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8Old.java @@ -0,0 +1,106 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package com.google.flatbuffers; + +import java.nio.ByteBuffer; +import java.nio.CharBuffer; +import java.nio.charset.CharacterCodingException; +import java.nio.charset.CharsetDecoder; +import java.nio.charset.CharsetEncoder; +import java.nio.charset.CoderResult; +import java.nio.charset.StandardCharsets; + +/** + * This class implements the Utf8 API using the Java Utf8 encoder. Use + * Utf8.setDefault(new Utf8Old()); to use it. + */ +public class Utf8Old extends Utf8 { + + private static class Cache { + final CharsetEncoder encoder; + final CharsetDecoder decoder; + CharSequence lastInput = null; + ByteBuffer lastOutput = null; + + Cache() { + encoder = StandardCharsets.UTF_8.newEncoder(); + decoder = StandardCharsets.UTF_8.newDecoder(); + } + } + + // ThreadLocal.withInitial() is not used to make the following code compatible with Android API + // level 23. + private static final ThreadLocal CACHE = + new ThreadLocal() { + @Override + protected Cache initialValue() { + return new Cache(); + } + }; + + // Play some games so that the old encoder doesn't pay twice for computing + // the length of the encoded string. + + @Override + public int encodedLength(CharSequence in) { + final Cache cache = CACHE.get(); + int estimated = (int) (in.length() * cache.encoder.maxBytesPerChar()); + if (cache.lastOutput == null || cache.lastOutput.capacity() < estimated) { + cache.lastOutput = ByteBuffer.allocate(Math.max(128, estimated)); + } + cache.lastOutput.clear(); + cache.lastInput = in; + CharBuffer wrap = (in instanceof CharBuffer) ? + (CharBuffer) in : CharBuffer.wrap(in); + CoderResult result = cache.encoder.encode(wrap, cache.lastOutput, true); + if (result.isError()) { + try { + result.throwException(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("bad character encoding", e); + } + } + cache.lastOutput.flip(); + return cache.lastOutput.remaining(); + } + + @Override + public void encodeUtf8(CharSequence in, ByteBuffer out) { + final Cache cache = CACHE.get(); + if (cache.lastInput != in) { + // Update the lastOutput to match our input, although flatbuffer should + // never take this branch. + encodedLength(in); + } + out.put(cache.lastOutput); + } + + @Override + public String decodeUtf8(ByteBuffer buffer, int offset, int length) { + CharsetDecoder decoder = CACHE.get().decoder; + decoder.reset(); + buffer = buffer.duplicate(); + buffer.position(offset); + buffer.limit(offset + length); + try { + CharBuffer result = decoder.decode(buffer); + return result.toString(); + } catch (CharacterCodingException e) { + throw new IllegalArgumentException("Bad encoding", e); + } + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8Safe.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8Safe.java new file mode 100644 index 00000000000..060379fd0f9 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/Utf8Safe.java @@ -0,0 +1,421 @@ +package com.google.flatbuffers; + +import java.nio.ByteBuffer; +import static java.lang.Character.MAX_SURROGATE; +import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; +import static java.lang.Character.MIN_SURROGATE; +import static java.lang.Character.isSurrogatePair; +import static java.lang.Character.toCodePoint; + +/** + * A set of low-level, high-performance static utility methods related + * to the UTF-8 character encoding. This class has no dependencies + * outside of the core JDK libraries. + * + *

There are several variants of UTF-8. The one implemented by + * this class is the restricted definition of UTF-8 introduced in + * Unicode 3.1, which mandates the rejection of "overlong" byte + * sequences as well as rejection of 3-byte surrogate codepoint byte + * sequences. Note that the UTF-8 decoder included in Oracle's JDK + * has been modified to also reject "overlong" byte sequences, but (as + * of 2011) still accepts 3-byte surrogate codepoint byte sequences. + * + *

The byte sequences considered valid by this class are exactly + * those that can be roundtrip converted to Strings and back to bytes + * using the UTF-8 charset, without loss:

 {@code
+ * Arrays.equals(bytes, new String(bytes, Internal.UTF_8).getBytes(Internal.UTF_8))
+ * }
+ * + *

See the Unicode Standard,
+ * Table 3-6. UTF-8 Bit Distribution,
+ * Table 3-7. Well Formed UTF-8 Byte Sequences. + */ +final public class Utf8Safe extends Utf8 { + + /** + * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, + * this method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in + * both time and space. + * + * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired + * surrogates) + */ + private static int computeEncodedLength(CharSequence sequence) { + // Warning to maintainers: this implementation is highly optimized. + int utf16Length = sequence.length(); + int utf8Length = utf16Length; + int i = 0; + + // This loop optimizes for pure ASCII. + while (i < utf16Length && sequence.charAt(i) < 0x80) { + i++; + } + + // This loop optimizes for chars less than 0x800. + for (; i < utf16Length; i++) { + char c = sequence.charAt(i); + if (c < 0x800) { + utf8Length += ((0x7f - c) >>> 31); // branch free! + } else { + utf8Length += encodedLengthGeneral(sequence, i); + break; + } + } + + if (utf8Length < utf16Length) { + // Necessary and sufficient condition for overflow because of maximum 3x expansion + throw new IllegalArgumentException("UTF-8 length does not fit in int: " + + (utf8Length + (1L << 32))); + } + return utf8Length; + } + + private static int encodedLengthGeneral(CharSequence sequence, int start) { + int utf16Length = sequence.length(); + int utf8Length = 0; + for (int i = start; i < utf16Length; i++) { + char c = sequence.charAt(i); + if (c < 0x800) { + utf8Length += (0x7f - c) >>> 31; // branch free! + } else { + utf8Length += 2; + // jdk7+: if (Character.isSurrogate(c)) { + if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) { + // Check that we have a well-formed surrogate pair. + int cp = Character.codePointAt(sequence, i); + if (cp < MIN_SUPPLEMENTARY_CODE_POINT) { + throw new Utf8Safe.UnpairedSurrogateException(i, utf16Length); + } + i++; + } + } + } + return utf8Length; + } + + public static String decodeUtf8Array(byte[] bytes, int index, int size) { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((index | size | bytes.length - index - size) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size)); + } + + int offset = index; + final int limit = offset + size; + + // The longest possible resulting String is the same as the number of input bytes, when it is + // all ASCII. For other cases, this over-allocates and we will truncate in the end. + char[] resultArr = new char[size]; + int resultPos = 0; + + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (offset < limit) { + byte b = bytes[offset]; + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + + while (offset < limit) { + byte byte1 = bytes[offset++]; + if (DecodeUtil.isOneByte(byte1)) { + DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (offset < limit) { + byte b = bytes[offset]; + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + } else if (DecodeUtil.isTwoBytes(byte1)) { + if (offset >= limit) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + DecodeUtil.handleTwoBytes(byte1, /* byte2 */ bytes[offset++], resultArr, resultPos++); + } else if (DecodeUtil.isThreeBytes(byte1)) { + if (offset >= limit - 1) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + DecodeUtil.handleThreeBytes( + byte1, + /* byte2 */ bytes[offset++], + /* byte3 */ bytes[offset++], + resultArr, + resultPos++); + } else { + if (offset >= limit - 2) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + DecodeUtil.handleFourBytes( + byte1, + /* byte2 */ bytes[offset++], + /* byte3 */ bytes[offset++], + /* byte4 */ bytes[offset++], + resultArr, + resultPos++); + // 4-byte case requires two chars. + resultPos++; + } + } + + return new String(resultArr, 0, resultPos); + } + + public static String decodeUtf8Buffer(ByteBuffer buffer, int offset, + int length) { + // Bitwise OR combines the sign bits so any negative value fails the check. + if ((offset | length | buffer.limit() - offset - length) < 0) { + throw new ArrayIndexOutOfBoundsException( + String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), + offset, length)); + } + + final int limit = offset + length; + + // The longest possible resulting String is the same as the number of input bytes, when it is + // all ASCII. For other cases, this over-allocates and we will truncate in the end. + char[] resultArr = new char[length]; + int resultPos = 0; + + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (offset < limit) { + byte b = buffer.get(offset); + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + + while (offset < limit) { + byte byte1 = buffer.get(offset++); + if (DecodeUtil.isOneByte(byte1)) { + DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (offset < limit) { + byte b = buffer.get(offset); + if (!DecodeUtil.isOneByte(b)) { + break; + } + offset++; + DecodeUtil.handleOneByte(b, resultArr, resultPos++); + } + } else if (DecodeUtil.isTwoBytes(byte1)) { + if (offset >= limit) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + DecodeUtil.handleTwoBytes( + byte1, /* byte2 */ buffer.get(offset++), resultArr, resultPos++); + } else if (DecodeUtil.isThreeBytes(byte1)) { + if (offset >= limit - 1) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + DecodeUtil.handleThreeBytes( + byte1, + /* byte2 */ buffer.get(offset++), + /* byte3 */ buffer.get(offset++), + resultArr, + resultPos++); + } else { + if (offset >= limit - 2) { + throw new IllegalArgumentException("Invalid UTF-8"); + } + DecodeUtil.handleFourBytes( + byte1, + /* byte2 */ buffer.get(offset++), + /* byte3 */ buffer.get(offset++), + /* byte4 */ buffer.get(offset++), + resultArr, + resultPos++); + // 4-byte case requires two chars. + resultPos++; + } + } + + return new String(resultArr, 0, resultPos); + } + + @Override + public int encodedLength(CharSequence in) { + return computeEncodedLength(in); + } + + /** + * Decodes the given UTF-8 portion of the {@link ByteBuffer} into a {@link String}. + * + * @throws IllegalArgumentException if the input is not valid UTF-8. + */ + @Override + public String decodeUtf8(ByteBuffer buffer, int offset, int length) + throws IllegalArgumentException { + if (buffer.hasArray()) { + return decodeUtf8Array(buffer.array(), buffer.arrayOffset() + offset, length); + } else { + return decodeUtf8Buffer(buffer, offset, length); + } + } + + + private static void encodeUtf8Buffer(CharSequence in, ByteBuffer out) { + final int inLength = in.length(); + int outIx = out.position(); + int inIx = 0; + + // Since ByteBuffer.putXXX() already checks boundaries for us, no need to explicitly check + // access. Assume the buffer is big enough and let it handle the out of bounds exception + // if it occurs. + try { + // Designed to take advantage of + // https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination + for (char c; inIx < inLength && (c = in.charAt(inIx)) < 0x80; ++inIx) { + out.put(outIx + inIx, (byte) c); + } + if (inIx == inLength) { + // Successfully encoded the entire string. + out.position(outIx + inIx); + return; + } + + outIx += inIx; + for (char c; inIx < inLength; ++inIx, ++outIx) { + c = in.charAt(inIx); + if (c < 0x80) { + // One byte (0xxx xxxx) + out.put(outIx, (byte) c); + } else if (c < 0x800) { + // Two bytes (110x xxxx 10xx xxxx) + + // Benchmarks show put performs better than putShort here (for HotSpot). + out.put(outIx++, (byte) (0xC0 | (c >>> 6))); + out.put(outIx, (byte) (0x80 | (0x3F & c))); + } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { + // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx) + // Maximum single-char code point is 0xFFFF, 16 bits. + + // Benchmarks show put performs better than putShort here (for HotSpot). + out.put(outIx++, (byte) (0xE0 | (c >>> 12))); + out.put(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); + out.put(outIx, (byte) (0x80 | (0x3F & c))); + } else { + // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx) + + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 + // bytes + final char low; + if (inIx + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { + throw new UnpairedSurrogateException(inIx, inLength); + } + // TODO(nathanmittler): Consider using putInt() to improve performance. + int codePoint = toCodePoint(c, low); + out.put(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); + out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); + out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); + out.put(outIx, (byte) (0x80 | (0x3F & codePoint))); + } + } + + // Successfully encoded the entire string. + out.position(outIx); + } catch (IndexOutOfBoundsException e) { + // TODO(nathanmittler): Consider making the API throw IndexOutOfBoundsException instead. + + // If we failed in the outer ASCII loop, outIx will not have been updated. In this case, + // use inIx to determine the bad write index. + int badWriteIndex = out.position() + Math.max(inIx, outIx - out.position() + 1); + throw new ArrayIndexOutOfBoundsException( + "Failed writing " + in.charAt(inIx) + " at index " + badWriteIndex); + } + } + + private static int encodeUtf8Array(CharSequence in, byte[] out, + int offset, int length) { + int utf16Length = in.length(); + int j = offset; + int i = 0; + int limit = offset + length; + // Designed to take advantage of + // https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination + for (char c; i < utf16Length && i + j < limit && (c = in.charAt(i)) < 0x80; i++) { + out[j + i] = (byte) c; + } + if (i == utf16Length) { + return j + utf16Length; + } + j += i; + for (char c; i < utf16Length; i++) { + c = in.charAt(i); + if (c < 0x80 && j < limit) { + out[j++] = (byte) c; + } else if (c < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes + out[j++] = (byte) ((0xF << 6) | (c >>> 6)); + out[j++] = (byte) (0x80 | (0x3F & c)); + } else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) && j <= limit - 3) { + // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes + out[j++] = (byte) ((0xF << 5) | (c >>> 12)); + out[j++] = (byte) (0x80 | (0x3F & (c >>> 6))); + out[j++] = (byte) (0x80 | (0x3F & c)); + } else if (j <= limit - 4) { + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, + // four UTF-8 bytes + final char low; + if (i + 1 == in.length() + || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) { + throw new UnpairedSurrogateException((i - 1), utf16Length); + } + int codePoint = Character.toCodePoint(c, low); + out[j++] = (byte) ((0xF << 4) | (codePoint >>> 18)); + out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 12))); + out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 6))); + out[j++] = (byte) (0x80 | (0x3F & codePoint)); + } else { + // If we are surrogates and we're not a surrogate pair, always throw an + // UnpairedSurrogateException instead of an ArrayOutOfBoundsException. + if ((Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) + && (i + 1 == in.length() + || !Character.isSurrogatePair(c, in.charAt(i + 1)))) { + throw new UnpairedSurrogateException(i, utf16Length); + } + throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j); + } + } + return j; + } + + /** + * Encodes the given characters to the target {@link ByteBuffer} using UTF-8 encoding. + * + *

Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) + * and the capabilities of the platform. + * + * @param in the source string to be encoded + * @param out the target buffer to receive the encoded string. + */ + @Override + public void encodeUtf8(CharSequence in, ByteBuffer out) { + if (out.hasArray()) { + int start = out.arrayOffset(); + int end = encodeUtf8Array(in, out.array(), start + out.position(), + out.remaining()); + out.position(end - start); + } else { + encodeUtf8Buffer(in, out); + } + } + + // These UTF-8 handling methods are copied from Guava's Utf8Unsafe class with + // a modification to throw a local exception. This exception can be caught + // to fallback to more lenient behavior. + static class UnpairedSurrogateException extends IllegalArgumentException { + UnpairedSurrogateException(int index, int length) { + super("Unpaired surrogate at index " + index + " of " + length); + } + } +} diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/AdvancedFeatures.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/AdvancedFeatures.java new file mode 100644 index 00000000000..cf49086cd5f --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/AdvancedFeatures.java @@ -0,0 +1,16 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +/** + * New schema language features that are not supported by old code generators. + */ +@SuppressWarnings("unused") +public final class AdvancedFeatures { + private AdvancedFeatures() { } + public static final long AdvancedArrayFeatures = 1L; + public static final long AdvancedUnionFeatures = 2L; + public static final long OptionalScalars = 4L; + public static final long DefaultVectorsAndStrings = 8L; +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/BaseType.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/BaseType.java new file mode 100644 index 00000000000..ef6ba2d4019 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/BaseType.java @@ -0,0 +1,33 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +@SuppressWarnings("unused") +public final class BaseType { + private BaseType() { } + public static final byte None = 0; + public static final byte UType = 1; + public static final byte Bool = 2; + public static final byte Byte = 3; + public static final byte UByte = 4; + public static final byte Short = 5; + public static final byte UShort = 6; + public static final byte Int = 7; + public static final byte UInt = 8; + public static final byte Long = 9; + public static final byte ULong = 10; + public static final byte Float = 11; + public static final byte Double = 12; + public static final byte String = 13; + public static final byte Vector = 14; + public static final byte Obj = 15; + public static final byte Union = 16; + public static final byte Array = 17; + public static final byte Vector64 = 18; + public static final byte MaxBaseType = 19; + + public static final String[] names = { "None", "UType", "Bool", "Byte", "UByte", "Short", "UShort", "Int", "UInt", "Long", "ULong", "Float", "Double", "String", "Vector", "Obj", "Union", "Array", "Vector64", "MaxBaseType", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Enum.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Enum.java new file mode 100644 index 00000000000..a28a158d0b8 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Enum.java @@ -0,0 +1,135 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Enum extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Enum getRootAsEnum(ByteBuffer _bb) { return getRootAsEnum(_bb, new Enum()); } + public static Enum getRootAsEnum(ByteBuffer _bb, Enum obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Enum __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public com.google.flatbuffers.reflection.EnumVal values(int j) { return values(new com.google.flatbuffers.reflection.EnumVal(), j); } + public com.google.flatbuffers.reflection.EnumVal values(com.google.flatbuffers.reflection.EnumVal obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int valuesLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.EnumVal valuesByKey(long key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.EnumVal.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.EnumVal valuesByKey(com.google.flatbuffers.reflection.EnumVal obj, long key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.EnumVal.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.EnumVal.Vector valuesVector() { return valuesVector(new com.google.flatbuffers.reflection.EnumVal.Vector()); } + public com.google.flatbuffers.reflection.EnumVal.Vector valuesVector(com.google.flatbuffers.reflection.EnumVal.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public boolean isUnion() { int o = __offset(8); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public com.google.flatbuffers.reflection.Type underlyingType() { return underlyingType(new com.google.flatbuffers.reflection.Type()); } + public com.google.flatbuffers.reflection.Type underlyingType(com.google.flatbuffers.reflection.Type obj) { int o = __offset(10); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); } + public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int attributesLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(12); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(12); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String documentation(int j) { int o = __offset(14); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int documentationLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } + public StringVector documentationVector() { return documentationVector(new StringVector()); } + public StringVector documentationVector(StringVector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + /** + * File that this Enum is declared in. + */ + public String declarationFile() { int o = __offset(16); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer declarationFileAsByteBuffer() { return __vector_as_bytebuffer(16, 1); } + public ByteBuffer declarationFileInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 16, 1); } + + public static int createEnum(FlatBufferBuilder builder, + int nameOffset, + int valuesOffset, + boolean isUnion, + int underlyingTypeOffset, + int attributesOffset, + int documentationOffset, + int declarationFileOffset) { + builder.startTable(7); + Enum.addDeclarationFile(builder, declarationFileOffset); + Enum.addDocumentation(builder, documentationOffset); + Enum.addAttributes(builder, attributesOffset); + Enum.addUnderlyingType(builder, underlyingTypeOffset); + Enum.addValues(builder, valuesOffset); + Enum.addName(builder, nameOffset); + Enum.addIsUnion(builder, isUnion); + return Enum.endEnum(builder); + } + + public static void startEnum(FlatBufferBuilder builder) { builder.startTable(7); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); } + public static void addValues(FlatBufferBuilder builder, int valuesOffset) { builder.addOffset(1, valuesOffset, 0); } + public static int createValuesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startValuesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addIsUnion(FlatBufferBuilder builder, boolean isUnion) { builder.addBoolean(2, isUnion, false); } + public static void addUnderlyingType(FlatBufferBuilder builder, int underlyingTypeOffset) { builder.addOffset(3, underlyingTypeOffset, 0); } + public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(4, attributesOffset, 0); } + public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(5, documentationOffset, 0); } + public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDeclarationFile(FlatBufferBuilder builder, int declarationFileOffset) { builder.addOffset(6, declarationFileOffset, 0); } + public static int endEnum(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // name + builder.required(o, 6); // values + builder.required(o, 10); // underlying_type + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static Enum __lookup_by_key(Enum obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Enum() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Enum get(int j) { return get(new Enum(), j); } + public Enum get(Enum obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Enum getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public Enum getByKey(Enum obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/EnumVal.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/EnumVal.java new file mode 100644 index 00000000000..024e05057b1 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/EnumVal.java @@ -0,0 +1,116 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class EnumVal extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static EnumVal getRootAsEnumVal(ByteBuffer _bb) { return getRootAsEnumVal(_bb, new EnumVal()); } + public static EnumVal getRootAsEnumVal(ByteBuffer _bb, EnumVal obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public EnumVal __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public long value() { int o = __offset(6); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public com.google.flatbuffers.reflection.Type unionType() { return unionType(new com.google.flatbuffers.reflection.Type()); } + public com.google.flatbuffers.reflection.Type unionType(com.google.flatbuffers.reflection.Type obj) { int o = __offset(10); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public String documentation(int j) { int o = __offset(12); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int documentationLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; } + public StringVector documentationVector() { return documentationVector(new StringVector()); } + public StringVector documentationVector(StringVector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); } + public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(14); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int attributesLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createEnumVal(FlatBufferBuilder builder, + int nameOffset, + long value, + int unionTypeOffset, + int documentationOffset, + int attributesOffset) { + builder.startTable(6); + EnumVal.addValue(builder, value); + EnumVal.addAttributes(builder, attributesOffset); + EnumVal.addDocumentation(builder, documentationOffset); + EnumVal.addUnionType(builder, unionTypeOffset); + EnumVal.addName(builder, nameOffset); + return EnumVal.endEnumVal(builder); + } + + public static void startEnumVal(FlatBufferBuilder builder) { builder.startTable(6); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(0, nameOffset, 0); } + public static void addValue(FlatBufferBuilder builder, long value) { builder.addLong(value); builder.slot(1); } + public static void addUnionType(FlatBufferBuilder builder, int unionTypeOffset) { builder.addOffset(3, unionTypeOffset, 0); } + public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(4, documentationOffset, 0); } + public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(5, attributesOffset, 0); } + public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endEnumVal(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // name + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { + long val_1 = _bb.getLong(__offset(6, o1, _bb)); + long val_2 = _bb.getLong(__offset(6, o2, _bb)); + return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0; + } + + public static EnumVal __lookup_by_key(EnumVal obj, int vectorLocation, long key, ByteBuffer bb) { + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + long val = bb.getLong(__offset(6, bb.capacity() - tableOffset, bb)); + int comp = val > key ? 1 : val < key ? -1 : 0; + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new EnumVal() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public EnumVal get(int j) { return get(new EnumVal(), j); } + public EnumVal get(EnumVal obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public EnumVal getByKey(long key) { return __lookup_by_key(null, __vector(), key, bb); } + public EnumVal getByKey(EnumVal obj, long key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Field.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Field.java new file mode 100644 index 00000000000..8cd742e01fc --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Field.java @@ -0,0 +1,155 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Field extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Field getRootAsField(ByteBuffer _bb) { return getRootAsField(_bb, new Field()); } + public static Field getRootAsField(ByteBuffer _bb, Field obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Field __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public com.google.flatbuffers.reflection.Type type() { return type(new com.google.flatbuffers.reflection.Type()); } + public com.google.flatbuffers.reflection.Type type(com.google.flatbuffers.reflection.Type obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public int id() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + public int offset() { int o = __offset(10); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + public long defaultInteger() { int o = __offset(12); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public double defaultReal() { int o = __offset(14); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; } + public boolean deprecated() { int o = __offset(16); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public boolean required() { int o = __offset(18); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public boolean key() { int o = __offset(20); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); } + public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(22); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int attributesLength() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(22); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(22); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(22); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String documentation(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int documentationLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; } + public StringVector documentationVector() { return documentationVector(new StringVector()); } + public StringVector documentationVector(StringVector obj) { int o = __offset(24); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public boolean optional() { int o = __offset(26); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + /** + * Number of padding octets to always add after this field. Structs only. + */ + public int padding() { int o = __offset(28); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + /** + * If the field uses 64-bit offsets. + */ + public boolean offset64() { int o = __offset(30); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + + public static int createField(FlatBufferBuilder builder, + int nameOffset, + int typeOffset, + int id, + int offset, + long defaultInteger, + double defaultReal, + boolean deprecated, + boolean required, + boolean key, + int attributesOffset, + int documentationOffset, + boolean optional, + int padding, + boolean offset64) { + builder.startTable(14); + Field.addDefaultReal(builder, defaultReal); + Field.addDefaultInteger(builder, defaultInteger); + Field.addDocumentation(builder, documentationOffset); + Field.addAttributes(builder, attributesOffset); + Field.addType(builder, typeOffset); + Field.addName(builder, nameOffset); + Field.addPadding(builder, padding); + Field.addOffset(builder, offset); + Field.addId(builder, id); + Field.addOffset64(builder, offset64); + Field.addOptional(builder, optional); + Field.addKey(builder, key); + Field.addRequired(builder, required); + Field.addDeprecated(builder, deprecated); + return Field.endField(builder); + } + + public static void startField(FlatBufferBuilder builder) { builder.startTable(14); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); } + public static void addType(FlatBufferBuilder builder, int typeOffset) { builder.addOffset(1, typeOffset, 0); } + public static void addId(FlatBufferBuilder builder, int id) { builder.addShort(2, (short) id, (short) 0); } + public static void addOffset(FlatBufferBuilder builder, int offset) { builder.addShort(3, (short) offset, (short) 0); } + public static void addDefaultInteger(FlatBufferBuilder builder, long defaultInteger) { builder.addLong(4, defaultInteger, 0L); } + public static void addDefaultReal(FlatBufferBuilder builder, double defaultReal) { builder.addDouble(5, defaultReal, 0.0); } + public static void addDeprecated(FlatBufferBuilder builder, boolean deprecated) { builder.addBoolean(6, deprecated, false); } + public static void addRequired(FlatBufferBuilder builder, boolean required) { builder.addBoolean(7, required, false); } + public static void addKey(FlatBufferBuilder builder, boolean key) { builder.addBoolean(8, key, false); } + public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(9, attributesOffset, 0); } + public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(10, documentationOffset, 0); } + public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addOptional(FlatBufferBuilder builder, boolean optional) { builder.addBoolean(11, optional, false); } + public static void addPadding(FlatBufferBuilder builder, int padding) { builder.addShort(12, (short) padding, (short) 0); } + public static void addOffset64(FlatBufferBuilder builder, boolean offset64) { builder.addBoolean(13, offset64, false); } + public static int endField(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // name + builder.required(o, 6); // type + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static Field __lookup_by_key(Field obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Field() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Field get(int j) { return get(new Field(), j); } + public Field get(Field obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Field getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public Field getByKey(Field obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/KeyValue.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/KeyValue.java new file mode 100644 index 00000000000..7279933c7df --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/KeyValue.java @@ -0,0 +1,88 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class KeyValue extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static KeyValue getRootAsKeyValue(ByteBuffer _bb) { return getRootAsKeyValue(_bb, new KeyValue()); } + public static KeyValue getRootAsKeyValue(ByteBuffer _bb, KeyValue obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public KeyValue __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String key() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer keyAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer keyInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public String value() { int o = __offset(6); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer valueAsByteBuffer() { return __vector_as_bytebuffer(6, 1); } + public ByteBuffer valueInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 6, 1); } + + public static int createKeyValue(FlatBufferBuilder builder, + int keyOffset, + int valueOffset) { + builder.startTable(2); + KeyValue.addValue(builder, valueOffset); + KeyValue.addKey(builder, keyOffset); + return KeyValue.endKeyValue(builder); + } + + public static void startKeyValue(FlatBufferBuilder builder) { builder.startTable(2); } + public static void addKey(FlatBufferBuilder builder, int keyOffset) { builder.addOffset(keyOffset); builder.slot(0); } + public static void addValue(FlatBufferBuilder builder, int valueOffset) { builder.addOffset(1, valueOffset, 0); } + public static int endKeyValue(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // key + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static KeyValue __lookup_by_key(KeyValue obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new KeyValue() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public KeyValue get(int j) { return get(new KeyValue(), j); } + public KeyValue get(KeyValue obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public KeyValue getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public KeyValue getByKey(KeyValue obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Object.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Object.java new file mode 100644 index 00000000000..62e3c5287aa --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Object.java @@ -0,0 +1,137 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Object extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Object getRootAsObject(ByteBuffer _bb) { return getRootAsObject(_bb, new Object()); } + public static Object getRootAsObject(ByteBuffer _bb, Object obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Object __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public com.google.flatbuffers.reflection.Field fields(int j) { return fields(new com.google.flatbuffers.reflection.Field(), j); } + public com.google.flatbuffers.reflection.Field fields(com.google.flatbuffers.reflection.Field obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int fieldsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.Field fieldsByKey(String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Field.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Field fieldsByKey(com.google.flatbuffers.reflection.Field obj, String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Field.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Field.Vector fieldsVector() { return fieldsVector(new com.google.flatbuffers.reflection.Field.Vector()); } + public com.google.flatbuffers.reflection.Field.Vector fieldsVector(com.google.flatbuffers.reflection.Field.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public boolean isStruct() { int o = __offset(8); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public int minalign() { int o = __offset(10); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public int bytesize() { int o = __offset(12); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); } + public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(14); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int attributesLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String documentation(int j) { int o = __offset(16); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int documentationLength() { int o = __offset(16); return o != 0 ? __vector_len(o) : 0; } + public StringVector documentationVector() { return documentationVector(new StringVector()); } + public StringVector documentationVector(StringVector obj) { int o = __offset(16); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + /** + * File that this Object is declared in. + */ + public String declarationFile() { int o = __offset(18); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer declarationFileAsByteBuffer() { return __vector_as_bytebuffer(18, 1); } + public ByteBuffer declarationFileInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 18, 1); } + + public static int createObject(FlatBufferBuilder builder, + int nameOffset, + int fieldsOffset, + boolean isStruct, + int minalign, + int bytesize, + int attributesOffset, + int documentationOffset, + int declarationFileOffset) { + builder.startTable(8); + Object.addDeclarationFile(builder, declarationFileOffset); + Object.addDocumentation(builder, documentationOffset); + Object.addAttributes(builder, attributesOffset); + Object.addBytesize(builder, bytesize); + Object.addMinalign(builder, minalign); + Object.addFields(builder, fieldsOffset); + Object.addName(builder, nameOffset); + Object.addIsStruct(builder, isStruct); + return Object.endObject(builder); + } + + public static void startObject(FlatBufferBuilder builder) { builder.startTable(8); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); } + public static void addFields(FlatBufferBuilder builder, int fieldsOffset) { builder.addOffset(1, fieldsOffset, 0); } + public static int createFieldsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startFieldsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addIsStruct(FlatBufferBuilder builder, boolean isStruct) { builder.addBoolean(2, isStruct, false); } + public static void addMinalign(FlatBufferBuilder builder, int minalign) { builder.addInt(3, minalign, 0); } + public static void addBytesize(FlatBufferBuilder builder, int bytesize) { builder.addInt(4, bytesize, 0); } + public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(5, attributesOffset, 0); } + public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(6, documentationOffset, 0); } + public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDeclarationFile(FlatBufferBuilder builder, int declarationFileOffset) { builder.addOffset(7, declarationFileOffset, 0); } + public static int endObject(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // name + builder.required(o, 6); // fields + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static Object __lookup_by_key(Object obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Object() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Object get(int j) { return get(new Object(), j); } + public Object get(Object obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Object getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public Object getByKey(Object obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/RPCCall.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/RPCCall.java new file mode 100644 index 00000000000..83af2378b7a --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/RPCCall.java @@ -0,0 +1,115 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class RPCCall extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static RPCCall getRootAsRPCCall(ByteBuffer _bb) { return getRootAsRPCCall(_bb, new RPCCall()); } + public static RPCCall getRootAsRPCCall(ByteBuffer _bb, RPCCall obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public RPCCall __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public com.google.flatbuffers.reflection.Object request() { return request(new com.google.flatbuffers.reflection.Object()); } + public com.google.flatbuffers.reflection.Object request(com.google.flatbuffers.reflection.Object obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public com.google.flatbuffers.reflection.Object response() { return response(new com.google.flatbuffers.reflection.Object()); } + public com.google.flatbuffers.reflection.Object response(com.google.flatbuffers.reflection.Object obj) { int o = __offset(8); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); } + public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(10); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int attributesLength() { int o = __offset(10); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(10); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(10); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(10); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String documentation(int j) { int o = __offset(12); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int documentationLength() { int o = __offset(12); return o != 0 ? __vector_len(o) : 0; } + public StringVector documentationVector() { return documentationVector(new StringVector()); } + public StringVector documentationVector(StringVector obj) { int o = __offset(12); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createRPCCall(FlatBufferBuilder builder, + int nameOffset, + int requestOffset, + int responseOffset, + int attributesOffset, + int documentationOffset) { + builder.startTable(5); + RPCCall.addDocumentation(builder, documentationOffset); + RPCCall.addAttributes(builder, attributesOffset); + RPCCall.addResponse(builder, responseOffset); + RPCCall.addRequest(builder, requestOffset); + RPCCall.addName(builder, nameOffset); + return RPCCall.endRPCCall(builder); + } + + public static void startRPCCall(FlatBufferBuilder builder) { builder.startTable(5); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); } + public static void addRequest(FlatBufferBuilder builder, int requestOffset) { builder.addOffset(1, requestOffset, 0); } + public static void addResponse(FlatBufferBuilder builder, int responseOffset) { builder.addOffset(2, responseOffset, 0); } + public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(3, attributesOffset, 0); } + public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(4, documentationOffset, 0); } + public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endRPCCall(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // name + builder.required(o, 6); // request + builder.required(o, 8); // response + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static RPCCall __lookup_by_key(RPCCall obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new RPCCall() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public RPCCall get(int j) { return get(new RPCCall(), j); } + public RPCCall get(RPCCall obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public RPCCall getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public RPCCall getByKey(RPCCall obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Schema.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Schema.java new file mode 100644 index 00000000000..af281aac48d --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Schema.java @@ -0,0 +1,127 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Schema extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Schema getRootAsSchema(ByteBuffer _bb) { return getRootAsSchema(_bb, new Schema()); } + public static Schema getRootAsSchema(ByteBuffer _bb, Schema obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public static boolean SchemaBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "BFBS"); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Schema __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public com.google.flatbuffers.reflection.Object objects(int j) { return objects(new com.google.flatbuffers.reflection.Object(), j); } + public com.google.flatbuffers.reflection.Object objects(com.google.flatbuffers.reflection.Object obj, int j) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int objectsLength() { int o = __offset(4); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.Object objectsByKey(String key) { int o = __offset(4); return o != 0 ? com.google.flatbuffers.reflection.Object.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Object objectsByKey(com.google.flatbuffers.reflection.Object obj, String key) { int o = __offset(4); return o != 0 ? com.google.flatbuffers.reflection.Object.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Object.Vector objectsVector() { return objectsVector(new com.google.flatbuffers.reflection.Object.Vector()); } + public com.google.flatbuffers.reflection.Object.Vector objectsVector(com.google.flatbuffers.reflection.Object.Vector obj) { int o = __offset(4); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public com.google.flatbuffers.reflection.Enum enums(int j) { return enums(new com.google.flatbuffers.reflection.Enum(), j); } + public com.google.flatbuffers.reflection.Enum enums(com.google.flatbuffers.reflection.Enum obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int enumsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.Enum enumsByKey(String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Enum.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Enum enumsByKey(com.google.flatbuffers.reflection.Enum obj, String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.Enum.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Enum.Vector enumsVector() { return enumsVector(new com.google.flatbuffers.reflection.Enum.Vector()); } + public com.google.flatbuffers.reflection.Enum.Vector enumsVector(com.google.flatbuffers.reflection.Enum.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String fileIdent() { int o = __offset(8); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer fileIdentAsByteBuffer() { return __vector_as_bytebuffer(8, 1); } + public ByteBuffer fileIdentInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 8, 1); } + public String fileExt() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer fileExtAsByteBuffer() { return __vector_as_bytebuffer(10, 1); } + public ByteBuffer fileExtInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 1); } + public com.google.flatbuffers.reflection.Object rootTable() { return rootTable(new com.google.flatbuffers.reflection.Object()); } + public com.google.flatbuffers.reflection.Object rootTable(com.google.flatbuffers.reflection.Object obj) { int o = __offset(12); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public com.google.flatbuffers.reflection.Service services(int j) { return services(new com.google.flatbuffers.reflection.Service(), j); } + public com.google.flatbuffers.reflection.Service services(com.google.flatbuffers.reflection.Service obj, int j) { int o = __offset(14); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int servicesLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.Service servicesByKey(String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.Service.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Service servicesByKey(com.google.flatbuffers.reflection.Service obj, String key) { int o = __offset(14); return o != 0 ? com.google.flatbuffers.reflection.Service.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.Service.Vector servicesVector() { return servicesVector(new com.google.flatbuffers.reflection.Service.Vector()); } + public com.google.flatbuffers.reflection.Service.Vector servicesVector(com.google.flatbuffers.reflection.Service.Vector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public long advancedFeatures() { int o = __offset(16); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + /** + * All the files used in this compilation. Files are relative to where + * flatc was invoked. + */ + public com.google.flatbuffers.reflection.SchemaFile fbsFiles(int j) { return fbsFiles(new com.google.flatbuffers.reflection.SchemaFile(), j); } + public com.google.flatbuffers.reflection.SchemaFile fbsFiles(com.google.flatbuffers.reflection.SchemaFile obj, int j) { int o = __offset(18); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int fbsFilesLength() { int o = __offset(18); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.SchemaFile fbsFilesByKey(String key) { int o = __offset(18); return o != 0 ? com.google.flatbuffers.reflection.SchemaFile.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.SchemaFile fbsFilesByKey(com.google.flatbuffers.reflection.SchemaFile obj, String key) { int o = __offset(18); return o != 0 ? com.google.flatbuffers.reflection.SchemaFile.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.SchemaFile.Vector fbsFilesVector() { return fbsFilesVector(new com.google.flatbuffers.reflection.SchemaFile.Vector()); } + public com.google.flatbuffers.reflection.SchemaFile.Vector fbsFilesVector(com.google.flatbuffers.reflection.SchemaFile.Vector obj) { int o = __offset(18); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createSchema(FlatBufferBuilder builder, + int objectsOffset, + int enumsOffset, + int fileIdentOffset, + int fileExtOffset, + int rootTableOffset, + int servicesOffset, + long advancedFeatures, + int fbsFilesOffset) { + builder.startTable(8); + Schema.addAdvancedFeatures(builder, advancedFeatures); + Schema.addFbsFiles(builder, fbsFilesOffset); + Schema.addServices(builder, servicesOffset); + Schema.addRootTable(builder, rootTableOffset); + Schema.addFileExt(builder, fileExtOffset); + Schema.addFileIdent(builder, fileIdentOffset); + Schema.addEnums(builder, enumsOffset); + Schema.addObjects(builder, objectsOffset); + return Schema.endSchema(builder); + } + + public static void startSchema(FlatBufferBuilder builder) { builder.startTable(8); } + public static void addObjects(FlatBufferBuilder builder, int objectsOffset) { builder.addOffset(0, objectsOffset, 0); } + public static int createObjectsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startObjectsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addEnums(FlatBufferBuilder builder, int enumsOffset) { builder.addOffset(1, enumsOffset, 0); } + public static int createEnumsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startEnumsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addFileIdent(FlatBufferBuilder builder, int fileIdentOffset) { builder.addOffset(2, fileIdentOffset, 0); } + public static void addFileExt(FlatBufferBuilder builder, int fileExtOffset) { builder.addOffset(3, fileExtOffset, 0); } + public static void addRootTable(FlatBufferBuilder builder, int rootTableOffset) { builder.addOffset(4, rootTableOffset, 0); } + public static void addServices(FlatBufferBuilder builder, int servicesOffset) { builder.addOffset(5, servicesOffset, 0); } + public static int createServicesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startServicesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addAdvancedFeatures(FlatBufferBuilder builder, long advancedFeatures) { builder.addLong(6, advancedFeatures, 0L); } + public static void addFbsFiles(FlatBufferBuilder builder, int fbsFilesOffset) { builder.addOffset(7, fbsFilesOffset, 0); } + public static int createFbsFilesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startFbsFilesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endSchema(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // objects + builder.required(o, 6); // enums + return o; + } + public static void finishSchemaBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "BFBS"); } + public static void finishSizePrefixedSchemaBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "BFBS"); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Schema get(int j) { return get(new Schema(), j); } + public Schema get(Schema obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/SchemaFile.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/SchemaFile.java new file mode 100644 index 00000000000..54c924ebae4 --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/SchemaFile.java @@ -0,0 +1,102 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * File specific information. + * Symbols declared within a file may be recovered by iterating over all + * symbols and examining the `declaration_file` field. + */ +@SuppressWarnings("unused") +public final class SchemaFile extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb) { return getRootAsSchemaFile(_bb, new SchemaFile()); } + public static SchemaFile getRootAsSchemaFile(ByteBuffer _bb, SchemaFile obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public SchemaFile __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + /** + * Filename, relative to project root. + */ + public String filename() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer filenameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer filenameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + /** + * Names of included files, relative to project root. + */ + public String includedFilenames(int j) { int o = __offset(6); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int includedFilenamesLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } + public StringVector includedFilenamesVector() { return includedFilenamesVector(new StringVector()); } + public StringVector includedFilenamesVector(StringVector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createSchemaFile(FlatBufferBuilder builder, + int filenameOffset, + int includedFilenamesOffset) { + builder.startTable(2); + SchemaFile.addIncludedFilenames(builder, includedFilenamesOffset); + SchemaFile.addFilename(builder, filenameOffset); + return SchemaFile.endSchemaFile(builder); + } + + public static void startSchemaFile(FlatBufferBuilder builder) { builder.startTable(2); } + public static void addFilename(FlatBufferBuilder builder, int filenameOffset) { builder.addOffset(filenameOffset); builder.slot(0); } + public static void addIncludedFilenames(FlatBufferBuilder builder, int includedFilenamesOffset) { builder.addOffset(1, includedFilenamesOffset, 0); } + public static int createIncludedFilenamesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startIncludedFilenamesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endSchemaFile(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // filename + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static SchemaFile __lookup_by_key(SchemaFile obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new SchemaFile() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public SchemaFile get(int j) { return get(new SchemaFile(), j); } + public SchemaFile get(SchemaFile obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public SchemaFile getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public SchemaFile getByKey(SchemaFile obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Service.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Service.java new file mode 100644 index 00000000000..da98d40939e --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Service.java @@ -0,0 +1,124 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Service extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Service getRootAsService(ByteBuffer _bb) { return getRootAsService(_bb, new Service()); } + public static Service getRootAsService(ByteBuffer _bb, Service obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Service __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String name() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public com.google.flatbuffers.reflection.RPCCall calls(int j) { return calls(new com.google.flatbuffers.reflection.RPCCall(), j); } + public com.google.flatbuffers.reflection.RPCCall calls(com.google.flatbuffers.reflection.RPCCall obj, int j) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int callsLength() { int o = __offset(6); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.RPCCall callsByKey(String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.RPCCall.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.RPCCall callsByKey(com.google.flatbuffers.reflection.RPCCall obj, String key) { int o = __offset(6); return o != 0 ? com.google.flatbuffers.reflection.RPCCall.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.RPCCall.Vector callsVector() { return callsVector(new com.google.flatbuffers.reflection.RPCCall.Vector()); } + public com.google.flatbuffers.reflection.RPCCall.Vector callsVector(com.google.flatbuffers.reflection.RPCCall.Vector obj) { int o = __offset(6); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributes(int j) { return attributes(new com.google.flatbuffers.reflection.KeyValue(), j); } + public com.google.flatbuffers.reflection.KeyValue attributes(com.google.flatbuffers.reflection.KeyValue obj, int j) { int o = __offset(8); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int attributesLength() { int o = __offset(8); return o != 0 ? __vector_len(o) : 0; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(String key) { int o = __offset(8); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(null, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue attributesByKey(com.google.flatbuffers.reflection.KeyValue obj, String key) { int o = __offset(8); return o != 0 ? com.google.flatbuffers.reflection.KeyValue.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector() { return attributesVector(new com.google.flatbuffers.reflection.KeyValue.Vector()); } + public com.google.flatbuffers.reflection.KeyValue.Vector attributesVector(com.google.flatbuffers.reflection.KeyValue.Vector obj) { int o = __offset(8); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String documentation(int j) { int o = __offset(10); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int documentationLength() { int o = __offset(10); return o != 0 ? __vector_len(o) : 0; } + public StringVector documentationVector() { return documentationVector(new StringVector()); } + public StringVector documentationVector(StringVector obj) { int o = __offset(10); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + /** + * File that this Service is declared in. + */ + public String declarationFile() { int o = __offset(12); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer declarationFileAsByteBuffer() { return __vector_as_bytebuffer(12, 1); } + public ByteBuffer declarationFileInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 12, 1); } + + public static int createService(FlatBufferBuilder builder, + int nameOffset, + int callsOffset, + int attributesOffset, + int documentationOffset, + int declarationFileOffset) { + builder.startTable(5); + Service.addDeclarationFile(builder, declarationFileOffset); + Service.addDocumentation(builder, documentationOffset); + Service.addAttributes(builder, attributesOffset); + Service.addCalls(builder, callsOffset); + Service.addName(builder, nameOffset); + return Service.endService(builder); + } + + public static void startService(FlatBufferBuilder builder) { builder.startTable(5); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(0); } + public static void addCalls(FlatBufferBuilder builder, int callsOffset) { builder.addOffset(1, callsOffset, 0); } + public static int createCallsVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startCallsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addAttributes(FlatBufferBuilder builder, int attributesOffset) { builder.addOffset(2, attributesOffset, 0); } + public static int createAttributesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startAttributesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDocumentation(FlatBufferBuilder builder, int documentationOffset) { builder.addOffset(3, documentationOffset, 0); } + public static int createDocumentationVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startDocumentationVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addDeclarationFile(FlatBufferBuilder builder, int declarationFileOffset) { builder.addOffset(4, declarationFileOffset, 0); } + public static int endService(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 4); // name + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(4, o1, _bb), __offset(4, o2, _bb), _bb); } + + public static Service __lookup_by_key(Service obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(4, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Service() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Service get(int j) { return get(new Service(), j); } + public Service get(Service obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Service getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public Service getByKey(Service obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Type.java b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Type.java new file mode 100644 index 00000000000..0d2d66dc11d --- /dev/null +++ b/third_party/flatbuffers/java/src/main/java/com/google/flatbuffers/reflection/Type.java @@ -0,0 +1,79 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package com.google.flatbuffers.reflection; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Type extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Type getRootAsType(ByteBuffer _bb) { return getRootAsType(_bb, new Type()); } + public static Type getRootAsType(ByteBuffer _bb, Type obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Type __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public byte baseType() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; } + public byte element() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) : 0; } + public int index() { int o = __offset(8); return o != 0 ? bb.getInt(o + bb_pos) : -1; } + public int fixedLength() { int o = __offset(10); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + /** + * The size (octets) of the `base_type` field. + */ + public long baseSize() { int o = __offset(12); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 4L; } + /** + * The size (octets) of the `element` field, if present. + */ + public long elementSize() { int o = __offset(14); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; } + + public static int createType(FlatBufferBuilder builder, + byte baseType, + byte element, + int index, + int fixedLength, + long baseSize, + long elementSize) { + builder.startTable(6); + Type.addElementSize(builder, elementSize); + Type.addBaseSize(builder, baseSize); + Type.addIndex(builder, index); + Type.addFixedLength(builder, fixedLength); + Type.addElement(builder, element); + Type.addBaseType(builder, baseType); + return Type.endType(builder); + } + + public static void startType(FlatBufferBuilder builder) { builder.startTable(6); } + public static void addBaseType(FlatBufferBuilder builder, byte baseType) { builder.addByte(0, baseType, 0); } + public static void addElement(FlatBufferBuilder builder, byte element) { builder.addByte(1, element, 0); } + public static void addIndex(FlatBufferBuilder builder, int index) { builder.addInt(2, index, -1); } + public static void addFixedLength(FlatBufferBuilder builder, int fixedLength) { builder.addShort(3, (short) fixedLength, (short) 0); } + public static void addBaseSize(FlatBufferBuilder builder, long baseSize) { builder.addInt(4, (int) baseSize, (int) 4L); } + public static void addElementSize(FlatBufferBuilder builder, long elementSize) { builder.addInt(5, (int) elementSize, (int) 0L); } + public static int endType(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Type get(int j) { return get(new Type(), j); } + public Type get(Type obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } +} + diff --git a/third_party/flatbuffers/java/src/test/java/DictionaryLookup b/third_party/flatbuffers/java/src/test/java/DictionaryLookup new file mode 120000 index 00000000000..231bcd8006c --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/DictionaryLookup @@ -0,0 +1 @@ +../../../../tests/DictionaryLookup \ No newline at end of file diff --git a/third_party/flatbuffers/java/src/test/java/JavaTest.java b/third_party/flatbuffers/java/src/test/java/JavaTest.java new file mode 100644 index 00000000000..c392e040eb3 --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/JavaTest.java @@ -0,0 +1,1533 @@ + +import static com.google.flatbuffers.Constants.*; +import static com.google.common.truth.Truth.assertThat; + +import DictionaryLookup.*; +import MyGame.Example.*; +import com.google.common.io.ByteStreams; +import optional_scalars.ScalarStuff; +import optional_scalars.OptionalByte; +import NamespaceA.*; +import NamespaceA.NamespaceB.*; +import com.google.flatbuffers.ByteBufferUtil; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FlexBuffers; +import com.google.flatbuffers.FlexBuffersBuilder; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.UnionVector; + +import com.google.flatbuffers.FlexBuffers.FlexBufferException; +import com.google.flatbuffers.FlexBuffers.Reference; +import com.google.flatbuffers.FlexBuffers.Vector; +import com.google.flatbuffers.ArrayReadWriteBuf; +import com.google.flatbuffers.FlexBuffers.KeyVector; + +import java.io.*; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; +import java.nio.channels.FileChannel; +import java.nio.charset.StandardCharsets; +import java.util.Arrays; +import java.util.HashMap; +import java.util.Map; +import org.junit.Rule; +import org.junit.rules.TemporaryFolder; +import org.junit.runner.RunWith; +import org.junit.runners.JUnit4; + + +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@RunWith(JUnit4.class) +public class JavaTest { + + @Rule + public TemporaryFolder tempFolder = new TemporaryFolder(); + + @org.junit.Test + public void mainTest() throws IOException { + // First, let's test reading a FlatBuffer generated by C++ code: + // This file was generated from monsterdata_test.json + byte[] data = ByteStreams.toByteArray( + JavaTest.class.getClassLoader().getResourceAsStream("monsterdata_test.mon")); + + // Now test it: + ByteBuffer bb = ByteBuffer.wrap(data); + TestBuffer(bb); + TestPackUnpack(bb); + } + + @org.junit.Test + public void testFlatBufferBuilder() { + // We use an initial size of 1 to exercise the reallocation algorithm, + // normally a size larger than the typical FlatBuffer you generate would be + // better for performance. + FlatBufferBuilder fbb = new FlatBufferBuilder(1); + TestBuilderBasics(fbb, true); + TestBuilderBasics(fbb, false); + TestExtendedBuffer(fbb.dataBuffer().asReadOnlyBuffer()); + } + + @org.junit.Test + public void TestEnums() { + assertThat(Color.name(Color.Red)).isEqualTo("Red"); + assertThat(Color.name(Color.Blue)).isEqualTo("Blue"); + assertThat(Any.name(Any.NONE)).isEqualTo("NONE"); + assertThat(Any.name(Any.Monster)).isEqualTo("Monster"); + } + + static void TestBuffer(ByteBuffer bb) { + assertThat(Monster.MonsterBufferHasIdentifier(bb)).isEqualTo(true); + + Monster monster = Monster.getRootAsMonster(bb); + + assertThat(monster.hp()).isEqualTo((short) 80); + // default + assertThat(monster.mana()).isEqualTo((short) 150); + + assertThat(monster.name()).isEqualTo("MyMonster"); + // monster.friendly() // can't access, deprecated + + Vec3 pos = monster.pos(); + assertThat(pos.x()).isEqualTo(1.0f); + assertThat(pos.y()).isEqualTo(2.0f); + assertThat(pos.z()).isEqualTo(3.0f); + assertThat(pos.test1()).isEqualTo(3.0); + // issue: int != byte + assertThat(pos.test2()).isEqualTo((int) Color.Green); + Test t = pos.test3(); + assertThat(t.a()).isEqualTo((short) 5); + assertThat(t.b()).isEqualTo((byte) 6); + + assertThat(monster.testType()).isEqualTo((byte) Any.Monster); + Monster monster2 = new Monster(); + assertThat(monster.test(monster2) != null).isTrue(); + assertThat(monster2.name()).isEqualTo("Fred"); + + assertThat(monster.inventoryLength()).isEqualTo(5); + int invsum = 0; + for (int i = 0; i < monster.inventoryLength(); i++) + invsum += monster.inventory(i); + assertThat(invsum).isEqualTo(10); + + // Method using a vector access object: + ByteVector inventoryVector = monster.inventoryVector(); + assertThat(inventoryVector.length()).isEqualTo(5); + invsum = 0; + for (int i = 0; i < inventoryVector.length(); i++) + invsum += inventoryVector.getAsUnsigned(i); + assertThat(invsum).isEqualTo(10); + + // Alternative way of accessing a vector: + ByteBuffer ibb = monster.inventoryAsByteBuffer(); + invsum = 0; + while (ibb.position() < ibb.limit()) + invsum += ibb.get(); + assertThat(invsum).isEqualTo(10); + + Test test_0 = monster.test4(0); + Test test_1 = monster.test4(1); + assertThat(monster.test4Length()).isEqualTo(2); + assertThat(test_0.a() + test_0.b() + test_1.a() + test_1.b()).isEqualTo((Integer) 100); + + Test.Vector test4Vector = monster.test4Vector(); + test_0 = test4Vector.get(0); + test_1 = test4Vector.get(1); + assertThat(test4Vector.length()).isEqualTo(2); + assertThat(test_0.a() + test_0.b() + test_1.a() + test_1.b()).isEqualTo((Integer) 100); + + assertThat(monster.testarrayofstringLength()).isEqualTo(2); + assertThat(monster.testarrayofstring(0)).isEqualTo("test1"); + assertThat(monster.testarrayofstring(1)).isEqualTo("test2"); + + // Method using a vector access object: + StringVector testarrayofstringVector = monster.testarrayofstringVector(); + assertThat(testarrayofstringVector.length()).isEqualTo(2); + assertThat(testarrayofstringVector.get(0)).isEqualTo("test1"); + assertThat(testarrayofstringVector.get(1)).isEqualTo("test2"); + + assertThat(monster.testbool()).isEqualTo(true); + } + + // this method checks additional fields not present in the binary buffer read from file + // these new tests are performed on top of the regular tests + static void TestExtendedBuffer(ByteBuffer bb) { + TestBuffer(bb); + + Monster monster = Monster.getRootAsMonster(bb); + + assertThat(monster.testhashu32Fnv1()).isEqualTo((Integer.MAX_VALUE + 1L)); + } + + + @org.junit.Test public void TestNamespaceNesting() { + // reference / manipulate these to verify compilation + FlatBufferBuilder fbb = new FlatBufferBuilder(1); + + TableInNestedNS.startTableInNestedNS(fbb); + TableInNestedNS.addFoo(fbb, 1234); + int nestedTableOff = TableInNestedNS.endTableInNestedNS(fbb); + + TableInFirstNS.startTableInFirstNS(fbb); + TableInFirstNS.addFooTable(fbb, nestedTableOff); + int off = TableInFirstNS.endTableInFirstNS(fbb); + } + + @org.junit.Test public void TestNestedFlatBuffer() { + final String nestedMonsterName = "NestedMonsterName"; + final short nestedMonsterHp = 600; + final short nestedMonsterMana = 1024; + + FlatBufferBuilder fbb1 = new FlatBufferBuilder(16); + int str1 = fbb1.createString(nestedMonsterName); + Monster.startMonster(fbb1); + Monster.addName(fbb1, str1); + Monster.addHp(fbb1, nestedMonsterHp); + Monster.addMana(fbb1, nestedMonsterMana); + int monster1 = Monster.endMonster(fbb1); + Monster.finishMonsterBuffer(fbb1, monster1); + byte[] fbb1Bytes = fbb1.sizedByteArray(); + fbb1 = null; + + FlatBufferBuilder fbb2 = new FlatBufferBuilder(16); + int str2 = fbb2.createString("My Monster"); + int nestedBuffer = Monster.createTestnestedflatbufferVector(fbb2, fbb1Bytes); + Monster.startMonster(fbb2); + Monster.addName(fbb2, str2); + Monster.addHp(fbb2, (short)50); + Monster.addMana(fbb2, (short)32); + Monster.addTestnestedflatbuffer(fbb2, nestedBuffer); + int monster = Monster.endMonster(fbb2); + Monster.finishMonsterBuffer(fbb2, monster); + + // Now test the data extracted from the nested buffer + Monster mons = Monster.getRootAsMonster(fbb2.dataBuffer()); + Monster nestedMonster = mons.testnestedflatbufferAsMonster(); + + assertThat(nestedMonsterMana).isEqualTo(nestedMonster.mana()); + assertThat(nestedMonsterHp).isEqualTo(nestedMonster.hp()); + assertThat(nestedMonsterName).isEqualTo(nestedMonster.name()); + } + + @org.junit.Test public void TestCreateByteVector() { + FlatBufferBuilder fbb = new FlatBufferBuilder(16); + int str = fbb.createString("MyMonster"); + byte[] inventory = new byte[] { 0, 1, 2, 3, 4 }; + int vec = fbb.createByteVector(inventory); + Monster.startMonster(fbb); + Monster.addInventory(fbb, vec); + Monster.addName(fbb, str); + int monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat((Integer) monsterObject.inventory(1)).isEqualTo((int)inventory[1]); + assertThat(monsterObject.inventoryLength()).isEqualTo(inventory.length); + ByteVector inventoryVector = monsterObject.inventoryVector(); + assertThat(inventoryVector.getAsUnsigned(1)).isEqualTo((int)inventory[1]); + assertThat(inventoryVector.length()).isEqualTo(inventory.length); + + assertThat(ByteBuffer.wrap(inventory)).isEqualTo( + monsterObject.inventoryAsByteBuffer()); + } + + @org.junit.Test public void TestCreateUninitializedVector() { + FlatBufferBuilder fbb = new FlatBufferBuilder(16); + int str = fbb.createString("MyMonster"); + byte[] inventory = new byte[] { 0, 1, 2, 3, 4 }; + ByteBuffer bb = fbb.createUnintializedVector(1, inventory.length, 1); + for (byte i:inventory) { + bb.put(i); + } + int vec = fbb.endVector(); + Monster.startMonster(fbb); + Monster.addInventory(fbb, vec); + Monster.addName(fbb, str); + int monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat((Integer) monsterObject.inventory(1)).isEqualTo((int)inventory[1]); + assertThat(monsterObject.inventoryLength()).isEqualTo(inventory.length); + ByteVector inventoryVector = monsterObject.inventoryVector(); + assertThat(inventoryVector.getAsUnsigned(1)).isEqualTo((int)inventory[1]); + assertThat(inventoryVector.length()).isEqualTo(inventory.length); + assertThat(ByteBuffer.wrap(inventory)).isEqualTo( + monsterObject.inventoryAsByteBuffer()); + } + + @org.junit.Test public void TestByteBufferFactory() throws IOException { + File file = tempFolder.newFile("javatest.bin"); + final class MappedByteBufferFactory extends FlatBufferBuilder.ByteBufferFactory { + @Override + public ByteBuffer newByteBuffer(int capacity) { + ByteBuffer bb; + try { + RandomAccessFile f = new RandomAccessFile(file, "rw"); + bb = f.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, capacity).order(ByteOrder.LITTLE_ENDIAN); + f.close(); + } catch(Throwable e) { + System.out.println("FlatBuffers test: couldn't map ByteBuffer to a file"); + bb = null; + } + return bb; + } + } + + FlatBufferBuilder fbb = new FlatBufferBuilder(1, new MappedByteBufferFactory()); + + TestBuilderBasics(fbb, false); + } + + @org.junit.Test public void TestSizedInputStream() { + // Test on default FlatBufferBuilder that uses HeapByteBuffer + FlatBufferBuilder fbb = new FlatBufferBuilder(1); + + TestBuilderBasics(fbb, false); + + InputStream in = fbb.sizedInputStream(); + byte[] array = fbb.sizedByteArray(); + int count = 0; + int currentVal = 0; + + while (currentVal != -1 && count < array.length) { + try { + currentVal = in.read(); + } catch(java.io.IOException e) { + System.out.println("FlatBuffers test: couldn't read from InputStream"); + return; + } + assertThat((byte)currentVal).isEqualTo(array[count]); + count++; + } + assertThat(count).isEqualTo(array.length); + } + + void TestBuilderBasics(FlatBufferBuilder fbb, boolean sizePrefix) { + int[] names = {fbb.createString("Frodo"), fbb.createString("Barney"), fbb.createString("Wilma")}; + int[] off = new int[3]; + Monster.startMonster(fbb); + Monster.addName(fbb, names[0]); + off[0] = Monster.endMonster(fbb); + Monster.startMonster(fbb); + Monster.addName(fbb, names[1]); + off[1] = Monster.endMonster(fbb); + Monster.startMonster(fbb); + Monster.addName(fbb, names[2]); + off[2] = Monster.endMonster(fbb); + int sortMons = fbb.createSortedVectorOfTables(new Monster(), off); + + // We set up the same values as monsterdata.json: + + int str = fbb.createString("MyMonster"); + + int inv = Monster.createInventoryVector(fbb, new byte[] { 0, 1, 2, 3, 4 }); + + int fred = fbb.createString("Fred"); + Monster.startMonster(fbb); + Monster.addName(fbb, fred); + int mon2 = Monster.endMonster(fbb); + + Monster.startTest4Vector(fbb, 2); + Test.createTest(fbb, (short)10, (byte)20); + Test.createTest(fbb, (short)30, (byte)40); + int test4 = fbb.endVector(); + + int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] { + fbb.createString("test1"), + fbb.createString("test2") + }); + + Monster.startMonster(fbb); + Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, + Color.Green, (short)5, (byte)6)); + Monster.addHp(fbb, (short)80); + Monster.addName(fbb, str); + Monster.addInventory(fbb, inv); + Monster.addTestType(fbb, (byte)Any.Monster); + Monster.addTest(fbb, mon2); + Monster.addTest4(fbb, test4); + Monster.addTestarrayofstring(fbb, testArrayOfString); + Monster.addTestbool(fbb, true); + Monster.addTesthashu32Fnv1(fbb, Integer.MAX_VALUE + 1L); + Monster.addTestarrayoftables(fbb, sortMons); + int mon = Monster.endMonster(fbb); + + if (sizePrefix) { + Monster.finishSizePrefixedMonsterBuffer(fbb, mon); + } else { + Monster.finishMonsterBuffer(fbb, mon); + } + + // Write the result to a file for debugging purposes: + // Note that the binaries are not necessarily identical, since the JSON + // parser may serialize in a slightly different order than the above + // Java code. They are functionally equivalent though. + + try { + String filename = "monsterdata_java_wire" + (sizePrefix ? "_sp" : "") + ".mon"; + FileChannel fc = new FileOutputStream(tempFolder.newFile(filename)).getChannel(); + fc.write(fbb.dataBuffer().duplicate()); + fc.close(); + } catch(java.io.IOException e) { + System.out.println("FlatBuffers test: couldn't write file"); + return; + } + + // Test it: + ByteBuffer dataBuffer = fbb.dataBuffer(); + if (sizePrefix) { + assertThat(ByteBufferUtil.getSizePrefix(dataBuffer) + SIZE_PREFIX_LENGTH).isEqualTo( + dataBuffer.remaining()); + dataBuffer = ByteBufferUtil.removeSizePrefix(dataBuffer); + } + TestExtendedBuffer(dataBuffer); + + // Make sure it also works with read only ByteBuffers. This is slower, + // since creating strings incurs an additional copy + // (see Table.__string). + TestExtendedBuffer(dataBuffer.asReadOnlyBuffer()); + + //Attempt to mutate Monster fields and check whether the buffer has been mutated properly + // revert to original values after testing + Monster monster = Monster.getRootAsMonster(dataBuffer); + + // mana is optional and does not exist in the buffer so the mutation should fail + // the mana field should retain its default value + assertThat(monster.mutateMana((short)10)).isFalse(); + assertThat(monster.mana()).isEqualTo((short) 150); + + // Accessing a vector of sorted by the key tables + assertThat(monster.testarrayoftables(0).name()).isEqualTo("Barney"); + assertThat(monster.testarrayoftables(1).name()).isEqualTo("Frodo"); + assertThat(monster.testarrayoftables(2).name()).isEqualTo("Wilma"); + Monster.Vector testarrayoftablesVector = monster.testarrayoftablesVector(); + assertThat(testarrayoftablesVector.get(0).name()).isEqualTo("Barney"); + assertThat(testarrayoftablesVector.get(1).name()).isEqualTo("Frodo"); + assertThat(testarrayoftablesVector.get(2).name()).isEqualTo("Wilma"); + + // Example of searching for a table by the key + assertThat(monster.testarrayoftablesByKey("Frodo").name()).isEqualTo("Frodo"); + assertThat(monster.testarrayoftablesByKey("Barney").name()).isEqualTo("Barney"); + assertThat(monster.testarrayoftablesByKey("Wilma").name()).isEqualTo("Wilma"); + assertThat(testarrayoftablesVector.getByKey("Frodo").name()).isEqualTo("Frodo"); + assertThat(testarrayoftablesVector.getByKey("Barney").name()).isEqualTo("Barney"); + assertThat(testarrayoftablesVector.getByKey("Wilma").name()).isEqualTo("Wilma"); + + // testType is an existing field and mutating it should succeed + assertThat(monster.testType()).isEqualTo((byte) Any.Monster); + + //mutate the inventory vector + assertThat(monster.mutateInventory(0, 1)).isTrue(); + assertThat(monster.mutateInventory(1, 2)).isTrue(); + assertThat(monster.mutateInventory(2, 3)).isTrue(); + assertThat(monster.mutateInventory(3, 4)).isTrue(); + assertThat(monster.mutateInventory(4, 5)).isTrue(); + + for (int i = 0; i < monster.inventoryLength(); i++) { + assertThat((Integer) monster.inventory(i)).isEqualTo(i + 1); + } + ByteVector inventoryVector = monster.inventoryVector(); + for (int i = 0; i < inventoryVector.length(); i++) { + assertThat((int)inventoryVector.get(i)).isEqualTo(i + 1); + } + + //reverse mutation + assertThat(monster.mutateInventory(0, 0)).isTrue(); + assertThat(monster.mutateInventory(1, 1)).isTrue(); + assertThat(monster.mutateInventory(2, 2)).isTrue(); + assertThat(monster.mutateInventory(3, 3)).isTrue(); + assertThat(monster.mutateInventory(4, 4)).isTrue(); + + // get a struct field and edit one of its fields + Vec3 pos = monster.pos(); + assertThat(pos.x()).isEqualTo(1.0f); + pos.mutateX(55.0f); + assertThat(pos.x()).isEqualTo(55.0f); + pos.mutateX(1.0f); + assertThat(pos.x()).isEqualTo(1.0f); + } + + @org.junit.Test public void TestVectorOfUnions() { + final FlatBufferBuilder fbb = new FlatBufferBuilder(); + + final int swordAttackDamage = 1; + + final int[] characterVector = new int[] { + Attacker.createAttacker(fbb, swordAttackDamage), + }; + + final byte[] characterTypeVector = new byte[]{ + Character.MuLan, + }; + + Movie.finishMovieBuffer( + fbb, + Movie.createMovie( + fbb, + (byte)0, + (byte)0, + Movie.createCharactersTypeVector(fbb, characterTypeVector), + Movie.createCharactersVector(fbb, characterVector) + ) + ); + + final Movie movie = Movie.getRootAsMovie(fbb.dataBuffer()); + ByteVector charactersTypeByteVector = movie.charactersTypeVector(); + UnionVector charactersVector = movie.charactersVector(); + + assertThat(movie.charactersTypeLength()).isEqualTo(characterTypeVector.length); + assertThat(charactersTypeByteVector.length()).isEqualTo(characterTypeVector.length); + assertThat(movie.charactersLength()).isEqualTo(characterVector.length); + assertThat(charactersVector.length()).isEqualTo(characterVector.length); + + assertThat((Byte) movie.charactersType(0)).isEqualTo(characterTypeVector[0]); + assertThat(charactersTypeByteVector.get(0)).isEqualTo(characterTypeVector[0]); + + assertThat(((Attacker)movie.characters(new Attacker(), 0)).swordAttackDamage()).isEqualTo( + swordAttackDamage); + } + + @org.junit.Test public void TestFixedLengthArrays() { + FlatBufferBuilder builder = new FlatBufferBuilder(0); + + float a; + int[] b = new int[15]; + byte c; + int[][] d_a = new int[2][2]; + byte[] d_b = new byte[2]; + byte[][] d_c = new byte[2][2]; + long[][] d_d = new long[2][2]; + int e; + long[] f = new long[2]; + + a = 0.5f; + for (int i = 0; i < 15; i++) b[i] = i; + c = 1; + d_a[0][0] = 1; + d_a[0][1] = 2; + d_a[1][0] = 3; + d_a[1][1] = 4; + d_b[0] = TestEnum.B; + d_b[1] = TestEnum.C; + d_c[0][0] = TestEnum.A; + d_c[0][1] = TestEnum.B; + d_c[1][0] = TestEnum.C; + d_c[1][1] = TestEnum.B; + d_d[0][0] = -1; + d_d[0][1] = 1; + d_d[1][0] = -2; + d_d[1][1] = 2; + e = 2; + f[0] = -1; + f[1] = 1; + + int arrayOffset = ArrayStruct.createArrayStruct(builder, + a, b, c, d_a, d_b, d_c, d_d, e, f); + + // Create a table with the ArrayStruct. + ArrayTable.startArrayTable(builder); + ArrayTable.addA(builder, arrayOffset); + int tableOffset = ArrayTable.endArrayTable(builder); + + ArrayTable.finishArrayTableBuffer(builder, tableOffset); + + ArrayTable table = ArrayTable.getRootAsArrayTable(builder.dataBuffer()); + NestedStruct nested = new NestedStruct(); + + assertThat(table.a().a()).isEqualTo(0.5f); + for (int i = 0; i < 15; i++) + assertThat(table.a().b(i)).isEqualTo(i); + assertThat(table.a().c()).isEqualTo((byte)1); + assertThat(table.a().d(nested, 0).a(0)).isEqualTo(1); + assertThat(table.a().d(nested, 0).a(1)).isEqualTo(2); + assertThat(table.a().d(nested, 1).a(0)).isEqualTo(3); + assertThat(table.a().d(nested, 1).a(1)).isEqualTo(4); + assertThat(table.a().d(nested, 0).b()).isEqualTo(TestEnum.B); + assertThat(table.a().d(nested, 1).b()).isEqualTo(TestEnum.C); + assertThat(table.a().d(nested, 0).c(0)).isEqualTo(TestEnum.A); + assertThat(table.a().d(nested, 0).c(1)).isEqualTo(TestEnum.B); + assertThat(table.a().d(nested, 1).c(0)).isEqualTo(TestEnum.C); + assertThat(table.a().d(nested, 1).c(1)).isEqualTo(TestEnum.B); + assertThat(table.a().d(nested, 0).d(0)).isEqualTo((long)-1); + assertThat(table.a().d(nested, 0).d(1)).isEqualTo((long)1); + assertThat(table.a().d(nested, 1).d(0)).isEqualTo((long)-2); + assertThat(table.a().d(nested, 1).d(1)).isEqualTo((long)2); + assertThat(table.a().e()).isEqualTo(2); + assertThat(table.a().f(0)).isEqualTo((long)-1); + assertThat(table.a().f(1)).isEqualTo((long)1); + } + + @org.junit.Test public void testFlexBuffersTest() { + FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512), + FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); + testFlexBuffersTest(builder); + int bufferLimit1 = ((ArrayReadWriteBuf) builder.getBuffer()).limit(); + + // Repeat after clearing the builder to ensure the builder is reusable + builder.clear(); + testFlexBuffersTest(builder); + int bufferLimit2 = ((ArrayReadWriteBuf) builder.getBuffer()).limit(); + assertThat(bufferLimit1).isEqualTo(bufferLimit2); + } + + public static void testFlexBuffersTest(FlexBuffersBuilder builder) { + // Write the equivalent of: + // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ], + // foo: 100, bool: true, mymap: { foo: "Fred" } } + // It's possible to do this without std::function support as well. + int map1 = builder.startMap(); + + int vec1 = builder.startVector(); + builder.putInt(-100); + builder.putString("Fred"); + builder.putBlob(new byte[]{(byte) 77}); + builder.putBoolean(false); + builder.putInt(Long.MAX_VALUE); + + int map2 = builder.startMap(); + builder.putInt("test", 200); + builder.endMap(null, map2); + + builder.putFloat(150.9); + builder.putFloat(150.9999998); + builder.endVector("vec", vec1, false, false); + + vec1 = builder.startVector(); + builder.putInt(1); + builder.putInt(2); + builder.putInt(3); + builder.endVector("bar", vec1, true, false); + + vec1 = builder.startVector(); + builder.putBoolean(true); + builder.putBoolean(false); + builder.putBoolean(true); + builder.putBoolean(false); + builder.endVector("bools", vec1, true, false); + + builder.putBoolean("bool", true); + builder.putFloat("foo", 100); + + map2 = builder.startMap(); + builder.putString("bar", "Fred"); // Testing key and string reuse. + builder.putInt("int", -120); + builder.putFloat("float", -123.0f); + builder.putBlob("blob", new byte[]{ 65, 67 }); + builder.endMap("mymap", map2); + + builder.endMap(null, map1); + builder.finish(); + + FlexBuffers.Map m = FlexBuffers.getRoot(builder.getBuffer()).asMap(); + + assertThat(m.size()).isEqualTo(6); + + // test empty (an null) + // empty if fail + assertThat(m.get("no_key").asString()).isEqualTo(""); + // empty if fail + assertThat(m.get("no_key").asMap()).isEqualTo(FlexBuffers.Map.empty()); + // empty if fail + assertThat(m.get("no_key").asKey()).isEqualTo(FlexBuffers.Key.empty()); + // empty if fail + assertThat(m.get("no_key").asVector()).isEqualTo(Vector.empty()); + // empty if fail + assertThat(m.get("no_key").asBlob()).isEqualTo(FlexBuffers.Blob.empty()); + assert(m.get("no_key").asVector().isEmpty()); // empty if fail + + // testing "vec" field + FlexBuffers.Vector vec = m.get("vec").asVector(); + assertThat(vec.size()).isEqualTo(8); + assertThat(vec.get(0).asLong()).isEqualTo((long) -100); + assertThat(vec.get(1).asString()).isEqualTo("Fred"); + assertThat(vec.get(2).isBlob()).isTrue(); + assertThat(vec.get(2).asBlob().size()).isEqualTo(1); + assertThat(vec.get(2).asBlob().data().get(0)).isEqualTo((byte) 77); + // Check if type is a bool + assertThat(vec.get(3).isBoolean()).isTrue(); + // Check if value is false + assertThat(vec.get(3).asBoolean()).isFalse(); + assertThat(vec.get(4).asLong()).isEqualTo(Long.MAX_VALUE); + assertThat(vec.get(5).isMap()).isTrue(); + assertThat(vec.get(5).asMap().get("test").asInt()).isEqualTo(200); + assertThat(Float.compare((float)vec.get(6).asFloat(), 150.9f)).isEqualTo(0); + assertThat(Double.compare(vec.get(7).asFloat(), 150.9999998)).isEqualTo(0); + //conversion fail returns 0 as C++ + assertThat((long)0).isEqualTo((long)vec.get(1).asLong()); + + // bar vector + FlexBuffers.Vector tvec = m.get("bar").asVector(); + assertThat(tvec.size()).isEqualTo(3); + assertThat(tvec.get(0).asInt()).isEqualTo(1); + assertThat(tvec.get(1).asInt()).isEqualTo(2); + assertThat(tvec.get(2).asInt()).isEqualTo(3); + assertThat(((FlexBuffers.TypedVector) tvec).getElemType()).isEqualTo(FlexBuffers.FBT_INT); + + // bools vector + FlexBuffers.Vector bvec = m.get("bools").asVector(); + assertThat(bvec.size()).isEqualTo(4); + assertThat(bvec.get(0).asBoolean()).isTrue(); + assertThat(bvec.get(1).asBoolean()).isFalse(); + assertThat(bvec.get(2).asBoolean()).isTrue(); + assertThat(bvec.get(3).asBoolean()).isFalse(); + assertThat(((FlexBuffers.TypedVector) bvec).getElemType()).isEqualTo(FlexBuffers.FBT_BOOL); + + assertThat((float)m.get("foo").asFloat()).isEqualTo((float) 100); + assertThat(m.get("unknown").isNull()).isTrue(); + + // mymap vector + FlexBuffers.Map mymap = m.get("mymap").asMap(); + // These should be equal by pointer equality, since key and value are shared. + assertThat(mymap.keys().get(0)).isEqualTo(m.keys().get(0)); + assertThat(mymap.keys().get(0).toString()).isEqualTo("bar"); + assertThat(mymap.values().get(0).asString()).isEqualTo(vec.get(1).asString()); + assertThat(mymap.get("int").asInt()).isEqualTo(-120); + assertThat((float)mymap.get("float").asFloat()).isEqualTo(-123.0f); + assertThat(Arrays.equals(mymap.get("blob").asBlob().getBytes(), new byte[]{ 65, 67 })).isEqualTo( + true); + assertThat(mymap.get("blob").asBlob().toString()).isEqualTo("AC"); + assertThat(mymap.get("blob").toString()).isEqualTo("\"AC\""); + } + + @org.junit.Test public void testFlexBufferVectorStrings() { + FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(10000000)); + + int size = 3000; + StringBuilder sb = new StringBuilder(); + for (int i=0; i< size; i++) { + sb.append("a"); + } + + String text = sb.toString(); + assertThat(text.length()).isEqualTo(size); + + int pos = builder.startVector(); + + for (int i=0; i source = new HashMap<>(); + for (int i = 0; i < entriesCount; i++) { + source.put("foo_param_" + i, "foo_value_" + i); + } + + FlexBuffersBuilder builder = new FlexBuffersBuilder(1000); + int mapStart = builder.startMap(); + for (Map.Entry entry : source.entrySet()) { + builder.putString(entry.getKey(), entry.getValue()); + } + builder.endMap(null, mapStart); + ByteBuffer bb = builder.finish(); + bb.rewind(); + + FlexBuffers.Reference rootReference = FlexBuffers.getRoot(bb); + + assertThat(rootReference.isMap()).isTrue(); + + FlexBuffers.Map flexMap = rootReference.asMap(); + + FlexBuffers.KeyVector keys = flexMap.keys(); + FlexBuffers.Vector values = flexMap.values(); + + assertThat(entriesCount).isEqualTo(keys.size()); + assertThat(entriesCount).isEqualTo(values.size()); + + HashMap result = new HashMap<>(); + for (int i = 0; i < keys.size(); i++) { + result.put(keys.get(i).toString(), values.get(i).asString()); + } + + assertThat(source).isEqualTo(result); + } + + @org.junit.Test public void testBuilderGrowth() { + FlexBuffersBuilder builder = new FlexBuffersBuilder(); + String someString = "This is a small string"; + builder.putString(someString); + ByteBuffer b = builder.finish(); + assertThat(someString).isEqualTo(FlexBuffers.getRoot(b).asString()); + + FlexBuffersBuilder failBuilder = new FlexBuffersBuilder(ByteBuffer.allocate(1)); + failBuilder.putString(someString); + } + + @org.junit.Test + public void testFlexBuffersUtf8Map() { + FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512), + FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); + + String key0 = "😨 face1"; + String key1 = "😩 face2"; + String key2 = "😨 face3"; + String key3 = "trademark ®"; + String key4 = "€ euro"; + String utf8keys[] = { "😨 face1", "😩 face2", "😨 face3", "trademark ®", "€ euro"}; + + int map = builder.startMap(); + + for (int i=0; i< utf8keys.length; i++) { + builder.putString(utf8keys[i], utf8keys[i]); // Testing key and string reuse. + } + builder.endMap(null, map); + builder.finish(); + + FlexBuffers.Map m = FlexBuffers.getRoot(builder.getBuffer()).asMap(); + + assertThat(m.size()).isEqualTo(5); + + KeyVector kv = m.keys(); + for (int i=0; i< utf8keys.length; i++) { + assertThat(kv.get(i).toString()).isEqualTo(m.get(i).asString()); + } + + assertThat(m.get(key0).asString()).isEqualTo(utf8keys[0]); + assertThat(m.get(key1).asString()).isEqualTo(utf8keys[1]); + assertThat(m.get(key2).asString()).isEqualTo(utf8keys[2]); + assertThat(m.get(key3).asString()).isEqualTo(utf8keys[3]); + assertThat(m.get(key4).asString()).isEqualTo(utf8keys[4]); + } + + @org.junit.Test public void testFlexBuffersMapLookup() { + FlexBuffersBuilder builder = new FlexBuffersBuilder(ByteBuffer.allocate(512), + FlexBuffersBuilder.BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); + + String key0 = "123"; + String key1 = "1234"; + String key2 = "12345"; + String[] keys = new String[]{key0, key1, key2}; + + int map = builder.startMap(); + + for (int i=0; i< keys.length; i++) { + builder.putString(keys[i], keys[i]); // Testing key and string reuse. + } + builder.endMap(null, map); + builder.finish(); + + FlexBuffers.Map m = FlexBuffers.getRoot(builder.getBuffer()).asMap(); + for (int i=0; i< keys.length; i++) { + assertThat(m.get(keys[i]).asString()).isEqualTo(keys[i]); + assertThat(m.get(keys[i].getBytes(StandardCharsets.UTF_8)).asString()).isEqualTo(keys[i]); + } + } + + @org.junit.Test public void TestDictionaryLookup() { + FlatBufferBuilder fbb = new FlatBufferBuilder(16); + int lfIndex = LongFloatEntry.createLongFloatEntry(fbb, 0, 99); + int vectorEntriesIdx = LongFloatMap.createEntriesVector(fbb, new int[] { lfIndex }); + int rootIdx = LongFloatMap.createLongFloatMap(fbb, vectorEntriesIdx); + + LongFloatMap.finishLongFloatMapBuffer(fbb, rootIdx); + LongFloatMap map = LongFloatMap.getRootAsLongFloatMap(fbb.dataBuffer()); + assertThat(map.entriesLength()).isEqualTo(1); + + LongFloatEntry e = map.entries(0); + assertThat(e.key()).isEqualTo(0L); + assertThat(e.value()).isEqualTo(99.0f); + + LongFloatEntry e2 = map.entriesByKey(0); + assertThat(e2.key()).isEqualTo(0L); + assertThat(e2.value()).isEqualTo(99.0f); + } + + @org.junit.Test public void TestVectorOfBytes() { + FlatBufferBuilder fbb = new FlatBufferBuilder(16); + int str = fbb.createString("ByteMonster"); + byte[] data = new byte[] {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; + int offset = Monster.createInventoryVector(fbb, data); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + int monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject.inventoryLength()).isEqualTo(data.length); + assertThat((Integer) monsterObject.inventory(4)).isEqualTo((int) data[4]); + assertThat(ByteBuffer.wrap(data)).isEqualTo(monsterObject.inventoryAsByteBuffer()); + + fbb.clear(); + ByteBuffer bb = ByteBuffer.wrap(data); + offset = fbb.createByteVector(bb); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject2 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject2.inventoryLength()).isEqualTo(data.length); + for (int i = 0; i < data.length; i++) { + assertThat((Integer) monsterObject2.inventory(i)).isEqualTo((int) bb.get(i)); + } + + fbb.clear(); + offset = fbb.createByteVector(data, 3, 4); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject3 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject3.inventoryLength()).isEqualTo(4); + assertThat((Integer) monsterObject3.inventory(0)).isEqualTo((int) data[3]); + + fbb.clear(); + bb = ByteBuffer.wrap(data); + offset = Monster.createInventoryVector(fbb, bb); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject4 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject4.inventoryLength()).isEqualTo(data.length); + assertThat((Integer) monsterObject4.inventory(8)).isEqualTo((int) 8); + + fbb.clear(); + byte[] largeData = new byte[1024]; + offset = fbb.createByteVector(largeData); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject5 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject5.inventoryLength()).isEqualTo(largeData.length); + assertThat((Integer) monsterObject5.inventory(25)).isEqualTo((int) largeData[25]); + + fbb.clear(); + bb = ByteBuffer.wrap(largeData); + bb.position(512); + ByteBuffer bb2 = bb.slice(); + assertThat(bb2.arrayOffset()).isEqualTo(512); + offset = fbb.createByteVector(bb2); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject6 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject6.inventoryLength()).isEqualTo(512); + assertThat((Integer) monsterObject6.inventory(0)).isEqualTo((int) largeData[512]); + + fbb.clear(); + bb = ByteBuffer.wrap(largeData); + bb.limit(256); + offset = fbb.createByteVector(bb); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject7 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject7.inventoryLength()).isEqualTo(256); + + fbb.clear(); + bb = ByteBuffer.allocateDirect(2048); + offset = fbb.createByteVector(bb); + str = fbb.createString("ByteMonster"); + Monster.startMonster(fbb); + Monster.addName(fbb, str); + Monster.addInventory(fbb, offset); + monster1 = Monster.endMonster(fbb); + Monster.finishMonsterBuffer(fbb, monster1); + Monster monsterObject8 = Monster.getRootAsMonster(fbb.dataBuffer()); + + assertThat(monsterObject8.inventoryLength()).isEqualTo(2048); + } + + @org.junit.Test public void TestSharedStringPool() { + FlatBufferBuilder fb = new FlatBufferBuilder(1); + String testString = "My string"; + int offset = fb.createSharedString(testString); + for (int i=0; i< 10; i++) { + assertThat(offset).isEqualTo(fb.createSharedString(testString)); + } + } + + @org.junit.Test public void TestScalarOptional() { + FlatBufferBuilder fbb = new FlatBufferBuilder(1); + ScalarStuff.startScalarStuff(fbb); + int pos = ScalarStuff.endScalarStuff(fbb); + fbb.finish(pos); + + ScalarStuff scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer()); + assertThat(scalarStuff.justI8()).isEqualTo((byte)0); + assertThat(scalarStuff.maybeI8()).isEqualTo((byte)0); + assertThat(scalarStuff.defaultI8()).isEqualTo((byte)42); + assertThat(scalarStuff.justU8()).isEqualTo(0); + assertThat(scalarStuff.maybeU8()).isEqualTo(0); + assertThat(scalarStuff.defaultU8()).isEqualTo(42); + assertThat(scalarStuff.justI16()).isEqualTo((short)0); + assertThat(scalarStuff.maybeI16()).isEqualTo((short)0); + assertThat(scalarStuff.defaultI16()).isEqualTo((short)42); + assertThat(scalarStuff.justU16()).isEqualTo(0); + assertThat(scalarStuff.maybeU16()).isEqualTo(0); + assertThat(scalarStuff.defaultU16()).isEqualTo(42); + assertThat(scalarStuff.justI32()).isEqualTo(0); + assertThat(scalarStuff.maybeI32()).isEqualTo(0); + assertThat(scalarStuff.defaultI32()).isEqualTo(42); + assertThat(scalarStuff.justU32()).isEqualTo(0L); + assertThat(scalarStuff.maybeU32()).isEqualTo(0L); + assertThat(scalarStuff.defaultU32()).isEqualTo(42L); + assertThat(scalarStuff.justI64()).isEqualTo(0L); + assertThat(scalarStuff.maybeI64()).isEqualTo(0L); + assertThat(scalarStuff.defaultI64()).isEqualTo(42L); + assertThat(scalarStuff.justU64()).isEqualTo(0L); + assertThat(scalarStuff.maybeU64()).isEqualTo(0L); + assertThat(scalarStuff.defaultU64()).isEqualTo(42L); + assertThat(scalarStuff.justF32()).isEqualTo(0.0f); + assertThat(scalarStuff.maybeF32()).isEqualTo(0f); + assertThat(scalarStuff.defaultF32()).isEqualTo(42.0f); + assertThat(scalarStuff.justF64()).isEqualTo(0.0); + assertThat(scalarStuff.maybeF64()).isEqualTo(0.0); + assertThat(scalarStuff.defaultF64()).isEqualTo(42.0); + assertThat(scalarStuff.justBool()).isFalse(); + assertThat(scalarStuff.maybeBool()).isFalse(); + assertThat(scalarStuff.defaultBool()).isTrue(); + assertThat(scalarStuff.justEnum()).isEqualTo(OptionalByte.None); + assertThat(scalarStuff.maybeEnum()).isEqualTo(OptionalByte.None); + assertThat(scalarStuff.defaultEnum()).isEqualTo(OptionalByte.One); + + assertThat(scalarStuff.hasMaybeI8()).isFalse(); + assertThat(scalarStuff.hasMaybeI16()).isFalse(); + assertThat(scalarStuff.hasMaybeI32()).isFalse(); + assertThat(scalarStuff.hasMaybeI64()).isFalse(); + assertThat(scalarStuff.hasMaybeU8()).isFalse(); + assertThat(scalarStuff.hasMaybeU16()).isFalse(); + assertThat(scalarStuff.hasMaybeU32()).isFalse(); + assertThat(scalarStuff.hasMaybeU64()).isFalse(); + assertThat(scalarStuff.hasMaybeF32()).isFalse(); + assertThat(scalarStuff.hasMaybeF64()).isFalse(); + assertThat(scalarStuff.hasMaybeBool()).isFalse(); + assertThat(scalarStuff.hasMaybeEnum()).isFalse(); + + fbb.clear(); + + ScalarStuff.startScalarStuff(fbb); + ScalarStuff.addJustI8(fbb, (byte)5); + ScalarStuff.addMaybeI8(fbb, (byte)5); + ScalarStuff.addDefaultI8(fbb, (byte)5); + ScalarStuff.addJustU8(fbb, 6); + ScalarStuff.addMaybeU8(fbb, 6); + ScalarStuff.addDefaultU8(fbb, 6); + ScalarStuff.addJustI16(fbb, (short)7); + ScalarStuff.addMaybeI16(fbb, (short)7); + ScalarStuff.addDefaultI16(fbb, (short)7); + ScalarStuff.addJustU16(fbb, 8); + ScalarStuff.addMaybeU16(fbb, 8); + ScalarStuff.addDefaultU16(fbb, 8); + ScalarStuff.addJustI32(fbb, 9); + ScalarStuff.addMaybeI32(fbb, 9); + ScalarStuff.addDefaultI32(fbb, 9); + ScalarStuff.addJustU32(fbb, (long)10); + ScalarStuff.addMaybeU32(fbb, (long)10); + ScalarStuff.addDefaultU32(fbb, (long)10); + ScalarStuff.addJustI64(fbb, 11L); + ScalarStuff.addMaybeI64(fbb, 11L); + ScalarStuff.addDefaultI64(fbb, 11L); + ScalarStuff.addJustU64(fbb, 12L); + ScalarStuff.addMaybeU64(fbb, 12L); + ScalarStuff.addDefaultU64(fbb, 12L); + ScalarStuff.addJustF32(fbb, 13.0f); + ScalarStuff.addMaybeF32(fbb, 13.0f); + ScalarStuff.addDefaultF32(fbb, 13.0f); + ScalarStuff.addJustF64(fbb, 14.0); + ScalarStuff.addMaybeF64(fbb, 14.0); + ScalarStuff.addDefaultF64(fbb, 14.0); + ScalarStuff.addJustBool(fbb, true); + ScalarStuff.addMaybeBool(fbb, true); + ScalarStuff.addDefaultBool(fbb, true); + ScalarStuff.addJustEnum(fbb, OptionalByte.Two); + ScalarStuff.addMaybeEnum(fbb, OptionalByte.Two); + ScalarStuff.addDefaultEnum(fbb, OptionalByte.Two); + + pos = ScalarStuff.endScalarStuff(fbb); + + fbb.finish(pos); + + scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer()); + + assertThat(scalarStuff.justI8()).isEqualTo((byte)5); + assertThat(scalarStuff.maybeI8()).isEqualTo((byte)5); + assertThat(scalarStuff.defaultI8()).isEqualTo((byte)5); + assertThat(scalarStuff.justU8()).isEqualTo(6); + assertThat(scalarStuff.maybeU8()).isEqualTo(6); + assertThat(scalarStuff.defaultU8()).isEqualTo(6); + assertThat(scalarStuff.justI16()).isEqualTo((short)7); + assertThat(scalarStuff.maybeI16()).isEqualTo((short)7); + assertThat(scalarStuff.defaultI16()).isEqualTo((short)7); + assertThat(scalarStuff.justU16()).isEqualTo(8); + assertThat(scalarStuff.maybeU16()).isEqualTo(8); + assertThat(scalarStuff.defaultU16()).isEqualTo(8); + assertThat(scalarStuff.justI32()).isEqualTo(9); + assertThat(scalarStuff.maybeI32()).isEqualTo(9); + assertThat(scalarStuff.defaultI32()).isEqualTo(9); + assertThat(scalarStuff.justU32()).isEqualTo(10L); + assertThat(scalarStuff.maybeU32()).isEqualTo(10L); + assertThat(scalarStuff.defaultU32()).isEqualTo(10L); + assertThat(scalarStuff.justI64()).isEqualTo(11L); + assertThat(scalarStuff.maybeI64()).isEqualTo(11L); + assertThat(scalarStuff.defaultI64()).isEqualTo(11L); + assertThat(scalarStuff.justU64()).isEqualTo(12L); + assertThat(scalarStuff.maybeU64()).isEqualTo(12L); + assertThat(scalarStuff.defaultU64()).isEqualTo(12L); + assertThat(scalarStuff.justF32()).isEqualTo(13.0f); + assertThat(scalarStuff.maybeF32()).isEqualTo(13.0f); + assertThat(scalarStuff.defaultF32()).isEqualTo(13.0f); + assertThat(scalarStuff.justF64()).isEqualTo(14.0); + assertThat(scalarStuff.maybeF64()).isEqualTo(14.0); + assertThat(scalarStuff.defaultF64()).isEqualTo(14.0); + assertThat(scalarStuff.justBool()).isTrue(); + assertThat(scalarStuff.maybeBool()).isTrue(); + assertThat(scalarStuff.defaultBool()).isTrue(); + assertThat(scalarStuff.justEnum()).isEqualTo(OptionalByte.Two); + assertThat(scalarStuff.maybeEnum()).isEqualTo(OptionalByte.Two); + assertThat(scalarStuff.defaultEnum()).isEqualTo(OptionalByte.Two); + + assertThat(scalarStuff.hasMaybeI8()).isTrue(); + assertThat(scalarStuff.hasMaybeI16()).isTrue(); + assertThat(scalarStuff.hasMaybeI32()).isTrue(); + assertThat(scalarStuff.hasMaybeI64()).isTrue(); + assertThat(scalarStuff.hasMaybeU8()).isTrue(); + assertThat(scalarStuff.hasMaybeU16()).isTrue(); + assertThat(scalarStuff.hasMaybeU32()).isTrue(); + assertThat(scalarStuff.hasMaybeU64()).isTrue(); + assertThat(scalarStuff.hasMaybeF32()).isTrue(); + assertThat(scalarStuff.hasMaybeF64()).isTrue(); + assertThat(scalarStuff.hasMaybeBool()).isTrue(); + assertThat(scalarStuff.hasMaybeEnum()).isTrue(); + } + + static void TestObject(MonsterT monster) { + assertThat(monster.getHp()).isEqualTo((short) 80); + // default + assertThat(monster.getMana()).isEqualTo((short) 150); + + assertThat(monster.getName()).isEqualTo("MyMonster"); + assertThat(monster.getColor()).isEqualTo((Integer) Color.Blue); + // monster.friendly() // can't access, deprecated + + Vec3T pos = monster.getPos(); + assertThat(pos.getX()).isEqualTo(1.0f); + assertThat(pos.getY()).isEqualTo(2.0f); + assertThat(pos.getZ()).isEqualTo(3.0f); + assertThat(pos.getTest1()).isEqualTo(3.0); + // issue: int != byte + assertThat(pos.getTest2()).isEqualTo((int) Color.Green); + TestT t = pos.getTest3(); + assertThat(t.getA()).isEqualTo((short) 5); + assertThat(t.getB()).isEqualTo((byte) 6); + + assertThat(monster.getTest().getType()).isEqualTo((byte) Any.Monster); + MonsterT monster2 = (MonsterT) monster.getTest().getValue(); + assertThat(monster2 != null).isTrue(); + assertThat(monster2.getName()).isEqualTo("Fred"); + + int[] inv = monster.getInventory(); + assertThat(inv.length).isEqualTo(5); + int[] expInv = {0, 1, 2, 3, 4}; + for (int i = 0; i < inv.length; i++) + assertThat(expInv[i]).isEqualTo(inv[i]); + + TestT[] test4 = monster.getTest4(); + TestT test_0 = test4[0]; + TestT test_1 = test4[1]; + assertThat(test4.length).isEqualTo(2); + assertThat(test_0.getA()).isEqualTo((short) 10); + assertThat(test_0.getB()).isEqualTo((byte) 20); + assertThat(test_1.getA()).isEqualTo((short) 30); + assertThat(test_1.getB()).isEqualTo((byte) 40); + + String[] testarrayofstring = monster.getTestarrayofstring(); + assertThat(testarrayofstring.length).isEqualTo(2); + assertThat(testarrayofstring[0]).isEqualTo("test1"); + assertThat(testarrayofstring[1]).isEqualTo("test2"); + + MonsterT[] testarrayoftables = monster.getTestarrayoftables(); + assertThat(testarrayoftables.length).isEqualTo(0); + + MonsterT enemy = monster.getEnemy(); + assertThat(enemy != null).isTrue(); + assertThat(enemy.getName()).isEqualTo("Fred"); + + int[] testnestedflatbuffer = monster.getTestnestedflatbuffer(); + assertThat(testnestedflatbuffer.length).isEqualTo(0); + + assertThat(monster.getTestempty() == null).isTrue(); + + assertThat(monster.getTestbool()).isTrue(); + + boolean[] testarrayofbools = monster.getTestarrayofbools(); + assertThat(testarrayofbools.length).isEqualTo(3); + assertThat(testarrayofbools[0]).isTrue(); + assertThat(testarrayofbools[1]).isFalse(); + assertThat(testarrayofbools[2]).isTrue(); + + assertThat(monster.getTestf()).isEqualTo(3.14159f); + assertThat(monster.getTestf2()).isEqualTo(3.0f); + assertThat(monster.getTestf3()).isEqualTo(0.0f); + assertThat(monster.getTestf3()).isEqualTo(0.0f); + + AbilityT[] testarrayofsortedstruct = monster.getTestarrayofsortedstruct(); + assertThat(testarrayofsortedstruct.length).isEqualTo(3); + assertThat(testarrayofsortedstruct[0].getId()).isEqualTo((long) 0); + assertThat(testarrayofsortedstruct[1].getId()).isEqualTo((long) 1); + assertThat(testarrayofsortedstruct[2].getId()).isEqualTo((long) 5); + assertThat(testarrayofsortedstruct[0].getDistance()).isEqualTo((long) 45); + assertThat(testarrayofsortedstruct[1].getDistance()).isEqualTo((long) 21); + assertThat(testarrayofsortedstruct[2].getDistance()).isEqualTo((long) 12); + + int[] flex = monster.getFlex(); + assertThat(flex.length).isEqualTo(0); + + long[] vectorOfLongs = monster.getVectorOfLongs(); + assertThat(vectorOfLongs.length).isEqualTo(5); + long l = 1; + for (int i = 0; i < vectorOfLongs.length; i++) { + assertThat(vectorOfLongs[i]).isEqualTo(l); + l *= 100; + } + + double[] vectorOfDoubles = monster.getVectorOfDoubles(); + assertThat(vectorOfDoubles.length).isEqualTo(3); + assertThat(vectorOfDoubles[0]).isEqualTo(-1.7976931348623157E308); + assertThat(vectorOfDoubles[1]).isEqualTo(0.0); + assertThat(vectorOfDoubles[2]).isEqualTo(1.7976931348623157E308); + + assertThat(monster.getParentNamespaceTest() == null).isTrue(); + ReferrableT[] vectorOfReferrables = monster.getVectorOfReferrables(); + assertThat(vectorOfReferrables.length).isEqualTo(0); + + assertThat(monster.getSignedEnum()).isEqualTo((byte) -1); + } + + static void TestPackUnpack(ByteBuffer bb) { + Monster m = Monster.getRootAsMonster(bb); + MonsterT mObject = m.unpack(); + TestObject(mObject); + FlatBufferBuilder fbb = new FlatBufferBuilder(); + int monster = Monster.pack(fbb, mObject); + Monster.finishMonsterBuffer(fbb, monster); + TestBuffer(fbb.dataBuffer()); + + byte[] bytes = mObject.serializeToBinary(); + MonsterT newMonsterT = MonsterT.deserializeFromBinary(bytes); + TestObject(newMonsterT); + } +} diff --git a/third_party/flatbuffers/java/src/test/java/MyGame b/third_party/flatbuffers/java/src/test/java/MyGame new file mode 120000 index 00000000000..0ba918ed02d --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/MyGame @@ -0,0 +1 @@ +../../../../tests/MyGame \ No newline at end of file diff --git a/third_party/flatbuffers/java/src/test/java/NamespaceA b/third_party/flatbuffers/java/src/test/java/NamespaceA new file mode 120000 index 00000000000..37a8d897e4c --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/NamespaceA @@ -0,0 +1 @@ +../../../../tests/namespace_test/NamespaceA \ No newline at end of file diff --git a/third_party/flatbuffers/java/src/test/java/NamespaceC b/third_party/flatbuffers/java/src/test/java/NamespaceC new file mode 120000 index 00000000000..c1e44a8c94b --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/NamespaceC @@ -0,0 +1 @@ +../../../../tests/namespace_test/NamespaceC \ No newline at end of file diff --git a/third_party/flatbuffers/java/src/test/java/optional_scalars b/third_party/flatbuffers/java/src/test/java/optional_scalars new file mode 120000 index 00000000000..44a35f96769 --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/optional_scalars @@ -0,0 +1 @@ +../../../../tests/optional_scalars \ No newline at end of file diff --git a/third_party/flatbuffers/java/src/test/java/union_vector b/third_party/flatbuffers/java/src/test/java/union_vector new file mode 120000 index 00000000000..cc82221f5de --- /dev/null +++ b/third_party/flatbuffers/java/src/test/java/union_vector @@ -0,0 +1 @@ +../../../../tests/union_vector \ No newline at end of file diff --git a/third_party/flatbuffers/java/src/test/resources/monsterdata_test.mon b/third_party/flatbuffers/java/src/test/resources/monsterdata_test.mon new file mode 100644 index 00000000000..da0ed8698fc Binary files /dev/null and b/third_party/flatbuffers/java/src/test/resources/monsterdata_test.mon differ diff --git a/third_party/flatbuffers/js/README.md b/third_party/flatbuffers/js/README.md new file mode 100644 index 00000000000..cbcebe051cd --- /dev/null +++ b/third_party/flatbuffers/js/README.md @@ -0,0 +1 @@ +This folder is intentionally empty and will contain transpiled js modules in Common JS format after compiling with tsc. \ No newline at end of file diff --git a/third_party/flatbuffers/kotlin/benchmark/build.gradle.kts b/third_party/flatbuffers/kotlin/benchmark/build.gradle.kts new file mode 100644 index 00000000000..df4af2b25f4 --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/build.gradle.kts @@ -0,0 +1,152 @@ +import groovy.xml.XmlParser + +plugins { + kotlin("multiplatform") + id("org.jetbrains.kotlinx.benchmark") + id("io.morethan.jmhreport") + id("de.undercouch.download") +} + +group = "com.google.flatbuffers.jmh" +version = "2.0.0-SNAPSHOT" + +// Reads latest version from Java's runtime pom.xml, +// so we can use it for benchmarking against Kotlin's +// runtime +fun readJavaFlatBufferVersion(): String { + val pom = XmlParser().parse(File("../java/pom.xml")) + val versionTag = pom.children().find { + val node = it as groovy.util.Node + node.name().toString().contains("version") + } as groovy.util.Node + return versionTag.value().toString() +} + +// This plugin generates a static html page with the aggregation +// of all benchmarks ran. very useful visualization tool. +jmhReport { + val baseFolder = project.file("build/reports/benchmarks/main").absolutePath + val lastFolder = project.file(baseFolder).list()?.sortedArray()?.lastOrNull() ?: "" + jmhResultPath = "$baseFolder/$lastFolder/jvm.json" + jmhReportOutput = "$baseFolder/$lastFolder" +} + +// For now we benchmark on JVM only +benchmark { + configurations { + this.getByName("main") { + iterations = 5 + iterationTime = 300 + iterationTimeUnit = "ms" + // uncomment for benchmarking JSON op only + include(".*FlatbufferBenchmark.*") + } + } + targets { + register("jvm") + } +} + +kotlin { + jvm { + compilations { + val main by getting { } + // custom benchmark compilation + val benchmarks by compilations.creating { + defaultSourceSet { + dependencies { + // Compile against the main compilation's compile classpath and outputs: + implementation(main.compileDependencyFiles + main.output.classesDirs) + } + } + } + } + } + + sourceSets { + val jvmMain by getting { + dependencies { + implementation(kotlin("stdlib-common")) + implementation(project(":flatbuffers-kotlin")) + implementation(libs.kotlinx.benchmark.runtime) + // json serializers + implementation(libs.moshi.kotlin) + implementation(libs.gson) + } + kotlin.srcDir("src/jvmMain/generated/kotlin/") + kotlin.srcDir("src/jvmMain/generated/java/") + kotlin.srcDir("../../java/src/main/java") + } + } +} + +// This task download all JSON files used for benchmarking +tasks.register("downloadMultipleFiles") { + // We are downloading json benchmark samples from serdes-rs project. + // see: https://github.com/serde-rs/json-benchmark/blob/master/data + val baseUrl = "https://github.com/serde-rs/json-benchmark/raw/master/data/" + src(listOf("$baseUrl/canada.json", "$baseUrl/twitter.json", "$baseUrl/citm_catalog.json")) + dest(File("${project.projectDir.absolutePath}/src/jvmMain/resources")) + overwrite(false) +} + +abstract class GenerateFBTestClasses : DefaultTask() { + @get:InputFiles + abstract val inputFiles: ConfigurableFileCollection + + @get:Input + abstract val includeFolder: Property + + @get:Input + abstract val outputFolder: Property + + @get:Input + abstract val variants: ListProperty + + @Inject + protected open fun getExecActionFactory(): org.gradle.process.internal.ExecActionFactory? { + throw UnsupportedOperationException() + } + + init { + includeFolder.set("") + } + + @TaskAction + fun compile() { + val execAction = getExecActionFactory()!!.newExecAction() + val sources = inputFiles.asPath.split(":") + val langs = variants.get().map { "--$it" } + val args = mutableListOf("flatc","-o", outputFolder.get(), *langs.toTypedArray()) + if (includeFolder.get().isNotEmpty()) { + args.add("-I") + args.add(includeFolder.get()) + } + args.addAll(sources) + println(args) + execAction.commandLine = args + print(execAction.execute()) + } +} + +// Use the default greeting +tasks.register("generateFBTestClassesKt") { + inputFiles.setFrom("$projectDir/monster_test_kotlin.fbs") + includeFolder.set("$rootDir/../tests/include_test") + outputFolder.set("${projectDir}/src/jvmMain/generated/kotlin/") + variants.addAll("kotlin-kmp") +} + +tasks.register("generateFBTestClassesJava") { + inputFiles.setFrom("$projectDir/monster_test_java.fbs") + includeFolder.set("$rootDir/../tests/include_test") + outputFolder.set("${projectDir}/src/jvmMain/generated/java/") + variants.addAll("kotlin") +} + +project.tasks.forEach { + if (it.name.contains("compileKotlin")) { + it.dependsOn("generateFBTestClassesKt") + it.dependsOn("generateFBTestClassesJava") + } +} diff --git a/third_party/flatbuffers/kotlin/benchmark/monster_test_java.fbs b/third_party/flatbuffers/kotlin/benchmark/monster_test_java.fbs new file mode 100644 index 00000000000..7007310071f --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/monster_test_java.fbs @@ -0,0 +1,37 @@ +// Example IDL file for our monster's schema. + +namespace jmonster; + +enum JColor:byte { Red = 0, Green, Blue = 2 } + +union JEquipment { JWeapon } // Optionally add more tables. + +struct JVec3 { + x:float; + y:float; + z:float; +} + +table JMonster { + pos:JVec3; + mana:short = 150; + hp:short = 100; + name:string; + friendly:bool = false (deprecated); + inventory:[ubyte]; + color:JColor = Blue; + weapons:[JWeapon]; + equipped:JEquipment; + path:[JVec3]; +} + +table JWeapon { + name:string; + damage:short; +} + +table JAllMonsters { + monsters: [JMonster]; +} + +root_type JAllMonsters; diff --git a/third_party/flatbuffers/kotlin/benchmark/monster_test_kotlin.fbs b/third_party/flatbuffers/kotlin/benchmark/monster_test_kotlin.fbs new file mode 100644 index 00000000000..2513fd3ecb9 --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/monster_test_kotlin.fbs @@ -0,0 +1,37 @@ +// Example IDL file for our monster's schema. + +namespace monster; + +enum Color:byte { Red = 0, Green, Blue = 2 } + +union Equipment { Weapon } // Optionally add more tables. + +struct Vec3 { + x:float; + y:float; + z:float; +} + +table Monster { + pos:Vec3; + mana:short = 150; + hp:short = 100; + name:string; + friendly:bool = false (deprecated); + inventory:[ubyte]; + color:Color = Blue; + weapons:[Weapon]; + equipped:Equipment; + path:[Vec3]; +} + +table Weapon { + name:string; + damage:short; +} + +table AllMonsters { + monsters: [Monster]; +} + +root_type AllMonsters; diff --git a/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlatbufferBenchmark.kt b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlatbufferBenchmark.kt new file mode 100644 index 00000000000..a4f3d250d75 --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlatbufferBenchmark.kt @@ -0,0 +1,129 @@ +@file:OptIn(ExperimentalUnsignedTypes::class) + +package com.google.flatbuffers.kotlin.benchmark + + +import com.google.flatbuffers.kotlin.FlatBufferBuilder +import jmonster.JAllMonsters +import jmonster.JColor +import jmonster.JMonster +import jmonster.JVec3 +import monster.AllMonsters +import monster.AllMonsters.Companion.createAllMonsters +import monster.AllMonsters.Companion.createMonstersVector +import monster.Monster +import monster.Monster.Companion.createInventoryVector +import monster.MonsterOffsetArray +import monster.Vec3 +import org.openjdk.jmh.annotations.* +import org.openjdk.jmh.infra.Blackhole +import java.util.concurrent.TimeUnit + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Measurement(iterations = 20, time = 1, timeUnit = TimeUnit.NANOSECONDS) +open class FlatbufferBenchmark { + + val repetition = 1000000 + val fbKotlin = FlatBufferBuilder(1024 * repetition) + val fbDeserializationKotlin = FlatBufferBuilder(1024 * repetition) + val fbJava = com.google.flatbuffers.FlatBufferBuilder(1024 * repetition) + val fbDeserializationJava = com.google.flatbuffers.FlatBufferBuilder(1024 * repetition) + + init { + populateMosterKotlin(fbDeserializationKotlin) + populateMosterJava(fbDeserializationJava) + } + @OptIn(ExperimentalUnsignedTypes::class) + private fun populateMosterKotlin(fb: FlatBufferBuilder) { + fb.clear() + val monsterName = fb.createString("MonsterName"); + val items = ubyteArrayOf(0u, 1u, 2u, 3u, 4u) + val inv = createInventoryVector(fb, items) + val monsterOffsets: MonsterOffsetArray = MonsterOffsetArray(repetition) { + Monster.startMonster(fb) + Monster.addName(fb, monsterName) + Monster.addPos(fb, Vec3.createVec3(fb, 1.0f, 2.0f, 3.0f)) + Monster.addHp(fb, 80) + Monster.addMana(fb, 150) + Monster.addInventory(fb, inv) + Monster.addColor(fb, monster.Color.Red) + Monster.endMonster(fb) + } + val monsters = createMonstersVector(fb, monsterOffsets) + val allMonsters = createAllMonsters(fb, monsters) + fb.finish(allMonsters) + } + + @OptIn(ExperimentalUnsignedTypes::class) + private fun populateMosterJava(fb: com.google.flatbuffers.FlatBufferBuilder){ + fb.clear() + val monsterName = fb.createString("MonsterName"); + val inv = JMonster.createInventoryVector(fb, ubyteArrayOf(0u, 1u, 2u, 3u, 4u)) + val monsters = JAllMonsters.createMonstersVector(fb, IntArray(repetition) { + JMonster.startJMonster(fb) + JMonster.addName(fb, monsterName) + JMonster.addPos(fb, JVec3.createJVec3(fb, 1.0f, 2.0f, 3.0f)) + JMonster.addHp(fb, 80) + JMonster.addMana(fb, 150) + JMonster.addInventory(fb, inv) + JMonster.addColor(fb, JColor.Red) + JMonster.endJMonster(fb) + }) + val allMonsters = JAllMonsters.createJAllMonsters(fb, monsters) + fb.finish(allMonsters) + } + @Benchmark + fun monstersSerializationKotlin() { + populateMosterKotlin(fbKotlin) + } + + @OptIn(ExperimentalUnsignedTypes::class) + @Benchmark + fun monstersDeserializationKotlin(hole: Blackhole) { + val monstersRef = AllMonsters.asRoot(fbDeserializationKotlin.dataBuffer()) + + for (i in 0 until monstersRef.monstersLength) { + val monster = monstersRef.monsters(i)!! + val pos = monster.pos!! + hole.consume(monster.name) + hole.consume(pos.x) + hole.consume(pos.y) + hole.consume(pos.z) + hole.consume(monster.hp) + hole.consume(monster.mana) + hole.consume(monster.color) + hole.consume(monster.inventory(0).toByte()) + hole.consume(monster.inventory(1)) + hole.consume(monster.inventory(2)) + hole.consume(monster.inventory(3)) + } + } + @Benchmark + fun monstersSerializationJava() { + populateMosterJava(fbJava) + } + + @Benchmark + fun monstersDeserializationJava(hole: Blackhole) { + val monstersRef = JAllMonsters.getRootAsJAllMonsters(fbDeserializationJava.dataBuffer()) + + for (i in 0 until monstersRef.monstersLength) { + val monster = monstersRef.monsters(i)!! + val pos = monster.pos!! + hole.consume(monster.name) + hole.consume(pos.x) + hole.consume(pos.y) + hole.consume(pos.z) + hole.consume(monster.hp) + hole.consume(monster.mana) + hole.consume(monster.color) + hole.consume(monster.inventory(0)) + hole.consume(monster.inventory(1)) + hole.consume(monster.inventory(2)) + hole.consume(monster.inventory(3)) + } + } + +} diff --git a/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlexBuffersBenchmark.kt b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlexBuffersBenchmark.kt new file mode 100644 index 00000000000..03788285d0d --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/FlexBuffersBenchmark.kt @@ -0,0 +1,199 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:OptIn(ExperimentalUnsignedTypes::class) + +package com.google.flatbuffers.kotlin.benchmark +import com.google.flatbuffers.ArrayReadWriteBuf +import com.google.flatbuffers.FlexBuffers +import com.google.flatbuffers.FlexBuffersBuilder.BUILDER_FLAG_SHARE_ALL +import com.google.flatbuffers.kotlin.FlexBuffersBuilder +import com.google.flatbuffers.kotlin.getRoot +import kotlinx.benchmark.Blackhole +import org.openjdk.jmh.annotations.Benchmark +import org.openjdk.jmh.annotations.BenchmarkMode +import org.openjdk.jmh.annotations.Measurement +import org.openjdk.jmh.annotations.Mode +import org.openjdk.jmh.annotations.OutputTimeUnit +import org.openjdk.jmh.annotations.Scope +import org.openjdk.jmh.annotations.Setup +import org.openjdk.jmh.annotations.State +import java.util.concurrent.TimeUnit + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.NANOSECONDS) +@Measurement(iterations = 20, time = 1, timeUnit = TimeUnit.NANOSECONDS) +open class FlexBuffersBenchmark { + + var initialCapacity = 1024 + var value: Double = 0.0 + val stringKey = Array(500) { "Ḧ̵̘́ȩ̵̐myFairlyBigKey$it" } + val stringValue = Array(500) { "Ḧ̵̘́ȩ̵̐myFairlyBigValue$it" } + val bigIntArray = IntArray(5000) { it } + + @Setup + fun setUp() { + value = 3.0 + } + + @Benchmark + open fun mapKotlin(blackhole: Blackhole) { + val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + kBuilder.putMap { + this["hello"] = "world" + this["int"] = 10 + this["float"] = 12.3 + this["intarray"] = bigIntArray + this.putMap("myMap") { + this["cool"] = "beans" + } + } + val ref = getRoot(kBuilder.finish()) + val map = ref.toMap() + blackhole.consume(map.size) + blackhole.consume(map["hello"].toString()) + blackhole.consume(map["int"].toInt()) + blackhole.consume(map["float"].toDouble()) + blackhole.consume(map["intarray"].toIntArray()) + blackhole.consume(ref["myMap"]["cool"].toString()) + blackhole.consume(ref["invalid_key"].isNull) + } + + @Benchmark + open fun mapJava(blackhole: Blackhole) { + val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL) + val startMap = jBuilder.startMap() + jBuilder.putString("hello", "world") + jBuilder.putInt("int", 10) + jBuilder.putFloat("float", 12.3) + + val startVec = jBuilder.startVector() + bigIntArray.forEach { jBuilder.putInt(it) } + jBuilder.endVector("intarray", startVec, true, false) + + val startInnerMap = jBuilder.startMap() + jBuilder.putString("cool", "beans") + jBuilder.endMap("myMap", startInnerMap) + + jBuilder.endMap(null, startMap) + val ref = FlexBuffers.getRoot(jBuilder.finish()) + val map = ref.asMap() + blackhole.consume(map.size()) + blackhole.consume(map.get("hello").toString()) + blackhole.consume(map.get("int").asInt()) + blackhole.consume(map.get("float").asFloat()) + val vec = map.get("intarray").asVector() + blackhole.consume(IntArray(vec.size()) { vec.get(it).asInt() }) + + blackhole.consume(ref.asMap()["myMap"].asMap()["cool"].toString()) + blackhole.consume(ref.asMap()["invalid_key"].isNull) + } + + @Benchmark + open fun intArrayKotlin(blackhole: Blackhole) { + val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + kBuilder.put(bigIntArray) + val root = getRoot(kBuilder.finish()) + blackhole.consume(root.toIntArray()) + } + + @Benchmark + open fun intArrayJava(blackhole: Blackhole) { + val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL) + val v = jBuilder.startVector() + bigIntArray.forEach { jBuilder.putInt(it) } + jBuilder.endVector(null, v, true, false) + jBuilder.finish() + val root = FlexBuffers.getRoot(jBuilder.buffer) + val vec = root.asVector() + blackhole.consume( + IntArray(vec.size()) { + vec[it].asInt() + } + ) + } + + @Benchmark + open fun stringArrayKotlin(blackhole: Blackhole) { + val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + kBuilder.putVector { stringValue.forEach { kBuilder.put(it) } } + kBuilder.finish() + val root = getRoot(kBuilder.buffer) + val vec = root.toVector() + blackhole.consume(Array(vec.size) { vec[it].toString() }) + } + + @Benchmark + open fun stringArrayJava(blackhole: Blackhole) { + val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL) + val v = jBuilder.startVector() + stringValue.forEach { jBuilder.putString(it) } + jBuilder.endVector(null, v, false, false) + jBuilder.finish() + val root = FlexBuffers.getRoot(jBuilder.buffer) + val vec = root.asVector() + blackhole.consume(Array(vec.size()) { vec[it].toString() }) + } + + @Benchmark + open fun stringMapKotlin(blackhole: Blackhole) { + val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + val pos = kBuilder.startMap() + for (i in stringKey.indices) { + kBuilder[stringKey[i]] = stringValue[i] + } + kBuilder.endMap(pos) + val ref = getRoot(kBuilder.finish()) + val map = ref.toMap() + val keys = map.keys + + for (key in keys) { + blackhole.consume(map[key.toString()].toString()) + } + } + + @Benchmark + open fun stringMapBytIndexKotlin(blackhole: Blackhole) { + val kBuilder = FlexBuffersBuilder(initialCapacity, FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + val pos = kBuilder.startMap() + for (i in stringKey.indices) { + kBuilder[stringKey[i]] = stringValue[i] + } + kBuilder.endMap(pos) + val ref = getRoot(kBuilder.finish()) + val map = ref.toMap() + for (index in 0 until map.size) { + blackhole.consume(map[index].toString()) + } + } + + @Benchmark + open fun stringMapJava(blackhole: Blackhole) { + val jBuilder = com.google.flatbuffers.FlexBuffersBuilder(ArrayReadWriteBuf(initialCapacity), BUILDER_FLAG_SHARE_ALL) + val v = jBuilder.startMap() + for (i in stringKey.indices) { + jBuilder.putString(stringKey[i], stringValue[i]) + } + jBuilder.endMap(null, v) + val ref = FlexBuffers.getRoot(jBuilder.finish()) + val map = ref.asMap() + val keyVec = map.keys() + for (i in 0 until keyVec.size()) { + val s = keyVec[i].toString() + blackhole.consume(map[s].toString()) + } + } +} diff --git a/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/JsonBenchmark.kt b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/JsonBenchmark.kt new file mode 100644 index 00000000000..e39b29ff1b4 --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/JsonBenchmark.kt @@ -0,0 +1,122 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin.benchmark + +import com.google.flatbuffers.kotlin.ArrayReadBuffer +import com.google.flatbuffers.kotlin.JSONParser +import com.google.flatbuffers.kotlin.Reference +import com.google.flatbuffers.kotlin.toJson +import com.google.gson.Gson +import com.google.gson.JsonObject +import com.google.gson.JsonParser +import com.squareup.moshi.Moshi +import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory +import kotlinx.benchmark.Blackhole +import okio.Buffer +import org.openjdk.jmh.annotations.Benchmark +import org.openjdk.jmh.annotations.BenchmarkMode +import org.openjdk.jmh.annotations.Measurement +import org.openjdk.jmh.annotations.Mode +import org.openjdk.jmh.annotations.OutputTimeUnit +import org.openjdk.jmh.annotations.Scope +import org.openjdk.jmh.annotations.State +import java.io.ByteArrayInputStream +import java.io.InputStreamReader +import java.util.concurrent.TimeUnit + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Measurement(iterations = 100, time = 1, timeUnit = TimeUnit.MICROSECONDS) +open class JsonBenchmark { + + final val moshi = Moshi.Builder() + .addLast(KotlinJsonAdapterFactory()) + .build() + final val moshiAdapter = moshi.adapter(Map::class.java) + + final val gson = Gson() + final val gsonParser = JsonParser() + + val fbParser = JSONParser() + + final val classLoader = this.javaClass.classLoader + final val twitterData = classLoader.getResourceAsStream("twitter.json")!!.readBytes() + final val canadaData = classLoader.getResourceAsStream("canada.json")!!.readBytes() + final val citmData = classLoader.getResourceAsStream("citm_catalog.json")!!.readBytes() + + val fbCitmRef = JSONParser().parse(ArrayReadBuffer(citmData)) + val moshiCitmRef = moshi.adapter(Map::class.java).fromJson(citmData.decodeToString()) + val gsonCitmRef = gsonParser.parse(citmData.decodeToString()) + + fun readFlexBuffers(data: ByteArray): Reference = fbParser.parse(ArrayReadBuffer(data)) + + fun readMoshi(data: ByteArray): Map<*, *>? { + val buffer = Buffer().write(data) + return moshiAdapter.fromJson(buffer) + } + + fun readGson(data: ByteArray): JsonObject { + val parser = JsonParser() + val jsonReader = InputStreamReader(ByteArrayInputStream(data)) + return parser.parse(jsonReader).asJsonObject + } + + // TWITTER + @Benchmark + open fun readTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData)) + @Benchmark + open fun readTwitterMoshi(hole: Blackhole?) = hole?.consume(readMoshi(twitterData)) + @Benchmark + open fun readTwitterGson(hole: Blackhole?) = hole?.consume(readGson(twitterData)) + + @Benchmark + open fun roundTripTwitterFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(twitterData).toJson()) + @Benchmark + open fun roundTripTwitterMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(twitterData))) + @Benchmark + open fun roundTripTwitterGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(twitterData))) + + // CITM + @Benchmark + open fun readCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData)) + @Benchmark + open fun readCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData))) + @Benchmark + open fun readCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData))) + + @Benchmark + open fun roundTripCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(citmData).toJson()) + @Benchmark + open fun roundTripCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(readMoshi(citmData))) + @Benchmark + open fun roundTripCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(readGson(citmData))) + + @Benchmark + open fun writeCITMFlexBuffers(hole: Blackhole? = null) = hole?.consume(fbCitmRef.toJson()) + @Benchmark + open fun writeCITMMoshi(hole: Blackhole?) = hole?.consume(moshiAdapter.toJson(moshiCitmRef)) + @Benchmark + open fun writeCITMGson(hole: Blackhole?) = hole?.consume(gson.toJson(gsonCitmRef)) + + // CANADA + @Benchmark + open fun readCanadaFlexBuffers(hole: Blackhole? = null) = hole?.consume(readFlexBuffers(canadaData)) + @Benchmark + open fun readCanadaMoshi(hole: Blackhole?) = hole?.consume(readMoshi(canadaData)) + @Benchmark + open fun readCanadaGson(hole: Blackhole?) = hole?.consume(readGson(canadaData)) +} diff --git a/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/UTF8Benchmark.kt b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/UTF8Benchmark.kt new file mode 100644 index 00000000000..426253882e2 --- /dev/null +++ b/third_party/flatbuffers/kotlin/benchmark/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/benchmark/UTF8Benchmark.kt @@ -0,0 +1,235 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin.benchmark + +import com.google.flatbuffers.kotlin.ArrayReadWriteBuffer +import com.google.flatbuffers.kotlin.Key +import com.google.flatbuffers.kotlin.Utf8 +import kotlinx.benchmark.Blackhole +import org.openjdk.jmh.annotations.Benchmark +import org.openjdk.jmh.annotations.BenchmarkMode +import org.openjdk.jmh.annotations.Measurement +import org.openjdk.jmh.annotations.Mode +import org.openjdk.jmh.annotations.OutputTimeUnit +import org.openjdk.jmh.annotations.Scope +import org.openjdk.jmh.annotations.Setup +import org.openjdk.jmh.annotations.State +import java.nio.ByteBuffer +import java.util.concurrent.TimeUnit +import kotlin.random.Random + +@State(Scope.Benchmark) +@BenchmarkMode(Mode.AverageTime) +@OutputTimeUnit(TimeUnit.MICROSECONDS) +@Measurement(iterations = 100, time = 1, timeUnit = TimeUnit.MICROSECONDS) +open class UTF8Benchmark { + + private val sampleSize = 5000 + private val stringSize = 25 + private var sampleSmallUtf8 = (0..sampleSize).map { populateUTF8(stringSize) }.toList() + private var sampleSmallUtf8Decoded = sampleSmallUtf8.map { it.encodeToByteArray() }.toList() + private var sampleSmallAscii = (0..sampleSize).map { populateAscii(stringSize) }.toList() + private var sampleSmallAsciiDecoded = sampleSmallAscii.map { it.encodeToByteArray() }.toList() + + @Setup + fun setUp() { + } + + @Benchmark + fun encodeUtf8KotlinStandard(blackhole: Blackhole) { + for (i in sampleSmallUtf8) { + blackhole.consume(i.encodeToByteArray()) + } + } + @Benchmark + fun encodeUtf8KotlinFlatbuffers(blackhole: Blackhole) { + for (i in sampleSmallUtf8) { + val byteArray = ByteArray((i.length * 4)) + blackhole.consume(Utf8.encodeUtf8Array(i, byteArray, 0, byteArray.size)) + } + } + @Benchmark + fun encodeUtf8JavaFlatbuffers(blackhole: Blackhole) { + val javaUtf8 = com.google.flatbuffers.Utf8.getDefault() + for (i in sampleSmallUtf8) { + val byteBuffer = ByteBuffer.wrap(ByteArray(i.length * 4)) + blackhole.consume(javaUtf8.encodeUtf8(i, byteBuffer)) + } + } + + @Benchmark + fun decodeUtf8KotlinStandard(blackhole: Blackhole) { + for (ary in sampleSmallUtf8Decoded) { + blackhole.consume(ary.decodeToString()) + } + } + + @Benchmark + fun decodeUtf8KotlinFlatbuffers(blackhole: Blackhole) { + for (ary in sampleSmallUtf8Decoded) { + blackhole.consume(Utf8.decodeUtf8Array(ary, 0, ary.size)) + } + } + + @Benchmark + fun decodeUtf8JavaFlatbuffers(blackhole: Blackhole) { + val javaUtf8 = com.google.flatbuffers.Utf8.getDefault() + for (ary in sampleSmallUtf8Decoded) { + val byteBuffer = ByteBuffer.wrap(ary) + blackhole.consume(javaUtf8.decodeUtf8(byteBuffer, 0, ary.size)) + } + } + + // ASCII TESTS + + @Benchmark + fun encodeAsciiKotlinStandard(blackhole: Blackhole) { + for (i in sampleSmallAscii) { + blackhole.consume(i.encodeToByteArray()) + } + } + @Benchmark + fun encodeAsciiKotlinFlatbuffers(blackhole: Blackhole) { + for (i in sampleSmallAscii) { + val byteArray = ByteArray(i.length) // Utf8.encodedLength(i)) + blackhole.consume(Utf8.encodeUtf8Array(i, byteArray, 0, byteArray.size)) + } + } + @Benchmark + fun encodeAsciiJavaFlatbuffers(blackhole: Blackhole) { + val javaUtf8 = com.google.flatbuffers.Utf8.getDefault() + for (i in sampleSmallAscii) { + val byteBuffer = ByteBuffer.wrap(ByteArray(i.length)) + blackhole.consume(javaUtf8.encodeUtf8(i, byteBuffer)) + } + } + + @Benchmark + fun decodeAsciiKotlinStandard(blackhole: Blackhole) { + + for (ary in sampleSmallAsciiDecoded) { + String(ary) + blackhole.consume(ary.decodeToString()) + } + } + + @Benchmark + fun decodeAsciiKotlinFlatbuffers(blackhole: Blackhole) { + for (ary in sampleSmallAsciiDecoded) { + blackhole.consume(Utf8.decodeUtf8Array(ary, 0, ary.size)) + } + } + + @Benchmark + fun decodeAsciiJavaFlatbuffers(blackhole: Blackhole) { + val javaUtf8 = com.google.flatbuffers.Utf8.getDefault() + for (ary in sampleSmallAsciiDecoded) { + val byteBuffer = ByteBuffer.wrap(ary) + blackhole.consume(javaUtf8.decodeUtf8(byteBuffer, 0, ary.size)) + } + } + + @Benchmark + fun readAllCharsString(blackhole: Blackhole) { + for (ary in sampleSmallAsciiDecoded) { + val key = Utf8.decodeUtf8Array(ary, 0, ary.size) + for (i in key.indices) { + blackhole.consume(key[i]) + } + } + } + + @Benchmark + fun readAllCharsCharSequence(blackhole: Blackhole) { + for (ary in sampleSmallAsciiDecoded) { + val key = Key(ArrayReadWriteBuffer(ary), 0, ary.size) + for (i in 0 until key.sizeInChars) { + blackhole.consume(key[i]) + } + } + } + + fun populateAscii(size: Int): String { + val data = ByteArray(size) + for (i in data.indices) { + data[i] = Random.nextInt(0, 127).toByte() + } + + return String(data, 0, data.size) + } + + // generate a string having at least length N + // can exceed by up to 3 chars, returns the actual length + fun populateUTF8(size: Int): String { + val data = ByteArray(size + 3) + var i = 0 + while (i < size) { + val w = Random.nextInt() and 0xFF + when { + w < 0x80 -> data[i++] = 0x20; // w; + w < 0xE0 -> { + data[i++] = (0xC2 + Random.nextInt() % (0xDF - 0xC2 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w == 0xE0 -> { + data[i++] = w.toByte() + data[i++] = (0xA0 + Random.nextInt() % (0xBF - 0xA0 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w <= 0xEC -> { + data[i++] = w.toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w == 0xED -> { + data[i++] = w.toByte() + data[i++] = (0x80 + Random.nextInt() % (0x9F - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w <= 0xEF -> { + data[i++] = w.toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w < 0xF0 -> { + data[i++] = (0xF1 + Random.nextInt() % (0xF3 - 0xF1 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w == 0xF0 -> { + data[i++] = w.toByte() + data[i++] = (0x90 + Random.nextInt() % (0xBF - 0x90 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w <= 0xF3 -> { + data[i++] = (0xF1 + Random.nextInt() % (0xF3 - 0xF1 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + w == 0xF4 -> { + data[i++] = w.toByte() + data[i++] = (0x80 + Random.nextInt() % (0x8F - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + data[i++] = (0x80 + Random.nextInt() % (0xBF - 0x80 + 1)).toByte() + } + } + } + return String(data, 0, i) + } +} diff --git a/third_party/flatbuffers/kotlin/build.gradle.kts b/third_party/flatbuffers/kotlin/build.gradle.kts new file mode 100644 index 00000000000..0daf4e362a3 --- /dev/null +++ b/third_party/flatbuffers/kotlin/build.gradle.kts @@ -0,0 +1,44 @@ +import org.gradle.internal.impldep.org.testng.ITestResult.STARTED +import org.jetbrains.kotlin.gradle.dsl.KotlinCommonOptions +import org.jetbrains.kotlin.gradle.tasks.KotlinCompile +import java.nio.charset.StandardCharsets + +buildscript { + repositories { + gradlePluginPortal() + google() + mavenCentral() + } + dependencies { + classpath(libs.plugin.kotlin.gradle) + classpath(libs.plugin.kotlinx.benchmark) + classpath(libs.plugin.jmhreport) + classpath(libs.plugin.download) + } +} + +allprojects { + repositories { + google() + mavenCentral() + } +} + +tasks.withType>().configureEach { + kotlinOptions { + freeCompilerArgs += "-progressive" // https://kotlinlang.org/docs/whatsnew13.html#progressive-mode + } +} + +tasks.withType().configureEach { + kotlinOptions { + jvmTarget = JavaVersion.VERSION_1_8.toString() + freeCompilerArgs += "-Xjvm-default=all" + } +} + +tasks.withType { + options.encoding = StandardCharsets.UTF_8.toString() + sourceCompatibility = JavaVersion.VERSION_1_8.toString() + targetCompatibility = JavaVersion.VERSION_1_8.toString() +} diff --git a/third_party/flatbuffers/kotlin/convention-plugins/build.gradle.kts b/third_party/flatbuffers/kotlin/convention-plugins/build.gradle.kts new file mode 100644 index 00000000000..52b9cc0a8c6 --- /dev/null +++ b/third_party/flatbuffers/kotlin/convention-plugins/build.gradle.kts @@ -0,0 +1,7 @@ +plugins { + `kotlin-dsl` +} + +repositories { + gradlePluginPortal() +} diff --git a/third_party/flatbuffers/kotlin/convention-plugins/src/main/kotlin/convention.publication.gradle.kts b/third_party/flatbuffers/kotlin/convention-plugins/src/main/kotlin/convention.publication.gradle.kts new file mode 100644 index 00000000000..e526279654b --- /dev/null +++ b/third_party/flatbuffers/kotlin/convention-plugins/src/main/kotlin/convention.publication.gradle.kts @@ -0,0 +1,95 @@ +import org.gradle.api.publish.maven.MavenPublication +import org.gradle.api.tasks.bundling.Jar +import org.gradle.kotlin.dsl.`maven-publish` +import org.gradle.kotlin.dsl.signing +import java.util.* + +plugins { + `maven-publish` + signing +} + +// Stub secrets to let the project sync and build without the publication values set up +ext["signing.keyId"] = null +ext["signing.password"] = null +ext["signing.secretKeyRingFile"] = null +ext["ossrhUsername"] = null +ext["ossrhPassword"] = null + +// Grabbing secrets from local.properties file or from environment variables, which could be used on CI +val secretPropsFile = project.rootProject.file("local.properties") +if (secretPropsFile.exists()) { + secretPropsFile.reader().use { + Properties().apply { + load(it) + } + }.onEach { (name, value) -> + ext[name.toString()] = value + } +} else { + ext["signing.keyId"] = System.getenv("OSSRH_USERNAME") + ext["signing.password"] = System.getenv("OSSRH_PASSWORD") + ext["signing.secretKeyRingFile"] = System.getenv("INPUT_GPG_PRIVATE_KEY") + ext["ossrhUsername"] = System.getenv("OSSRH_USERNAME") + ext["ossrhPassword"] = System.getenv("OSSRH_PASSWORD") +} + +val javadocJar by tasks.registering(Jar::class) { + archiveClassifier.set("javadoc") +} + +fun getExtraString(name: String) = ext[name]?.toString() + +publishing { + // Configure maven central repository + repositories { + maven { + name = "sonatype" + setUrl("https://s01.oss.sonatype.org/service/local/staging/deploy/maven2/") + credentials { + username = getExtraString("ossrhUsername") + password = getExtraString("ossrhPassword") + } + } + } + + // Configure all publications + publications.withType { + // Stub javadoc.jar artifact + artifact(javadocJar.get()) + + // Provide artifacts information requited by Maven Central + pom { + name.set("Flatbuffers Kotlin") + description.set("Memory Efficient Serialization Library") + url.set("https://github.com/google/flatbuffers") + + licenses { + license { + name.set("Apache License V2.0") + url.set("https://raw.githubusercontent.com/google/flatbuffers/master/LICENSE") + } + } + developers { + developer { + id.set("https://github.com/paulovap") + name.set("Paulo Pinheiro") + email.set("paulovictor.pinheiro@gmail.com") + } + developer { + id.set("https://github.com/dbaileychess") + name.set("Derek Bailey") + email.set("dbaileychess@gmail.com") + } + } + scm { + url.set("https://github.com/google/flatbuffers") + } + } + } +} + +// Signing artifacts. Signing.* extra properties values will be used +signing { + sign(publishing.publications) +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/build.gradle.kts b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/build.gradle.kts new file mode 100644 index 00000000000..1b8d2242dbd --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/build.gradle.kts @@ -0,0 +1,143 @@ +import org.gradle.internal.impldep.org.fusesource.jansi.AnsiRenderer.test +import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFramework +import org.jetbrains.kotlin.cli.common.toBooleanLenient +import org.jetbrains.kotlin.gradle.plugin.mpp.KotlinNativeTarget +import org.jetbrains.kotlin.gradle.plugin.mpp.NativeBuildType +import org.jetbrains.kotlin.gradle.plugin.mpp.apple.XCFrameworkConfig + +plugins { + kotlin("multiplatform") + id("convention.publication") +} + + +val libName = "Flatbuffers" +group = "com.google.flatbuffers.kotlin" +version = "2.0.0-SNAPSHOT" + +kotlin { + explicitApi() + jvm() + js(IR) { + browser { + testTask { + enabled = false + } + } + binaries.executable() + } + macosX64() + macosArm64() + iosArm64() + iosSimulatorArm64() + + sourceSets { + + val commonMain by getting { + dependencies { + implementation(kotlin("stdlib-common")) + } + } + + val commonTest by getting { + dependencies { + implementation(kotlin("test")) + } + + kotlin.srcDir("src/commonTest/generated/kotlin/") + } + val jvmTest by getting { + dependencies { + implementation(kotlin("test-junit")) + implementation("com.google.flatbuffers:flatbuffers-java:2.0.3") + } + } + val jvmMain by getting { + } + + val macosX64Main by getting + val macosArm64Main by getting + val iosArm64Main by getting + val iosSimulatorArm64Main by getting + + val nativeMain by creating { + // this sourceSet will hold common cold for all iOS targets + dependsOn(commonMain) + macosArm64Main.dependsOn(this) + macosX64Main.dependsOn(this) + iosArm64Main.dependsOn(this) + iosSimulatorArm64Main.dependsOn(this) + } + + all { + languageSettings.optIn("kotlin.ExperimentalUnsignedTypes") + } + } +} + +// Fixes JS issue: https://youtrack.jetbrains.com/issue/KT-49109 +rootProject.plugins.withType { + rootProject.the().nodeVersion = "16.0.0" + +} + +// Use the default greeting +tasks.register("generateFBTestClassesKt") { + inputFiles.setFrom("$rootDir/../tests/monster_test.fbs", + "$rootDir/../tests/dictionary_lookup.fbs", +// @todo Seems like nesting code generation is broken for all generators. +// disabling test for now. +// "$rootDir/../tests/namespace_test/namespace_test1.fbs", +// "$rootDir/../tests/namespace_test/namespace_test2.fbs", + "$rootDir/../tests/union_vector/union_vector.fbs", + "$rootDir/../tests/optional_scalars.fbs") + includeFolder.set("$rootDir/../tests/include_test") + outputFolder.set("${projectDir}/src/commonTest/generated/kotlin/") + variant.set("kotlin-kmp") +} + + +project.tasks.forEach { + if (it.name.contains("compileKotlin")) + it.dependsOn("generateFBTestClassesKt") +} + +fun String.intProperty() = findProperty(this).toString().toInt() + +abstract class GenerateFBTestClasses : DefaultTask() { + @get:InputFiles + abstract val inputFiles: ConfigurableFileCollection + + @get:Input + abstract val includeFolder: Property + + @get:Input + abstract val outputFolder: Property + + @get:Input + abstract val variant: Property + + @Inject + protected open fun getExecActionFactory(): org.gradle.process.internal.ExecActionFactory? { + throw UnsupportedOperationException() + } + + init { + includeFolder.set("") + } + + @TaskAction + fun compile() { + val execAction = getExecActionFactory()!!.newExecAction() + val sources = inputFiles.asPath.split(":") + val args = mutableListOf("flatc","-o", outputFolder.get(), "--${variant.get()}") + if (includeFolder.get().isNotEmpty()) { + args.add("-I") + args.add(includeFolder.get()) + } + args.addAll(sources) + println(args) + execAction.commandLine = args + print(execAction.execute()) + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Buffers.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Buffers.kt new file mode 100644 index 00000000000..e10037a0dc9 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Buffers.kt @@ -0,0 +1,616 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import kotlin.math.max +import kotlin.math.min + +/** + * Represent a chunk of data, where FlexBuffers will be read from. + */ +public interface ReadBuffer { + + /** + * Scan through the buffer for first byte matching value. + * @param value to be match + * @param start inclusive initial position to start searching + * @param end exclusive final position of the search + * @return position of a match or -1 + */ + public fun findFirst(value: Byte, start: Int, end: Int = limit): Int + + /** + * Read boolean from the buffer. Booleans as stored as a single byte + * @param index position of the element in [ReadBuffer] + * @return [Boolean] element + */ + public fun getBoolean(index: Int): Boolean + + /** + * Read a [Byte] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a byte + */ + public operator fun get(index: Int): Byte + + /** + * Read a [UByte] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a [UByte] + */ + public fun getUByte(index: Int): UByte + + /** + * Read a [Short] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a [Short] + */ + public fun getShort(index: Int): Short + + /** + * Read a [UShort] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a [UShort] + */ + public fun getUShort(index: Int): UShort + + /** + * Read a [Int] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return an [Int] + */ + public fun getInt(index: Int): Int + + /** + * Read a [UInt] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return an [UInt] + */ + public fun getUInt(index: Int): UInt + + /** + * Read a [Long] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a [Long] + */ + public fun getLong(index: Int): Long + + /** + * Read a [ULong] from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a [ULong] + */ + public fun getULong(index: Int): ULong + + /** + * Read a 32-bit float from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a float + */ + public fun getFloat(index: Int): Float + + /** + * Read a 64-bit float from the buffer. + * @param index position of the element in [ReadBuffer] + * @return a double + */ + public fun getDouble(index: Int): Double + + /** + * Read a UTF-8 string from the buffer. + * @param start initial element of the string + * @param size size of the string in bytes. + * @return a `String` + */ + public fun getString(start: Int = 0, size: Int = limit): String + + /** + * Read a ByteArray from the buffer. + * @param start position from the [ReadBuffer] to be read + * @param length maximum number of bytes to be written in the buffer + */ + public fun getBytes(array: ByteArray, start: Int, length: Int = array.size) + + /** + * Expose [ReadBuffer] as an array of bytes. + * This method is meant to be as efficient as possible, so for an array-backed [ReadBuffer], it should + * return its own internal data. In case access to internal data is not possible, + * a copy of the data into an array of bytes might occur. + * @return [ReadBuffer] as an array of bytes + */ + public fun data(): ByteArray + + /** + * Creates a new [ReadBuffer] point to a region of the current buffer, starting at [start] with size [size]. + * @param start starting position of the [ReadBuffer] + * @param size in bytes of the [ReadBuffer] + * @return [ReadBuffer] slice. + */ + public fun slice(start: Int, size: Int): ReadBuffer + + /** + * Defines the size of the message in the buffer. It also determines last position that buffer + * can be read. Last byte to be accessed is in position `limit() -1`. + * @return indicate last position + */ + public val limit: Int +} + +/** + * Interface to represent a read-write buffers. This interface will be used to access and write FlexBuffer messages. + */ +public interface ReadWriteBuffer : ReadBuffer { + /** + * Clears (resets) the buffer so that it can be reused. Write position will be set to the start. + */ + public fun clear() + + /** + * Request capacity of the buffer relative to [writePosition]. In case buffer is already larger + * than the requested, this method will just return true. Otherwise, + * It might try to resize the buffer. In case of being unable to allocate + * enough memory, an exception will be thrown. + * @param additional capacity in bytes to be added on top of [writePosition] + * @param copyAtEnd copy current data at the end of new underlying buffer + * @return new capacity in bytes + */ + public fun requestAdditionalCapacity(additional: Int, copyAtEnd: Boolean = false): Int = + requestCapacity(writePosition + additional, copyAtEnd) + + /** + * Request capacity of the buffer in absolute values. In case buffer is already larger + * than the requested the method is a no-op. Otherwise, + * It might try to resize the buffer. In case of being unable to allocate + * enough memory, an exception will be thrown. + * @param capacity new capacity + * @param copyAtEnd copy current data at the end of new underlying buffer + * @return new capacity in bytes + */ + public fun requestCapacity(capacity: Int, copyAtEnd: Boolean = false): Int + + /** + * Put a [Boolean] into the buffer at [writePosition] . Booleans as stored as single byte. + * Write position will be incremented. + * @return [Boolean] element + */ + public fun put(value: Boolean) + + /** + * Put an array of bytes into the buffer at [writePosition]. Write position will be incremented. + * @param value the data to be copied + * @param start initial position on value to be copied + * @param length amount of bytes to be copied + */ + public fun put(value: ByteArray, start: Int = 0, length: Int = value.size) + + /** + * Put an array of bytes into the buffer at [writePosition]. Write position will be incremented. + * @param value [ReadBuffer] the data to be copied + * @param start initial position on value to be copied + * @param length amount of bytes to be copied + */ + public fun put(value: ReadBuffer, start: Int = 0, length: Int = value.limit - start) + + /** + * Write a [Byte] into the buffer at [writePosition]. Write position will be incremented. + */ + public fun put(value: Byte) + + /** + * Write a [UByte] into the buffer at [writePosition]. Write position will be incremented. + */ + public fun put(value: UByte) + + /** + * Write a [Short] into in the buffer at [writePosition]. Write position will be incremented. + */ + public fun put(value: Short) + + /** + * Write a [UShort] into in the buffer at [writePosition]. Write position will be incremented. + */ + public fun put(value: UShort) + + /** + * Write a [Int] in the buffer at [writePosition]. Write position will be incremented. + */ + public fun put(value: Int) + + /** + * Write a [UInt] into in the buffer at [writePosition]. Write position will be incremented. + */ + public fun put(value: UInt) + + /** + * Write a [Long] into in the buffer at [writePosition]. Write position will be + * incremented. + */ + public fun put(value: Long) + + /** + * Write a [ULong] into in the buffer at [writePosition]. Write position will be + * incremented. + */ + public fun put(value: ULong) + + /** + * Write a 32-bit [Float] into the buffer at [writePosition]. Write position will be + * incremented. + */ + public fun put(value: Float) + + /** + * Write a 64-bit [Double] into the buffer at [writePosition]. Write position will be + * incremented. + */ + public fun put(value: Double) + + /** + * Write a [String] encoded as UTF-8 into the buffer at [writePosition]. Write position will be incremented. + * @return size in bytes of the encoded string + */ + public fun put(value: CharSequence, encodedLength: Int = -1): Int + + /** + * Write an array of bytes into the buffer. + * @param dstIndex initial position where [src] will be copied into. + * @param src the data to be copied. + * @param srcStart initial position on [src] that will be copied. + * @param srcLength amount of bytes to be copied + */ + public fun set(dstIndex: Int, src: ByteArray, srcStart: Int = 0, srcLength: Int = src.size) + + /** + * Write an array of bytes into the buffer. + * @param dstIndex initial position where [src] will be copied into. + * @param src the data to be copied. + * @param srcStart initial position on [src] that will be copied. + * @param srcLength amount of bytes to be copied + */ + public operator fun set(dstIndex: Int, src: ReadBuffer, srcStart: Int = 0, srcLength: Int) + + /** + * Write [Boolean] into a given position [index] on the buffer. Booleans as stored as single byte. + * @param index position of the element in buffer + */ + public operator fun set(index: Int, value: Boolean) + + /** + * Write [Byte] into a given position [index] on the buffer. + * @param index position of the element in the buffer + */ + public operator fun set(index: Int, value: Byte) + + /** + * Write [UByte] into a given position [index] on the buffer. + * @param index position of the element in the buffer + */ + public operator fun set(index: Int, value: UByte) + + /** + Short + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: Short) + + /** + * Write [UShort] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: UShort) + + /** + * Write [Int] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: Int) + + /** + * Write [UInt] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: UInt) + + /** + * Write [Long] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: Long) + + /** + * Write [ULong] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: ULong) + + /** + * Write [Float] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: Float) + + /** + * Write [Double] into a given position [index] on the buffer. + * @param index position of the element in [ReadBuffer] + */ + public fun set(index: Int, value: Double) + + public fun fill(value: Byte, start: Int, end: Int) + + /** + * Current position of the buffer to be written. It will be automatically updated on [put] operations. + */ + public var writePosition: Int + + /** + * Creates a new [ReadWriteBuffer] point to a region of the current buffer, starting at [offset] with size [size]. + * @param offset starting position of the [ReadWriteBuffer] + * @param size in bytes of the [ReadWriteBuffer] + * @return [ReadWriteBuffer] slice. + */ + public fun writeSlice(offset: Int, size: Int): ReadWriteBuffer + + /** + * Special operation where we increase the backed buffer size to [capacity] + * and shift all already written data to the end of the buffer. + * + * This function is mostly used when creating a Flatbuffer message, as + * data is written from the end of the buffer towards index 0. + * @param capacity required in bytes + * @return new capacity in bytes + */ + public fun moveWrittenDataToEnd(capacity: Int): Int + + /** + * Maximum size in bytes that the backed buffer supports. + */ + public val capacity: Int + + /** + * Defines last relative position of the backed buffer that can be written. + * Any addition to the buffer that goes beyond will throw an exception + * instead of regrow the buffer (default behavior). + */ + public val writeLimit: Int +} + +public open class ArrayReadBuffer(protected var buffer: ByteArray, + // offsets writePosition against backed buffer e.g. offset = 1, writePosition = 1 + // will write first byte at position 2 of the backed buffer + internal val offset: Int = 0, + override val limit: Int = buffer.size - offset) : ReadBuffer { + + + override fun findFirst(value: Byte, start: Int, end: Int): Int { + val e = min(end, limit) + val s = max(0, this.offset + start) + for (i in s until e) if (buffer[i] == value) return i + return -1 + } + + override fun getBoolean(index: Int): Boolean = buffer[offset + index] != 0.toByte() + + override operator fun get(index: Int): Byte = buffer[offset + index] + + override fun getUByte(index: Int): UByte = buffer.getUByte(offset + index) + + override fun getShort(index: Int): Short = buffer.getShort(offset + index) + + override fun getUShort(index: Int): UShort = buffer.getUShort(offset + index) + + override fun getInt(index: Int): Int = buffer.getInt(offset + index) + + override fun getUInt(index: Int): UInt = buffer.getUInt(offset + index) + + override fun getLong(index: Int): Long = buffer.getLong(offset + index) + + override fun getULong(index: Int): ULong = buffer.getULong(offset + index) + + override fun getFloat(index: Int): Float = buffer.getFloat(offset + index) + + override fun getDouble(index: Int): Double = buffer.getDouble(offset + index) + + override fun getString(start: Int, size: Int): String = buffer.decodeToString(this.offset + start, + this.offset + start + size) + + override fun getBytes(array: ByteArray, start: Int, length: Int) { + val end = min(this.offset + start + length, buffer.size) + var j = 0 + for (i in this.offset + start until end) { + array[j++] = buffer[i] + } + } + + override fun data(): ByteArray = buffer + + override fun slice(start: Int, size: Int): ReadBuffer = ArrayReadBuffer(buffer, this.offset + start, size) +} +/** + * Implements `[ReadWriteBuffer]` using [ByteArray] as backing buffer. Using array of bytes are + * usually faster than `ByteBuffer`. + * + * This class is not thread-safe, meaning that + * it must operate on a single thread. Operating from + * multiple thread leads into an undefined behavior + * + * All operations assume Little Endian byte order. + */ + +public class ArrayReadWriteBuffer( + buffer: ByteArray, + offset: Int = 0, + // Defines last position of the backed buffer that can be written. + // Any addition to the buffer that goes beyond will throw an exception + // instead of regrow the buffer (default behavior). + public override val writeLimit: Int = -1, + override var writePosition: Int = offset +) : ArrayReadBuffer(buffer, offset, writePosition), ReadWriteBuffer { + + public constructor(initialCapacity: Int = 10) : this(ByteArray(initialCapacity)) + + override val limit: Int get() = writePosition + + override fun clear(): Unit = run { writePosition = 0 } + + override fun put(value: Boolean) { + set(writePosition, value) + writePosition++ + } + + override fun put(value: ByteArray, start: Int, length: Int) { + set(writePosition, value, start, length) + writePosition += length + } + + override fun put(value: ReadBuffer, start: Int, length: Int) { + set(writePosition, value, start, length) + writePosition += length + } + + override fun put(value: Byte) { + set(writePosition, value) + writePosition++ + } + + override fun put(value: UByte) { + set(writePosition, value) + writePosition++ + } + + override fun put(value: Short) { + set(writePosition, value) + writePosition += 2 + } + + override fun put(value: UShort) { + set(writePosition, value) + writePosition += 2 + } + + override fun put(value: Int) { + set(writePosition, value) + writePosition += 4 + } + + override fun put(value: UInt) { + set(writePosition, value) + writePosition += 4 + } + + override fun put(value: Long) { + set(writePosition, value) + writePosition += 8 + } + + override fun put(value: ULong) { + set(writePosition, value) + writePosition += 8 + } + + override fun put(value: Float) { + set(writePosition, value) + writePosition += 4 + } + + override fun put(value: Double) { + set(writePosition, value) + writePosition += 8 + } + + override fun put(value: CharSequence, encodedLength: Int): Int { + val length = if (encodedLength != -1) encodedLength else Utf8.encodedLength(value) + writePosition = buffer.setCharSequence(writePosition, value) + return length + } + + override fun set(index: Int, value: Boolean) { + buffer[index] = if (value) 1.toByte() else 0.toByte() + } + + override fun set(dstIndex: Int, src: ByteArray, srcStart: Int, srcLength: Int) { + src.copyInto(buffer, dstIndex, srcStart, srcStart + srcLength) + } + + override operator fun set(dstIndex: Int, src: ReadBuffer, srcStart: Int, srcLength: Int) { + when(src) { + is ArrayReadBuffer -> { + src.data().copyInto(buffer, dstIndex, src.offset + srcStart, src.offset + srcStart + srcLength) + } + else -> { + for (i in 0 until srcLength) { + buffer[dstIndex + i] = src[srcStart + i] + } + } + } + } + + override operator fun set(index: Int, value: Byte) { buffer[index] = value } + override operator fun set(index: Int, value: UByte) { buffer.setUByte(index, value) } + override operator fun set(index: Int, value: Short) { buffer.setShort(index, value) } + override operator fun set(index: Int, value: UShort) { buffer.setUShort(index, value) } + override operator fun set(index: Int, value: Int) { buffer.setInt(index, value) } + override operator fun set(index: Int, value: UInt) { buffer.setUInt(index, value) } + override operator fun set(index: Int, value: Long) { buffer.setLong(index, value) } + override operator fun set(index: Int, value: ULong) { buffer.setULong(index, value) } + override operator fun set(index: Int, value: Float) { buffer.setFloat(index, value) } + override operator fun set(index: Int, value: Double) { buffer.setDouble(index, value) } + override fun fill(value: Byte, start: Int, end: Int) { buffer.fill(value, start, end) } + + /** + * Request capacity of the buffer. In case buffer is already larger + * than the requested, it is a no-op. Otherwise, + * It might try to resize the buffer. In case of being unable to allocate + * enough memory, an exception will be thrown. + * @param capacity new capacity + * @param copyAtEnd copy current data at the end of new underlying buffer + */ + override fun requestCapacity(capacity: Int, copyAtEnd: Boolean): Int { + if (capacity < 0) error("Capacity may not be negative (likely a previous int overflow)") + + if (buffer.size >= capacity) return buffer.size + + if (writeLimit > 0 && writeLimit + offset >= buffer.size) error("Buffer in writeLimit mode. In writeLimit mode" + + " the buffer does not grow automatically and any write beyond writeLimit will throw exception. " + + "(writeLimit: $writeLimit, newCapacity: $capacity") + // implemented in the same growing fashion as ArrayList + val oldCapacity = buffer.size + if (oldCapacity == Int.MAX_VALUE - 8) { // Ensure we don't grow beyond what fits in an int. + error("FlatBuffers: cannot grow buffer beyond 2 gigabytes.") + } + //(old_buf_size & 0xC0000000) != 0 ? MAX_BUFFER_SIZE : old_buf_size << 1; + var newCapacity = 8 + while (newCapacity < capacity) { // Note: this also catches newCapacity int overflow + newCapacity = if (newCapacity and -0x40000000 != 0) Int.MAX_VALUE - 8 else newCapacity shl 1 + } + val newBuffer = ByteArray(newCapacity) + + buffer.copyInto(newBuffer, if (copyAtEnd) newBuffer.size - buffer.size else 0) + buffer = newBuffer + return newCapacity + } + + override fun writeSlice(offset: Int, size: Int): ReadWriteBuffer { + return ArrayReadWriteBuffer(this.buffer, offset=offset, writeLimit=size) + } + + override fun moveWrittenDataToEnd(capacity: Int): Int = requestCapacity(capacity, true) + + override val capacity: Int + get() = buffer.size + +} + +public val emptyBuffer: ReadWriteBuffer = ArrayReadWriteBuffer(ByteArray(1)) diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt new file mode 100644 index 00000000000..e851f5d2ab3 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt @@ -0,0 +1,124 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +import kotlin.experimental.and + +internal fun ByteArray.getString(index: Int, size: Int): String = Utf8.decodeUtf8Array(this, index, size) + +internal fun ByteArray.setCharSequence(index: Int, value: CharSequence): Int = + Utf8.encodeUtf8Array(value, this, index, this.size - index) + +// List of functions that needs to be implemented on all platforms. +internal expect inline fun ByteArray.getUByte(index: Int): UByte +internal expect inline fun ByteArray.getShort(index: Int): Short +internal expect inline fun ByteArray.getUShort(index: Int): UShort +internal expect inline fun ByteArray.getInt(index: Int): Int +internal expect inline fun ByteArray.getUInt(index: Int): UInt +internal expect inline fun ByteArray.getLong(index: Int): Long +internal expect inline fun ByteArray.getULong(index: Int): ULong +internal expect inline fun ByteArray.getFloat(index: Int): Float +internal expect inline fun ByteArray.getDouble(index: Int): Double + +internal expect inline fun ByteArray.setUByte(index: Int, value: UByte) +public expect inline fun ByteArray.setShort(index: Int, value: Short) +internal expect inline fun ByteArray.setUShort(index: Int, value: UShort) +internal expect inline fun ByteArray.setInt(index: Int, value: Int) +internal expect inline fun ByteArray.setUInt(index: Int, value: UInt) +internal expect inline fun ByteArray.setLong(index: Int, value: Long) +internal expect inline fun ByteArray.setULong(index: Int, value: ULong) +internal expect inline fun ByteArray.setFloat(index: Int, value: Float) +internal expect inline fun ByteArray.setDouble(index: Int, value: Double) + +/** + * This implementation uses Little Endian order. + */ +public object ByteArrayOps { + public inline fun getUByte(ary: ByteArray, index: Int): UByte = ary[index].toUByte() + public inline fun getShort(ary: ByteArray, index: Int): Short { + return (ary[index + 1].toInt() shl 8 or (ary[index].toInt() and 0xff)).toShort() + } + + public inline fun getUShort(ary: ByteArray, index: Int): UShort = getShort(ary, index).toUShort() + + public inline fun getInt(ary: ByteArray, index: Int): Int { + return ( + (ary[index + 3].toInt() shl 24) or + ((ary[index + 2].toInt() and 0xff) shl 16) or + ((ary[index + 1].toInt() and 0xff) shl 8) or + ((ary[index].toInt() and 0xff)) + ) + } + + public inline fun getUInt(ary: ByteArray, index: Int): UInt = getInt(ary, index).toUInt() + + public inline fun getLong(ary: ByteArray, index: Int): Long { + var idx = index + return ary[idx++].toLong() and 0xff or + (ary[idx++].toLong() and 0xff shl 8) or + (ary[idx++].toLong() and 0xff shl 16) or + (ary[idx++].toLong() and 0xff shl 24) or + (ary[idx++].toLong() and 0xff shl 32) or + (ary[idx++].toLong() and 0xff shl 40) or + (ary[idx++].toLong() and 0xff shl 48) or + (ary[idx].toLong() shl 56) + } + + public inline fun getULong(ary: ByteArray, index: Int): ULong = getLong(ary, index).toULong() + + public inline fun setUByte(ary: ByteArray, index: Int, value: UByte) { + ary[index] = value.toByte() + } + public inline fun setShort(ary: ByteArray, index: Int, value: Short) { + var idx = index + ary[idx++] = (value and 0xff).toByte() + ary[idx] = (value.toInt() shr 8 and 0xff).toByte() + } + + public inline fun setUShort(ary: ByteArray, index: Int, value: UShort): Unit = setShort(ary, index, value.toShort()) + + public inline fun setInt(ary: ByteArray, index: Int, value: Int) { + var idx = index + ary[idx++] = (value and 0xff).toByte() + ary[idx++] = (value shr 8 and 0xff).toByte() + ary[idx++] = (value shr 16 and 0xff).toByte() + ary[idx] = (value shr 24 and 0xff).toByte() + } + + public inline fun setUInt(ary: ByteArray, index: Int, value: UInt): Unit = setInt(ary, index, value.toInt()) + + public inline fun setLong(ary: ByteArray, index: Int, value: Long) { + var i = value.toInt() + setInt(ary, index, i) + i = (value shr 32).toInt() + setInt(ary, index + 4, i) + } + + public inline fun setULong(ary: ByteArray, index: Int, value: ULong): Unit = setLong(ary, index, value.toLong()) + + public inline fun setFloat(ary: ByteArray, index: Int, value: Float) { + setInt(ary, index, value.toRawBits()) + } + + public inline fun setDouble(ary: ByteArray, index: Int, value: Double) { + setLong(ary, index, value.toRawBits()) + } + + public inline fun getFloat(ary: ByteArray, index: Int): Float = Float.fromBits(getInt(ary, index)) + public inline fun getDouble(ary: ByteArray, index: Int): Double = Double.fromBits(getLong(ary, index)) +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlatBufferBuilder.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlatBufferBuilder.kt new file mode 100644 index 00000000000..28ab2ca9889 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlatBufferBuilder.kt @@ -0,0 +1,1105 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import kotlin.jvm.JvmOverloads + + +/** + * Class that helps you build a FlatBuffer. See the section + * "Use in Kotlin" in the main FlatBuffers documentation. + */ +public class FlatBufferBuilder @JvmOverloads constructor( + private val initialSize: Int = 1024, + private var buffer: ReadWriteBuffer = ArrayReadWriteBuffer(initialSize) +) { + // Remaining space in the ByteBuffer. + private var space: Int = buffer.capacity + + // Minimum alignment encountered so far. + private var minalign: Int = 1 + + // The vtable for the current table. + private var vtable: IntArray = IntArray(16) + + // The amount of fields we're actually using. + private var vtableInUse: Int = 0 + + // Whether we are currently serializing a table. + private var nested: Boolean = false + + // Whether the buffer is finished. + private var finished: Boolean = false + + // Starting offset of the current struct/table. + private var objectStart: Int = 0 + + // List of offsets of all vtables. + private var vtables = IntArray(16) + + // Number of entries in `vtables` in use. + private var numVtables = 0 + + // For the current vector being built. + private var vectorNumElems = 0 + + // False omits default values from the serialized data. + private var forceDefaults = false + + // map used to cache shared strings. + private var stringPool: MutableMap>? = null + + /** + * Reset the FlatBufferBuilder by purging all data that it holds. + */ + public fun clear() { + space = buffer.capacity + buffer.clear() + minalign = 1 + vtable.fill(0, 0, vtableInUse) + vtableInUse = 0 + nested = false + finished = false + objectStart = 0 + numVtables = 0 + vectorNumElems = 0 + stringPool?.clear() + } + + /** + * Offset relative to the end of the buffer. + * + * @return Offset relative to the end of the buffer. + */ + public fun offset(): Int = buffer.capacity - space + + /** + * Add zero valued bytes to prepare a new entry to be added. + * + * @param byteSize Number of bytes to add. + */ + public fun pad(byteSize: Int) { + for (i in 0 until byteSize) buffer[--space] = 0.toByte() + } + + /** + * Prepare to write an element of `size` after `additional_bytes` + * have been written, e.g. if you write a string, you need to align such + * the int length field is aligned to [com.google.flatbuffers.Int.SIZE_BYTES], and + * the string data follows it directly. If all you need to do is alignment, `additional_bytes` + * will be 0. + * + * @param size This is the of the new element to write. + * @param additionalBytes The padding size. + */ + public fun prep(size: Int, additionalBytes: Int) { + // Track the biggest thing we've ever aligned to. + if (size > minalign) minalign = size + // Find the amount of alignment needed such that `size` is properly + // aligned after `additional_bytes` + + val alignSize: Int = ((buffer.capacity - space + additionalBytes).inv() + 1).and(size - 1) + // Reallocate the buffer if needed. + while (space < alignSize + size + additionalBytes) { + val oldBufSize: Int = buffer.capacity + val newBufSize = buffer.moveWrittenDataToEnd(oldBufSize + alignSize + size + additionalBytes) + space += newBufSize - oldBufSize + } + if (alignSize > 0) { + pad(alignSize) + } + } + + /** + * Add a `boolean` to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A `boolean` to put into the buffer. + */ + public fun put(x: Boolean) { + space -= Byte.SIZE_BYTES + buffer[space] = (if (x) 1 else 0).toByte() + } + + /** + * Add a [UByte] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [UByte] to put into the buffer. + */ + public fun put(x: UByte): Unit = put(x.toByte()) + + /** + * Add a [Byte] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [Byte] to put into the buffer. + */ + public fun put(x: Byte) { + space -= Byte.SIZE_BYTES + buffer[space] = x + } + + /** + * Add a [UShort] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [UShort] to put into the buffer. + */ + public fun put(x: UShort): Unit = put(x.toShort()) + + /** + * Add a [Short] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [Short] to put into the buffer. + */ + public fun put(x: Short) { + space -= Short.SIZE_BYTES + buffer.set(space, x) + } + + /** + * Add an [UInt] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x An [UInt] to put into the buffer. + */ + public fun put(x: UInt): Unit = put(x.toInt()) + + /** + * Add an [Int] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x An [Int] to put into the buffer. + */ + public fun put(x: Int){ + space -= Int.SIZE_BYTES + buffer.set(space, x) + } + + /** + * Add a [ULong] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [ULong] to put into the buffer. + */ + public fun put(x: ULong): Unit = put(x.toLong()) + + /** + * Add a [Long] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [Long] to put into the buffer. + */ + public fun put(x: Long) { + space -= Long.SIZE_BYTES + buffer.set(space, x) + } + + /** + * Add a [Float] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [Float] to put into the buffer. + */ + public fun put(x: Float) { + space -= Float.SIZE_BYTES + buffer.set(space, x) + } + + /** + * Add a [Double] to the buffer, backwards from the current location. Doesn't align nor + * check for space. + * + * @param x A [Double] to put into the buffer. + */ + public fun put(x: Double) { + space -= Double.SIZE_BYTES + buffer.set(space, x) + } + + /** + * Add a [Boolean] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [Boolean] to put into the buffer. + */ + public fun add(x: Boolean) { + prep(Byte.SIZE_BYTES, 0) + put(x) + } + + /** + * Add a [UByte] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [UByte] to put into the buffer. + */ + public fun add(x: UByte): Unit = add(x.toByte()) + + /** + * Add a [Byte] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [Byte] to put into the buffer. + */ + public fun add(x: Byte) { + prep(Byte.SIZE_BYTES, 0) + put(x) + } + + /** + * Add a [UShort] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [UShort] to put into the buffer. + */ + public fun add(x: UShort): Unit = add(x.toShort()) + + /** + * Add a [Short] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [Short] to put into the buffer. + */ + public fun add(x: Short) { + prep(Short.SIZE_BYTES, 0) + put(x) + } + + /** + * Add an [Unit] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x An [Unit] to put into the buffer. + */ + public fun add(x: UInt): Unit = add(x.toInt()) + + /** + * Add an [Int] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x An [Int] to put into the buffer. + */ + public fun add(x: Int) { + prep(Int.SIZE_BYTES, 0) + put(x) + } + + /** + * Add a [ULong] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [ULong] to put into the buffer. + */ + public fun add(x: ULong): Unit = add(x.toLong()) + + /** + * Add a `long` to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A `long` to put into the buffer. + */ + public fun add(x: Long) { + prep(Long.SIZE_BYTES, 0) + put(x) + } + + /** + * Add a [Float] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [Float] to put into the buffer. + */ + public fun add(x: Float) { + prep(Float.SIZE_BYTES, 0) + put(x) + } + + /** + * Add a [Double] to the buffer, properly aligned, and grows the buffer (if necessary). + * + * @param x A [Double] to put into the buffer. + */ + public fun add(x: Double) { + prep(Double.SIZE_BYTES, 0) + put(x) + } + + /** + * Adds on offset, relative to where it will be written. + * + * @param off The offset to add. + */ + public fun add(off: Offset<*>): Unit = addOffset(off.value) + public fun add(off: VectorOffset<*>): Unit = addOffset(off.value) + private fun addOffset(off: Int) { + prep(Int.SIZE_BYTES, 0) // Ensure alignment is already done. + put(buffer.capacity - space - off + Int.SIZE_BYTES) + } + + /** + * Start a new array/vector of objects. Users usually will not call + * this directly. The `FlatBuffers` compiler will create a start/end + * method for vector types in generated code. + * + * + * The expected sequence of calls is: + * + * 1. Start the array using this method. + * 1. Call [.addOffset] `num_elems` number of times to set + * the offset of each element in the array. + * 1. Call [.endVector] to retrieve the offset of the array. + * + * + * + * For example, to create an array of strings, do: + *

`// Need 10 strings
+   * FlatBufferBuilder builder = new FlatBufferBuilder(existingBuffer);
+   * int[] offsets = new int[10];
+   *
+   * for (int i = 0; i < 10; i++) {
+   * offsets[i] = fbb.createString(" " + i);
+   * }
+   *
+   * // Have the strings in the buffer, but don't have a vector.
+   * // Add a vector that references the newly created strings:
+   * builder.startVector(4, offsets.length, 4);
+   *
+   * // Add each string to the newly created vector
+   * // The strings are added in reverse order since the buffer
+   * // is filled in back to front
+   * for (int i = offsets.length - 1; i >= 0; i--) {
+   * builder.addOffset(offsets[i]);
+   * }
+   *
+   * // Finish off the vector
+   * int offsetOfTheVector = fbb.endVector();
+   `
* + * + * @param elemSize The size of each element in the array. + * @param numElems The number of elements in the array. + * @param alignment The alignment of the array. + */ + public fun startVector(elemSize: Int, numElems: Int, alignment: Int) { + notNested() + vectorNumElems = numElems + prep(Int.SIZE_BYTES, elemSize * numElems) + prep(alignment, elemSize * numElems) // Just in case alignment > int. + nested = true + } + public fun startString(numElems: Int): Unit = startVector(1, numElems, 1) + + /** + * Finish off the creation of an array and all its elements. The array + * must be created with [.startVector]. + * + * @return The offset at which the newly created array starts. + * @see .startVector + */ + public fun endVector(): VectorOffset { + if (!nested) throw AssertionError("FlatBuffers: endVector called without startVector") + nested = false + put(vectorNumElems) + return VectorOffset(offset()) + } + + public fun endString(): Offset { + if (!nested) throw AssertionError("FlatBuffers: endString called without startString") + nested = false + put(vectorNumElems) + return Offset(offset()) + } + + private fun endVector(): Int { + if (!nested) throw AssertionError("FlatBuffers: endVector called without startVector") + nested = false + put(vectorNumElems) + return offset() + } + + /** + * Create a new array/vector and return a ByteBuffer to be filled later. + * Call [endVector] after this method to get an offset to the beginning + * of vector. + * + * @param elemSize the size of each element in bytes. + * @param numElems number of elements in the vector. + * @param alignment byte alignment. + * @return ByteBuffer with position and limit set to the space allocated for the array. + */ + public fun createUnintializedVector(elemSize: Int, numElems: Int, alignment: Int): ReadWriteBuffer { + val length = elemSize * numElems + startVector(elemSize, numElems, alignment) + space -= length + buffer.writePosition = space + return buffer.writeSlice(buffer.writePosition, length) + } + + /** + * Create a vector of tables. + * + * @param offsets Offsets of the tables. + * @return Returns offset of the vector. + */ + public fun createVectorOfTables(offsets: Array>): VectorOffset { + notNested() + startVector(Int.SIZE_BYTES, offsets.size, Int.SIZE_BYTES) + for (i in offsets.indices.reversed()) add(offsets[i]) + return VectorOffset(endVector()) + } + + /** + * Create a vector of sorted by the key tables. + * + * @param obj Instance of the table subclass. + * @param offsets Offsets of the tables. + * @return Returns offset of the sorted vector. + */ + public fun createSortedVectorOfTables(obj: T, offsets: Array>): VectorOffset { + obj.sortTables(offsets, buffer) + return createVectorOfTables(offsets) + } + + /** + * Encode the String `s` in the buffer using UTF-8. If a String with + * this exact contents has already been serialized using this method, + * instead simply returns the offset of the existing String. + * + * Usage of the method will incur into additional allocations, + * so it is advisable to use it only when it is known upfront that + * your message will have several repeated strings. + * + * @param s The String to encode. + * @return The offset in the buffer where the encoded String starts. + */ + public fun createSharedString(s: CharSequence): Offset { + if (stringPool == null) { + stringPool = HashMap() + val offset = createString(s) + stringPool!![s] = offset + return offset + } + var offset = stringPool!![s] + if (offset == null) { + offset = createString(s) + stringPool?.put(s, offset) + } + return offset + } + + /** + * Encode the [CharSequence] `s` in the buffer using UTF-8. + * @param s The [CharSequence] to encode. + * @return The offset in the buffer where the encoded string starts. + */ + public fun createString(s: CharSequence): Offset { + val length: Int = Utf8.encodedLength(s) + add(0.toByte()) + startString(length) + space -= length + buffer.writePosition = space + buffer.put(s, length) + return endString() + } + + /** + * Create a string in the buffer from an already encoded UTF-8 string in a ByteBuffer. + * + * @param s An already encoded UTF-8 string as a `ByteBuffer`. + * @return The offset in the buffer where the encoded string starts. + */ + public fun createString(s: ReadBuffer): Offset { + val length: Int = s.limit + add(0.toByte()) + startVector(1, length, 1) + space -= length + buffer.writePosition = space + buffer.put(s) + return endString() + } + + /** + * Create a byte array in the buffer. + * + * @param arr A source array with data + * @return The offset in the buffer where the encoded array starts. + */ + public fun createByteVector(arr: ByteArray): VectorOffset { + val length = arr.size + startVector(1, length, 1) + space -= length + buffer.writePosition = space + buffer.put(arr) + return VectorOffset(endVector()) + } + + /** + * Create a byte array in the buffer. + * + * @param arr a source array with data. + * @param offset the offset in the source array to start copying from. + * @param length the number of bytes to copy from the source array. + * @return The offset in the buffer where the encoded array starts. + */ + public fun createByteVector(arr: ByteArray, offset: Int, length: Int): VectorOffset { + startVector(1, length, 1) + space -= length + buffer.writePosition = space + buffer.put(arr, offset, length) + return VectorOffset(endVector()) + } + + /** + * Create a byte array in the buffer. + * + * The source [ReadBuffer] position is advanced until [ReadBuffer.limit] + * after this call. + * + * @param data A source [ReadBuffer] with data. + * @return The offset in the buffer where the encoded array starts. + */ + public fun createByteVector(data: ReadBuffer, from: Int = 0, until: Int = data.limit): VectorOffset { + val length: Int = until - from + startVector(1, length, 1) + space -= length + buffer.writePosition = space + buffer.put(data, from, until) + return VectorOffset(endVector()) + } + + /** + * Should not be accessing the final buffer before it is finished. + */ + public fun finished() { + if (!finished) throw AssertionError( + "FlatBuffers: you can only access the serialized buffer after it has been" + + " finished by FlatBufferBuilder.finish()." + ) + } + + /** + * Should not be creating any other object, string or vector + * while an object is being constructed. + */ + public fun notNested() { + if (nested) throw AssertionError("FlatBuffers: object serialization must not be nested.") + } + + /** + * Structures are always stored inline, they need to be created right + * where they're used. You'll get this assertion failure if you + * created it elsewhere. + * + * @param obj The offset of the created object. + */ + public fun nested(obj: Int) { + if (obj != offset()) throw AssertionError("FlatBuffers: struct must be serialized inline.") + } + + /** + * Start encoding a new object in the buffer. Users will not usually need to + * call this directly. The `FlatBuffers` compiler will generate helper methods + * that call this method internally. + * + * + * For example, using the "Monster" code found on the "landing page". An + * object of type `Monster` can be created using the following code: + * + *
`int testArrayOfString = Monster.createTestarrayofstringVector(fbb, new int[] {
+   * fbb.createString("test1"),
+   * fbb.createString("test2")
+   * });
+   *
+   * Monster.startMonster(fbb);
+   * Monster.addPos(fbb, Vec3.createVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0,
+   * Color.Green, (short)5, (byte)6));
+   * Monster.addHp(fbb, (short)80);
+   * Monster.addName(fbb, str);
+   * Monster.addInventory(fbb, inv);
+   * Monster.addTestType(fbb, (byte)Any.Monster);
+   * Monster.addTest(fbb, mon2);
+   * Monster.addTest4(fbb, test4);
+   * Monster.addTestarrayofstring(fbb, testArrayOfString);
+   * int mon = Monster.endMonster(fbb);
+   `
* + * + * + * Here: + * + * * The call to `Monster#startMonster(FlatBufferBuilder)` will call this + * method with the right number of fields set. + * * `Monster#endMonster(FlatBufferBuilder)` will ensure [.endObject] is called. + * + * + * + * It's not recommended to call this method directly. If it's called manually, you must ensure + * to audit all calls to it whenever fields are added or removed from your schema. This is + * automatically done by the code generated by the `FlatBuffers` compiler. + * + * @param numFields The number of fields found in this object. + */ + public fun startTable(numFields: Int) { + notNested() + if (vtable.size < numFields) { + vtable = IntArray(numFields) + } + vtableInUse = numFields + for (i in 0 until vtableInUse) + vtable[i] = 0 + nested = true + objectStart = offset() + } + + /** + * Add a [Boolean] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Boolean, d: Boolean?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Boolean, d: Boolean) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + + /** + * Add a [UByte] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: UByte, d: UByte?): Unit = add(o, x.toByte(), d?.toByte()) + // unboxed specialization + public fun add(o: Int, x: UByte, d: UByte): Unit = add(o, x.toByte(), d.toByte()) + + /** + * Add a [Byte] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Byte, d: Byte?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Byte, d: Byte) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + /** + * Add a [UShort] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: UShort, d: UShort?): Unit = add(o, x.toShort(), d?.toShort()) + // unboxed specialization + public fun add(o: Int, x: UShort, d: UShort): Unit = add(o, x.toShort(), d.toShort()) + + + /** + * Add a [Short] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Short, d: Short?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Short, d: Short) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + + /** + * Add a [UInt] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: UInt, d: UInt?): Unit = add(o, x.toInt(), d?.toInt()) + // unboxed specialization + public fun add(o: Int, x: UInt, d: UInt): Unit = add(o, x.toInt(), d.toInt()) + + /** + * Add a [Int] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Int, d: Int?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Int, d: Int) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + /** + * Add a [ULong] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: ULong, d: ULong?): Unit = add(o, x.toLong(), d?.toLong()) + // unboxed specialization + public fun add(o: Int, x: ULong, d: ULong): Unit = add(o, x.toLong(), d.toLong()) + /** + * Add a [Long] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Long, d: Long?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Long, d: Long) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + + /** + * Add a [Float] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Float, d: Float?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Float, d: Float) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + + /** + * Add a [Double] to a table at `o` into its vtable, with value `x` and default `d`. + * If `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + */ + public fun add(o: Int, x: Double, d: Double?) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + // unboxed specialization + public fun add(o: Int, x: Double, d: Double) { + if (forceDefaults || x != d) { + add(x) + slot(o) + } + } + + /** + * Add an `offset` to a table at `o` into its vtable, with value `x` and default `d`. + * + * @param o The index into the vtable. + * @param x An `offset` to put into the buffer, depending on how defaults are handled. If + * `force_defaults` is `false`, compare `x` against the default value `d`. If `x` contains the + * default value, it can be skipped. + * @param d An `offset` default value to compare against when `force_defaults` is `false`. + */ + public fun add(o: Int, x: Offset<*>, d: Int) { + if (forceDefaults || x.value != d) { + add(x) + slot(o) + } + } + public fun add(o: Int, x: VectorOffset<*>, d: Int) { + if (forceDefaults || x.value != d) { + add(x) + slot(o) + } + } + + /** + * Add a struct to the table. Structs are stored inline, so nothing additional is being added. + * + * @param vOffset The index into the vtable. + * @param x The offset of the created struct. + * @param d The default value is always `0`. + */ + public fun addStruct(vOffset: Int, x: Offset<*>, d: Offset<*>?): Unit = addStruct(vOffset, x.value, d?.value) + // unboxed specialization + public fun addStruct(vOffset: Int, x: Offset<*>, d: Offset<*>): Unit = addStruct(vOffset, x.value, d.value) + public fun addStruct(vOffset: Int, x: Int, d: Int?) { + if (x != d) { + nested(x) + slot(vOffset) + } + } + // unboxed specialization + public fun addStruct(vOffset: Int, x: Int, d: Int) { + if (x != d) { + nested(x) + slot(vOffset) + } + } + + /** + * Set the current vtable at `voffset` to the current location in the buffer. + * + * @param vOffset The index into the vtable to store the offset relative to the end of the + * buffer. + */ + public fun slot(vOffset: Int) { + vtable[vOffset] = offset() + } + + /** + * Finish off writing the object that is under construction. + * + * @return The offset to the object inside [.dataBuffer]. + * @see .startTable + */ + public fun endTable(): Offset { + if (!nested) throw AssertionError("FlatBuffers: endTable called without startTable") + + val vtable = this.vtable + + add(0) + val vtableloc = offset() + // Write out the current vtable. + var i: Int = vtableInUse - 1 + // Trim trailing zeroes. + while (i >= 0 && vtable[i] == 0) { + i-- + } + val trimmedSize = i + 1 + while (i >= 0) { + // Offset relative to the start of the table. + add((if (vtable[i] != 0) vtableloc - vtable[i] else 0).toShort()) + i-- + } + + add((vtableloc - objectStart).toShort()) + add(((trimmedSize + 2) * Short.SIZE_BYTES).toShort()) + + // Search for an existing vtable that matches the current one. + var existingVtable = 0 + i = 0 + outer_loop@ while (i < numVtables) { + val vt1: Int = buffer.capacity - vtables[i] + val vt2 = space + val len: Short = buffer.getShort(vt1) + if (len == buffer.getShort(vt2)) { + var j: Int = Short.SIZE_BYTES + while (j < len) { + if (buffer.getShort(vt1 + j) != buffer.getShort(vt2 + j)) { + i++ + continue@outer_loop + } + j += Short.SIZE_BYTES + } + existingVtable = vtables[i] + break@outer_loop + } + i++ + } + if (existingVtable != 0) { + // Found a match: + // Remove the current vtable. + space = buffer.capacity - vtableloc + // Point table to existing vtable. + buffer.set(space, existingVtable - vtableloc) + } else { + // No match: + // Add the location of the current vtable to the list of vtables. + if (numVtables == vtables.size) vtables = vtables.copyOf(numVtables * 2) + vtables[numVtables++] = offset() + // Point table to current vtable. + buffer.set(buffer.capacity - vtableloc, offset() - vtableloc) + } + nested = false + return Offset(vtableloc) + } + + /** + * Checks that a required field has been set in a given table that has + * just been constructed. + * + * @param table The offset to the start of the table from the `ByteBuffer` capacity. + * @param field The offset to the field in the vtable. + */ + public fun required(table: Offset<*>, field: Int, fileName: String? = null) { + val tableStart: Int = buffer.capacity - table + val vtableStart: Int = tableStart - buffer.getInt(tableStart) + val ok = buffer.getShort(vtableStart + field).toInt() != 0 + // If this fails, the caller will show what field needs to be set. + if (!ok) throw AssertionError("FlatBuffers: field ${fileName ?: field} must be set") + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param rootTable An offset to be added to the buffer. + * @param sizePrefix Whether to prefix the size to the buffer. + */ + protected fun finish(rootTable: Offset<*>, sizePrefix: Boolean) { + prep(minalign, Int.SIZE_BYTES + if (sizePrefix) Int.SIZE_BYTES else 0) + add(rootTable) + if (sizePrefix) { + add(buffer.capacity - space) + } + buffer.writePosition = space + finished = true + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param rootTable An offset to be added to the buffer. + */ + public fun finish(rootTable: Offset<*>) { + finish(rootTable, false) + } + + /** + * Finalize a buffer, pointing to the given `root_table`, with the size prefixed. + * + * @param rootTable An offset to be added to the buffer. + */ + public fun finishSizePrefixed(rootTable: Offset<*>) { + finish(rootTable, true) + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param rootTable An offset to be added to the buffer. + * @param fileIdentifier A FlatBuffer file identifier to be added to the buffer before + * `root_table`. + * @param sizePrefix Whether to prefix the size to the buffer. + */ + protected fun finish(rootTable: Offset<*>, fileIdentifier: String, sizePrefix: Boolean) { + val identifierSize = 4 + prep(minalign, Int.SIZE_BYTES + identifierSize + if (sizePrefix) Int.SIZE_BYTES else 0) + if (fileIdentifier.length != identifierSize) throw AssertionError( + "FlatBuffers: file identifier must be length " + + identifierSize + ) + for (i in identifierSize - 1 downTo 0) { + add(fileIdentifier[i].code.toByte()) + } + finish(rootTable, sizePrefix) + } + + /** + * Finalize a buffer, pointing to the given `root_table`. + * + * @param rootTable An offset to be added to the buffer. + * @param fileIdentifier A FlatBuffer file identifier to be added to the buffer before + * `root_table`. + */ + public fun finish(rootTable: Offset<*>, fileIdentifier: String) { + finish(rootTable, fileIdentifier, false) + } + + /** + * Finalize a buffer, pointing to the given `root_table`, with the size prefixed. + * + * @param rootTable An offset to be added to the buffer. + * @param fileIdentifier A FlatBuffer file identifier to be added to the buffer before + * `root_table`. + */ + public fun finishSizePrefixed(rootTable: Offset<*>, fileIdentifier: String) { + finish(rootTable, fileIdentifier, true) + } + + /** + * In order to save space, fields that are set to their default value + * don't get serialized into the buffer. Forcing defaults provides a + * way to manually disable this optimization. + * + * @param forceDefaults When set to `true`, always serializes default values. + * @return Returns `this`. + */ + public fun forceDefaults(forceDefaults: Boolean): FlatBufferBuilder { + this.forceDefaults = forceDefaults + return this + } + + /** + * Get the ByteBuffer representing the FlatBuffer. Only call this after you've + * called `finish()`. The actual data starts at the ByteBuffer's current position, + * not necessarily at `0`. + * + * @return The [ReadBuffer] representing the FlatBuffer + */ + public fun dataBuffer(): ReadWriteBuffer { + finished() + return buffer + } + + /** + * A utility function to copy and return the ByteBuffer data as a `byte[]`. + * + * @return A full copy of the [data buffer][.dataBuffer]. + */ + public fun sizedByteArray(start: Int = space, length: Int = buffer.capacity - space): ByteArray { + finished() + val array = ByteArray(length) + buffer.getBytes(array, start) + return array + } + + /** + * Helper function to test if a field is present in the table + * + * @param offset virtual table offset + * @return true if the filed is present + */ + public fun Table.isFieldPresent(offset: Int): Boolean = this.offset(offset) != 0 +} + +public fun Double.sign(): Double = when { + this.isNaN() -> Double.NaN + this > 0 -> 1.0 + this < 0 -> -1.0 + else -> this +} + +public fun Float.sign(): Float = when { + this.isNaN() -> Float.NaN + this > 0 -> 1.0f + this < 0 -> -1.0f + else -> this +} + +public fun Int.sign(): Int = when { + this > 0 -> 1 + this < 0 -> -1 + else -> this +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Flatbuffers.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Flatbuffers.kt new file mode 100644 index 00000000000..cdfe09a6796 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Flatbuffers.kt @@ -0,0 +1,367 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import kotlin.jvm.JvmInline +import kotlin.math.min + +// For now a typealias to guarantee type safety. +public typealias UnionOffset = Offset +public typealias UnionOffsetArray = OffsetArray +public typealias StringOffsetArray = OffsetArray + +public inline fun UnionOffsetArray(size: Int, crossinline call: (Int) -> Offset): UnionOffsetArray = + UnionOffsetArray(IntArray(size) { call(it).value }) +public inline fun StringOffsetArray(size: Int, crossinline call: (Int) -> Offset): StringOffsetArray = + StringOffsetArray(IntArray(size) { call(it).value }) +/** + * Represents a "pointer" to a pointer types (table, string, struct) within the buffer + */ +@JvmInline +public value class Offset(public val value: Int) { + public fun toUnion(): UnionOffset = UnionOffset(value) +} + +/** + * Represents an array of offsets. Used to avoid boxing + * offset types. + */ +@JvmInline +public value class OffsetArray(public val value: IntArray) { + public inline val size: Int + get() = value.size + public inline operator fun get(index: Int): Offset = Offset(value[index]) +} + +public inline fun OffsetArray(size: Int, crossinline call: (Int) -> Offset): OffsetArray { + return OffsetArray(IntArray(size) { call(it).value }) +} + + +/** + * Represents a "pointer" to a vector type with elements T + */ +@JvmInline +public value class VectorOffset(public val value: Int) + +public fun Int.toOffset(): Offset = Offset(this) + +public operator fun Offset.minus(other: Int): Offset = Offset(this.value - other) + +public operator fun Int.minus(other: Offset): Int { + return this - other.value +} +/** + * All tables in the generated code derive from this class, and add their own accessors. + */ +public open class Table { + + /** Used to hold the position of the `bb` buffer. */ + public var bufferPos: Int = 0 + + /** The underlying ReadWriteBuffer to hold the data of the Table. */ + public var bb: ReadWriteBuffer = emptyBuffer + + /** Used to hold the vtable position. */ + public var vtableStart: Int = 0 + + /** Used to hold the vtable size. */ + public var vtableSize: Int = 0 + + protected inline fun Int.invalid(default: T, crossinline valid: (Int) -> T) : T = + if (this != 0) valid(this) else default + + protected inline fun lookupField(i: Int, default: T, crossinline found: (Int) -> T) : T = + offset(i).invalid(default) { found(it) } + + /** + * Look up a field in the vtable. + * + * @param vtableOffset An `int` offset to the vtable in the Table's ReadWriteBuffer. + * @return Returns an offset into the object, or `0` if the field is not present. + */ + public fun offset(vtableOffset: Int): Int = + if (vtableOffset < vtableSize) bb.getShort(vtableStart + vtableOffset).toInt() else 0 + + /** + * Retrieve a relative offset. + * + * @param offset An `int` index into the Table's ReadWriteBuffer containing the relative offset. + * @return Returns the relative offset stored at `offset`. + */ + public fun indirect(offset: Int): Int = offset + bb.getInt(offset) + + /** + * Create a Java `String` from UTF-8 data stored inside the FlatBuffer. + * + * This allocates a new string and converts to wide chars upon each access, + * which is not very efficient. Instead, each FlatBuffer string also comes with an + * accessor based on __vector_as_ReadWriteBuffer below, which is much more efficient, + * assuming your Java program can handle UTF-8 data directly. + * + * @param offset An `int` index into the Table's ReadWriteBuffer. + * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`. + */ + public fun string(offset: Int): String = string(offset, bb) + + /** + * Get the length of a vector. + * + * @param offset An `int` index into the Table's ReadWriteBuffer. + * @return Returns the length of the vector whose offset is stored at `offset`. + */ + public fun vectorLength(offset: Int): Int { + var newOffset = offset + newOffset += bufferPos + newOffset += bb.getInt(newOffset) + return bb.getInt(newOffset) + } + + /** + * Get the start data of a vector. + * + * @param offset An `int` index into the Table's ReadWriteBuffer. + * @return Returns the start of the vector data whose offset is stored at `offset`. + */ + public fun vector(offset: Int): Int { + var newOffset = offset + newOffset += bufferPos + return newOffset + bb.getInt(newOffset) + Int.SIZE_BYTES // data starts after the length + } + /** + * Initialize vector as a ReadWriteBuffer. + * + * This is more efficient than using duplicate, since it doesn't copy the data + * nor allocates a new [ReadBuffer], creating no garbage to be collected. + * + * @param buffer The [ReadBuffer] for the array + * @param vectorOffset The position of the vector in the byte buffer + * @param elemSize The size of each element in the array + * @return The [ReadBuffer] for the array + */ + public fun vectorAsBuffer(buffer: ReadWriteBuffer, vectorOffset: Int, elemSize: Int): ReadBuffer { + val o = offset(vectorOffset) + if (o == 0) return emptyBuffer + val vectorStart = vector(o) + return buffer.slice(vectorStart, vectorLength(o) * elemSize) + } + + /** + * Initialize any Table-derived type to point to the union at the given `offset`. + * + * @param t A `Table`-derived type that should point to the union at `offset`. + * @param offset An `int` index into the Table's ReadWriteBuffer. + * @return Returns the Table that points to the union at `offset`. + */ + public fun union(t: Table, offset: Int): Table = union(t, offset, bb) + + /** + * Sort tables by the key. + * + * @param offsets An 'int' indexes of the tables into the bb. + * @param bb A `ReadWriteBuffer` to get the tables. + */ + public fun sortTables(offsets: Array>, bb: ReadWriteBuffer) { + val off = offsets.sortedWith { o1, o2 -> keysCompare(o1, o2, bb) } + for (i in offsets.indices) offsets[i] = off[i] + } + + /** + * Compare two tables by the key. + * + * @param o1 An 'Integer' index of the first key into the bb. + * @param o2 An 'Integer' index of the second key into the bb. + * @param buffer A `ReadWriteBuffer` to get the keys. + */ + public open fun keysCompare(o1: Offset<*>, o2: Offset<*>, buffer: ReadWriteBuffer): Int = 0 + + /** + * Re-init the internal state with an external buffer `ReadWriteBuffer` and an offset within. + * + * This method exists primarily to allow recycling Table instances without risking memory leaks + * due to `ReadWriteBuffer` references. + */ + public inline fun reset(i: Int, reuseBuffer: ReadWriteBuffer): T { + bb = reuseBuffer + if (bb != emptyBuffer) { + bufferPos = i + vtableStart = bufferPos - bb.getInt(bufferPos) + vtableSize = bb.getShort(vtableStart).toInt() + } else { + bufferPos = 0 + vtableStart = 0 + vtableSize = 0 + } + return this as T + } + + /** + * Resets the internal state with a null `ReadWriteBuffer` and a zero position. + * + * This method exists primarily to allow recycling Table instances without risking memory leaks + * due to `ReadWriteBuffer` references. The instance will be unusable until it is assigned + * again to a `ReadWriteBuffer`. + */ + public inline fun reset(): T = reset(0, emptyBuffer) + + public companion object { + + public fun offset(vtableOffset: Int, offset: Offset<*>, bb: ReadWriteBuffer): Int { + val vtable: Int = bb.capacity - offset.value + return bb.getShort(vtable + vtableOffset - bb.getInt(vtable)) + vtable + } + + /** + * Retrieve a relative offset. + * + * @param offset An `int` index into a ReadWriteBuffer containing the relative offset. + * @param bb from which the relative offset will be retrieved. + * @return Returns the relative offset stored at `offset`. + */ + public fun indirect(offset: Int, bb: ReadWriteBuffer): Int { + return offset + bb.getInt(offset) + } + + /** + * Create a Java `String` from UTF-8 data stored inside the FlatBuffer. + * + * This allocates a new string and converts to wide chars upon each access, + * which is not very efficient. Instead, each FlatBuffer string also comes with an + * accessor based on __vector_as_ReadWriteBuffer below, which is much more efficient, + * assuming your Java program can handle UTF-8 data directly. + * + * @param offset An `int` index into the Table's ReadWriteBuffer. + * @param bb Table ReadWriteBuffer used to read a string at given offset. + * @return Returns a `String` from the data stored inside the FlatBuffer at `offset`. + */ + public fun string(offset: Int, bb: ReadWriteBuffer): String { + var newOffset = offset + newOffset += bb.getInt(newOffset) + val length: Int = bb.getInt(newOffset) + return bb.getString(newOffset + Int.SIZE_BYTES, length) + } + + /** + * Initialize any Table-derived type to point to the union at the given `offset`. + * + * @param t A `Table`-derived type that should point to the union at `offset`. + * @param offset An `int` index into the Table's ReadWriteBuffer. + * @param bb Table ReadWriteBuffer used to initialize the object Table-derived type. + * @return Returns the Table that points to the union at `offset`. + */ + public fun union(t: Table, offset: Int, bb: ReadWriteBuffer): Table = + t.reset(indirect(offset, bb), bb) + + /** + * Check if a [ReadWriteBuffer] contains a file identifier. + * + * @param bb A `ReadWriteBuffer` to check if it contains the identifier + * `ident`. + * @param ident A `String` identifier of the FlatBuffer file. + * @return True if the buffer contains the file identifier + */ + public fun hasIdentifier(bb: ReadWriteBuffer?, ident: String): Boolean { + val identifierLength = 4 + if (ident.length != identifierLength) + throw AssertionError("FlatBuffers: file identifier must be length $identifierLength") + for (i in 0 until identifierLength) { + if (ident[i].code.toByte() != bb!![bb.limit + Int.SIZE_BYTES + i]) return false + } + return true + } + + /** + * Compare two strings in the buffer. + * + * @param offsetA An 'int' index of the first string into the bb. + * @param offsetB An 'int' index of the second string into the bb. + * @param bb A `ReadWriteBuffer` to get the strings. + */ + public fun compareStrings(offsetA: Int, offsetB: Int, bb: ReadWriteBuffer): Int { + var offset1 = offsetA + var offset2 = offsetB + offset1 += bb.getInt(offset1) + offset2 += bb.getInt(offset2) + val len1: Int = bb.getInt(offset1) + val len2: Int = bb.getInt(offset2) + val startPos1: Int = offset1 + Int.SIZE_BYTES + val startPos2: Int = offset2 + Int.SIZE_BYTES + val len: Int = min(len1, len2) + for (i in 0 until len) { + if (bb[i + startPos1] != bb[i + startPos2]) { + return bb[i + startPos1] - bb[i + startPos2] + } + } + return len1 - len2 + } + + /** + * Compare string from the buffer with the 'String' object. + * + * @param offset An 'int' index of the first string into the bb. + * @param key Second string as a byte array. + * @param bb A `ReadWriteBuffer` to get the first string. + */ + public fun compareStrings(offset: Int, key: ByteArray, bb: ReadWriteBuffer): Int { + var offset1 = offset + offset1 += bb.getInt(offset1) + val len1: Int = bb.getInt(offset1) + val len2 = key.size + val startPos: Int = offset1 + Int.SIZE_BYTES + val len: Int = min(len1, len2) + for (i in 0 until len) { + if (bb[i + startPos] != key[i]) return bb[i + startPos] - key[i] + } + return len1 - len2 + } + } +} + +/** + * All structs in the generated code derive from this class, and add their own accessors. + */ +public open class Struct { + /** Used to hold the position of the `bb` buffer. */ + protected var bufferPos: Int = 0 + + /** The underlying ByteBuffer to hold the data of the Struct. */ + protected var bb: ReadWriteBuffer = emptyBuffer + + /** + * Re-init the internal state with an external buffer `ByteBuffer` and an offset within. + * + * This method exists primarily to allow recycling Table instances without risking memory leaks + * due to `ByteBuffer` references. + */ + protected inline fun reset(i: Int, reuseBuffer: ReadWriteBuffer): T { + bb = reuseBuffer + bufferPos = if (bb != emptyBuffer) i else 0 + return this as T + } + + /** + * Resets internal state with a null `ByteBuffer` and a zero position. + * + * This method exists primarily to allow recycling Struct instances without risking memory leaks + * due to `ByteBuffer` references. The instance will be unusable until it is assigned + * again to a `ByteBuffer`. + */ + private inline fun reset(): T = reset(0, emptyBuffer) +} + +public inline val T.value: T get() = this + +public const val VERSION_2_0_8: Int = 1 diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffers.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffers.kt new file mode 100644 index 00000000000..0f9cd7d45a4 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffers.kt @@ -0,0 +1,915 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") +@file:JvmName("FlexBuffers") +package com.google.flatbuffers.kotlin + +import kotlin.jvm.JvmName + +/** + * Reads a FlexBuffer message in ReadBuf and returns [Reference] to + * the root element. + * @param buffer ReadBuf containing FlexBuffer message + * @return [Reference] to the root object + */ +public fun getRoot(buffer: ReadBuffer): Reference { + var end: Int = buffer.limit + val byteWidth = buffer[--end].toInt() + val packetType = buffer[--end].toInt() + end -= byteWidth // The root data item. + return Reference(buffer, end, ByteWidth(byteWidth), packetType) +} + +/** + * Represents an generic element in the buffer. It can be specialized into scalar types, using for example, + * [Reference.toInt], or casted into Flexbuffer object types, like [Reference.toMap] or [Reference.toBlob]. + */ +@Suppress("NOTHING_TO_INLINE") +public class Reference internal constructor( + internal val buffer: ReadBuffer, + internal val end: Int, + internal val parentWidth: ByteWidth, + internal val byteWidth: ByteWidth, + public val type: FlexBufferType +) { + + internal constructor(bb: ReadBuffer, end: Int, parentWidth: ByteWidth, packedType: Int) : + this(bb, end, parentWidth, ByteWidth(1 shl (packedType and 3)), FlexBufferType((packedType shr 2))) + + /** + * Checks whether the element is null type + * @return true if null type + */ + public val isNull: Boolean get() = type == T_NULL + + /** + * Checks whether the element is boolean type + * @return true if boolean type + */ + public val isBoolean: Boolean get() = type == T_BOOL + + /** + * Checks whether the element type is numeric (signed/unsigned integers and floats) + * @return true if numeric type + */ + public val isNumeric: Boolean get() = isIntOrUInt || isFloat + + /** + * Checks whether the element type is signed or unsigned integers + * @return true if an integer type + */ + public val isIntOrUInt: Boolean get() = isInt || isUInt + + /** + * Checks whether the element type is float + * @return true if a float type + */ + public val isFloat: Boolean get() = type == T_FLOAT || type == T_INDIRECT_FLOAT + + /** + * Checks whether the element type is signed integer + * @return true if a signed integer type + */ + public val isInt: Boolean get() = type == T_INT || type == T_INDIRECT_INT + + /** + * Checks whether the element type is signed integer + * @return true if a signed integer type + */ + public val isUInt: Boolean get() = type == T_UINT || type == T_INDIRECT_UINT + + /** + * Checks whether the element type is string + * @return true if a string type + */ + public val isString: Boolean get() = type == T_STRING + + /** + * Checks whether the element type is key + * @return true if a key type + */ + public val isKey: Boolean get() = type == T_KEY + + /** + * Checks whether the element type is vector or a map. [TypedVector] are considered different types and will return + * false. + * @return true if a vector type + */ + public val isVector: Boolean get() = type == T_VECTOR || type == T_MAP + + /** + * Checks whether the element type is typed vector + * @return true if a typed vector type + */ + public val isTypedVector: Boolean get() = type.isTypedVector() + + /** + * Checks whether the element type is a map + * @return true if a map type + */ + public val isMap: Boolean get() = type == T_MAP + + /** + * Checks whether the element type is a blob + * @return true if a blob type + */ + public val isBlob: Boolean get() = type == T_BLOB + + /** + * Assumes [Reference] as a [Vector] and returns a [Reference] at index [index]. + */ + public operator fun get(index: Int): Reference = toVector()[index] + + /** + * Assumes [Reference] as a [Map] and returns a [Reference] for the value at key [key]. + */ + public operator fun get(key: String): Reference = toMap()[key] + + /** + * Returns element as a [Boolean]. + * If element type is not boolean, it will be casted to integer and compared against 0 + * @return element as [Boolean] + */ + public fun toBoolean(): Boolean = if (isBoolean) buffer.getBoolean(end) else toUInt() != 0u + + /** + * Returns element as [Byte]. + * For vector types, it will return size of the vector. + * For String type, it will be parsed as integer. + * Unsigned elements will become signed (with possible overflow). + * Float elements will be casted to [Byte]. + * @return [Byte] or 0 if fail to convert element to integer. + */ + public fun toByte(): Byte = toULong().toByte() + + /** + * Returns element as [Short]. + * For vector types, it will return size of the vector. + * For String type, it will type to be parsed as integer. + * Unsigned elements will become signed (with possible overflow). + * Float elements will be casted to [Short] + * @return [Short] or 0 if fail to convert element to integer. + */ + public fun toShort(): Short = toULong().toShort() + + /** + * Returns element as [Int]. + * For vector types, it will return size of the vector. + * For String type, it will type to be parsed as integer. + * Unsigned elements will become signed (with possible overflow). + * Float elements will be casted to [Int] + * @return [Int] or 0 if fail to convert element to integer. + */ + public fun toInt(): Int = toULong().toInt() + + /** + * Returns element as [Long]. + * For vector types, it will return size of the vector + * For String type, it will type to be parsed as integer + * Unsigned elements will become negative + * Float elements will be casted to integer + * @return [Long] integer or 0 if fail to convert element to long. + */ + public fun toLong(): Long = toULong().toLong() + + /** + * Returns element as [UByte]. + * For vector types, it will return size of the vector. + * For String type, it will type to be parsed as integer. + * Negative elements will become unsigned counterpart. + * Float elements will be casted to [UByte] + * @return [UByte] or 0 if fail to convert element to integer. + */ + public fun toUByte(): UByte = toULong().toUByte() + + /** + * Returns element as [UShort]. + * For vector types, it will return size of the vector. + * For String type, it will type to be parsed as integer. + * Negative elements will become unsigned counterpart. + * Float elements will be casted to [UShort] + * @return [UShort] or 0 if fail to convert element to integer. + */ + public fun toUShort(): UShort = toULong().toUShort() + + /** + * Returns element as [UInt]. + * For vector types, it will return size of the vector. + * For String type, it will type to be parsed as integer. + * Negative elements will become unsigned counterpart. + * Float elements will be casted to [UInt] + * @return [UInt] or 0 if fail to convert element to integer. + */ + public fun toUInt(): UInt = toULong().toUInt() + + /** + * Returns element as [ULong] integer. + * For vector types, it will return size of the vector + * For String type, it will type to be parsed as integer + * Negative elements will become unsigned counterpart. + * Float elements will be casted to integer + * @return [ULong] integer or 0 if fail to convert element to long. + */ + public fun toULong(): ULong = resolve { pos: Int, width: ByteWidth -> + when (type) { + T_INDIRECT_INT, T_INDIRECT_UINT, T_INT, T_BOOL, T_UINT -> buffer.readULong(pos, width) + T_FLOAT, T_INDIRECT_FLOAT -> buffer.readFloat(pos, width).toULong() + T_STRING -> toString().toULong() + T_VECTOR -> toVector().size.toULong() + else -> 0UL + } + } + + /** + * Returns element as [Float]. + * For vector types, it will return size of the vector + * For String type, it will type to be parsed as [Float] + * Float elements will be casted to integer + * @return [Float] integer or 0 if fail to convert element to long. + */ + public fun toFloat(): Float = resolve { pos: Int, width: ByteWidth -> + when (type) { + T_INDIRECT_FLOAT, T_FLOAT -> buffer.readFloat(pos, width).toFloat() + T_INT -> buffer.readInt(end, parentWidth).toFloat() + T_UINT, T_BOOL -> buffer.readUInt(end, parentWidth).toFloat() + T_INDIRECT_INT -> buffer.readInt(pos, width).toFloat() + T_INDIRECT_UINT -> buffer.readUInt(pos, width).toFloat() + T_NULL -> 0.0f + T_STRING -> toString().toFloat() + T_VECTOR -> toVector().size.toFloat() + else -> 0f + } + } + + /** + * Returns element as [Double]. + * For vector types, it will return size of the vector + * For String type, it will type to be parsed as [Double] + * @return [Float] integer or 0 if fail to convert element to long. + */ + public fun toDouble(): Double = resolve { pos: Int, width: ByteWidth -> + when (type) { + T_INDIRECT_FLOAT, T_FLOAT -> buffer.readFloat(pos, width) + T_INT -> buffer.readInt(pos, width).toDouble() + T_UINT, T_BOOL -> buffer.readUInt(pos, width).toDouble() + T_INDIRECT_INT -> buffer.readInt(pos, width).toDouble() + T_INDIRECT_UINT -> buffer.readUInt(pos, width).toDouble() + T_NULL -> 0.0 + T_STRING -> toString().toDouble() + T_VECTOR -> toVector().size.toDouble() + else -> 0.0 + } + } + + /** + * Returns element as [Key] or invalid key. + */ + public fun toKey(): Key = when (type) { + T_KEY -> Key(buffer, buffer.indirect(end, parentWidth)) + else -> nullKey() + } + /** + * Returns element as a [String] + * @return element as [String] or empty [String] if fail + */ + override fun toString(): String = when (type) { + T_STRING -> { + val start = buffer.indirect(end, parentWidth) + val size = buffer.readULong(start - byteWidth, byteWidth).toInt() + buffer.getString(start, size) + } + T_KEY -> buffer.getKeyString(buffer.indirect(end, parentWidth)) + T_MAP -> "{ ${toMap().entries.joinToString(", ") { "${it.key}: ${it.value}"}} }" + T_VECTOR, T_VECTOR_BOOL, T_VECTOR_FLOAT, T_VECTOR_INT, + T_VECTOR_UINT, T_VECTOR_KEY, T_VECTOR_STRING_DEPRECATED -> + "[ ${toVector().joinToString(", ") { it.toString() }} ]" + T_INT -> toLong().toString() + T_UINT -> toULong().toString() + T_FLOAT -> toDouble().toString() + else -> "${type.typeToString()}(end=$end)" + } + + /** + * Returns element as a [ByteArray], converting scalar types when possible. + * @return element as [ByteArray] or empty [ByteArray] if fail. + */ + public fun toByteArray(): ByteArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> ByteArray(vec.size) { vec.getInt(it).toByte() } + T_VECTOR_UINT -> ByteArray(vec.size) { vec.getUInt(it).toByte() } + T_VECTOR -> ByteArray(vec.size) { vec[it].toByte() } + T_VECTOR_FLOAT -> ByteArray(vec.size) { vec.getFloat(it).toInt().toByte() } + else -> ByteArray(0) + } + } + + /** + * Returns element as a [ByteArray], converting scalar types when possible. + * @return element as [ByteArray] or empty [ByteArray] if fail. + */ + public fun toShortArray(): ShortArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> ShortArray(vec.size) { vec.getInt(it).toShort() } + T_VECTOR_UINT -> ShortArray(vec.size) { vec.getUInt(it).toShort() } + T_VECTOR -> ShortArray(vec.size) { vec[it].toShort() } + T_VECTOR_FLOAT -> ShortArray(vec.size) { vec.getFloat(it).toInt().toShort() } + else -> ShortArray(0) + } + } + + /** + * Returns element as a [IntArray], converting scalar types when possible. + * @return element as [IntArray] or empty [IntArray] if fail. + */ + public fun toIntArray(): IntArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> IntArray(vec.size) { vec.getInt(it).toInt() } + T_VECTOR_UINT -> IntArray(vec.size) { vec.getUInt(it).toInt() } + T_VECTOR -> IntArray(vec.size) { vec[it].toInt() } + T_VECTOR_FLOAT -> IntArray(vec.size) { vec.getFloat(it).toInt() } + else -> IntArray(0) + } + } + + /** + * Returns element as a [LongArray], converting scalar types when possible. + * @return element as [LongArray] or empty [LongArray] if fail. + */ + public fun toLongArray(): LongArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> LongArray(vec.size) { vec.getInt(it) } + T_VECTOR_UINT -> LongArray(vec.size) { vec.getInt(it) } + T_VECTOR -> LongArray(vec.size) { vec[it].toLong() } + T_VECTOR_FLOAT -> LongArray(vec.size) { vec.getFloat(it).toLong() } + else -> LongArray(0) + } + } + + /** + * Returns element as a [UByteArray], converting scalar types when possible. + * @return element as [UByteArray] or empty [UByteArray] if fail. + */ + public fun toUByteArray(): UByteArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> UByteArray(vec.size) { vec.getInt(it).toUByte() } + T_VECTOR_UINT -> UByteArray(vec.size) { vec.getUInt(it).toUByte() } + T_VECTOR -> UByteArray(vec.size) { vec[it].toUByte() } + T_VECTOR_FLOAT -> UByteArray(vec.size) { vec.getFloat(it).toInt().toUByte() } + else -> UByteArray(0) + } + } + + /** + * Returns element as a [UIntArray], converting scalar types when possible. + * @return element as [UIntArray] or empty [UIntArray] if fail. + */ + public fun toUShortArray(): UShortArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> UShortArray(vec.size) { vec.getInt(it).toUShort() } + T_VECTOR_UINT -> UShortArray(vec.size) { vec.getUInt(it).toUShort() } + T_VECTOR -> UShortArray(vec.size) { vec[it].toUShort() } + T_VECTOR_FLOAT -> UShortArray(vec.size) { vec.getFloat(it).toUInt().toUShort() } + else -> UShortArray(0) + } + } + + /** + * Returns element as a [UIntArray], converting scalar types when possible. + * @return element as [UIntArray] or empty [UIntArray] if fail. + */ + public fun toUIntArray(): UIntArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> UIntArray(vec.size) { vec.getInt(it).toUInt() } + T_VECTOR_UINT -> UIntArray(vec.size) { vec.getUInt(it).toUInt() } + T_VECTOR -> UIntArray(vec.size) { vec[it].toUInt() } + T_VECTOR_FLOAT -> UIntArray(vec.size) { vec.getFloat(it).toUInt() } + else -> UIntArray(0) + } + } + + /** + * Returns element as a [ULongArray], converting scalar types when possible. + * @return element as [ULongArray] or empty [ULongArray] if fail. + */ + public fun toULongArray(): ULongArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_INT -> ULongArray(vec.size) { vec.getUInt(it) } + T_VECTOR_UINT -> ULongArray(vec.size) { vec.getUInt(it) } + T_VECTOR -> ULongArray(vec.size) { vec[it].toULong() } + T_VECTOR_FLOAT -> ULongArray(vec.size) { vec.getFloat(it).toULong() } + else -> ULongArray(0) + } + } + + /** + * Returns element as a [FloatArray], converting scalar types when possible. + * @return element as [FloatArray] or empty [FloatArray] if fail. + */ + public fun toFloatArray(): FloatArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_FLOAT -> FloatArray(vec.size) { vec.getFloat(it).toFloat() } + T_VECTOR_INT -> FloatArray(vec.size) { vec.getInt(it).toFloat() } + T_VECTOR_UINT -> FloatArray(vec.size) { vec.getUInt(it).toFloat() } + T_VECTOR -> FloatArray(vec.size) { vec[it].toFloat() } + else -> FloatArray(0) + } + } + + /** + * Returns element as a [DoubleArray], converting scalar types when possible. + * @return element as [DoubleArray] or empty [DoubleArray] if fail. + */ + public fun toDoubleArray(): DoubleArray { + val vec = TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + return when (type) { + T_VECTOR_FLOAT -> DoubleArray(vec.size) { vec[it].toDouble() } + T_VECTOR_INT -> DoubleArray(vec.size) { vec[it].toDouble() } + T_VECTOR_UINT -> DoubleArray(vec.size) { vec[it].toDouble() } + T_VECTOR -> DoubleArray(vec.size) { vec[it].toDouble() } + else -> DoubleArray(0) + } + } + + /** + * Returns element as a [Vector] + * @return element as [Vector] or empty [Vector] if fail + */ + public fun toVector(): Vector { + return when { + isVector -> Vector(buffer, buffer.indirect(end, parentWidth), byteWidth) + isTypedVector -> TypedVector(type.toElementTypedVector(), buffer, buffer.indirect(end, parentWidth), byteWidth) + else -> emptyVector() + } + } + + /** + * Returns element as a [Blob] + * @return element as [Blob] or empty [Blob] if fail + */ + public fun toBlob(): Blob { + return when (type) { + T_BLOB, T_STRING -> Blob(buffer, buffer.indirect(end, parentWidth), byteWidth) + else -> emptyBlob() + } + } + + /** + * Returns element as a [Map]. + * @return element as [Map] or empty [Map] if fail + */ + public fun toMap(): Map = when (type) { + T_MAP -> Map(buffer, buffer.indirect(end, parentWidth), byteWidth) + else -> emptyMap() + } + + private inline fun resolve(crossinline block: (pos: Int, width: ByteWidth) -> T): T { + return if (type.isIndirectScalar()) { + block(buffer.indirect(end, byteWidth), byteWidth) + } else { + block(end, parentWidth) + } + } + + override fun equals(other: Any?): Boolean { + if (this === other) return true + if (other == null || this::class != other::class) return false + other as Reference + if (buffer != other.buffer || + end != other.end || + parentWidth != other.parentWidth || + byteWidth != other.byteWidth || + type != other.type + ) return false + return true + } + + override fun hashCode(): Int { + var result = buffer.hashCode() + result = 31 * result + end + result = 31 * result + parentWidth.value + result = 31 * result + byteWidth.value + result = 31 * result + type.hashCode() + return result + } +} + +/** + * Represents any element that has a size property to it, like: [Map], [Vector] and [TypedVector]. + */ +public open class Sized internal constructor( + public val buffer: ReadBuffer, + public val end: Int, + public val byteWidth: ByteWidth +) { + public open val size: Int = buffer.readSize(end, byteWidth) +} + +/** + * Represent an array of bytes in the buffer. + */ +public open class Blob internal constructor( + buffer: ReadBuffer, + end: Int, + byteWidth: ByteWidth +) : Sized(buffer, end, byteWidth) { + /** + * Return [Blob] as [ReadBuffer] + * @return blob as [ReadBuffer] + */ + public fun data(): ReadBuffer = buffer.slice(end, size) + + /** + * Copy [Blob] into a [ByteArray] + * @return A [ByteArray] containing the blob data. + */ + public fun toByteArray(): ByteArray { + val result = ByteArray(size) + for (i in 0 until size) { + result[i] = buffer[end + i] + } + return result + } + + /** + * Return individual byte at a given position + * @param pos position of the byte to be read + */ + public operator fun get(pos: Int): Byte { + if (pos !in 0..size) error("$pos index out of bounds. Should be in range 0..$size") + return buffer[end + pos] + } + + override fun toString(): String = buffer.getString(end, size) +} + +/** + * [Vector] represents an array of elements in the buffer. The element can be of any type. + */ +public open class Vector internal constructor( + buffer: ReadBuffer, + end: Int, + byteWidth: ByteWidth +) : Collection, + Sized(buffer, end, byteWidth) { + + /** + * Returns a [Reference] from the [Vector] at position [index]. Returns a null reference + * @param index position in the vector. + * @return [Reference] for a key or a null [Reference] if not found. + */ + public open operator fun get(index: Int): Reference { + if (index >= size) return nullReference() + val packedType = buffer[(end + size * byteWidth.value + index)].toInt() + val objEnd = end + index * byteWidth + return Reference(buffer, objEnd, byteWidth, packedType) + } + + // overrides from Collection + + override fun contains(element: Reference): Boolean = find { it == element } != null + + override fun containsAll(elements: Collection): Boolean { + elements.forEach { if (!contains(it)) return false } + return true + } + + override fun isEmpty(): Boolean = size == 0 + + override fun iterator(): Iterator = object : Iterator { + var position = 0 + override fun hasNext(): Boolean = position != size + override fun next(): Reference = get(position++) + } +} + +/** + * [TypedVector] represents an array of scalar elements of the same type in the buffer. + */ +public open class TypedVector( + private val elementType: FlexBufferType, + buffer: ReadBuffer, + end: Int, + byteWidth: ByteWidth +) : Vector(buffer, end, byteWidth) { + + /** + * Returns a [Reference] from the [TypedVector] at position [index]. Returns a null reference + * @param index position in the vector. + * @return [Reference] for a key or a null [Reference] if not found. + */ + override operator fun get(index: Int): Reference { + if (index >= size) return nullReference() + val childPos: Int = end + index * byteWidth + return Reference(buffer, childPos, byteWidth, ByteWidth(1), elementType) + } + + private inline fun resolveAt(index: Int, crossinline block: (Int, ByteWidth) -> T): T { + val childPos: Int = end + index * byteWidth + return block(childPos, byteWidth) + } + + internal fun getBoolean(index: Int): Boolean = resolveAt(index) { + pos: Int, _: ByteWidth -> buffer.getBoolean(pos) + } + internal fun getInt(index: Int): Long = resolveAt(index) { + pos: Int, width: ByteWidth -> buffer.readLong(pos, width) + } + internal fun getUInt(index: Int): ULong = resolveAt(index) { + pos: Int, width: ByteWidth -> buffer.readULong(pos, width) + } + internal fun getFloat(index: Int): Double = resolveAt(index) { + pos: Int, width: ByteWidth -> buffer.readFloat(pos, width) + } +} + +/** + * Represents a key element in the buffer. Keys are + * used to reference objects in a [Map] + */ +public data class Key( + public val buffer: ReadBuffer, + public val start: Int, + public val end: Int = buffer.findFirst(ZeroByte, start) +) { + + val sizeInBytes: Int = end - start + + private val codePoint = CharArray(2) + + val sizeInChars: Int + get() { + var count = 0 + var i = start + while (i < end) { + val size = codePointSizeInBytes(i) + i += size + count += if (size == 4) 2 else 1 + } + return count + } + + public operator fun get(index: Int): Char { + var count = 0 + var i = start + var size = 0 + // we loop over the bytes to find the right position for the "char" at index i + while (i < end && count < index) { + size = codePointSizeInBytes(i) + i += size + // 4 bytes utf8 are 2 chars wide, the rest is on char. + count += if (size == 4) 2 else 1 + } + return when { + count == index -> { + Utf8.decodeUtf8CodePoint(buffer, i, codePoint) + codePoint[0] + } + count == index + 1 && size == 4 -> { + Utf8.decodeUtf8CodePoint(buffer, i - size, codePoint) + codePoint[1] + } + else -> error("Invalid count=$count, index=$index") + } + } + + private inline fun codePointSizeInBytes(pos: Int): Int { + val b = buffer[pos] + return when { + Utf8.isOneByte(b) -> 1 + Utf8.isTwoBytes(b) -> 2 + Utf8.isThreeBytes(b) -> 3 + else -> 4 + } + } + + override fun toString(): String = if (sizeInBytes > 0) buffer.getString(start, sizeInBytes) else "" + + /** + * Checks whether Key is invalid or not. + */ + public fun isInvalid(): Boolean = sizeInBytes <= 0 +} + +/** + * A Map class that provide support to access Key-Value data from Flexbuffers. + */ +public class Map + internal constructor(buffer: ReadBuffer, end: Int, byteWidth: ByteWidth): + Sized(buffer, end, byteWidth), + kotlin.collections.Map { + + // used for accessing the key vector elements + private var keyVectorEnd: Int + private var keyVectorByteWidth: ByteWidth + init { + val keysOffset = end - (3 * byteWidth) // 3 is number of prefixed fields + keyVectorEnd = buffer.indirect(keysOffset, byteWidth) + keyVectorByteWidth = ByteWidth(buffer.readInt(keysOffset + byteWidth, byteWidth)) + } + + /** + * Returns a [Reference] from the [Map] at position [index]. Returns a null reference + * @param index position in the map + * @return [Reference] for a key or a null [Reference] if not found. + */ + public operator fun get(index: Int): Reference { + if (index >= size) return nullReference() + val packedPos = end + size * byteWidth + index + val packedType = buffer[packedPos].toInt() + val objEnd = end + index * byteWidth + return Reference(buffer, objEnd, byteWidth, packedType) + } + + /** + * Returns a [Reference] from the [Map] for a given [String] [key]. + * @param key access key to element on map + * @return [Reference] for a key or a null [Reference] if not found. + */ + public operator fun get(key: String): Reference { + val index: Int = binarySearch(key) + return if (index in 0 until size) { + get(index) + } else nullReference() + } + + /** + * Returns a [Reference] from the [Map] for a given [Key] [key]. + * @param key access key to element on map + * @return [Reference] for a key or a null [Reference] if not found. + */ + override operator fun get(key: Key): Reference { + val index = binarySearch(key) + return if (index in 0 until size) { + get(index) + } else nullReference() + } + + /** + * Checks whether the map contains a [key]. + * @param key [String] + * @return true if key is found in the map, otherwise false. + */ + public operator fun contains(key: String): Boolean = binarySearch(key) >= 0 + + /** + * Returns a [Key] for a given position [index] in the [Map]. + * @param index of the key in the map + * @return a Key for the given index. Out of bounds indexes returns invalid keys. + */ + public fun keyAt(index: Int): Key { + val childPos: Int = keyVectorEnd + index * keyVectorByteWidth + return Key(buffer, buffer.indirect(childPos, keyVectorByteWidth)) + } + + /** + * Returns a [Key] as [String] for a given position [index] in the [Map]. + * @param index of the key in the map + * @return a Key for the given index. Out of bounds indexes returns empty string. + */ + public fun keyAsString(index: Int): String { + val childPos: Int = keyVectorEnd + index * keyVectorByteWidth + val start = buffer.indirect(childPos, keyVectorByteWidth) + val end = buffer.findFirst(ZeroByte, start) + return if (end > start) buffer.getString(start, end - start) else "" + } + + // Overrides from kotlin.collections.Map + + public data class Entry(override val key: Key, override val value: Reference) : + kotlin.collections.Map.Entry + + override val entries: Set> + get() = keys.map { Entry(it, get(it.toString())) }.toSet() + + override val keys: Set + get() { + val set = LinkedHashSet(size) + for (i in 0 until size) { + val key = keyAt(i) + set.add(key) + } + return set + } + + /** + * Returns a [Vector] for accessing all values in the [Map]. + * @return [Vector] of values. + */ + override val values: Collection + get() = Vector(buffer, end, byteWidth) + + override fun containsKey(key: Key): Boolean { + for (i in 0 until size) { + if (key == keyAt(i)) + return true + } + return false + } + + override fun containsValue(value: Reference): Boolean = values.contains(value) + + override fun isEmpty(): Boolean = size == 0 + + // Performs a binary search on a key vector and return index of the key in key vector + private fun binarySearch(searchedKey: String) = binarySearch { compareCharSequence(it, searchedKey) } + // Performs a binary search on a key vector and return index of the key in key vector + private fun binarySearch(key: Key): Int = binarySearch { compareKeys(it, key.start) } + + private inline fun binarySearch(crossinline comparisonBlock: (Int) -> Int): Int { + var low = 0 + var high = size - 1 + while (low <= high) { + val mid = low + high ushr 1 + val keyPos: Int = buffer.indirect(keyVectorEnd + mid * keyVectorByteWidth, keyVectorByteWidth) + val cmp: Int = comparisonBlock(keyPos) + if (cmp < 0) low = mid + 1 else if (cmp > 0) high = mid - 1 else return mid // key found + } + return -(low + 1) // key not found + } + + // compares a CharSequence against a T_KEY + private fun compareKeys(start: Int, other: Int): Int { + var bufferPos = start + var otherPos = other + val limit: Int = buffer.limit + var c1: Byte = ZeroByte + var c2: Byte = ZeroByte + while (otherPos < limit) { + c1 = buffer[bufferPos++] + c2 = buffer[otherPos++] + when { + c1 == ZeroByte -> return c1 - c2 + c1 != c2 -> return c1 - c2 + } + } + return c1 - c2 + } + + // compares a CharSequence against a [CharSequence] + private fun compareCharSequence(start: Int, other: CharSequence): Int { + var bufferPos = start + var otherPos = 0 + val limit: Int = buffer.limit + val otherLimit = other.length + // special loop for ASCII characters. Most of keys should be ASCII only, so this + // loop should be optimized for that. + // breaks if a multi-byte character is found + while (otherPos < otherLimit) { + val c2 = other[otherPos] + // not a single byte codepoint + if (c2.code >= 0x80) { + break + } + val b: Byte = buffer[bufferPos] + when { + b == ZeroByte -> return -c2.code + b < 0 -> break + b != c2.code.toByte() -> return b - c2.code.toByte() + } + ++bufferPos + ++otherPos + } + if (bufferPos < limit) + return 0 + + val comparisonBuffer = ByteArray(4) + while (bufferPos < limit) { + val sizeInBuff = Utf8.encodeUtf8CodePoint(other, otherPos, comparisonBuffer) + if (sizeInBuff == 0) { + return buffer[bufferPos].toInt() + } + for (i in 0 until sizeInBuff) { + val bufferByte: Byte = buffer[bufferPos++] + val otherByte: Byte = comparisonBuffer[i] + when { + bufferByte == ZeroByte -> return -otherByte + bufferByte != otherByte -> return bufferByte - otherByte + } + } + otherPos += if (sizeInBuff == 4) 2 else 1 + } + return 0 + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt new file mode 100644 index 00000000000..52e16af9b23 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersBuilder.kt @@ -0,0 +1,786 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +@ExperimentalUnsignedTypes +public class FlexBuffersBuilder( + public val buffer: ReadWriteBuffer, + private val shareFlag: Int = SHARE_KEYS +) { + + public constructor(initialCapacity: Int = 1024, shareFlag: Int = SHARE_KEYS) : + this(ArrayReadWriteBuffer(initialCapacity), shareFlag) + + private val stringValuePool: HashMap = HashMap() + private val stringKeyPool: HashMap = HashMap() + private val stack: MutableList = mutableListOf() + private var finished: Boolean = false + + /** + * Reset the FlexBuffersBuilder by purging all data that it holds. Buffer might + * keep its capacity after a reset. + */ + public fun clear() { + buffer.clear() + stringValuePool.clear() + stringKeyPool.clear() + stack.clear() + finished = false + } + + /** + * Finish writing the message into the buffer. After that no other element must + * be inserted into the buffer. Also, you must call this function before start using the + * FlexBuffer message + * @return [ReadBuffer] containing the FlexBuffer message + */ + public fun finish(): ReadBuffer { + // If you hit this, you likely have objects that were never included + // in a parent. You need to have exactly one root to finish a buffer. + // Check your Start/End calls are matched, and all objects are inside + // some other object. + if (stack.size != 1) error("There is must be only on object as root. Current ${stack.size}.") + // Write root value. + val byteWidth = align(stack[0].elemWidth(buffer.writePosition, 0)) + buffer.requestAdditionalCapacity(byteWidth.value + 2) + writeAny(stack[0], byteWidth) + // Write root type. + buffer.put(stack[0].storedPackedType()) + // Write root size. Normally determined by parent, but root has no parent :) + buffer.put(byteWidth.value.toByte()) + this.finished = true + return buffer // TODO: make a read-only shallow copy + } + + /** + * Insert a single [Boolean] into the buffer + * @param value true or false + */ + public fun put(value: Boolean): Unit = run { this[null] = value } + + /** + * Insert a null reference into the buffer. A key must be present if element is inserted into a map. + */ + public fun putNull(key: String? = null): Unit = + run { stack.add(Value(T_NULL, putKey(key), W_8, 0UL)) } + + /** + * Insert a single [Boolean] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: Boolean): Unit = + run { stack.add(Value(T_BOOL, putKey(key), W_8, if (value) 1UL else 0UL)) } + + /** + * Insert a single [Byte] into the buffer + */ + public fun put(value: Byte): Unit = set(null, value.toLong()) + + /** + * Insert a single [Byte] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: Byte): Unit = set(key, value.toLong()) + + /** + * Insert a single [Short] into the buffer. + */ + public fun put(value: Short): Unit = set(null, value.toLong()) + + /** + * Insert a single [Short] into the buffer. A key must be present if element is inserted into a map. + */ + public inline operator fun set(key: String? = null, value: Short): Unit = set(key, value.toLong()) + + /** + * Insert a single [Int] into the buffer. + */ + public fun put(value: Int): Unit = set(null, value.toLong()) + + /** + * Insert a single [Int] into the buffer. A key must be present if element is inserted into a map. + */ + public inline operator fun set(key: String? = null, value: Int): Unit = set(key, value.toLong()) + + /** + * Insert a single [Long] into the buffer. + */ + public fun put(value: Long): Unit = set(null, value) + + /** + * Insert a single [Long] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: Long): Unit = + run { stack.add(Value(T_INT, putKey(key), value.toULong().widthInUBits(), value.toULong())) } + + /** + * Insert a single [UByte] into the buffer + */ + public fun put(value: UByte): Unit = set(null, value.toULong()) + + /** + * Insert a single [UByte] into the buffer. A key must be present if element is inserted into a map. + */ + public inline operator fun set(key: String? = null, value: UByte): Unit = set(key, value.toULong()) + + /** + * Insert a single [UShort] into the buffer. + */ + public fun put(value: UShort): Unit = set(null, value.toULong()) + + /** + * Insert a single [UShort] into the buffer. A key must be present if element is inserted into a map. + */ + private inline operator fun set(key: String? = null, value: UShort): Unit = set(key, value.toULong()) + + /** + * Insert a single [UInt] into the buffer. + */ + public fun put(value: UInt): Unit = set(null, value.toULong()) + + /** + * Insert a single [UInt] into the buffer. A key must be present if element is inserted into a map. + */ + private inline operator fun set(key: String? = null, value: UInt): Unit = set(key, value.toULong()) + + /** + * Insert a single [ULong] into the buffer. + */ + public fun put(value: ULong): Unit = set(null, value) + + /** + * Insert a single [ULong] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: ULong): Unit = + run { stack.add(Value(T_UINT, putKey(key), value.widthInUBits(), value)) } + + /** + * Insert a single [Float] into the buffer. + */ + public fun put(value: Float): Unit = run { this[null] = value } + + /** + * Insert a single [Float] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: Float): Unit = + run { stack.add(Value(T_FLOAT, putKey(key), W_32, dValue = value.toDouble())) } + + /** + * Insert a single [Double] into the buffer. + */ + public fun put(value: Double): Unit = run { this[null] = value } + + /** + * Insert a single [Double] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: Double): Unit = + run { stack.add(Value(T_FLOAT, putKey(key), W_64, dValue = value)) } + + /** + * Insert a single [String] into the buffer. + */ + public fun put(value: String): Int = set(null, value) + + /** + * Insert a single [String] into the buffer. A key must be present if element is inserted into a map. + */ + public operator fun set(key: String? = null, value: String): Int { + val iKey = putKey(key) + val holder = if (shareFlag and SHARE_STRINGS != 0) { + stringValuePool.getOrPut(value) { + writeString(iKey, value).also { stringValuePool[value] = it } + }.copy(key = iKey) + } else { + writeString(iKey, value) + } + stack.add(holder) + return holder.iValue.toInt() + } + + /** + * Adds a [ByteArray] into the message as a [Blob]. + * @param value byte array + * @return position in buffer as the start of byte array + */ + public fun put(value: ByteArray): Int = set(null, value) + + /** + * Adds a [ByteArray] into the message as a [Blob]. A key must be present if element is inserted into a map. + * @param value byte array + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: ByteArray): Int { + val element = writeBlob(putKey(key), value, T_BLOB, false) + stack.add(element) + return element.iValue.toInt() + } + + /** + * Adds a [IntArray] into the message as a typed vector of fixed size. + * @param value [IntArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: IntArray): Int = set(null, value) + + /** + * Adds a [IntArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [IntArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: IntArray): Int = + setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } + + /** + * Adds a [ShortArray] into the message as a typed vector of fixed size. + * @param value [ShortArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: ShortArray): Int = set(null, value) + + /** + * Adds a [ShortArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [ShortArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: ShortArray): Int = + setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } + + /** + * Adds a [LongArray] into the message as a typed vector of fixed size. + * @param value [LongArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: LongArray): Int = set(null, value) + + /** + * Adds a [LongArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [LongArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: LongArray): Int = + setTypedVector(key, value.size, T_VECTOR_INT, value.widthInUBits()) { writeIntArray(value, it) } + + /** + * Adds a [FloatArray] into the message as a typed vector of fixed size. + * @param value [FloatArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: FloatArray): Int = set(null, value) + + /** + * Adds a [FloatArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [FloatArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: FloatArray): Int = + setTypedVector(key, value.size, T_VECTOR_FLOAT, W_32) { writeFloatArray(value) } + + /** + * Adds a [DoubleArray] into the message as a typed vector of fixed size. + * @param value [DoubleArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: DoubleArray): Int = set(null, value) + + /** + * Adds a [DoubleArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [DoubleArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: DoubleArray): Int = + setTypedVector(key, value.size, T_VECTOR_FLOAT, W_64) { writeFloatArray(value) } + + /** + * Adds a [UByteArray] into the message as a typed vector of fixed size. + * @param value [UByteArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: UByteArray): Int = set(null, value) + + /** + * Adds a [UByteArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [UByteArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: UByteArray): Int = + setTypedVec(key) { value.forEach { put(it) } } + + /** + * Adds a [UShortArray] into the message as a typed vector of fixed size. + * @param value [UShortArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: UShortArray): Int = set(null, value) + + /** + * Adds a [UShortArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [UShortArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: UShortArray): Int = + setTypedVec(key) { value.forEach { put(it) } } + + /** + * Adds a [UIntArray] into the message as a typed vector of fixed size. + * @param value [UIntArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: UIntArray): Int = set(null, value) + + /** + * Adds a [UIntArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [UIntArray] + * @return position in buffer as the start of byte array + */ + public fun set(key: String? = null, value: UIntArray): Int = + setTypedVec(key) { value.forEach { put(it) } } + + /** + * Adds a [ULongArray] into the message as a typed vector of fixed size. + * @param value [ULongArray] + * @return position in buffer as the start of byte array + */ + public fun put(value: ULongArray): Int = set(null, value) + + /** + * Adds a [ULongArray] into the message as a typed vector of fixed size. + * A key must be present if element is inserted into a map. + * @param value [ULongArray] + * @return position in buffer as the start of byte array + */ + public operator fun set(key: String? = null, value: ULongArray): Int = + setTypedVec(key) { value.forEach { put(it) } } + + /** + * Creates a new vector will all elements inserted in [block]. + * @param block where elements will be inserted + * @return position in buffer as the start of byte array + */ + public inline fun putVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int { + val pos = startVector() + this.block() + return endVector(pos) + } + + /** + * Creates a new typed vector will all elements inserted in [block]. + * @param block where elements will be inserted + * @return position in buffer as the start of byte array + */ + public inline fun putTypedVector(crossinline block: FlexBuffersBuilder.() -> Unit): Int { + val pos = startVector() + this.block() + return endTypedVector(pos) + } + + /** + * Helper function to return position for starting a new vector. + */ + public fun startVector(): Int = stack.size + + /** + * Finishes a vector element. The initial position of the vector must be passed + * @param position position at the start of the vector + */ + public fun endVector(position: Int): Int = endVector(null, position) + + /** + * Finishes a vector element. The initial position of the vector must be passed + * @param position position at the start of the vector + */ + public fun endVector(key: String? = null, position: Int): Int = + endAnyVector(position) { createVector(putKey(key), position, stack.size - position) } + /** + * Finishes a typed vector element. The initial position of the vector must be passed + * @param position position at the start of the vector + */ + public fun endTypedVector(position: Int): Int = endTypedVector(position, null) + + /** + * Helper function to return position for starting a new vector. + */ + public fun startMap(): Int = stack.size + + /** + * Creates a new map will all elements inserted in [block]. + * @param block where elements will be inserted + * @return position in buffer as the start of byte array + */ + public inline fun putMap(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int { + val pos = startMap() + this.block() + return endMap(pos, key) + } + + /** + * Finishes a map, but writing the information in the buffer + * @param key key used to store element in map + * @return Reference to the map + */ + public fun endMap(start: Int, key: String? = null): Int { + stack.subList(start, stack.size).sortWith(keyComparator) + val length = stack.size - start + val keys = createKeyVector(start, length) + val vec = putMap(putKey(key), start, length, keys) + // Remove temp elements and return map. + while (stack.size > start) { + stack.removeAt(stack.size - 1) + } + stack.add(vec) + return vec.iValue.toInt() + } + + private inline fun setTypedVector( + key: String? = null, + length: Int, + vecType: FlexBufferType, + bitWidth: BitWidth, + crossinline writeBlock: (ByteWidth) -> Unit + ): Int { + val keyPos = putKey(key) + val byteWidth = align(bitWidth) + // Write vector. First the keys width/offset if available, and size. + // write the size + writeInt(length, byteWidth) + + // Then the actual data. + val vloc: Int = buffer.writePosition + writeBlock(byteWidth) + stack.add(Value(vecType, keyPos, bitWidth, vloc.toULong())) + return vloc + } + + private inline fun setTypedVec(key: String? = null, crossinline block: FlexBuffersBuilder.() -> Unit): Int { + val pos = startVector() + this.block() + return endTypedVector(pos, key) + } + + public fun endTypedVector(position: Int, key: String? = null): Int = + endAnyVector(position) { createTypedVector(putKey(key), position, stack.size - position) } + + private inline fun endAnyVector(start: Int, crossinline creationBlock: () -> Value): Int { + val vec = creationBlock() + // Remove temp elements and return vector. + while (stack.size > start) { + stack.removeLast() + } + stack.add(vec) + return vec.iValue.toInt() + } + + private inline fun putKey(key: String? = null): Int { + if (key == null) return -1 + return if ((shareFlag and SHARE_KEYS) != 0) { + stringKeyPool.getOrPut(key) { + val pos: Int = buffer.writePosition + val encodedKeySize = Utf8.encodedLength(key) + buffer.requestAdditionalCapacity(encodedKeySize + 1) + buffer.put(key, encodedKeySize) + buffer.put(ZeroByte) + pos + } + } else { + val pos: Int = buffer.writePosition + val encodedKeySize = Utf8.encodedLength(key) + buffer.requestAdditionalCapacity(encodedKeySize + 1) + buffer.put(key, encodedKeySize) + buffer.put(ZeroByte) + pos + } + } + + private fun writeAny(toWrite: Value, byteWidth: ByteWidth) = when (toWrite.type) { + T_NULL, T_BOOL, T_INT, T_UINT -> writeInt(toWrite.iValue, byteWidth) + T_FLOAT -> writeDouble(toWrite.dValue, byteWidth) + else -> writeOffset(toWrite.iValue.toInt(), byteWidth) + } + + private fun writeString(key: Int, s: String): Value { + val encodedSize = Utf8.encodedLength(s) + val bitWidth = encodedSize.toULong().widthInUBits() + val byteWidth = align(bitWidth) + + writeInt(encodedSize, byteWidth) + + buffer.requestAdditionalCapacity(encodedSize + 1) + val sloc: Int = buffer.writePosition + if (encodedSize > 0) + buffer.put(s, encodedSize) + buffer.put(ZeroByte) + return Value(T_STRING, key, bitWidth, sloc.toULong()) + } + + private fun writeDouble(toWrite: Double, byteWidth: ByteWidth) { + buffer.requestAdditionalCapacity(byteWidth.value) + when (byteWidth.value) { + 4 -> buffer.put(toWrite.toFloat()) + 8 -> buffer.put(toWrite) + else -> Unit + } + } + + private fun writeOffset(toWrite: Int, byteWidth: ByteWidth) { + buffer.requestAdditionalCapacity(byteWidth.value) + val relativeOffset = (buffer.writePosition - toWrite) + if (byteWidth.value != 8 && relativeOffset >= 1L shl byteWidth.value * 8) error("invalid offset $relativeOffset, writer pos ${buffer.writePosition}") + writeInt(relativeOffset, byteWidth) + } + + private inline fun writeBlob(key: Int, blob: ByteArray, type: FlexBufferType, trailing: Boolean): Value { + val bitWidth = blob.size.toULong().widthInUBits() + val byteWidth = align(bitWidth) + + writeInt(blob.size, byteWidth) + + val sloc: Int = buffer.writePosition + buffer.requestAdditionalCapacity(blob.size + trailing.compareTo(false)) + buffer.put(blob, 0, blob.size) + if (trailing) { + buffer.put(ZeroByte) + } + return Value(type, key, bitWidth, sloc.toULong()) + } + + private fun writeIntArray(value: IntArray, byteWidth: ByteWidth) = + writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } + + private fun writeIntArray(value: ShortArray, byteWidth: ByteWidth) = + writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } + + private fun writeIntArray(value: LongArray, byteWidth: ByteWidth) = + writeIntegerArray(0, value.size, byteWidth) { value[it].toULong() } + + private fun writeFloatArray(value: FloatArray) { + buffer.requestAdditionalCapacity(Float.SIZE_BYTES * value.size) + value.forEach { buffer.put(it) } + } + + private fun writeFloatArray(value: DoubleArray) { + buffer.requestAdditionalCapacity(Double.SIZE_BYTES * value.size) + value.forEach { buffer.put(it) } + } + + private inline fun writeIntegerArray( + start: Int, + size: Int, + byteWidth: ByteWidth, + crossinline valueBlock: (Int) -> ULong + ) { + buffer.requestAdditionalCapacity(size * byteWidth.value) + return when (byteWidth.value) { + 1 -> for (i in start until start + size) { + buffer.put(valueBlock(i).toUByte()) + } + 2 -> for (i in start until start + size) { + buffer.put(valueBlock(i).toUShort()) + } + 4 -> for (i in start until start + size) { + buffer.put(valueBlock(i).toUInt()) + } + 8 -> for (i in start until start + size) { + buffer.put(valueBlock(i)) + } + else -> Unit + } + } + + private fun writeInt(value: Int, byteWidth: ByteWidth) { + buffer.requestAdditionalCapacity(byteWidth.value) + when (byteWidth.value) { + 1 -> buffer.put(value.toUByte()) + 2 -> buffer.put(value.toUShort()) + 4 -> buffer.put(value.toUInt()) + 8 -> buffer.put(value.toULong()) + else -> Unit + } + } + + private fun writeInt(value: ULong, byteWidth: ByteWidth) { + buffer.requestAdditionalCapacity(byteWidth.value) + when(byteWidth.value) { + 1 -> buffer.put(value.toUByte()) + 2 -> buffer.put(value.toUShort()) + 4 -> buffer.put(value.toUInt()) + 8 -> buffer.put(value) + else -> Unit + } + } + + // Align to prepare for writing a scalar with a certain size. + // returns the amounts of bytes needed to be written. + private fun align(alignment: BitWidth): ByteWidth { + val byteWidth = 1 shl alignment.value + var padBytes = paddingBytes(buffer.writePosition, byteWidth) + buffer.requestCapacity(buffer.capacity + padBytes) + while (padBytes-- != 0) { + buffer.put(ZeroByte) + } + return ByteWidth(byteWidth) + } + + private fun calculateKeyVectorBitWidth(start: Int, length: Int): BitWidth { + val bitWidth = length.toULong().widthInUBits() + var width = bitWidth + val prefixElems = 1 + // Check bit widths and types for all elements. + for (i in start until stack.size) { + val elemWidth = elemWidth(T_KEY, W_8, stack[i].key.toLong(), buffer.writePosition, i + prefixElems) + width = width.max(elemWidth) + } + return width + } + + private fun createKeyVector(start: Int, length: Int): Value { + // Figure out smallest bit width we can store this vector with. + val bitWidth = calculateKeyVectorBitWidth(start, length) + val byteWidth = align(bitWidth) + // Write vector. First the keys width/offset if available, and size. + writeInt(length, byteWidth) + // Then the actual data. + val vloc = buffer.writePosition.toULong() + for (i in start until stack.size) { + val pos = stack[i].key + if (pos == -1) error("invalid position $pos for key") + writeOffset(stack[i].key, byteWidth) + } + // Then the types. + return Value(T_VECTOR_KEY, -1, bitWidth, vloc) + } + + private inline fun createVector(key: Int, start: Int, length: Int, keys: Value? = null): Value { + return createAnyVector(key, start, length, T_VECTOR, keys) { + // add types since we are not creating a typed vector. + buffer.requestAdditionalCapacity(stack.size) + for (i in start until stack.size) { + buffer.put(stack[i].storedPackedType(it)) + } + } + } + + private fun putMap(key: Int, start: Int, length: Int, keys: Value? = null): Value { + return createAnyVector(key, start, length, T_MAP, keys) { + // add types since we are not creating a typed vector. + buffer.requestAdditionalCapacity(stack.size) + for (i in start until stack.size) { + buffer.put(stack[i].storedPackedType(it)) + } + } + } + + private inline fun createTypedVector(key: Int, start: Int, length: Int, keys: Value? = null): Value { + // We assume the callers of this method guarantees all elements are of the same type. + val elementType: FlexBufferType = stack[start].type + for (i in start + 1 until length) { + if (elementType != stack[i].type) error("TypedVector does not support array of different element types") + } + if (!elementType.isTypedVectorElementType()) error("TypedVector does not support this element type") + return createAnyVector(key, start, length, elementType.toTypedVector(), keys) + } + + private inline fun createAnyVector( + key: Int, + start: Int, + length: Int, + type: FlexBufferType, + keys: Value? = null, + crossinline typeBlock: (BitWidth) -> Unit = {} + ): Value { + // Figure out the smallest bit width we can store this vector with. + var bitWidth = W_8.max(length.toULong().widthInUBits()) + var prefixElems = 1 + if (keys != null) { + // If this vector is part of a map, we will pre-fix an offset to the keys + // to this vector. + bitWidth = bitWidth.max(keys.elemWidth(buffer.writePosition, 0)) + prefixElems += 2 + } + // Check bit widths and types for all elements. + for (i in start until stack.size) { + val elemWidth = stack[i].elemWidth(buffer.writePosition, i + prefixElems) + bitWidth = bitWidth.max(elemWidth) + } + val byteWidth = align(bitWidth) + // Write vector. First the keys width/offset if available, and size. + if (keys != null) { + writeOffset(keys.iValue.toInt(), byteWidth) + writeInt(1 shl keys.minBitWidth.value, byteWidth) + } + // write the size + writeInt(length, byteWidth) + + // Then the actual data. + val vloc: Int = buffer.writePosition + for (i in start until stack.size) { + writeAny(stack[i], byteWidth) + } + + // Optionally you can introduce the types for non-typed vector + typeBlock(bitWidth) + return Value(type, key, bitWidth, vloc.toULong()) + } + + // A lambda to sort map keys + internal val keyComparator = object : Comparator { + override fun compare(a: Value, b: Value): Int { + var ia: Int = a.key + var io: Int = b.key + var c1: Byte + var c2: Byte + do { + c1 = buffer[ia] + c2 = buffer[io] + if (c1.toInt() == 0) return c1 - c2 + ia++ + io++ + } while (c1 == c2) + return c1 - c2 + } + } + + public companion object { + /** + * No keys or strings will be shared + */ + public const val SHARE_NONE: Int = 0 + + /** + * Keys will be shared between elements. Identical keys will only be serialized once, thus possibly saving space. + * But serialization performance might be slower and consumes more memory. + */ + public const val SHARE_KEYS: Int = 1 + + /** + * Strings will be shared between elements. Identical strings will only be serialized once, thus possibly saving space. + * But serialization performance might be slower and consumes more memory. This is ideal if you expect many repeated + * strings on the message. + */ + public const val SHARE_STRINGS: Int = 2 + + /** + * Strings and keys will be shared between elements. + */ + public const val SHARE_KEYS_AND_STRINGS: Int = 3 + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersInternals.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersInternals.kt new file mode 100644 index 00000000000..9a1e2435516 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/FlexBuffersInternals.kt @@ -0,0 +1,257 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +import kotlin.jvm.JvmInline + +@JvmInline +public value class BitWidth(public val value: Int) { + public inline fun max(other: BitWidth): BitWidth = if (this.value >= other.value) this else other +} + +@JvmInline +public value class ByteWidth(public val value: Int) + +@JvmInline +public value class FlexBufferType(public val value: Int) { + public operator fun minus(other: FlexBufferType): FlexBufferType = FlexBufferType(this.value - other.value) + public operator fun plus(other: FlexBufferType): FlexBufferType = FlexBufferType(this.value + other.value) + public operator fun compareTo(other: FlexBufferType): Int = this.value - other.value +} + +internal operator fun Int.times(width: ByteWidth): Int = this * width.value +internal operator fun Int.minus(width: ByteWidth): Int = this - width.value +internal operator fun Int.plus(width: ByteWidth): Int = this + width.value +internal operator fun Int.minus(type: FlexBufferType): Int = this - type.value + +// Returns a Key string from the buffer starting at index [start]. Key Strings are stored as +// C-Strings, ending with '\0'. If zero byte not found returns empty string. +internal inline fun ReadBuffer.getKeyString(start: Int): String { + val i = findFirst(0.toByte(), start) + return if (i >= 0) getString(start, i - start) else "" +} + +// read unsigned int with size byteWidth and return as a 64-bit integer +internal inline fun ReadBuffer.readULong(end: Int, byteWidth: ByteWidth): ULong { + return when (byteWidth.value) { + 1 -> this.getUByte(end).toULong() + 2 -> this.getUShort(end).toULong() + 4 -> this.getUInt(end).toULong() + 8 -> this.getULong(end) + else -> error("invalid byte width $byteWidth for scalar unsigned integer") + } +} + +internal inline fun ReadBuffer.readFloat(end: Int, byteWidth: ByteWidth): Double { + return when (byteWidth.value) { + 4 -> this.getFloat(end).toDouble() + 8 -> this.getDouble(end) + else -> error("invalid byte width $byteWidth for floating point scalar") // we should never reach here + } +} +// return position on the [ReadBuffer] of the element that the offset is pointing to +// we assume all offset fits on a int, since ReadBuffer operates with that assumption +internal inline fun ReadBuffer.indirect(offset: Int, byteWidth: ByteWidth): Int = offset - readInt(offset, byteWidth) +// returns the size of an array-like element from [ReadBuffer]. +internal inline fun ReadBuffer.readSize(end: Int, byteWidth: ByteWidth) = readInt(end - byteWidth, byteWidth) +internal inline fun ReadBuffer.readUInt(end: Int, byteWidth: ByteWidth): UInt = readULong(end, byteWidth).toUInt() +internal inline fun ReadBuffer.readInt(end: Int, byteWidth: ByteWidth): Int = readULong(end, byteWidth).toInt() +internal inline fun ReadBuffer.readLong(end: Int, byteWidth: ByteWidth): Long = readULong(end, byteWidth).toLong() + +internal fun IntArray.widthInUBits(): BitWidth = arrayWidthInUBits(this.size) { this[it].toULong().widthInUBits() } +internal fun ShortArray.widthInUBits(): BitWidth = arrayWidthInUBits(this.size) { this[it].toULong().widthInUBits() } +internal fun LongArray.widthInUBits(): BitWidth = arrayWidthInUBits(this.size) { this[it].toULong().widthInUBits() } + +private inline fun arrayWidthInUBits(size: Int, crossinline elemWidthBlock: (Int) -> BitWidth): BitWidth { + // Figure out smallest bit width we can store this vector with. + var bitWidth = W_8.max(size.toULong().widthInUBits()) + // Check bit widths and types for all elements. + for (i in 0 until size) { + // since we know its inline types we can just assume elmentWidth to be the value width in bits. + bitWidth = bitWidth.max(elemWidthBlock(i)) + } + return bitWidth +} + +internal fun ULong.widthInUBits(): BitWidth = when { + this <= MAX_UBYTE_ULONG -> W_8 + this <= UShort.MAX_VALUE -> W_16 + this <= UInt.MAX_VALUE -> W_32 + else -> W_64 +} + +// returns the number of bytes needed for padding the scalar of size scalarSize. +internal inline fun paddingBytes(bufSize: Int, scalarSize: Int): Int = bufSize.inv() + 1 and scalarSize - 1 + +internal inline fun FlexBufferType.isInline(): Boolean = this.value <= T_FLOAT.value || this == T_BOOL + +internal fun FlexBufferType.isScalar(): Boolean = when (this) { + T_INT, T_UINT, T_FLOAT, T_BOOL -> true + else -> false +} + +internal fun FlexBufferType.isIndirectScalar(): Boolean = when (this) { + T_INDIRECT_INT, T_INDIRECT_UINT, T_INDIRECT_FLOAT -> true + else -> false +} + +internal fun FlexBufferType.isTypedVector(): Boolean = + this >= T_VECTOR_INT && this <= T_VECTOR_STRING_DEPRECATED || this == T_VECTOR_BOOL + +internal fun FlexBufferType.isTypedVectorElementType(): Boolean = + (this.value in T_INT.value..T_KEY.value) || this == T_BOOL + +// returns the typed vector of a given scalar type. +internal fun FlexBufferType.toTypedVector(): FlexBufferType = (this - T_INT) + T_VECTOR_INT +// returns the element type of given typed vector. +internal fun FlexBufferType.toElementTypedVector(): FlexBufferType = this - T_VECTOR_INT + T_INT + +// Holds information about the elements inserted on the buffer. +internal data class Value( + var type: FlexBufferType = T_INT, + var key: Int = -1, + var minBitWidth: BitWidth = W_8, + var iValue: ULong = 0UL, // integer value + var dValue: Double = 0.0 // TODO(paulovap): maybe we can keep floating type on iValue as well. +) { // float value + + inline fun storedPackedType(parentBitWidth: BitWidth = W_8): Byte = packedType(storedWidth(parentBitWidth), type) + + private inline fun packedType(bitWidth: BitWidth, type: FlexBufferType): Byte = + (bitWidth.value or (type.value shl 2)).toByte() + + private inline fun storedWidth(parentBitWidth: BitWidth): BitWidth = + if (type.isInline()) minBitWidth.max(parentBitWidth) else minBitWidth + + fun elemWidth(bufSize: Int, elemIndex: Int): BitWidth = + elemWidth(type, minBitWidth, iValue.toLong(), bufSize, elemIndex) +} + +internal fun elemWidth( + type: FlexBufferType, + minBitWidth: BitWidth, + iValue: Long, + bufSize: Int, + elemIndex: Int +): BitWidth { + if (type.isInline()) return minBitWidth + + // We have an absolute offset, but want to store a relative offset + // elem_index elements beyond the current buffer end. Since whether + // the relative offset fits in a certain byte_width depends on + // the size of the elements before it (and their alignment), we have + // to test for each size in turn. + // Original implementation checks for largest scalar + // which is long unsigned int + var byteWidth = 1 + while (byteWidth <= 32) { + // Where are we going to write this offset? + val offsetLoc: Int = bufSize + paddingBytes(bufSize, byteWidth) + elemIndex * byteWidth + // Compute relative offset. + val offset: Int = offsetLoc - iValue.toInt() + // Does it fit? + val bitWidth = offset.toULong().widthInUBits() + if (1 shl bitWidth.value == byteWidth) return bitWidth + byteWidth *= 2 + } + return W_64 +} + +// For debugging purposes, convert type to a human-readable string. +internal fun FlexBufferType.typeToString(): String = when (this) { + T_NULL -> "Null" + T_INT -> "Int" + T_UINT -> "UInt" + T_FLOAT -> "Float" + T_KEY -> "Key" + T_STRING -> "String" + T_INDIRECT_INT -> "IndirectInt" + T_INDIRECT_UINT -> "IndirectUInt" + T_INDIRECT_FLOAT -> "IndirectFloat" + T_MAP -> "Map" + T_VECTOR -> "Vector" + T_VECTOR_INT -> "IntVector" + T_VECTOR_UINT -> "UIntVector" + T_VECTOR_FLOAT -> "FloatVector" + T_VECTOR_KEY -> "KeyVector" + T_VECTOR_STRING_DEPRECATED -> "StringVectorDeprecated" + T_VECTOR_INT2 -> "Int2Vector" + T_VECTOR_UINT2 -> "UInt2Vector" + T_VECTOR_FLOAT2 -> "Float2Vector" + T_VECTOR_INT3 -> "Int3Vector" + T_VECTOR_UINT3 -> "UInt3Vector" + T_VECTOR_FLOAT3 -> "Float3Vector" + T_VECTOR_INT4 -> "Int4Vector" + T_VECTOR_UINT4 -> "UInt4Vector" + T_VECTOR_FLOAT4 -> "Float4Vector" + T_BLOB -> "BlobVector" + T_BOOL -> "BoolVector" + T_VECTOR_BOOL -> "BoolVector" + else -> "UnknownType" +} + +// Few repeated values used in hot path is cached here +internal fun emptyBlob() = Blob(emptyBuffer, 1, ByteWidth(1)) +internal fun emptyVector() = Vector(emptyBuffer, 1, ByteWidth(1)) +internal fun emptyMap() = Map(ArrayReadWriteBuffer(3), 3, ByteWidth(1)) +internal fun nullReference() = Reference(emptyBuffer, 1, ByteWidth(0), T_NULL.value) +internal fun nullKey() = Key(emptyBuffer, 1) + +internal const val ZeroByte = 0.toByte() +internal const val MAX_UBYTE_ULONG = 255UL +internal const val MAX_UBYTE = 255 +internal const val MAX_USHORT = 65535 + +// value bit width possible sizes +internal val W_8 = BitWidth(0) +internal val W_16 = BitWidth(1) +internal val W_32 = BitWidth(2) +internal val W_64 = BitWidth(3) + +// These are used as the upper 6 bits of a type field to indicate the actual type. +internal val T_INVALID = FlexBufferType(-1) +internal val T_NULL = FlexBufferType(0) +internal val T_INT = FlexBufferType(1) +internal val T_UINT = FlexBufferType(2) +internal val T_FLOAT = FlexBufferType(3) // Types above stored inline, types below are stored in an offset. +internal val T_KEY = FlexBufferType(4) +internal val T_STRING = FlexBufferType(5) +internal val T_INDIRECT_INT = FlexBufferType(6) +internal val T_INDIRECT_UINT = FlexBufferType(7) +internal val T_INDIRECT_FLOAT = FlexBufferType(8) +internal val T_MAP = FlexBufferType(9) +internal val T_VECTOR = FlexBufferType(10) // Untyped. +internal val T_VECTOR_INT = FlexBufferType(11) // Typed any size = stores no type table). +internal val T_VECTOR_UINT = FlexBufferType(12) +internal val T_VECTOR_FLOAT = FlexBufferType(13) +internal val T_VECTOR_KEY = FlexBufferType(14) +// DEPRECATED, use FBT_VECTOR or FBT_VECTOR_KEY instead. +// more info on https://github.com/google/flatbuffers/issues/5627. +internal val T_VECTOR_STRING_DEPRECATED = FlexBufferType(15) +internal val T_VECTOR_INT2 = FlexBufferType(16) // Typed tuple = no type table; no size field). +internal val T_VECTOR_UINT2 = FlexBufferType(17) +internal val T_VECTOR_FLOAT2 = FlexBufferType(18) +internal val T_VECTOR_INT3 = FlexBufferType(19) // Typed triple = no type table; no size field). +internal val T_VECTOR_UINT3 = FlexBufferType(20) +internal val T_VECTOR_FLOAT3 = FlexBufferType(21) +internal val T_VECTOR_INT4 = FlexBufferType(22) // Typed quad = no type table; no size field). +internal val T_VECTOR_UINT4 = FlexBufferType(23) +internal val T_VECTOR_FLOAT4 = FlexBufferType(24) +internal val T_BLOB = FlexBufferType(25) +internal val T_BOOL = FlexBufferType(26) +internal val T_VECTOR_BOOL = FlexBufferType(36) // To Allow the same type of conversion of type to vector type diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt new file mode 100644 index 00000000000..bccc1518f84 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/Utf8.kt @@ -0,0 +1,420 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +public object Utf8 { + /** + * Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string, + * this method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in + * both time and space. + * + * @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired + * surrogates) + */ + private fun computeEncodedLength(sequence: CharSequence): Int { + // Warning to maintainers: this implementation is highly optimized. + val utf16Length = sequence.length + var utf8Length = utf16Length + var i = 0 + + // This loop optimizes for pure ASCII. + while (i < utf16Length && sequence[i].code < 0x80) { + i++ + } + + // This loop optimizes for chars less than 0x800. + while (i < utf16Length) { + val c = sequence[i] + if (c.code < 0x800) { + utf8Length += 0x7f - c.code ushr 31 // branch free! + } else { + utf8Length += encodedLengthGeneral(sequence, i) + break + } + i++ + } + if (utf8Length < utf16Length) { + // Necessary and sufficient condition for overflow because of maximum 3x expansion + error("UTF-8 length does not fit in int: ${(utf8Length + (1L shl 32))}") + } + return utf8Length + } + + private fun encodedLengthGeneral(sequence: CharSequence, start: Int): Int { + val utf16Length = sequence.length + var utf8Length = 0 + var i = start + while (i < utf16Length) { + val c = sequence[i] + if (c.code < 0x800) { + utf8Length += 0x7f - c.code ushr 31 // branch free! + } else { + utf8Length += 2 + if (c.isSurrogate()) { + // Check that we have a well-formed surrogate pair. + val cp: Int = codePointAt(sequence, i) + if (cp < MIN_SUPPLEMENTARY_CODE_POINT) { + errorSurrogate(i, utf16Length) + } + i++ + } + } + i++ + } + return utf8Length + } + + /** + * Returns the number of bytes in the UTF-8-encoded form of `sequence`. For a string, + * this method is equivalent to `string.getBytes(UTF_8).length`, but is more efficient in + * both time and space. + * + * @throws IllegalArgumentException if `sequence` contains ill-formed UTF-16 (unpaired + * surrogates) + */ + public fun encodedLength(sequence: CharSequence): Int = computeEncodedLength(sequence) + + /** + * Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. + */ + public inline fun isOneByte(b: Byte): Boolean = b >= 0 + + /** + * Returns whether this is a two-byte codepoint with the form 110xxxxx 0xC0..0xDF. + */ + public inline fun isTwoBytes(b: Byte): Boolean = b < 0xE0.toByte() + + /** + * Returns whether this is a three-byte codepoint with the form 1110xxxx 0xE0..0xEF. + */ + public inline fun isThreeBytes(b: Byte): Boolean = b < 0xF0.toByte() + + /** + * Returns whether this is a four-byte codepoint with the form 11110xxx 0xF0..0xF4. + */ + public inline fun isFourByte(b: Byte): Boolean = b < 0xF8.toByte() + + public fun handleOneByte(byte1: Byte, resultArr: CharArray, resultPos: Int) { + resultArr[resultPos] = byte1.toInt().toChar() + } + + public fun handleTwoBytes( + byte1: Byte, + byte2: Byte, + resultArr: CharArray, + resultPos: Int + ) { + // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and + // overlong 2-byte, '11000001'. + if (byte1 < 0xC2.toByte()) { + error("Invalid UTF-8: Illegal leading byte in 2 bytes utf") + } + if (isNotTrailingByte(byte2)) { + error("Invalid UTF-8: Illegal trailing byte in 2 bytes utf") + } + resultArr[resultPos] = (byte1.toInt() and 0x1F shl 6 or trailingByteValue(byte2)).toChar() + } + + public fun handleThreeBytes( + byte1: Byte, + byte2: Byte, + byte3: Byte, + resultArr: CharArray, + resultPos: Int + ) { + if (isNotTrailingByte(byte2) || // overlong? 5 most significant bits must not all be zero + byte1 == 0xE0.toByte() && byte2 < 0xA0.toByte() || // check for illegal surrogate codepoints + byte1 == 0xED.toByte() && byte2 >= 0xA0.toByte() || + isNotTrailingByte(byte3) + ) { + error("Invalid UTF-8") + } + resultArr[resultPos] = + (byte1.toInt() and 0x0F shl 12 or (trailingByteValue(byte2) shl 6) or trailingByteValue(byte3)).toChar() + } + + public fun handleFourBytes( + byte1: Byte, + byte2: Byte, + byte3: Byte, + byte4: Byte, + resultArr: CharArray, + resultPos: Int + ) { + if (isNotTrailingByte(byte2) || // Check that 1 <= plane <= 16. Tricky optimized form of: + // valid 4-byte leading byte? + // if (byte1 > (byte) 0xF4 || + // overlong? 4 most significant bits must not all be zero + // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || + // codepoint larger than the highest code point (U+10FFFF)? + // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) + (byte1.toInt() shl 28) + (byte2 - 0x90.toByte()) shr 30 != 0 || isNotTrailingByte(byte3) || + isNotTrailingByte(byte4) + ) { + error("Invalid UTF-8") + } + val codepoint: Int = ( + byte1.toInt() and 0x07 shl 18 + or (trailingByteValue(byte2) shl 12) + or (trailingByteValue(byte3) shl 6) + or trailingByteValue(byte4) + ) + resultArr[resultPos] = highSurrogate(codepoint) + resultArr[resultPos + 1] = lowSurrogate(codepoint) + } + + /** + * Returns whether the byte is not a valid continuation of the form '10XXXXXX'. + */ + private fun isNotTrailingByte(b: Byte): Boolean = b > 0xBF.toByte() + + /** + * Returns the actual value of the trailing byte (removes the prefix '10') for composition. + */ + private fun trailingByteValue(b: Byte): Int = b.toInt() and 0x3F + + private fun highSurrogate(codePoint: Int): Char = + ( + Char.MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT ushr 10) + + (codePoint ushr 10) + ) + + private fun lowSurrogate(codePoint: Int): Char = (Char.MIN_LOW_SURROGATE + (codePoint and 0x3ff)) + + /** + * Encode a [CharSequence] UTF8 codepoint into a byte array. + * @param `in` CharSequence to be encoded + * @param start start position of the first char in the codepoint + * @param out byte array of 4 bytes to be filled + * @return return the amount of bytes occupied by the codepoint + */ + public fun encodeUtf8CodePoint(input: CharSequence, start: Int, out: ByteArray): Int { + // utf8 codepoint needs at least 4 bytes + val inLength = input.length + if (start >= inLength) { + return 0 + } + val c = input[start] + return if (c.code < 0x80) { + // One byte (0xxx xxxx) + out[0] = c.code.toByte() + 1 + } else if (c.code < 0x800) { + // Two bytes (110x xxxx 10xx xxxx) + out[0] = (0xC0 or (c.code ushr 6)).toByte() + out[1] = (0x80 or (0x3F and c.code)).toByte() + 2 + } else if (c < Char.MIN_SURROGATE || Char.MAX_SURROGATE < c) { + // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx) + // Maximum single-char code point is 0xFFFF, 16 bits. + out[0] = (0xE0 or (c.code ushr 12)).toByte() + out[1] = (0x80 or (0x3F and (c.code ushr 6))).toByte() + out[2] = (0x80 or (0x3F and c.code)).toByte() + 3 + } else { + // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx) + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 + // bytes + val low: Char = input[start + 1] + if (start + 1 == inLength || !(c.isHighSurrogate() and low.isLowSurrogate())) { + errorSurrogate(start, inLength) + } + val codePoint: Int = toCodePoint(c, low) + out[0] = (0xF shl 4 or (codePoint ushr 18)).toByte() + out[1] = (0x80 or (0x3F and (codePoint ushr 12))).toByte() + out[2] = (0x80 or (0x3F and (codePoint ushr 6))).toByte() + out[3] = (0x80 or (0x3F and codePoint)).toByte() + 4 + } + } + + // Decodes a code point starting at index into out. Out parameter + // should have at least 2 chars. + public fun decodeUtf8CodePoint(bytes: ReadBuffer, index: Int, out: CharArray) { + // Bitwise OR combines the sign bits so any negative value fails the check. + val b1 = bytes[index] + when { + isOneByte(b1) -> handleOneByte(b1, out, 0) + isTwoBytes(b1) -> handleTwoBytes(b1, bytes[index + 1], out, 0) + isThreeBytes(b1) -> handleThreeBytes(b1, bytes[index + 1], bytes[index + 2], out, 0) + else -> handleFourBytes(b1, bytes[index + 1], bytes[index + 2], bytes[index + 3], out, 0) + } + } + + public fun decodeUtf8Array(bytes: ByteArray, index: Int = 0, size: Int = bytes.size): String { + // Bitwise OR combines the sign bits so any negative value fails the check. + if (index or size or bytes.size - index - size < 0) { + error("buffer length=${bytes.size}, index=$index, size=$size") + } + var offset = index + val limit = offset + size + + // The longest possible resulting String is the same as the number of input bytes, when it is + // all ASCII. For other cases, this over-allocates and we will truncate in the end. + val resultArr = CharArray(size) + var resultPos = 0 + + // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). + // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). + while (offset < limit) { + val b = bytes[offset] + if (!isOneByte(b)) { + break + } + offset++ + handleOneByte(b, resultArr, resultPos++) + } + while (offset < limit) { + val byte1 = bytes[offset++] + if (isOneByte(byte1)) { + handleOneByte(byte1, resultArr, resultPos++) + // It's common for there to be multiple ASCII characters in a run mixed in, so add an + // extra optimized loop to take care of these runs. + while (offset < limit) { + val b = bytes[offset] + if (!isOneByte(b)) { + break + } + offset++ + handleOneByte(b, resultArr, resultPos++) + } + } else if (isTwoBytes(byte1)) { + if (offset >= limit) { + error("Invalid UTF-8") + } + handleTwoBytes( + byte1, /* byte2 */ + bytes[offset++], resultArr, resultPos++ + ) + } else if (isThreeBytes(byte1)) { + if (offset >= limit - 1) { + error("Invalid UTF-8") + } + handleThreeBytes( + byte1, /* byte2 */ + bytes[offset++], /* byte3 */ + bytes[offset++], + resultArr, + resultPos++ + ) + } else { + if (offset >= limit - 2) { + error("Invalid UTF-8") + } + handleFourBytes( + byte1, /* byte2 */ + bytes[offset++], /* byte3 */ + bytes[offset++], /* byte4 */ + bytes[offset++], + resultArr, + resultPos++ + ) + // 4-byte case requires two chars. + resultPos++ + } + } + return resultArr.concatToString(0, resultPos) + } + + public fun encodeUtf8Array(input: CharSequence, + out: ByteArray, + offset: Int = 0, + length: Int = out.size - offset): Int { + val utf16Length = input.length + var j = offset + var i = 0 + val limit = offset + length + // Designed to take advantage of + // https://wikis.oracle.com/display/HotSpotInternals/RangeCheckElimination + + if (utf16Length == 0) + return 0 + var cc: Char = input[i] + while (i < utf16Length && i + j < limit && input[i].also { cc = it }.code < 0x80) { + out[j + i] = cc.code.toByte() + i++ + } + if (i == utf16Length) { + return j + utf16Length + } + j += i + var c: Char + while (i < utf16Length) { + c = input[i] + if (c.code < 0x80 && j < limit) { + out[j++] = c.code.toByte() + } else if (c.code < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes + out[j++] = (0xF shl 6 or (c.code ushr 6)).toByte() + out[j++] = (0x80 or (0x3F and c.code)).toByte() + } else if ((c < Char.MIN_SURROGATE || Char.MAX_SURROGATE < c) && j <= limit - 3) { + // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes + out[j++] = (0xF shl 5 or (c.code ushr 12)).toByte() + out[j++] = (0x80 or (0x3F and (c.code ushr 6))).toByte() + out[j++] = (0x80 or (0x3F and c.code)).toByte() + } else if (j <= limit - 4) { + // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, + // four UTF-8 bytes + var low: Char = Char.MIN_VALUE + if (i + 1 == input.length || + !isSurrogatePair(c, input[++i].also { low = it }) + ) { + errorSurrogate(i - 1, utf16Length) + } + val codePoint: Int = toCodePoint(c, low) + out[j++] = (0xF shl 4 or (codePoint ushr 18)).toByte() + out[j++] = (0x80 or (0x3F and (codePoint ushr 12))).toByte() + out[j++] = (0x80 or (0x3F and (codePoint ushr 6))).toByte() + out[j++] = (0x80 or (0x3F and codePoint)).toByte() + } else { + // If we are surrogates and we're not a surrogate pair, always throw an + // UnpairedSurrogateException instead of an ArrayOutOfBoundsException. + if (Char.MIN_SURROGATE <= c && c <= Char.MAX_SURROGATE && + (i + 1 == input.length || !isSurrogatePair(c, input[i + 1])) + ) { + errorSurrogate(i, utf16Length) + } + error("Failed writing character ${c.code.toShort().toString(radix = 16)} at index $j") + } + i++ + } + return j + } + + public fun codePointAt(seq: CharSequence, position: Int): Int { + var index = position + val c1 = seq[index] + if (c1.isHighSurrogate() && ++index < seq.length) { + val c2 = seq[index] + if (c2.isLowSurrogate()) { + return toCodePoint(c1, c2) + } + } + return c1.code + } + + private fun isSurrogatePair(high: Char, low: Char) = high.isHighSurrogate() and low.isLowSurrogate() + + private fun toCodePoint(high: Char, low: Char): Int = (high.code shl 10) + low.code + + (MIN_SUPPLEMENTARY_CODE_POINT - (Char.MIN_HIGH_SURROGATE.code shl 10) - Char.MIN_LOW_SURROGATE.code) + + private fun errorSurrogate(i: Int, utf16Length: Int): Unit = + error("Unpaired surrogate at index $i of $utf16Length length") + + // The minimum value of Unicode supplementary code point, constant `U+10000`. + private const val MIN_SUPPLEMENTARY_CODE_POINT = 0x010000 +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/json.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/json.kt new file mode 100644 index 00000000000..33867974b21 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonMain/kotlin/com/google/flatbuffers/kotlin/json.kt @@ -0,0 +1,832 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +import com.google.flatbuffers.kotlin.FlexBuffersBuilder.Companion.SHARE_KEYS_AND_STRINGS +import kotlin.experimental.and +import kotlin.jvm.JvmInline +import kotlin.math.pow + +/** + * Returns a minified version of this FlexBuffer as a JSON. + */ +public fun Reference.toJson(): String = ArrayReadWriteBuffer(1024).let { + toJson(it) + val data = it.data() // it.getString(0, it.writePosition) + return data.decodeToString(0, it.writePosition) +} + +/** + * Returns a minified version of this FlexBuffer as a JSON. + * @param out [ReadWriteBuffer] the JSON will be written. + */ +public fun Reference.toJson(out: ReadWriteBuffer) { + when (type) { + T_STRING -> { + val start = buffer.indirect(end, parentWidth) + val size = buffer.readULong(start - byteWidth, byteWidth).toInt() + out.jsonEscape(buffer, start, size) + } + T_KEY -> { + val start = buffer.indirect(end, parentWidth) + val end = buffer.findFirst(0.toByte(), start) + out.jsonEscape(buffer, start, end - start) + } + T_BLOB -> { + val blob = toBlob() + out.jsonEscape(out, blob.end, blob.size) + } + T_INT -> out.put(toLong().toString()) + T_UINT -> out.put(toULong().toString()) + T_FLOAT -> out.put(toDouble().toString()) + T_NULL -> out.put("null") + T_BOOL -> out.put(toBoolean().toString()) + T_MAP -> toMap().toJson(out) + T_VECTOR, T_VECTOR_BOOL, T_VECTOR_FLOAT, T_VECTOR_INT, + T_VECTOR_UINT, T_VECTOR_KEY, T_VECTOR_STRING_DEPRECATED -> toVector().toJson(out) + else -> error("Unable to convert type ${type.typeToString()} to JSON") + } +} + +/** + * Returns a minified version of this FlexBuffer as a JSON. + */ +public fun Map.toJson(): String = ArrayReadWriteBuffer(1024).let { toJson(it); it.toString() } + +/** + * Returns a minified version of this FlexBuffer as a JSON. + * @param out [ReadWriteBuffer] the JSON will be written. + */ +public fun Map.toJson(out: ReadWriteBuffer) { + out.put('{'.code.toByte()) + // key values pairs + for (i in 0 until size) { + val key = keyAt(i) + out.jsonEscape(buffer, key.start, key.sizeInBytes) + out.put(':'.code.toByte()) + get(i).toJson(out) + if (i != size - 1) { + out.put(','.code.toByte()) + } + } + // close bracket + out.put('}'.code.toByte()) +} + +/** + * Returns a minified version of this FlexBuffer as a JSON. + */ +public fun Vector.toJson(): String = ArrayReadWriteBuffer(1024).let { toJson(it); it.toString() } + +/** + * Returns a minified version of this FlexBuffer as a JSON. + * @param out that the JSON is being concatenated. + */ +public fun Vector.toJson(out: ReadWriteBuffer) { + out.put('['.code.toByte()) + for (i in indices) { + get(i).toJson(out) + if (i != size - 1) { + out.put(','.code.toByte()) + } + } + out.put(']'.code.toByte()) +} + +/** + * JSONParser class is used to parse a JSON as FlexBuffers. Calling [JSONParser.parse] fiils [output] + * and returns a [Reference] ready to be used. + */ +@ExperimentalUnsignedTypes +public class JSONParser(public var output: FlexBuffersBuilder = FlexBuffersBuilder(1024, SHARE_KEYS_AND_STRINGS)) { + private var readPos = 0 + private var scopes = ScopeStack() + + /** + * Parse a json as [String] and returns a [Reference] to a FlexBuffer. + */ + public fun parse(data: String): Reference = parse(ArrayReadBuffer(data.encodeToByteArray())) + + /** + * Parse a json as [ByteArray] and returns a [Reference] to a FlexBuffer. + */ + public fun parse(data: ByteArray): Reference = parse(ArrayReadBuffer(data)) + + /** + * Parse a json as [ReadBuffer] and returns a [Reference] to a FlexBuffer. + */ + public fun parse(data: ReadBuffer): Reference { + reset() + parseValue(data, nextToken(data), null) + if (readPos < data.limit) { + val tok = skipWhitespace(data) + if (tok != CHAR_EOF) { + makeError(data, "Extraneous charaters after parse has finished", tok) + } + } + output.finish() + return getRoot(output.buffer) + } + + private fun parseValue(data: ReadBuffer, token: Token, key: String? = null): FlexBufferType { + return when (token) { + TOK_BEGIN_OBJECT -> parseObject(data, key) + TOK_BEGIN_ARRAY -> parseArray(data, key) + TOK_TRUE -> T_BOOL.also { output[key] = true } + TOK_FALSE -> T_BOOL.also { output[key] = false } + TOK_NULL -> T_NULL.also { output.putNull(key) } + TOK_BEGIN_QUOTE -> parseString(data, key) + TOK_NUMBER -> parseNumber(data, data.data(), key) + else -> makeError(data, "Unexpected Character while parsing", 'x'.code.toByte()) + } + } + + private fun parseObject(data: ReadBuffer, key: String? = null): FlexBufferType { + this.scopes.push(SCOPE_OBJ_EMPTY) + + val fPos = output.startMap() + val limit = data.limit + while (readPos <= limit) { + when (val tok = nextToken(data)) { + TOK_END_OBJECT -> { + this.scopes.pop() + output.endMap(fPos, key); return T_MAP + } + TOK_BEGIN_QUOTE -> { + val childKey = readString(data) + parseValue(data, nextToken(data), childKey) + } + else -> makeError(data, "Expecting start of object key", tok) + } + } + makeError(data, "Unable to parse the object", "x".toByte()) + } + + private fun parseArray(data: ReadBuffer, key: String? = null): FlexBufferType { + this.scopes.push(SCOPE_ARRAY_EMPTY) + val fPos = output.startVector() + var elementType = T_INVALID + var multiType = false + val limit = data.limit + + while (readPos <= limit) { + when (val tok = nextToken(data)) { + TOK_END_ARRAY -> { + this.scopes.pop() + return if (!multiType && elementType.isScalar()) { + output.endTypedVector(fPos, key) + elementType.toElementTypedVector() + } else { + output.endVector(key, fPos) + T_VECTOR + } + } + + else -> { + val newType = parseValue(data, tok, null) + + if (elementType == T_INVALID) { + elementType = newType + } else if (newType != elementType) { + multiType = true + } + } + } + } + makeError(data, "Unable to parse the array") + } + + private fun parseNumber(data: ReadBuffer, array: ByteArray, key: String?): FlexBufferType { + val ary = array + var cursor = readPos + var c = data[readPos++] + var useDouble = false + val limit = ary.size + var sign = 1 + var double: Double + var long = 0L + var digits = 0 + + if (c == CHAR_MINUS) { + cursor++ + checkEOF(data, cursor) + c = ary[cursor] + sign = -1 + } + + // peek first byte + when (c) { + CHAR_0 -> { + cursor++ + if (cursor != limit) { + c = ary[cursor] + } + } + !in CHAR_0..CHAR_9 -> makeError(data, "Invalid Number", c) + else -> { + do { + val digit = c - CHAR_0 + // double = 10.0 * double + digit + long = 10 * long + digit + digits++ + cursor++ + if (cursor == limit) break + c = ary[cursor] + } while (c in CHAR_0..CHAR_9) + } + } + + var exponent = 0 + // If we find '.' we need to convert to double + if (c == CHAR_DOT) { + useDouble = true + checkEOF(data, cursor) + c = ary[++cursor] + if (c < CHAR_0 || c > CHAR_9) { + makeError(data, "Invalid Number", c) + } + do { + // double = double * 10 + (tok - CHAR_0) + long = 10 * long + (c - CHAR_0) + digits++ + --exponent + cursor++ + if (cursor == limit) break + c = ary[cursor] + } while (c in CHAR_0..CHAR_9) + } + + // If we find 'e' we need to convert to double + if (c == CHAR_e || c == CHAR_E) { + useDouble = true + ++cursor + checkEOF(data, cursor) + c = ary[cursor] + var negativeExponent = false + if (c == CHAR_MINUS) { + ++cursor + checkEOF(data, cursor) + negativeExponent = true + c = ary[cursor] + } else if (c == CHAR_PLUS) { + ++cursor + checkEOF(data, cursor) + c = ary[cursor] + } + if (c < CHAR_0 || c > CHAR_9) { + makeError(data, "Missing exponent", c) + } + var exp = 0 + do { + val digit = c - CHAR_0 + exp = 10 * exp + digit + ++cursor + if (cursor == limit) break + c = ary[cursor] + } while (c in CHAR_0..CHAR_9) + + exponent += if (negativeExponent) -exp else exp + } + + if (digits > 17 || exponent < -19 || exponent > 19) { + // if the float number is not simple enough + // we use language's Double parsing, which is slower but + // produce more expected results for extreme numbers. + val firstPos = readPos - 1 + val str = data.getString(firstPos, cursor - firstPos) + if (useDouble) { + double = str.toDouble() + output[key] = double + } else { + long = str.toLong() + output[key] = long + } + } else { + // this happens on single numbers outside any object + // or array + if (useDouble || exponent != 0) { + double = if (long == 0L) 0.0 else long.toDouble() * 10.0.pow(exponent) + double *= sign + output[key] = double + } else { + long *= sign + output[key] = long + } + } + readPos = cursor + return if (useDouble) T_FLOAT else T_INT + } + + private fun parseString(data: ReadBuffer, key: String?): FlexBufferType { + output[key] = readString(data) + return T_STRING + } + + private fun readString(data: ReadBuffer): String { + val limit = data.limit + if (data is ArrayReadBuffer) { + val ary = data.data() + // enables range check elimination + return readString(data, limit) { ary[it] } + } + return readString(data, limit) { data[it] } + } + + private inline fun readString(data: ReadBuffer, limit: Int, crossinline fetch: (Int) -> Byte): String { + var cursorPos = readPos + var foundEscape = false + var currentChar: Byte = 0 + // we loop over every 4 bytes until find any non-plain char + while (limit - cursorPos >= 4) { + currentChar = fetch(cursorPos) + if (!isPlainStringChar(currentChar)) { + foundEscape = true + break + } + currentChar = fetch(cursorPos + 1) + if (!isPlainStringChar(currentChar)) { + cursorPos += 1 + foundEscape = true + break + } + currentChar = fetch(cursorPos + 2) + if (!isPlainStringChar(currentChar)) { + cursorPos += 2 + foundEscape = true + break + } + currentChar = fetch(cursorPos + 3) + if (!isPlainStringChar(currentChar)) { + cursorPos += 3 + foundEscape = true + break + } + cursorPos += 4 + } + if (!foundEscape) { + // if non-plain string char is not found we loop over + // the remaining bytes + while (true) { + if (cursorPos >= limit) { + error("Unexpected end of string") + } + currentChar = fetch(cursorPos) + if (!isPlainStringChar(currentChar)) { + break + } + ++cursorPos + } + } + if (currentChar == CHAR_DOUBLE_QUOTE) { + val str = data.getString(readPos, cursorPos - readPos) + readPos = cursorPos + 1 + return str + } + if (currentChar in 0..0x1f) { + error("Illegal Codepoint") + } else { + // backslash or >0x7f + return readStringSlow(data, currentChar, cursorPos) + } + } + + private fun readStringSlow(data: ReadBuffer, first: Byte, lastPos: Int): String { + var cursorPos = lastPos + + var endOfString = lastPos + while (true) { + val pos = data.findFirst(CHAR_DOUBLE_QUOTE, endOfString) + when { + pos == -1 -> makeError(data, "Unexpected EOF, missing end of string '\"'", first) + data[pos - 1] == CHAR_BACKSLASH && data[pos - 2] != CHAR_BACKSLASH -> { + // here we are checking for double quotes preceded by backslash. eg \" + // we have to look past pos -2 to make sure that the backlash is not + // part of a previous escape, eg "\\" + endOfString = pos + 1 + } + else -> { + endOfString = pos; break + } + } + } + // copy everything before the escape + val builder = StringBuilder(data.getString(readPos, lastPos - readPos)) + while (true) { + when (val pos = data.findFirst(CHAR_BACKSLASH, cursorPos, endOfString)) { + -1 -> { + val doubleQuotePos = data.findFirst(CHAR_DOUBLE_QUOTE, cursorPos) + if (doubleQuotePos == -1) makeError(data, "Reached EOF before enclosing string", first) + val rest = data.getString(cursorPos, doubleQuotePos - cursorPos) + builder.append(rest) + readPos = doubleQuotePos + 1 + return builder.toString() + } + + else -> { + // we write everything up to \ + builder.append(data.getString(cursorPos, pos - cursorPos)) + val c = data[pos + 1] + builder.append(readEscapedChar(data, c, pos)) + cursorPos = pos + if (c == CHAR_u) 6 else 2 + } + } + } + } + + private inline fun isPlainStringChar(c: Byte): Boolean { + val flags = parseFlags + // return c in 0x20..0x7f && c != 0x22.toByte() && c != 0x5c.toByte() + return (flags[c.toInt() and 0xFF] and 1) != 0.toByte() + } + + private inline fun isWhitespace(c: Byte): Boolean { + val flags = parseFlags + // return c == '\r'.toByte() || c == '\n'.toByte() || c == '\t'.toByte() || c == ' '.toByte() + return (flags[c.toInt() and 0xFF] and 2) != 0.toByte() + } + + private fun reset() { + readPos = 0 + output.clear() + scopes.reset() + } + + private fun nextToken(data: ReadBuffer): Token { + val scope = this.scopes.last + + when (scope) { + SCOPE_ARRAY_EMPTY -> this.scopes.last = SCOPE_ARRAY_FILLED + SCOPE_ARRAY_FILLED -> { + when (val c = skipWhitespace(data)) { + CHAR_CLOSE_ARRAY -> return TOK_END_ARRAY + CHAR_COMMA -> Unit + else -> makeError(data, "Unfinished Array", c) + } + } + SCOPE_OBJ_EMPTY, SCOPE_OBJ_FILLED -> { + this.scopes.last = SCOPE_OBJ_KEY + // Look for a comma before the next element. + if (scope == SCOPE_OBJ_FILLED) { + when (val c = skipWhitespace(data)) { + CHAR_CLOSE_OBJECT -> return TOK_END_OBJECT + CHAR_COMMA -> Unit + else -> makeError(data, "Unfinished Object", c) + } + } + return when (val c = skipWhitespace(data)) { + CHAR_DOUBLE_QUOTE -> TOK_BEGIN_QUOTE + CHAR_CLOSE_OBJECT -> if (scope != SCOPE_OBJ_FILLED) { + TOK_END_OBJECT + } else { + makeError(data, "Expected Key", c) + } + else -> { + makeError(data, "Expected Key/Value", c) + } + } + } + SCOPE_OBJ_KEY -> { + this.scopes.last = SCOPE_OBJ_FILLED + when (val c = skipWhitespace(data)) { + CHAR_COLON -> Unit + else -> makeError(data, "Expect ${CHAR_COLON.print()}", c) + } + } + SCOPE_DOC_EMPTY -> this.scopes.last = SCOPE_DOC_FILLED + SCOPE_DOC_FILLED -> { + val c = skipWhitespace(data) + if (c != CHAR_EOF) + makeError(data, "Root object already finished", c) + return TOK_EOF + } + } + + val c = skipWhitespace(data) + when (c) { + CHAR_CLOSE_ARRAY -> if (scope == SCOPE_ARRAY_EMPTY) return TOK_END_ARRAY + CHAR_COLON -> makeError(data, "Unexpected character", c) + CHAR_DOUBLE_QUOTE -> return TOK_BEGIN_QUOTE + CHAR_OPEN_ARRAY -> return TOK_BEGIN_ARRAY + CHAR_OPEN_OBJECT -> return TOK_BEGIN_OBJECT + CHAR_t -> { + checkEOF(data, readPos + 2) + // 0x65757274 is equivalent to ['t', 'r', 'u', 'e' ] as a 4 byte Int + if (data.getInt(readPos - 1) != 0x65757274) { + makeError(data, "Expecting keyword \"true\"", c) + } + readPos += 3 + return TOK_TRUE + } + CHAR_n -> { + checkEOF(data, readPos + 2) + // 0x6c6c756e is equivalent to ['n', 'u', 'l', 'l' ] as a 4 byte Int + if (data.getInt(readPos - 1) != 0x6c6c756e) { + makeError(data, "Expecting keyword \"null\"", c) + } + readPos += 3 + return TOK_NULL + } + CHAR_f -> { + checkEOF(data, readPos + 3) + // 0x65736c61 is equivalent to ['a', 'l', 's', 'e' ] as a 4 byte Int + if (data.getInt(readPos) != 0x65736c61) { + makeError(data, "Expecting keyword \"false\"", c) + } + readPos += 4 + return TOK_FALSE + } + CHAR_0, CHAR_1, CHAR_2, CHAR_3, CHAR_4, CHAR_5, + CHAR_6, CHAR_7, CHAR_8, CHAR_9, CHAR_MINUS -> return TOK_NUMBER.also { + readPos-- // rewind one position so we don't lose first digit + } + } + makeError(data, "Expecting element", c) + } + + // keeps increasing [readPos] until finds a non-whitespace byte + private inline fun skipWhitespace(data: ReadBuffer): Byte { + val limit = data.limit + if (data is ArrayReadBuffer) { + // enables range check elimination + val ary = data.data() + return skipWhitespace(limit) { ary[it] } + } + return skipWhitespace(limit) { data[it] } + } + + private inline fun skipWhitespace(limit: Int, crossinline fetch: (Int) -> Byte): Byte { + var pos = readPos + while (pos < limit) { + val d = fetch(pos++) + if (!isWhitespace(d)) { + readPos = pos + return d + } + } + readPos = limit + return CHAR_EOF + } + + // byte1 is expected to be first char before `\` + private fun readEscapedChar(data: ReadBuffer, byte1: Byte, cursorPos: Int): Char { + return when (byte1) { + CHAR_u -> { + checkEOF(data, cursorPos + 1 + 4) + var result: Char = 0.toChar() + var i = cursorPos + 2 // cursorPos is on '\\', cursorPos + 1 is 'u' + val end = i + 4 + while (i < end) { + val part: Byte = data[i] + result = (result.code shl 4).toChar() + result += when (part) { + in CHAR_0..CHAR_9 -> part - CHAR_0 + in CHAR_a..CHAR_f -> part - CHAR_a + 10 + in CHAR_A..CHAR_F -> part - CHAR_A + 10 + else -> makeError(data, "Invalid utf8 escaped character", -1) + } + i++ + } + result + } + CHAR_b -> '\b' + CHAR_t -> '\t' + CHAR_r -> '\r' + CHAR_n -> '\n' + CHAR_f -> 12.toChar() // '\f' + CHAR_DOUBLE_QUOTE, CHAR_BACKSLASH, CHAR_FORWARDSLASH -> byte1.toInt().toChar() + else -> makeError(data, "Invalid escape sequence.", byte1) + } + } + + private fun Byte.print(): String = when (this) { + in 0x21..0x7E -> "'${this.toInt().toChar()}'" // visible ascii chars + CHAR_EOF -> "EOF" + else -> "'0x${this.toString(16)}'" + } + + private inline fun makeError(data: ReadBuffer, msg: String, tok: Byte? = null): Nothing { + val (line, column) = calculateErrorPosition(data, readPos) + if (tok != null) { + error("Error At ($line, $column): $msg, got ${tok.print()}") + } else { + error("Error At ($line, $column): $msg") + } + } + + private inline fun makeError(data: ReadBuffer, msg: String, tok: Token): Nothing { + val (line, column) = calculateErrorPosition(data, readPos) + error("Error At ($line, $column): $msg, got ${tok.print()}") + } + + private inline fun checkEOF(data: ReadBuffer, pos: Int) { + if (pos >= data.limit) + makeError(data, "Unexpected end of file", -1) + } + + private fun calculateErrorPosition(data: ReadBuffer, endPos: Int): Pair { + var line = 1 + var column = 1 + var current = 0 + while (current < endPos - 1) { + if (data[current++] == CHAR_NEWLINE) { + ++line + column = 1 + } else { + ++column + } + } + return Pair(line, column) + } +} + +internal inline fun Int.toPaddedHex(): String = "\\u${this.toString(16).padStart(4, '0')}" + +private inline fun ReadWriteBuffer.jsonEscape(data: ReadBuffer, start: Int, size: Int) { + val replacements = JSON_ESCAPE_CHARS + put(CHAR_DOUBLE_QUOTE) + var last = start + val length: Int = size + val ary = data.data() + for (i in start until start + length) { + val c = ary[i].toUByte() + var replacement: ByteArray? + if (c.toInt() < 128) { + replacement = replacements[c.toInt()] + if (replacement == null) { + continue + } + } else { + continue + } + if (last < i) { + put(ary, last, i - last) + } + put(replacement, 0, replacement.size) + last = i + 1 + } + if (last < (last + length)) { + put(ary, last, (start + length) - last) + } + put(CHAR_DOUBLE_QUOTE) +} + +// Following escape strategy defined in RFC7159. +private val JSON_ESCAPE_CHARS: Array = arrayOfNulls(128).apply { + this['\n'.code] = "\\n".encodeToByteArray() + this['\t'.code] = "\\t".encodeToByteArray() + this['\r'.code] = "\\r".encodeToByteArray() + this['\b'.code] = "\\b".encodeToByteArray() + this[0x0c] = "\\f".encodeToByteArray() + this['"'.code] = "\\\"".encodeToByteArray() + this['\\'.code] = "\\\\".encodeToByteArray() + for (i in 0..0x1f) { + this[i] = "\\u${i.toPaddedHex()}".encodeToByteArray() + } +} + +// Scope is used to the define current space that the scanner is operating. +@JvmInline +private value class Scope(val id: Int) +private val SCOPE_DOC_EMPTY = Scope(0) +private val SCOPE_DOC_FILLED = Scope(1) +private val SCOPE_OBJ_EMPTY = Scope(2) +private val SCOPE_OBJ_KEY = Scope(3) +private val SCOPE_OBJ_FILLED = Scope(4) +private val SCOPE_ARRAY_EMPTY = Scope(5) +private val SCOPE_ARRAY_FILLED = Scope(6) + +// Keeps the stack state of the scopes being scanned. Currently defined to have a +// max stack size of 22, as per tests cases defined in http://json.org/JSON_checker/ +private class ScopeStack( + private val ary: IntArray = IntArray(22) { SCOPE_DOC_EMPTY.id }, + var lastPos: Int = 0 +) { + var last: Scope + get() = Scope(ary[lastPos]) + set(x) { + ary[lastPos] = x.id + } + + fun reset() { + lastPos = 0 + ary[0] = SCOPE_DOC_EMPTY.id + } + + fun pop(): Scope { + // println("Popping: ${last.print()}") + return Scope(ary[lastPos--]) + } + + fun push(scope: Scope): Scope { + if (lastPos == ary.size - 1) + error("Too much nesting reached. Max nesting is ${ary.size} levels") + // println("PUSHING : ${scope.print()}") + ary[++lastPos] = scope.id + return scope + } +} + +@JvmInline +private value class Token(val id: Int) { + fun print(): String = when (this) { + TOK_EOF -> "TOK_EOF" + TOK_NONE -> "TOK_NONE" + TOK_BEGIN_OBJECT -> "TOK_BEGIN_OBJECT" + TOK_END_OBJECT -> "TOK_END_OBJECT" + TOK_BEGIN_ARRAY -> "TOK_BEGIN_ARRAY" + TOK_END_ARRAY -> "TOK_END_ARRAY" + TOK_NUMBER -> "TOK_NUMBER" + TOK_TRUE -> "TOK_TRUE" + TOK_FALSE -> "TOK_FALSE" + TOK_NULL -> "TOK_NULL" + TOK_BEGIN_QUOTE -> "TOK_BEGIN_QUOTE" + else -> this.toString() + } +} + +private val TOK_EOF = Token(-1) +private val TOK_NONE = Token(0) +private val TOK_BEGIN_OBJECT = Token(1) +private val TOK_END_OBJECT = Token(2) +private val TOK_BEGIN_ARRAY = Token(3) +private val TOK_END_ARRAY = Token(4) +private val TOK_NUMBER = Token(5) +private val TOK_TRUE = Token(6) +private val TOK_FALSE = Token(7) +private val TOK_NULL = Token(8) +private val TOK_BEGIN_QUOTE = Token(9) + +private const val CHAR_NEWLINE = '\n'.code.toByte() +private const val CHAR_OPEN_OBJECT = '{'.code.toByte() +private const val CHAR_COLON = ':'.code.toByte() +private const val CHAR_CLOSE_OBJECT = '}'.code.toByte() +private const val CHAR_OPEN_ARRAY = '['.code.toByte() +private const val CHAR_CLOSE_ARRAY = ']'.code.toByte() +private const val CHAR_DOUBLE_QUOTE = '"'.code.toByte() +private const val CHAR_BACKSLASH = '\\'.code.toByte() +private const val CHAR_FORWARDSLASH = '/'.code.toByte() +private const val CHAR_f = 'f'.code.toByte() +private const val CHAR_a = 'a'.code.toByte() +private const val CHAR_r = 'r'.code.toByte() +private const val CHAR_t = 't'.code.toByte() +private const val CHAR_n = 'n'.code.toByte() +private const val CHAR_b = 'b'.code.toByte() +private const val CHAR_e = 'e'.code.toByte() +private const val CHAR_E = 'E'.code.toByte() +private const val CHAR_u = 'u'.code.toByte() +private const val CHAR_A = 'A'.code.toByte() +private const val CHAR_F = 'F'.code.toByte() +private const val CHAR_EOF = (-1).toByte() +private const val CHAR_COMMA = ','.code.toByte() +private const val CHAR_0 = '0'.code.toByte() +private const val CHAR_1 = '1'.code.toByte() +private const val CHAR_2 = '2'.code.toByte() +private const val CHAR_3 = '3'.code.toByte() +private const val CHAR_4 = '4'.code.toByte() +private const val CHAR_5 = '5'.code.toByte() +private const val CHAR_6 = '6'.code.toByte() +private const val CHAR_7 = '7'.code.toByte() +private const val CHAR_8 = '8'.code.toByte() +private const val CHAR_9 = '9'.code.toByte() +private const val CHAR_MINUS = '-'.code.toByte() +private const val CHAR_PLUS = '+'.code.toByte() +private const val CHAR_DOT = '.'.code.toByte() + +// This template utilizes the One Definition Rule to create global arrays in a +// header. As seen in: +// https://github.com/chadaustin/sajson/blob/master/include/sajson.h +// bit 0 (1) - set if: plain ASCII string character +// bit 1 (2) - set if: whitespace +// bit 4 (0x10) - set if: 0-9 e E . +private val parseFlags = byteArrayOf( +// 0 1 2 3 4 5 6 7 8 9 A B C D E F + 0, 0, 0, 0, 0, 0, 0, 0, 0, 2, 2, 0, 0, 2, 0, 0, // 0 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, // 1 + 3, 1, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0x11, 1, // 2 + 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 1, 1, 1, 1, 1, 1, // 3 + 1, 1, 1, 1, 1, 0x11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 4 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 1, 1, 1, // 5 + 1, 1, 1, 1, 1, 0x11, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 6 + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, // 7 + + // 128-255 + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +) diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/Asserts.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/Asserts.kt new file mode 100644 index 00000000000..563a5a6bc46 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/Asserts.kt @@ -0,0 +1,55 @@ +package com.google.flatbuffers.kotlin + +import kotlin.test.assertTrue + +fun assertArrayEquals(expected: Array, actual: Array) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun assertArrayEquals(expected: IntArray, actual: IntArray) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun assertArrayEquals(expected: ShortArray, actual: ShortArray) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun assertArrayEquals(expected: LongArray, actual: LongArray) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun assertArrayEquals(expected: ByteArray, actual: ByteArray) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun assertArrayEquals(expected: DoubleArray, actual: DoubleArray) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun assertArrayEquals(expected: FloatArray, actual: FloatArray) = + assertTrue(expected contentEquals actual, arrayFailMessage(expected, actual)) + +fun arrayFailMessage(expected: Array, actual: Array): String = + failMessage(expected.contentToString(), actual.contentToString()) + +fun arrayFailMessage(expected: IntArray, actual: IntArray): String = + failMessage(expected.contentToString(), actual.contentToString()) + +fun arrayFailMessage(expected: ShortArray, actual: ShortArray): String = + failMessage(expected.contentToString(), actual.contentToString()) + +fun arrayFailMessage(expected: LongArray, actual: LongArray): String = + failMessage(expected.contentToString(), actual.contentToString()) + +fun failMessage(expected: String, actual: String): String = + "Expected: $expected\nActual: $actual" + +fun arrayFailMessage(expected: FloatArray, actual: FloatArray): String { + return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}" +} + +fun arrayFailMessage(expected: DoubleArray, actual: DoubleArray): String { + return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}" +} + +fun arrayFailMessage(expected: BooleanArray, actual: BooleanArray): String { + return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}" +} + +fun arrayFailMessage(expected: ByteArray, actual: ByteArray): String { + return "Expected: ${expected.contentToString()}\nActual: ${actual.contentToString()}" +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/BuffersTest.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/BuffersTest.kt new file mode 100644 index 00000000000..acae4dd384d --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/BuffersTest.kt @@ -0,0 +1,78 @@ +package com.google.flatbuffers.kotlin + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith + +class BuffersTest { + + @Test + fun readBufferStringTest() { + val text = "Hello world!" + val bytes = text.encodeToByteArray() + val fullRead = ArrayReadBuffer(bytes) + val helloRead = ArrayReadBuffer(bytes, limit = 5) + val worldRead = fullRead.slice(6, 6) + + assertEquals(bytes.size, fullRead.limit) + assertEquals(text, fullRead.getString(0, fullRead.limit)) + assertEquals("Hello" , helloRead.getString(0, helloRead.limit)) + assertEquals("world!" , worldRead.getString()) + assertEquals(fullRead.getString(0, 5) , helloRead.getString(0, helloRead.limit)) + assertEquals(fullRead.getString(6, 6) , worldRead.getString(0, worldRead.limit)) + + for (i in 0 until helloRead.limit) { + assertEquals(fullRead[i], helloRead[i]) + } + for (i in 0 until worldRead.limit) { + assertEquals(fullRead[6 + i], worldRead[i]) + } + } + + @Test + fun readWriteBufferPrimitivesTest() { + val text = "Hello world!" + val bytes = text.encodeToByteArray() + val wt = ArrayReadWriteBuffer(bytes) + wt.requestCapacity(4096) + wt.put("Tests") + val str1 = wt.writePosition + assertEquals("Tests world!", wt.getString(0, bytes.size)) + assertEquals("Tests", wt.getString(0, str1)) + wt.put(Int.MAX_VALUE) + assertEquals(Int.MAX_VALUE, wt.getInt(str1)) + + val pos = wt.writePosition + wt.put(Double.NEGATIVE_INFINITY) + assertEquals(Double.NEGATIVE_INFINITY, wt.getDouble(pos)) + + val jap = " are really すごい!".encodeToByteArray() + wt.writePosition = str1 + wt.put(jap) + assertEquals("Tests are really すごい!", wt.getString()) + } + + @Test + fun readWriteBufferGrowthTest() { + val a = ArrayReadWriteBuffer(1) + assertEquals(1, a.capacity) + a.put(0.toByte()) + assertEquals(1, a.capacity) + assertFailsWith(IndexOutOfBoundsException::class) { a.put(0xFF.toShort()) } + a.requestCapacity(8) + a.writePosition = 0 + a.put(0xFF.toShort()) + assertEquals(8, a.capacity) + assertEquals(0xFF, a.getShort(0)) + + a.requestCapacity(8 + 12) + a.put(ByteArray(12) { it.toByte() }) + + // we grow as power or two, so 20 jumps to 32 + assertEquals(32, a.capacity) + a.requestCapacity(513, false) + assertEquals(1024, a.capacity) + a.requestCapacity(234, false) + assertEquals(1024, a.capacity) + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/ByteArrayTest.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/ByteArrayTest.kt new file mode 100644 index 00000000000..776ab9574bc --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/ByteArrayTest.kt @@ -0,0 +1,147 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class ByteArrayTest { + + @Test + fun testByte() { + val testSet = arrayOf( + 67.toByte() to byteArrayOf(67), + Byte.MIN_VALUE to byteArrayOf(-128), + Byte.MAX_VALUE to byteArrayOf(127), + 0.toByte() to byteArrayOf(0) + ) + val data = ByteArray(1) + testSet.forEach { + data[0] = it.first + assertArrayEquals(data, it.second) + assertEquals(it.first, data[0]) + } + } + + @Test + fun testShort() { + val testSet = arrayOf( + 6712.toShort() to byteArrayOf(56, 26), + Short.MIN_VALUE to byteArrayOf(0, -128), + Short.MAX_VALUE to byteArrayOf(-1, 127), + 0.toShort() to byteArrayOf(0, 0,) + ) + + val data = ByteArray(Short.SIZE_BYTES) + testSet.forEach { + data.setShort(0, it.first) + assertArrayEquals(data, it.second) + assertEquals(it.first, data.getShort(0)) + } + } + + @Test + fun testInt() { + val testSet = arrayOf( + 33333500 to byteArrayOf(-4, -96, -4, 1), + Int.MIN_VALUE to byteArrayOf(0, 0, 0, -128), + Int.MAX_VALUE to byteArrayOf(-1, -1, -1, 127), + 0 to byteArrayOf(0, 0, 0, 0) + ) + val data = ByteArray(Int.SIZE_BYTES) + testSet.forEach { + data.setInt(0, it.first) + assertArrayEquals(data, it.second) + assertEquals(it.first, data.getInt(0)) + } + } + + @Test + fun testLong() { + val testSet = arrayOf( + 1234567123122890123L to byteArrayOf(-117, -91, 29, -23, 65, 16, 34, 17), + -1L to byteArrayOf(-1, -1, -1, -1, -1, -1, -1, -1), + Long.MIN_VALUE to byteArrayOf(0, 0, 0, 0, 0, 0, 0, -128), + Long.MAX_VALUE to byteArrayOf(-1, -1, -1, -1, -1, -1, -1, 127), + 0L to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0) + ) + val data = ByteArray(Long.SIZE_BYTES) + testSet.forEach { + data.setLong(0, it.first) + assertArrayEquals(data, it.second) + assertEquals(it.first, data.getLong(0)) + } + } + + @Test + fun testULong() { + val testSet = arrayOf( + 1234567123122890123UL to byteArrayOf(-117, -91, 29, -23, 65, 16, 34, 17), + ULong.MIN_VALUE to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0), + (-1L).toULong() to byteArrayOf(-1, -1, -1, -1, -1, -1, -1, -1), + 0UL to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0) + ) + val data = ByteArray(ULong.SIZE_BYTES) + testSet.forEach { + data.setULong(0, it.first) + assertArrayEquals(it.second, data) + assertEquals(it.first, data.getULong(0)) + } + } + + @Test + fun testFloat() { + val testSet = arrayOf( + 3545.56337f to byteArrayOf(4, -103, 93, 69), + Float.MIN_VALUE to byteArrayOf(1, 0, 0, 0), + Float.MAX_VALUE to byteArrayOf(-1, -1, 127, 127), + 0f to byteArrayOf(0, 0, 0, 0) + ) + val data = ByteArray(Float.SIZE_BYTES) + testSet.forEach { + data.setFloat(0, it.first) + assertArrayEquals(data, it.second) + } + } + + @Test + fun testDouble() { + val testSet = arrayOf( + 123456.523423423412 to byteArrayOf(88, 61, -15, 95, 8, 36, -2, 64), + Double.MIN_VALUE to byteArrayOf(1, 0, 0, 0, 0, 0, 0, 0), + Double.MAX_VALUE to byteArrayOf(-1, -1, -1, -1, -1, -1, -17, 127), + 0.0 to byteArrayOf(0, 0, 0, 0, 0, 0, 0, 0) + ) + val data = ByteArray(Long.SIZE_BYTES) + testSet.forEach { + data.setDouble(0, it.first) + assertArrayEquals(data, it.second) + assertEquals(it.first, data.getDouble(0)) + } + } + + @Test + fun testString() { + val testSet = "∮ E⋅da = Q" + val encoded = testSet.encodeToByteArray() + val data = ByteArray(encoded.size) + data.setCharSequence(0, testSet) + assertArrayEquals(encoded, data) + assertEquals(testSet, data.getString(0, encoded.size)) + } +} + diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlatBufferBuilderTest.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlatBufferBuilderTest.kt new file mode 100644 index 00000000000..90c10215b56 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlatBufferBuilderTest.kt @@ -0,0 +1,575 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("UNCHECKED_CAST") + +package com.google.flatbuffers.kotlin + +import Attacker +import AttackerOffsetArray +import CharacterEArray +import dictionaryLookup.LongFloatEntry +import dictionaryLookup.LongFloatMap +import Movie +import dictionaryLookup.LongFloatEntryOffsetArray +import myGame.example.* +import myGame.example.Test.Companion.createTest +import optionalScalars.OptionalByte +import optionalScalars.ScalarStuff +import kotlin.test.Test +import kotlin.test.assertEquals + + +@ExperimentalUnsignedTypes +class FlatBufferBuilderTest { + + @Test + fun testSingleTable() { + val fbb = FlatBufferBuilder() + val name = fbb.createString("Frodo") + val invValues = ubyteArrayOf(10u, 11u, 12u, 13u, 14u) + val inv = Monster.createInventoryVector(fbb, invValues) + Monster.startMonster(fbb) + Monster.addPos( + fbb, Vec3.createVec3( + fbb, 1.0f, 2.0f, 3.0f, 3.0, + Color.Green, 5.toShort(), 6.toByte() + ) + ) + Monster.addHp(fbb, 80.toShort()) + Monster.addName(fbb, name) + Monster.addMana(fbb, 150) + Monster.addInventory(fbb, inv) + Monster.addTestType(fbb, AnyE.Monster) + Monster.addTestbool(fbb, true) + Monster.addTesthashu32Fnv1(fbb, (Int.MAX_VALUE + 1L).toUInt()) + val root = Monster.endMonster(fbb) + fbb.finish(root) + + val monster = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monster.name, "Frodo") + assertEquals(monster.mana, 150.toShort()) + assertEquals(monster.hp, 80) + + val pos = monster.pos!! + assertEquals(monster.inventory(0), invValues[0]) + assertEquals(monster.inventory(1), invValues[1]) + assertEquals(monster.inventory(2), invValues[2]) + assertEquals(monster.inventory(3), invValues[3]) + assertEquals(pos.x, 1.0f) + assertEquals(pos.y, 2.0f) + assertEquals(pos.z, 3.0f) + assertEquals(pos.test1, 3.0) + assertEquals(pos.test2, Color.Green) + assertEquals(pos.test3!!.a, 5.toShort()) + assertEquals(pos.test3!!.b, 6.toByte()) + + val inventoryBuffer = monster.inventoryAsBuffer() + assertEquals(invValues.size, inventoryBuffer.limit) + for (i in invValues.indices) { + assertEquals(invValues[i], inventoryBuffer.getUByte(i)) + } + } + + @Test + fun testSortedVector() { + val fbb = FlatBufferBuilder() + val names = arrayOf(fbb.createString("Frodo"), fbb.createString("Barney"), fbb.createString("Wilma")) + val monsters = MonsterOffsetArray(3) { + Monster.startMonster(fbb) + Monster.addName(fbb, names[it]) + Monster.endMonster(fbb) + } + val ary = Monster.createTestarrayoftablesVector(fbb, monsters) + Monster.startMonster(fbb) + Monster.addName(fbb, names[0]) + Monster.addTestarrayoftables(fbb, ary) + val root = Monster.endMonster(fbb) + fbb.finish(root) + val a = Monster.asRoot(fbb.dataBuffer()) + assertEquals(a.name, "Frodo") + assertEquals(a.testarrayoftablesLength, 3) + val monster0 = a.testarrayoftables(0)!! + val monster1 = a.testarrayoftables(1)!! + val monster2 = a.testarrayoftables(2)!! + assertEquals(monster0.name, "Frodo") + assertEquals(monster1.name, "Barney") + assertEquals(monster2.name, "Wilma") + + // test AsBuffer feature + + } + + @Test + fun testCreateBufferVector() { + val fbb = FlatBufferBuilder(16) + val str = fbb.createString("MyMonster") + val inventory = ubyteArrayOf(0u, 1u, 2u, 3u, 4u, 5u, 6u, 88u, 99u, 122u, 1u) + val vec = Monster.createInventoryVector(fbb, inventory) + Monster.startMonster(fbb) + Monster.addInventory(fbb, vec) + Monster.addName(fbb, str) + val monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + val monsterObject: Monster = Monster.asRoot(fbb.dataBuffer()) + val iBuffer = monsterObject.inventoryAsBuffer() + + assertEquals(monsterObject.inventoryLength, inventory.size) + assertEquals(iBuffer.limit, inventory.size) + + for (i in inventory.indices) { + assertEquals(inventory[i], monsterObject.inventory(i)) + assertEquals(inventory[i], iBuffer.getUByte(i)) + } + } + + @Test + fun testCreateUninitializedVector() { + val fbb = FlatBufferBuilder(16) + val str = fbb.createString("MyMonster") + val inventory = byteArrayOf(10, 11, 12, 13, 14) + val uninitializedBuffer = fbb.createUnintializedVector(1, inventory.size, 1) + for (i in inventory) { + uninitializedBuffer.put(i) + } + val vec = fbb.endVector() + Monster.startMonster(fbb) + Monster.addInventory(fbb, vec) + Monster.addName(fbb, str) + val monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + val monsterObject: Monster = Monster.asRoot(fbb.dataBuffer()) + assertEquals(inventory[1].toUByte(), monsterObject.inventory(1)) + assertEquals(inventory.size, monsterObject.inventoryLength) + val inventoryBuffer = monsterObject.inventoryAsBuffer() + assertEquals(inventory[1].toInt().toUByte(), inventoryBuffer.getUByte(1)) + assertEquals(inventory.size, inventoryBuffer.limit) + } + + @Test + fun testBuilderBasics() { + val fbb = FlatBufferBuilder() + val names = arrayOf(fbb.createString("Frodo"), fbb.createString("Barney"), fbb.createString("Wilma")) + val off = Array>(3) { Offset(0) } + Monster.startMonster(fbb) + Monster.addName(fbb, names[0]) + off[0] = Monster.endMonster(fbb) + Monster.startMonster(fbb) + Monster.addName(fbb, names[1]) + off[1] = Monster.endMonster(fbb) + Monster.startMonster(fbb) + Monster.addName(fbb, names[2]) + off[2] = Monster.endMonster(fbb) + val sortMons = fbb.createSortedVectorOfTables(Monster(), off) + + // We set up the same values as monsterdata.json: + + val inv = Monster.createInventoryVector(fbb, byteArrayOf(0,1,2,3,4).toUByteArray()) + + val fred = fbb.createString("Fred") + Monster.startMonster(fbb) + Monster.addName(fbb, fred) + val mon2 = Monster.endMonster(fbb) + + Monster.startTest4Vector(fbb, 2) + createTest(fbb, 10.toShort(), 20.toByte()) + createTest(fbb, 30.toShort(), 40.toByte()) + val test4 = fbb.endVector() + + val strings = StringOffsetArray(2) { fbb.createString("test$it") } + val testArrayOfString = + Monster.createTestarrayofstringVector(fbb, strings) + + Monster.startMonster(fbb) + Monster.addName(fbb, names[0]) + Monster.addPos(fbb, Vec3.createVec3( + fbb, 1.0f, 2.0f, 3.0f, 3.0, + Color.Green, 5.toShort(), 6.toByte() + )) + Monster.addHp(fbb, 80) + Monster.addMana(fbb, 150) + Monster.addInventory(fbb, inv) + Monster.addTestType(fbb, AnyE.Monster) + Monster.addTest(fbb, mon2.toUnion()) + Monster.addTest4(fbb, test4) + Monster.addTestarrayofstring(fbb, testArrayOfString) + Monster.addTestbool(fbb, true) + Monster.addTesthashu32Fnv1(fbb, (Int.MAX_VALUE + 1L).toUInt()) + Monster.addTestarrayoftables(fbb, sortMons) + val mon = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, mon) + //Attempt to mutate Monster fields and check whether the buffer has been mutated properly + // revert to original values after testing + val monster = Monster.asRoot(fbb.dataBuffer()) + + // mana is optional and does not exist in the buffer so the mutation should fail + // the mana field should retain its default value + assertEquals(monster.mana, 150.toShort()) + assertEquals(monster.hp, 80) + + // Accessing a vector of sorted by the key tables + assertEquals(monster.testarrayoftables(0)!!.name, "Barney") + assertEquals(monster.testarrayoftables(1)!!.name, "Frodo") + assertEquals(monster.testarrayoftables(2)!!.name, "Wilma") + + // Example of searching for a table by the key + assertEquals(monster.testarrayoftablesByKey("Frodo")!!.name, "Frodo") + assertEquals(monster.testarrayoftablesByKey("Barney")!!.name, "Barney") + assertEquals(monster.testarrayoftablesByKey("Wilma")!!.name, "Wilma") + + for (i in 0 until monster.inventoryLength) { + assertEquals(monster.inventory(i), (i).toUByte()) + } + + // get a struct field and edit one of its fields + val pos2 = monster.pos!! + assertEquals(pos2.x, 1.0f) + assertEquals(pos2.test2, Color.Green) + } + + @Test + fun testVectorOfUnions() { + val fbb = FlatBufferBuilder() + val swordAttackDamage = 1 + val attacker = Attacker.createAttacker(fbb, swordAttackDamage).toUnion() + val attackers = UnionOffsetArray(1) { attacker } + val characters = CharacterEArray(1) + characters[0] = CharacterE.MuLan.value + + Movie.finishMovieBuffer( + fbb, + Movie.createMovie( + fbb, + CharacterE.MuLan, + attacker, + Movie.createCharactersTypeVector(fbb, characters), + Movie.createCharactersVector(fbb, attackers) + ) + ) + + val movie: Movie = Movie.asRoot(fbb.dataBuffer()) + + + + assertEquals(movie.charactersTypeLength, 1) + assertEquals(movie.charactersLength, 1) + + assertEquals(movie.charactersType(0), CharacterE.MuLan) + assertEquals((movie.characters(Attacker(), 0) as Attacker).swordAttackDamage, swordAttackDamage) + } + + @Test + fun TestVectorOfBytes() { + val fbb = FlatBufferBuilder(16) + var str = fbb.createString("ByteMonster") + val data = ubyteArrayOf(0u, 1u, 2u, 3u, 4u, 5u, 6u, 7u, 8u, 9u) + var offset = Monster.createInventoryVector(fbb, data) + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + var monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + + val monsterObject = Monster.asRoot(fbb.dataBuffer()) + assertEquals("ByteMonster", monsterObject.name) + assertEquals(data.size, monsterObject.inventoryLength) + assertEquals(monsterObject.inventory(4), data[4]) + offset = fbb.createByteVector(data.toByteArray()) as VectorOffset // TODO: fix me + str = fbb.createString("ByteMonster") + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + + val monsterObject2 = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monsterObject2.inventoryLength, data.size) + for (i in data.indices) { + assertEquals(monsterObject2.inventory(i), data[i]) + } + fbb.clear() + offset = fbb.createByteVector(data.toByteArray(), 3, 4) as VectorOffset + str = fbb.createString("ByteMonster") + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + + val monsterObject3 = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monsterObject3.inventoryLength, 4) + assertEquals(monsterObject3.inventory(0), data[3]) + fbb.clear() + offset = Monster.createInventoryVector(fbb, data) + str = fbb.createString("ByteMonster") + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + + val monsterObject4 = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monsterObject4.inventoryLength, data.size) + assertEquals(monsterObject4.inventory(8), 8u) + fbb.clear() + + val largeData = ByteArray(1024) + offset = fbb.createByteVector(largeData) as VectorOffset //TODO: fix me + str = fbb.createString("ByteMonster") + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + + val monsterObject5 = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monsterObject5.inventoryLength, largeData.size) + assertEquals(monsterObject5.inventory(25), largeData[25].toUByte()) + fbb.clear() + + var bb = ArrayReadBuffer(largeData, 512) + offset = fbb.createByteVector(bb) as VectorOffset //TODO: fix me + str = fbb.createString("ByteMonster") + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + val monsterObject6 = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monsterObject6.inventoryLength, 512) + assertEquals(monsterObject6.inventory(0), largeData[0].toUByte()) + fbb.clear() + + bb = ArrayReadBuffer(largeData, largeData.size - 216) + val stringBuffer = ArrayReadBuffer("AlreadyBufferedString".encodeToByteArray()) + offset = fbb.createByteVector(bb) as VectorOffset //TODO: fix me + str = fbb.createString(stringBuffer) + Monster.startMonster(fbb) + Monster.addName(fbb, str) + Monster.addInventory(fbb, offset) + monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + + val monsterObject7 = Monster.asRoot(fbb.dataBuffer()) + assertEquals(monsterObject7.inventoryLength, 216) + assertEquals("AlreadyBufferedString", monsterObject7.name) + } + + @Test + fun testEnums() { + assertEquals(Color.name(Color.Red), "Red") + assertEquals(Color.name(Color.Blue), "Blue") + assertEquals(AnyE.name(AnyE.None), "NONE") + assertEquals(AnyE.name(AnyE.Monster), "Monster") + } + + @Test + fun testSharedStringPool() { + val fb = FlatBufferBuilder(1) + val testString = "My string" + val offset = fb.createSharedString(testString) + for (i in 0..9) { + assertEquals(offset, fb.createSharedString(testString)) + } + } + + @Test + fun testScalarOptional() { + val fbb = FlatBufferBuilder(1) + ScalarStuff.startScalarStuff(fbb) + var pos = ScalarStuff.endScalarStuff(fbb) + fbb.finish(pos) + var scalarStuff: ScalarStuff = ScalarStuff.asRoot(fbb.dataBuffer()) + assertEquals(scalarStuff.justI8, 0.toByte()) + assertEquals(scalarStuff.maybeI8, null) + assertEquals(scalarStuff.defaultI8, 42.toByte()) + assertEquals(scalarStuff.justU8, 0u) + assertEquals(scalarStuff.maybeU8, null) + assertEquals(scalarStuff.defaultU8, 42u) + assertEquals(scalarStuff.justI16, 0.toShort()) + assertEquals(scalarStuff.maybeI16, null) + assertEquals(scalarStuff.defaultI16, 42.toShort()) + assertEquals(scalarStuff.justU16, 0u) + assertEquals(scalarStuff.maybeU16, null) + assertEquals(scalarStuff.defaultU16, 42u) + assertEquals(scalarStuff.justI32, 0) + assertEquals(scalarStuff.maybeI32, null) + assertEquals(scalarStuff.defaultI32, 42) + assertEquals(scalarStuff.justU32, 0u) + assertEquals(scalarStuff.maybeU32, null) + assertEquals(scalarStuff.defaultU32, 42u) + assertEquals(scalarStuff.justI64, 0L) + assertEquals(scalarStuff.maybeI64, null) + assertEquals(scalarStuff.defaultI64, 42L) + assertEquals(scalarStuff.justU64, 0UL) + assertEquals(scalarStuff.maybeU64, null) + assertEquals(scalarStuff.defaultU64, 42UL) + assertEquals(scalarStuff.justF32, 0.0f) + assertEquals(scalarStuff.maybeF32, null) + assertEquals(scalarStuff.defaultF32, 42.0f) + assertEquals(scalarStuff.justF64, 0.0) + assertEquals(scalarStuff.maybeF64, null) + assertEquals(scalarStuff.defaultF64, 42.0) + assertEquals(scalarStuff.justBool, false) + assertEquals(scalarStuff.maybeBool, null) + assertEquals(scalarStuff.defaultBool, true) + assertEquals(scalarStuff.justEnum, OptionalByte.None) + assertEquals(scalarStuff.maybeEnum, null) + assertEquals(scalarStuff.defaultEnum, OptionalByte.One) + fbb.clear() + ScalarStuff.startScalarStuff(fbb) + ScalarStuff.addJustI8(fbb, 5.toByte()) + ScalarStuff.addMaybeI8(fbb, 5.toByte()) + ScalarStuff.addDefaultI8(fbb, 5.toByte()) + ScalarStuff.addJustU8(fbb, 6u) + ScalarStuff.addMaybeU8(fbb, 6u) + ScalarStuff.addDefaultU8(fbb, 6u) + ScalarStuff.addJustI16(fbb, 7.toShort()) + ScalarStuff.addMaybeI16(fbb, 7.toShort()) + ScalarStuff.addDefaultI16(fbb, 7.toShort()) + ScalarStuff.addJustU16(fbb, 8u) + ScalarStuff.addMaybeU16(fbb, 8u) + ScalarStuff.addDefaultU16(fbb, 8u) + ScalarStuff.addJustI32(fbb, 9) + ScalarStuff.addMaybeI32(fbb, 9) + ScalarStuff.addDefaultI32(fbb, 9) + ScalarStuff.addJustU32(fbb, 10u) + ScalarStuff.addMaybeU32(fbb, 10u) + ScalarStuff.addDefaultU32(fbb, 10u) + ScalarStuff.addJustI64(fbb, 11L) + ScalarStuff.addMaybeI64(fbb, 11L) + ScalarStuff.addDefaultI64(fbb, 11L) + ScalarStuff.addJustU64(fbb, 12UL) + ScalarStuff.addMaybeU64(fbb, 12UL) + ScalarStuff.addDefaultU64(fbb, 12UL) + ScalarStuff.addJustF32(fbb, 13.0f) + ScalarStuff.addMaybeF32(fbb, 13.0f) + ScalarStuff.addDefaultF32(fbb, 13.0f) + ScalarStuff.addJustF64(fbb, 14.0) + ScalarStuff.addMaybeF64(fbb, 14.0) + ScalarStuff.addDefaultF64(fbb, 14.0) + ScalarStuff.addJustBool(fbb, true) + ScalarStuff.addMaybeBool(fbb, true) + ScalarStuff.addDefaultBool(fbb, true) + ScalarStuff.addJustEnum(fbb, OptionalByte.Two) + ScalarStuff.addMaybeEnum(fbb, OptionalByte.Two) + ScalarStuff.addDefaultEnum(fbb, OptionalByte.Two) + pos = ScalarStuff.endScalarStuff(fbb) + fbb.finish(pos) + scalarStuff = ScalarStuff.asRoot(fbb.dataBuffer()) + assertEquals(scalarStuff.justI8, 5.toByte()) + assertEquals(scalarStuff.maybeI8, 5.toByte()) + assertEquals(scalarStuff.defaultI8, 5.toByte()) + assertEquals(scalarStuff.justU8, 6u) + assertEquals(scalarStuff.maybeU8, 6u) + assertEquals(scalarStuff.defaultU8, 6u) + assertEquals(scalarStuff.justI16, 7.toShort()) + assertEquals(scalarStuff.maybeI16, 7.toShort()) + assertEquals(scalarStuff.defaultI16, 7.toShort()) + assertEquals(scalarStuff.justU16, 8u) + assertEquals(scalarStuff.maybeU16, 8u) + assertEquals(scalarStuff.defaultU16, 8u) + assertEquals(scalarStuff.justI32, 9) + assertEquals(scalarStuff.maybeI32, 9) + assertEquals(scalarStuff.defaultI32, 9) + assertEquals(scalarStuff.justU32, 10u) + assertEquals(scalarStuff.maybeU32, 10u) + assertEquals(scalarStuff.defaultU32, 10u) + assertEquals(scalarStuff.justI64, 11L) + assertEquals(scalarStuff.maybeI64, 11L) + assertEquals(scalarStuff.defaultI64, 11L) + assertEquals(scalarStuff.justU64, 12UL) + assertEquals(scalarStuff.maybeU64, 12UL) + assertEquals(scalarStuff.defaultU64, 12UL) + assertEquals(scalarStuff.justF32, 13.0f) + assertEquals(scalarStuff.maybeF32, 13.0f) + assertEquals(scalarStuff.defaultF32, 13.0f) + assertEquals(scalarStuff.justF64, 14.0) + assertEquals(scalarStuff.maybeF64, 14.0) + assertEquals(scalarStuff.defaultF64, 14.0) + assertEquals(scalarStuff.justBool, true) + assertEquals(scalarStuff.maybeBool, true) + assertEquals(scalarStuff.defaultBool, true) + assertEquals(scalarStuff.justEnum, OptionalByte.Two) + assertEquals(scalarStuff.maybeEnum, OptionalByte.Two) + assertEquals(scalarStuff.defaultEnum, OptionalByte.Two) + } + +// @todo Seems like nesting code generation is broken for all generators. +// disabling test for now. +// @Test +// fun testNamespaceNesting() { +// // reference / manipulate these to verify compilation +// val fbb = FlatBufferBuilder(1) +// TableInNestedNS.startTableInNestedNS(fbb) +// TableInNestedNS.addFoo(fbb, 1234) +// val nestedTableOff = TableInNestedNS.endTableInNestedNs(fbb) +// TableInFirstNS.startTableInFirstNS(fbb) +// TableInFirstNS.addFooTable(fbb, nestedTableOff) +// TableInFirstNS.endTableInFirstNs(fbb) +// } + + @Test + fun testNestedFlatBuffer() { + val nestedMonsterName = "NestedMonsterName" + val nestedMonsterHp: Short = 600 + val nestedMonsterMana: Short = 1024 + val fbb1 = FlatBufferBuilder(16) + val str1 = fbb1.createString(nestedMonsterName) + Monster.startMonster(fbb1) + Monster.addName(fbb1, str1) + Monster.addHp(fbb1, nestedMonsterHp) + Monster.addMana(fbb1, nestedMonsterMana) + val monster1 = Monster.endMonster(fbb1) + Monster.finishMonsterBuffer(fbb1, monster1) + val fbb1Bytes: ByteArray = fbb1.sizedByteArray() + val fbb2 = FlatBufferBuilder(16) + val str2 = fbb2.createString("My Monster") + val nestedBuffer = Monster.createTestnestedflatbufferVector(fbb2, fbb1Bytes.toUByteArray()) + Monster.startMonster(fbb2) + Monster.addName(fbb2, str2) + Monster.addHp(fbb2, 50.toShort()) + Monster.addMana(fbb2, 32.toShort()) + Monster.addTestnestedflatbuffer(fbb2, nestedBuffer) + val monster = Monster.endMonster(fbb2) + Monster.finishMonsterBuffer(fbb2, monster) + + // Now test the data extracted from the nested buffer + val mons = Monster.asRoot(fbb2.dataBuffer()) + val nestedMonster = mons.testnestedflatbufferAsMonster + assertEquals(nestedMonsterMana, nestedMonster!!.mana) + assertEquals(nestedMonsterHp, nestedMonster.hp) + assertEquals(nestedMonsterName, nestedMonster.name) + } + + @Test + fun testDictionaryLookup() { + val fbb = FlatBufferBuilder(16) + val lfIndex = LongFloatEntry.createLongFloatEntry(fbb, 0, 99.0f) + val vectorEntriesIdx = LongFloatMap.createEntriesVector(fbb, LongFloatEntryOffsetArray(1) { lfIndex }) + val rootIdx = LongFloatMap.createLongFloatMap(fbb, vectorEntriesIdx) + LongFloatMap.finishLongFloatMapBuffer(fbb, rootIdx) + val map: LongFloatMap = LongFloatMap.asRoot(fbb.dataBuffer()) + + assertEquals(1, map.entriesLength) + + val e: LongFloatEntry = map.entries(0)!! + assertEquals(0L, e.key) + assertEquals(99.0f, e.value) + val e2: LongFloatEntry = map.entriesByKey(0)!! + assertEquals(0L, e2.key) + assertEquals(99.0f, e2.value) + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlexBuffersTest.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlexBuffersTest.kt new file mode 100644 index 00000000000..524dd0e0dac --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/FlexBuffersTest.kt @@ -0,0 +1,302 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import com.google.flatbuffers.kotlin.FlexBuffersBuilder.Companion.SHARE_NONE +import kotlin.random.Random +import kotlin.test.Test +import kotlin.test.assertEquals + +class FlexBuffersTest { + + @Test + fun testWriteInt() { + val values = listOf( + Byte.MAX_VALUE.toLong() to 3, + Short.MAX_VALUE.toLong() to 4, + Int.MAX_VALUE.toLong() to 6, + Long.MAX_VALUE to 10 + ) + val builder = FlexBuffersBuilder() + values.forEach { + builder.clear() + builder.put(it.first) + val data = builder.finish() + val ref = getRoot(data) + // although we put a long, it is shrink to a byte + assertEquals(it.second, data.limit) + assertEquals(it.first, ref.toLong()) + } + } + + @Test + fun testWriteUInt() { + val values = listOf( + UByte.MAX_VALUE.toULong() to 3, + UShort.MAX_VALUE.toULong() to 4, + UInt.MAX_VALUE.toULong() to 6, + ULong.MAX_VALUE to 10 + ) + val builder = FlexBuffersBuilder() + values.forEach { + builder.clear() + builder.put(it.first) + val data = builder.finish() + val ref = getRoot(data) + // although we put a long, it is shrink to a byte + assertEquals(it.second, data.limit) + assertEquals(it.first, ref.toULong()) + } + } + + @Test + fun testWriteString() { + val text = "Ḧ̵̘́ȩ̵̐l̶̿͜l̶͚͝o̷̦̚ ̷̫̊w̴̤͊ö̸̞́r̴͎̾l̷͚̐d̶̰̍" + val builder = FlexBuffersBuilder() + builder.put(text) + val data = builder.finish() + val ref = getRoot(data) + assertEquals(text, ref.toString()) + } + + @Test + fun testInt8Array() { + val ary = intArrayOf(1, 2, 3, 4) + val builder = FlexBuffersBuilder() + builder.put(intArrayOf(1, 2, 3, 4)) + val data = builder.finish() + val ref = getRoot(data) + // although we put a long, it is shrink to a byte + assertEquals(8, data.limit) + assertArrayEquals(ary, ref.toIntArray()) + } + + @Test + fun testShortArray() { + val builder = FlexBuffersBuilder(ArrayReadWriteBuffer(20)) + val numbers = ShortArray(10) { it.toShort() } + builder.put(numbers) + val data = builder.finish() + val ref = getRoot(data) + assertArrayEquals(numbers, ref.toShortArray()) + } + + @Test + fun testHugeArray() { + val builder = FlexBuffersBuilder() + val numbers = IntArray(1024) { it } + builder.put(numbers) + val data = builder.finish() + val ref = getRoot(data) + assertArrayEquals(numbers, ref.toIntArray()) + } + + @Test + fun testFloatArray() { + val builder = FlexBuffersBuilder() + val numbers = FloatArray(1024) { it * 0.05f } + builder.put(numbers) + val data = builder.finish() + val ref = getRoot(data) + assertArrayEquals(numbers, ref.toFloatArray()) + } + + @Test + fun testDoubleArray() { + val builder = FlexBuffersBuilder() + val numbers = DoubleArray(1024) { it * 0.0005 } + builder.put(numbers) + val data = builder.finish() + val ref = getRoot(data) + assertArrayEquals(numbers, ref.toDoubleArray()) + } + + @Test + fun testLongArray() { + val ary: LongArray = longArrayOf(0, Short.MIN_VALUE.toLong(), Int.MAX_VALUE.toLong(), Long.MAX_VALUE) + val builder = FlexBuffersBuilder() + builder.put(ary) + val data = builder.finish() + val ref = getRoot(data) + // although we put a long, it is shrink to a byte + assertArrayEquals(ary, ref.toLongArray()) + } + + @Test + fun testStringArray() { + val ary = Array(5) { "Hello world number: $it" } + val builder = FlexBuffersBuilder(ArrayReadWriteBuffer(20), SHARE_NONE) + builder.putVector { + ary.forEach { put(it) } + } + val data = builder.finish() + val vec = getRoot(data).toVector() + // although we put a long, it is shrink to a byte + assertEquals(5, vec.size) + val stringAry = vec.map { it.toString() }.toTypedArray() + // although we put a long, it is shrink to a byte + assertArrayEquals(ary, stringAry) + } + + @Test + fun testBlobArray() { + val ary = ByteArray(1000) { Random.nextInt().toByte() } + val builder = FlexBuffersBuilder() + builder.put(ary) + val data = builder.finish() + val blob = getRoot(data).toBlob() + // although we put a long, it is shrink to a byte + assertArrayEquals(ary, blob.toByteArray()) + for (i in 0 until blob.size) { + assertEquals(ary[i], blob[i]) + } + } + + @Test + fun testArrays() { + val builder = FlexBuffersBuilder() + val ary: Array = Array(5) { "Hello world number: $it" } + val numbers = IntArray(10) { it } + val doubles = DoubleArray(10) { it * 0.35 } + + // add 3 level array of arrays in the following way + // [ [ "..", ...] [ "..", ..., [ "..", ...] ] ] + val vec = builder.startVector() + + // [0, 1, 2, 3 ,4 ,5 ,6 ,7 ,8, 9] + val vec1 = builder.startVector() + numbers.forEach { builder.put(it) } + builder.endTypedVector(vec1) + + // [0, 2, 4, 6 , 8, 10, 12, 14, 16, 18] + builder.putTypedVector { doubles.forEach { put(it) } } + + // nested array + // [ "He..", "He..", "He..", "He..", "He..", [ "He..", "He..", "He..", "He..", "He.." ] ] + val vec3 = builder.startVector() + ary.forEach { builder.put(it) } + builder.putVector { ary.forEach { put("inner: $it") } } + builder.endVector(vec3) + + builder.endVector(vec) + + val data = builder.finish() + val ref = getRoot(data) + val vecRef = getRoot(data).toVector() + // although we put a long, it is shrink to a byte + assertEquals(3, vecRef.size) + + assertArrayEquals(numbers, vecRef[0].toVector().map { it.toInt() }.toIntArray()) + assertArrayEquals(doubles, ref[1].toDoubleArray()) + assertEquals("Hello world number: 4", vecRef[2][4].toString()) + assertEquals("inner: Hello world number: 4", vecRef[2][5][4].toString()) + assertEquals("inner: Hello world number: 4", ref[2][5][4].toString()) + } + + @Test + fun testMap() { + val builder = FlexBuffersBuilder(shareFlag = FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + builder.putVector { + put(10) + putMap { + this["chello"] = "world" + this["aint"] = 10 + this["bfloat"] = 12.3 + } + put("aString") + } + + val ref = getRoot(builder.finish()) + val map = ref.toVector() + assertEquals(3, map.size) + assertEquals(10, map[0].toInt()) + assertEquals("aString", map[2].toString()) + assertEquals("world", map[1]["chello"].toString()) + assertEquals(10, map[1]["aint"].toInt()) + assertEquals(12.3, map[1]["bfloat"].toDouble()) + } + + @Test + fun testMultiMap() { + val builder = FlexBuffersBuilder(shareFlag = FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + builder.putMap { + this["hello"] = "world" + this["int"] = 10 + this["float"] = 12.3 + this["intarray"] = intArrayOf(1, 2, 3, 4, 5) + this.putMap("myMap") { + this["cool"] = "beans" + } + } + + val ref = getRoot(builder.finish()) + val map = ref.toMap() + assertEquals(5, map.size) + assertEquals("world", map["hello"].toString()) + assertEquals(10, map["int"].toInt()) + assertEquals(12.3, map["float"].toDouble()) + assertArrayEquals(intArrayOf(1, 2, 3, 4, 5), map["intarray"].toIntArray()) + assertEquals("beans", ref["myMap"]["cool"].toString()) + assertEquals(true, "myMap" in map) + assertEquals(true, "cool" in map["myMap"].toMap()) + + // testing null values + assertEquals(true, ref["invalid_key"].isNull) + + val keys = map.keys.toTypedArray() + arrayOf("hello", "int", "float", "intarray", "myMap").sortedArray().forEachIndexed { i: Int, it: String -> + assertEquals(it, keys[i].toString()) + } + } + + @Test + fun testBigStringMap() { + val builder = FlexBuffersBuilder(shareFlag = FlexBuffersBuilder.SHARE_KEYS_AND_STRINGS) + + val stringKey = Array(10000) { "Ḧ̵̘́ȩ̵̐myFairlyBigKey$it" } + val stringValue = Array(10000) { "Ḧ̵̘́ȩ̵̐myFairlyBigValue$it" } + val hashMap = mutableMapOf() + val pos = builder.startMap() + for (i in stringKey.indices) { + builder[stringKey[i]] = stringValue[i] + hashMap[stringKey[i]] = stringValue[i] + } + builder.endMap(pos) + val ref = getRoot(builder.finish()) + val map = ref.toMap() + val sortedKeys = stringKey.sortedArray() + val size = map.size + for (i in 0 until size) { + assertEquals(sortedKeys[i], map.keyAsString(i)) + assertEquals(sortedKeys[i], map.keyAt(i).toString()) + assertEquals(hashMap[sortedKeys[i]], map[map.keyAt(i)].toString()) + } + } + + @Test + fun testKeysAccess() { + for (i in 1 until 1000) { + val utf8String = "ሰማይ አይታረስ ንጉሥ አይከሰስ።$i" + val bytes = ByteArray(Utf8.encodedLength(utf8String)) + val pos = Utf8.encodeUtf8Array(utf8String, bytes) + val key = Key(ArrayReadWriteBuffer(bytes), 0, pos) + assertEquals(utf8String.length, key.sizeInChars) + for (j in utf8String.indices) { + assertEquals(utf8String[j], key[j]) + } + } + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt new file mode 100644 index 00000000000..0375bb53a46 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/commonTest/kotlin/com/google/flatbuffers/kotlin/JSONTest.kt @@ -0,0 +1,427 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertTrue + +class JSONTest { + + @Test + fun parse2Test() { + val dataStr = """ + { "myKey" : [1, "yay"] } + """.trimIndent() + val data = dataStr.encodeToByteArray() + val buffer = ArrayReadWriteBuffer(data, writePosition = data.size) + val parser = JSONParser() + val root = parser.parse(buffer) + println(root.toJson()) + } + + @Test + fun parseSample() { + val dataStr = """ + { + "ary" : [1, 2, 3], + "boolean_false": false, +"boolean_true": true, "double": 1.2E33, + "hello":"world" + ,"interesting": "value", + + "null_value": null, + + + "object" : { + "field1": "hello" + } + } + """ + val data = dataStr.encodeToByteArray() + val root = JSONParser().parse(ArrayReadWriteBuffer(data, writePosition = data.size)) + println(root.toJson()) + val map = root.toMap() + + assertEquals(8, map.size) + assertEquals("world", map["hello"].toString()) + assertEquals("value", map["interesting"].toString()) + assertEquals(12e32, map["double"].toDouble()) + assertArrayEquals(intArrayOf(1, 2, 3), map["ary"].toIntArray()) + assertEquals(true, map["boolean_true"].toBoolean()) + assertEquals(false, map["boolean_false"].toBoolean()) + assertEquals(true, map["null_value"].isNull) + assertEquals("hello", map["object"]["field1"].toString()) + + val obj = map["object"] + assertEquals(true, obj.isMap) + assertEquals("{\"field1\":\"hello\"}", obj.toJson()) + // TODO: Kotlin Double.toString() produce different strings dependending on the platform, so on JVM + // is 1.2E33, while on js is 1.2e+33. For now we are disabling this test. + // + // val minified = data.filterNot { it == ' '.toByte() || it == '\n'.toByte() }.toByteArray().decodeToString() + // assertEquals(minified, root.toJson()) + } + + @Test + fun testDoubles() { + val values = arrayOf( + "-0.0", + "1.0", + "1.7976931348613157", + "0.0", + "-0.5", + "3.141592653589793", + "2.718281828459045E-3", + "2.2250738585072014E-308", + "4.9E-15", + ) + val parser = JSONParser() + assertEquals(-0.0, parser.parse(values[0]).toDouble()) + assertEquals(1.0, parser.parse(values[1]).toDouble()) + assertEquals(1.7976931348613157, parser.parse(values[2]).toDouble()) + assertEquals(0.0, parser.parse(values[3]).toDouble()) + assertEquals(-0.5, parser.parse(values[4]).toDouble()) + assertEquals(3.141592653589793, parser.parse(values[5]).toDouble()) + assertEquals(2.718281828459045e-3, parser.parse(values[6]).toDouble()) + assertEquals(2.2250738585072014E-308, parser.parse(values[7]).toDouble()) + assertEquals(4.9E-15, parser.parse(values[8]).toDouble()) + } + + @Test + fun testInts() { + val values = arrayOf( + "-0", + "0", + "-1", + "${Int.MAX_VALUE}", + "${Int.MIN_VALUE}", + "${Long.MAX_VALUE}", + "${Long.MIN_VALUE}", + ) + val parser = JSONParser() + + assertEquals(parser.parse(values[0]).toInt(), 0) + assertEquals(parser.parse(values[1]).toInt(), 0) + assertEquals(parser.parse(values[2]).toInt(), -1) + assertEquals(parser.parse(values[3]).toInt(), Int.MAX_VALUE) + assertEquals(parser.parse(values[4]).toInt(), Int.MIN_VALUE) + assertEquals(parser.parse(values[5]).toLong(), Long.MAX_VALUE) + assertEquals(parser.parse(values[6]).toLong(), Long.MIN_VALUE) + } + + @Test + fun testBooleansAndNull() { + val values = arrayOf( + "true", + "false", + "null" + ) + val parser = JSONParser() + + assertEquals(true, parser.parse(values[0]).toBoolean()) + assertEquals(false, parser.parse(values[1]).toBoolean()) + assertEquals(true, parser.parse(values[2]).isNull) + } + + @Test + fun testStrings() { + val values = arrayOf( + "\"\"", + "\"a\"", + "\"hello world\"", + "\"\\\"\\\\\\/\\b\\f\\n\\r\\t cool\"", + "\"\\u0000\"", + "\"\\u0021\"", + "\"hell\\u24AC\\n\\ro wor \\u0021 ld\"", + "\"\\/_\\\\_\\\"_\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\n\\r\\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?\"", + ) + val parser = JSONParser() + + // empty + var ref = parser.parse(values[0]) + assertEquals(true, ref.isString) + assertEquals("", ref.toString()) + // a + ref = parser.parse(values[1]) + assertEquals(true, ref.isString) + assertEquals("a", ref.toString()) + // hello world + ref = parser.parse(values[2]) + assertEquals(true, ref.isString) + assertEquals("hello world", ref.toString()) + // "\\\"\\\\\\/\\b\\f\\n\\r\\t\"" + ref = parser.parse(values[3]) + assertEquals(true, ref.isString) + assertEquals("\"\\/\b${12.toChar()}\n\r\t cool", ref.toString()) + // 0 + ref = parser.parse(values[4]) + assertEquals(true, ref.isString) + assertEquals(0.toChar().toString(), ref.toString()) + // u0021 + ref = parser.parse(values[5]) + assertEquals(true, ref.isString) + assertEquals(0x21.toChar().toString(), ref.toString()) + // "\"hell\\u24AC\\n\\ro wor \\u0021 ld\"", + ref = parser.parse(values[6]) + assertEquals(true, ref.isString) + assertEquals("hell${0x24AC.toChar()}\n\ro wor ${0x21.toChar()} ld", ref.toString()) + + ref = parser.parse(values[7]) + println(ref.toJson()) + assertEquals(true, ref.isString) + assertEquals("/_\\_\"_쫾몾ꮘﳞ볚\b\n\r\t`1~!@#$%^&*()_+-=[]{}|;:',./<>?", ref.toString()) + } + + @Test + fun testUnicode() { + // took from test/unicode_test.json + val data = """ + { + "name": "unicode_test", + "testarrayofstring": [ + "Цлїςσδε", + "フムアムカモケモ", + "フムヤムカモケモ", + "㊀㊁㊂㊃㊄", + "☳☶☲", + "𡇙𝌆" + ], + "testarrayoftables": [ + { + "name": "Цлїςσδε" + }, + { + "name": "☳☶☲" + }, + { + "name": "フムヤムカモケモ" + }, + { + "name": "㊀㊁㊂㊃㊄" + }, + { + "name": "フムアムカモケモ" + }, + { + "name": "𡇙𝌆" + } + ] + } + """.trimIndent() + val parser = JSONParser() + val ref = parser.parse(data) + + // name + assertEquals(3, ref.toMap().size) + assertEquals("unicode_test", ref["name"].toString()) + // testarrayofstring + assertEquals(6, ref["testarrayofstring"].toVector().size) + assertEquals("Цлїςσδε", ref["testarrayofstring"][0].toString()) + assertEquals("フムアムカモケモ", ref["testarrayofstring"][1].toString()) + assertEquals("フムヤムカモケモ", ref["testarrayofstring"][2].toString()) + assertEquals("㊀㊁㊂㊃㊄", ref["testarrayofstring"][3].toString()) + assertEquals("☳☶☲", ref["testarrayofstring"][4].toString()) + assertEquals("𡇙𝌆", ref["testarrayofstring"][5].toString()) + // testarrayoftables + assertEquals(6, ref["testarrayoftables"].toVector().size) + assertEquals("Цлїςσδε", ref["testarrayoftables"][0]["name"].toString()) + assertEquals("☳☶☲", ref["testarrayoftables"][1]["name"].toString()) + assertEquals("フムヤムカモケモ", ref["testarrayoftables"][2]["name"].toString()) + assertEquals("㊀㊁㊂㊃㊄", ref["testarrayoftables"][3]["name"].toString()) + assertEquals("フムアムカモケモ", ref["testarrayoftables"][4]["name"].toString()) + assertEquals("𡇙𝌆", ref["testarrayoftables"][5]["name"].toString()) + } + + @Test + fun testArrays() { + val values = arrayOf( + "[]", + "[1]", + "[0,1, 2,3 , 4 ]", + "[1.0, 2.2250738585072014E-308, 4.9E-320]", + "[1.0, 2, \"hello world\"] ", + "[ 1.1, 2, [ \"hello\" ] ]", + "[[[1]]]" + ) + val parser = JSONParser() + + // empty + var ref = parser.parse(values[0]) + assertEquals(true, ref.isVector) + assertEquals(0, parser.parse(values[0]).toVector().size) + // single + ref = parser.parse(values[1]) + assertEquals(true, ref.isTypedVector) + assertEquals(1, ref[0].toInt()) + // ints + ref = parser.parse(values[2]) + assertEquals(true, ref.isTypedVector) + assertEquals(T_VECTOR_INT, ref.type) + assertEquals(5, ref.toVector().size) + for (i in 0..4) { + assertEquals(i, ref[i].toInt()) + } + // floats + ref = parser.parse(values[3]) + assertEquals(true, ref.isTypedVector) + assertEquals(T_VECTOR_FLOAT, ref.type) + assertEquals(3, ref.toVector().size) + assertEquals(1.0, ref[0].toDouble()) + assertEquals(2.2250738585072014E-308, ref[1].toDouble()) + assertEquals(4.9E-320, ref[2].toDouble()) + // mixed + ref = parser.parse(values[4]) + assertEquals(false, ref.isTypedVector) + assertEquals(T_VECTOR, ref.type) + assertEquals(1.0, ref[0].toDouble()) + assertEquals(2, ref[1].toInt()) + assertEquals("hello world", ref[2].toString()) + // nester array + ref = parser.parse(values[5]) + assertEquals(false, ref.isTypedVector) + assertEquals(T_VECTOR, ref.type) + assertEquals(1.1, ref[0].toDouble()) + assertEquals(2, ref[1].toInt()) + assertEquals("hello", ref[2][0].toString()) + } + + /** + * Several test cases provided by json.org + * For more details, see: http://json.org/JSON_checker/, with only + * one exception. Single strings are considered accepted, whereas on + * the test suit is should fail. + */ + @Test + fun testParseMustFail() { + val failList = listOf( + "[\"Unclosed array\"", + "{unquoted_key: \"keys must be quoted\"}", + "[\"extra comma\",]", + "[\"double extra comma\",,]", + "[ , \"<-- missing value\"]", + "[\"Comma after the close\"],", + "[\"Extra close\"]]", + "{\"Extra comma\": true,}", + "{\"Extra value after close\": true} \"misplaced quoted value\"", + "{\"Illegal expression\": 1 + 2}", + "{\"Illegal invocation\": alert()}", + "{\"Numbers cannot have leading zeroes\": 013}", + "{\"Numbers cannot be hex\": 0x14}", + "[\"Illegal backslash escape: \\x15\"]", + "[\\naked]", + "[\"Illegal backslash escape: \\017\"]", + "[[[[[[[[[[[[[[[[[[[[[[[\"Too deep\"]]]]]]]]]]]]]]]]]]]]]]]", + "{\"Missing colon\" null}", + "{\"Double colon\":: null}", + "{\"Comma instead of colon\", null}", + "[\"Colon instead of comma\": false]", + "[\"Bad value\", truth]", + "['single quote']", + "[\"\ttab\tcharacter\tin\tstring\t\"]", + "[\"tab\\ character\\ in\\ string\\ \"]", + "[\"line\nbreak\"]", + "[\"line\\\nbreak\"]", + "[0e]", + "[0e+]", + "[0e+-1]", + "{\"Comma instead if closing brace\": true,", + "[\"mismatch\"}" + ) + for (data in failList) { + try { + JSONParser().parse(ArrayReadBuffer(data.encodeToByteArray())) + assertTrue(false, "SHOULD NOT PASS: $data") + } catch (e: IllegalStateException) { + println("FAIL $e") + } + } + } + + @Test + fun testParseMustPass() { + val passList = listOf( + "[\n" + + " \"JSON Test Pattern pass1\",\n" + + " {\"object with 1 member\":[\"array with 1 element\"]},\n" + + " {},\n" + + " [],\n" + + " -42,\n" + + " true,\n" + + " false,\n" + + " null,\n" + + " {\n" + + " \"integer\": 1234567890,\n" + + " \"real\": -9876.543210,\n" + + " \"e\": 0.123456789e-12,\n" + + " \"E\": 1.234567890E+34,\n" + + " \"\": 23456789012E66,\n" + + " \"zero\": 0,\n" + + " \"one\": 1,\n" + + " \"space\": \" \",\n" + + " \"quote\": \"\\\"\",\n" + + " \"backslash\": \"\\\\\",\n" + + " \"controls\": \"\\b\\f\\n\\r\\t\",\n" + + " \"slash\": \"/ & \\/\",\n" + + " \"alpha\": \"abcdefghijklmnopqrstuvwyz\",\n" + + " \"ALPHA\": \"ABCDEFGHIJKLMNOPQRSTUVWYZ\",\n" + + " \"digit\": \"0123456789\",\n" + + " \"0123456789\": \"digit\",\n" + + " \"special\": \"`1~!@#\$%^&*()_+-={':[,]}|;.?\",\n" + + " \"hex\": \"\\u0123\\u4567\\u89AB\\uCDEF\\uabcd\\uef4A\",\n" + + " \"true\": true,\n" + + " \"false\": false,\n" + + " \"null\": null,\n" + + " \"array\":[ ],\n" + + " \"object\":{ },\n" + + " \"address\": \"50 St. James Street\",\n" + + " \"url\": \"http://www.JSON.org/\",\n" + + " \"comment\": \"// /* */\": \" \",\n" + + " \" s p a c e d \" :[1,2 , 3\n" + + "\n" + + ",\n" + + "\n" + + "4 , 5 , 6 ,7 ],\"compact\":[1,2,3,4,5,6,7],\n" + + " \"jsontext\": \"{\\\"object with 1 member\\\":[\\\"array with 1 element\\\"]}\",\n" + + " \"quotes\": \"" \\u0022 %22 0x22 034 "\",\n" + + " \"\\/\\\\\\\"\\uCAFE\\uBABE\\uAB98\\uFCDE\\ubcda\\uef4A\\b\\f\\n\\r\\t`1~!@#\$%^&*()_+-=[]{}|;:',./<>?\"\n" + + ": \"A key can be any string\"\n" + + " },\n" + + " 0.5 ,98.6\n" + + ",\n" + + "99.44\n" + + ",\n" + + "\n" + + "1066,\n" + + "1e1,\n" + + "0.1e1,\n" + + "1e-1,\n" + + "1e00,2e+00,2e-00\n" + + ",\"rosebud\"]", + "{\n" + + " \"JSON Test Pattern pass3\": {\n" + + " \"The outermost value\": \"must be an object or array.\",\n" + + " \"In this test\": \"It is an object.\"\n" + + " }\n" + + "}", + "[[[[[[[[[[[[[[[[[[[\"Not too deep\"]]]]]]]]]]]]]]]]]]]", + ) + for (data in passList) { + JSONParser().parse(ArrayReadBuffer(data.encodeToByteArray())) + } + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jsMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jsMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt new file mode 100644 index 00000000000..99c6b51c11c --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jsMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt @@ -0,0 +1,41 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +/** + * This implementation uses Little Endian order. + */ +public actual inline fun ByteArray.getUByte(index: Int): UByte = ByteArrayOps.getUByte(this, index) +public actual inline fun ByteArray.getShort(index: Int): Short = ByteArrayOps.getShort(this, index) +public actual inline fun ByteArray.getUShort(index: Int): UShort = ByteArrayOps.getUShort(this, index) +public actual inline fun ByteArray.getInt(index: Int): Int = ByteArrayOps.getInt(this, index) +public actual inline fun ByteArray.getUInt(index: Int): UInt = ByteArrayOps.getUInt(this, index) +public actual inline fun ByteArray.getLong(index: Int): Long = ByteArrayOps.getLong(this, index) +public actual inline fun ByteArray.getULong(index: Int): ULong = ByteArrayOps.getULong(this, index) +public actual inline fun ByteArray.getFloat(index: Int): Float = ByteArrayOps.getFloat(this, index) +public actual inline fun ByteArray.getDouble(index: Int): Double = ByteArrayOps.getDouble(this, index) + +public actual inline fun ByteArray.setUByte(index: Int, value: UByte): Unit = ByteArrayOps.setUByte(this, index, value) +public actual inline fun ByteArray.setShort(index: Int, value: Short): Unit = ByteArrayOps.setShort(this, index, value) +public actual inline fun ByteArray.setUShort(index: Int, value: UShort): Unit = ByteArrayOps.setUShort(this, index, value) +public actual inline fun ByteArray.setInt(index: Int, value: Int): Unit = ByteArrayOps.setInt(this, index, value) +public actual inline fun ByteArray.setUInt(index: Int, value: UInt): Unit = ByteArrayOps.setUInt(this, index, value) +public actual inline fun ByteArray.setLong(index: Int, value: Long): Unit = ByteArrayOps.setLong(this, index, value) +public actual inline fun ByteArray.setULong(index: Int, value: ULong): Unit = ByteArrayOps.setULong(this, index, value) +public actual inline fun ByteArray.setFloat(index: Int, value: Float): Unit = ByteArrayOps.setFloat(this, index, value) +public actual inline fun ByteArray.setDouble(index: Int, value: Double): Unit = ByteArrayOps.setDouble(this, index, value) diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt new file mode 100644 index 00000000000..94da7d3f021 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt @@ -0,0 +1,43 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +@file:JvmName("JVMByteArray") +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +/** + * This implementation uses Little Endian order. + */ +public actual inline fun ByteArray.getUByte(index: Int): UByte = ByteArrayOps.getUByte(this, index) +public actual inline fun ByteArray.getShort(index: Int): Short = ByteArrayOps.getShort(this, index) +public actual inline fun ByteArray.getUShort(index: Int): UShort = ByteArrayOps.getUShort(this, index) +public actual inline fun ByteArray.getInt(index: Int): Int = ByteArrayOps.getInt(this, index) +public actual inline fun ByteArray.getUInt(index: Int): UInt = ByteArrayOps.getUInt(this, index) +public actual inline fun ByteArray.getLong(index: Int): Long = ByteArrayOps.getLong(this, index) +public actual inline fun ByteArray.getULong(index: Int): ULong = ByteArrayOps.getULong(this, index) +public actual inline fun ByteArray.getFloat(index: Int): Float = ByteArrayOps.getFloat(this, index) +public actual inline fun ByteArray.getDouble(index: Int): Double = ByteArrayOps.getDouble(this, index) + +public actual inline fun ByteArray.setUByte(index: Int, value: UByte): Unit = ByteArrayOps.setUByte(this, index, value) +public actual inline fun ByteArray.setShort(index: Int, value: Short): Unit = ByteArrayOps.setShort(this, index, value) +public actual inline fun ByteArray.setUShort(index: Int, value: UShort): Unit = ByteArrayOps.setUShort(this, index, value) +public actual inline fun ByteArray.setInt(index: Int, value: Int): Unit = ByteArrayOps.setInt(this, index, value) +public actual inline fun ByteArray.setUInt(index: Int, value: UInt): Unit = ByteArrayOps.setUInt(this, index, value) +public actual inline fun ByteArray.setLong(index: Int, value: Long): Unit = ByteArrayOps.setLong(this, index, value) +public actual inline fun ByteArray.setULong(index: Int, value: ULong): Unit = ByteArrayOps.setULong(this, index, value) +public actual inline fun ByteArray.setFloat(index: Int, value: Float): Unit = ByteArrayOps.setFloat(this, index, value) +public actual inline fun ByteArray.setDouble(index: Int, value: Double): Unit = ByteArrayOps.setDouble(this, index, value) diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmTest/kotlin/com/google/flatbuffers/kotlin/Utf8Test.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmTest/kotlin/com/google/flatbuffers/kotlin/Utf8Test.kt new file mode 100644 index 00000000000..9b21741663b --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmTest/kotlin/com/google/flatbuffers/kotlin/Utf8Test.kt @@ -0,0 +1,40 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package com.google.flatbuffers.kotlin + +import org.junit.Test +import kotlin.test.assertEquals + +class Utf8Test { + + @Test + fun testUtf8EncodingDecoding() { + val classLoader = this.javaClass.classLoader + val utf8Lines = String(classLoader.getResourceAsStream("utf8_sample.txt")!!.readBytes()) + .split("\n") + .filter { it.trim().isNotEmpty() } + + val utf8Bytes = utf8Lines.map { + s -> ByteArray(Utf8.encodedLength(s)).also { + Utf8.encodeUtf8Array(s, it) + } + } + utf8Bytes.indices.forEach { + assertArrayEquals(utf8Lines[it].encodeToByteArray(), utf8Bytes[it]) + assertEquals(utf8Lines[it], Utf8.decodeUtf8Array(utf8Bytes[it])) + } + } +} diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmTest/resources/utf8_sample.txt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmTest/resources/utf8_sample.txt new file mode 100644 index 00000000000..4fea69b850d --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/jvmTest/resources/utf8_sample.txt @@ -0,0 +1,201 @@ +Markus Kuhn - 2015-08-28 - CC BY 4.0 +UTF-8 encoded sample plain-text file +‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ +Markus Kuhn [ˈmaʳkʊs kuːn] — 1999-08-20 + +The ASCII compatible UTF-8 encoding of ISO 10646 and Unicode +plain-text files is defined in RFC 2279 and in ISO 10646-1 Annex R. + + +Using Unicode/UTF-8, you can write in emails and source code things such as + +Mathematics and Sciences: + + ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), + + ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (A ⇔ B), + + 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm + +Linguistics and dictionaries: + + ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn + Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] + +APL: + + ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ + +Nicer typography in plain text files: + + ╔══════════════════════════════════════════╗ + ║ ║ + ║ • ‘single’ and “double” quotes ║ + ║ ║ + ║ • Curly apostrophes: “We’ve been here” ║ + ║ ║ + ║ • Latin-1 apostrophe and accents: '´` ║ + ║ ║ + ║ • ‚deutsche‘ „Anführungszeichen“ ║ + ║ ║ + ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ + ║ ║ + ║ • ASCII safety test: 1lI|, 0OD, 8B ║ + ║ ╭─────────╮ ║ + ║ • the euro symbol: │ 14.95 € │ ║ + ║ ╰─────────╯ ║ + ╚══════════════════════════════════════════╝ + +Greek (in Polytonic): + + The Greek anthem: + + Σὲ γνωρίζω ἀπὸ τὴν κόψη + τοῦ σπαθιοῦ τὴν τρομερή, + σὲ γνωρίζω ἀπὸ τὴν ὄψη + ποὺ μὲ βία μετράει τὴ γῆ. + + ᾿Απ᾿ τὰ κόκκαλα βγαλμένη + τῶν ῾Ελλήνων τὰ ἱερά + καὶ σὰν πρῶτα ἀνδρειωμένη + χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! + + From a speech of Demosthenes in the 4th century BC: + + Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, + ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς + λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ + τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ + εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ + πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν + οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, + οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν + ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον + τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι + γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν + προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους + σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ + τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ + τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς + τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. + + Δημοσθένους, Γ´ ᾿Ολυνθιακὸς + +Georgian: + + From a Unicode conference invitation: + + გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო + კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, + ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს + ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, + ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება + ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, + ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. + +Russian: + + From a Unicode conference invitation: + + Зарегистрируйтесь сейчас на Десятую Международную Конференцию по + Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. + Конференция соберет широкий круг экспертов по вопросам глобального + Интернета и Unicode, локализации и интернационализации, воплощению и + применению Unicode в различных операционных системах и программных + приложениях, шрифтах, верстке и многоязычных компьютерных системах. + +Thai (UCS Level 2): + + Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese + classic 'San Gua'): + + [----------------------------|------------------------] + ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ + สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา + ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา + โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ + เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ + ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ + พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ + ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ + + (The above is a two-column text. If combining characters are handled + correctly, the lines of the second column should be aligned with the + | character above.) + +Ethiopian: + + Proverbs in the Amharic language: + + ሰማይ አይታረስ ንጉሥ አይከሰስ። + ብላ ካለኝ እንደአባቴ በቆመጠኝ። + ጌጥ ያለቤቱ ቁምጥና ነው። + ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው። + የአፍ ወለምታ በቅቤ አይታሽም። + አይጥ በበላ ዳዋ ተመታ። + ሲተረጉሙ ይደረግሙ። + ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል። + ድር ቢያብር አንበሳ ያስር። + ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም። + እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም። + የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ። + ሥራ ከመፍታት ልጄን ላፋታት። + ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል። + የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ። + ተንጋሎ ቢተፉ ተመልሶ ባፉ። + ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው። + እግርህን በፍራሽህ ልክ ዘርጋ። + +Runes: + + ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ + + (Old English, which transcribed into Latin reads 'He cwaeth that he + bude thaem lande northweardum with tha Westsae.' and means 'He said + that he lived in the northern land near the Western Sea.') + +Braille: + + ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌ + + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞ + ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎ + ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂ + ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙ + ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑ + ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲ + + ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹ + ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞ + ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕ + ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹ + ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎ + ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎ + ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳ + ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞ + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + (The first couple of paragraphs of "A Christmas Carol" by Dickens) + +Compact font selection example text: + + ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789 + abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ + –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд + ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა + +Greetings in various languages: + + Hello world, Καλημέρα κόσμε, コンニチハ + +Box drawing alignment tests: █ + ▉ + ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳ + ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳ + ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳ + ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳ + ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎ + ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏ + ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█ diff --git a/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/nativeMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/nativeMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt new file mode 100644 index 00000000000..7c609522454 --- /dev/null +++ b/third_party/flatbuffers/kotlin/flatbuffers-kotlin/src/nativeMain/kotlin/com/google/flatbuffers/kotlin/ByteArray.kt @@ -0,0 +1,42 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@file:Suppress("NOTHING_TO_INLINE") + +package com.google.flatbuffers.kotlin + +/** + * This implementation assumes that of native macOSX64 the byte order of the implementation is Little Endian. + */ + +public actual inline fun ByteArray.getUByte(index: Int): UByte = getUByteAt(index) +public actual inline fun ByteArray.getShort(index: Int): Short = getShortAt(index) +public actual inline fun ByteArray.getUShort(index: Int): UShort = getUShortAt(index) +public actual inline fun ByteArray.getInt(index: Int): Int = getIntAt(index) +public actual inline fun ByteArray.getUInt(index: Int): UInt = getUIntAt(index) +public actual inline fun ByteArray.getLong(index: Int): Long = getLongAt(index) +public actual inline fun ByteArray.getULong(index: Int): ULong = getULongAt(index) + +public actual inline fun ByteArray.setUByte(index: Int, value: UByte): Unit = setUByteAt(index, value) +public actual inline fun ByteArray.setShort(index: Int, value: Short): Unit = setShortAt(index, value) +public actual inline fun ByteArray.setUShort(index: Int, value: UShort): Unit = setUShortAt(index, value) +public actual inline fun ByteArray.setInt(index: Int, value: Int): Unit = setIntAt(index, value) +public actual inline fun ByteArray.setUInt(index: Int, value: UInt): Unit = setUIntAt(index, value) +public actual inline fun ByteArray.setLong(index: Int, value: Long): Unit = setLongAt(index, value) +public actual inline fun ByteArray.setULong(index: Int, value: ULong): Unit = setULongAt(index, value) +public actual inline fun ByteArray.setFloat(index: Int, value: Float): Unit = setFloatAt(index, value) +public actual inline fun ByteArray.setDouble(index: Int, value: Double): Unit = setDoubleAt(index, value) +public actual inline fun ByteArray.getFloat(index: Int): Float = Float.fromBits(getIntAt(index)) +public actual inline fun ByteArray.getDouble(index: Int): Double = Double.fromBits(getLongAt(index)) diff --git a/third_party/flatbuffers/kotlin/gradle.properties b/third_party/flatbuffers/kotlin/gradle.properties new file mode 100644 index 00000000000..d16170eaf5a --- /dev/null +++ b/third_party/flatbuffers/kotlin/gradle.properties @@ -0,0 +1,20 @@ +#Gradle +group = "com.google.flatbuffers" +version = "2.0.0-SNAPSHOT" + +org.gradle.parallel=true +org.gradle.caching=true + +#Kotlin +kotlin.code.style=official + +#MPP +kotlin.js.compiler=ir +kotlin.native.ignoreDisabledTargets=true +kotlin.mpp.stability.nowarn=true +kotlin.incremental.multiplatform=true +kotlin.native.binary.memoryModel=experimental + +kotlin.native.distribution.type=prebuilt + +org.gradle.jvmargs="-XX:+HeapDumpOnOutOfMemoryError" diff --git a/third_party/flatbuffers/kotlin/gradle/libs.versions.toml b/third_party/flatbuffers/kotlin/gradle/libs.versions.toml new file mode 100644 index 00000000000..35f032c6c4f --- /dev/null +++ b/third_party/flatbuffers/kotlin/gradle/libs.versions.toml @@ -0,0 +1,27 @@ +[versions] +# Version 1.9.10 fix +# https://youtrack.jetbrains.com/issue/KT-60230/Native-unknown-options-iossimulatorversionmin-sdkversion-with-Xcode-15-beta-3 +kotlin = "1.9.10" +plugin-kotlin = "1.6.10" +plugin-gver = "0.42.0" +kotlinx-benchmark = "0.4.8" +junit = "4.12" +gson = "2.8.9" +moshi-kotlin = "1.11.0" + +[libraries] +kotlin-compiler = { module = "org.jetbrains.kotlin:kotlin-compiler", version.ref = "kotlin" } +moshi-kotlin = { module = "com.squareup.moshi:moshi-kotlin", version.ref = "moshi-kotlin" } +gson = { module = "com.google.code.gson:gson", version.ref = "gson" } +kotlinx-benchmark-runtime = { module = "org.jetbrains.kotlinx:kotlinx-benchmark-runtime", version.ref = "kotlinx-benchmark" } + +junit = { module="junit:junit", version.ref="junit"} +kotlin-allopen = { module = "org.jetbrains.kotlin:kotlin-allopen", version.ref = "kotlin"} + +plugin-kotlin-gradle = { module = "org.jetbrains.kotlin:kotlin-gradle-plugin", version.ref = "kotlin" } +plugin-kotlinx-benchmark = { module="org.jetbrains.kotlinx:kotlinx-benchmark-plugin", version.ref="kotlinx-benchmark"} +plugin-jmhreport = { module = "gradle.plugin.io.morethan.jmhreport:gradle-jmh-report", version="0.9.0" } +plugin-download = { module = "de.undercouch:gradle-download-task", version = "5.3.0"} + + + diff --git a/third_party/flatbuffers/kotlin/gradle/wrapper/gradle-wrapper.jar b/third_party/flatbuffers/kotlin/gradle/wrapper/gradle-wrapper.jar new file mode 100644 index 00000000000..41d9927a4d4 Binary files /dev/null and b/third_party/flatbuffers/kotlin/gradle/wrapper/gradle-wrapper.jar differ diff --git a/third_party/flatbuffers/kotlin/gradle/wrapper/gradle-wrapper.properties b/third_party/flatbuffers/kotlin/gradle/wrapper/gradle-wrapper.properties new file mode 100644 index 00000000000..f72df95a7e8 --- /dev/null +++ b/third_party/flatbuffers/kotlin/gradle/wrapper/gradle-wrapper.properties @@ -0,0 +1,5 @@ +distributionBase=GRADLE_USER_HOME +distributionPath=wrapper/dists +distributionUrl=https\://services.gradle.org/distributions/gradle-8.0.1-bin.zip +zipStoreBase=GRADLE_USER_HOME +zipStorePath=wrapper/dists diff --git a/third_party/flatbuffers/kotlin/gradlew b/third_party/flatbuffers/kotlin/gradlew new file mode 100755 index 00000000000..1b6c787337f --- /dev/null +++ b/third_party/flatbuffers/kotlin/gradlew @@ -0,0 +1,234 @@ +#!/bin/sh + +# +# Copyright © 2015-2021 the original authors. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# https://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +############################################################################## +# +# Gradle start up script for POSIX generated by Gradle. +# +# Important for running: +# +# (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is +# noncompliant, but you have some other compliant shell such as ksh or +# bash, then to run this script, type that shell name before the whole +# command line, like: +# +# ksh Gradle +# +# Busybox and similar reduced shells will NOT work, because this script +# requires all of these POSIX shell features: +# * functions; +# * expansions «$var», «${var}», «${var:-default}», «${var+SET}», +# «${var#prefix}», «${var%suffix}», and «$( cmd )»; +# * compound commands having a testable exit status, especially «case»; +# * various built-in commands including «command», «set», and «ulimit». +# +# Important for patching: +# +# (2) This script targets any POSIX shell, so it avoids extensions provided +# by Bash, Ksh, etc; in particular arrays are avoided. +# +# The "traditional" practice of packing multiple parameters into a +# space-separated string is a well documented source of bugs and security +# problems, so this is (mostly) avoided, by progressively accumulating +# options in "$@", and eventually passing that to Java. +# +# Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, +# and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; +# see the in-line comments for details. +# +# There are tweaks for specific operating systems such as AIX, CygWin, +# Darwin, MinGW, and NonStop. +# +# (3) This script is generated from the Groovy template +# https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt +# within the Gradle project. +# +# You can find Gradle at https://github.com/gradle/gradle/. +# +############################################################################## + +# Attempt to set APP_HOME + +# Resolve links: $0 may be a link +app_path=$0 + +# Need this for daisy-chained symlinks. +while + APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path + [ -h "$app_path" ] +do + ls=$( ls -ld "$app_path" ) + link=${ls#*' -> '} + case $link in #( + /*) app_path=$link ;; #( + *) app_path=$APP_HOME$link ;; + esac +done + +APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit + +APP_NAME="Gradle" +APP_BASE_NAME=${0##*/} + +# Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' + +# Use the maximum available, or set MAX_FD != -1 to use that value. +MAX_FD=maximum + +warn () { + echo "$*" +} >&2 + +die () { + echo + echo "$*" + echo + exit 1 +} >&2 + +# OS specific support (must be 'true' or 'false'). +cygwin=false +msys=false +darwin=false +nonstop=false +case "$( uname )" in #( + CYGWIN* ) cygwin=true ;; #( + Darwin* ) darwin=true ;; #( + MSYS* | MINGW* ) msys=true ;; #( + NONSTOP* ) nonstop=true ;; +esac + +CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar + + +# Determine the Java command to use to start the JVM. +if [ -n "$JAVA_HOME" ] ; then + if [ -x "$JAVA_HOME/jre/sh/java" ] ; then + # IBM's JDK on AIX uses strange locations for the executables + JAVACMD=$JAVA_HOME/jre/sh/java + else + JAVACMD=$JAVA_HOME/bin/java + fi + if [ ! -x "$JAVACMD" ] ; then + die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." + fi +else + JAVACMD=java + which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. + +Please set the JAVA_HOME variable in your environment to match the +location of your Java installation." +fi + +# Increase the maximum file descriptors if we can. +if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then + case $MAX_FD in #( + max*) + MAX_FD=$( ulimit -H -n ) || + warn "Could not query maximum file descriptor limit" + esac + case $MAX_FD in #( + '' | soft) :;; #( + *) + ulimit -n "$MAX_FD" || + warn "Could not set maximum file descriptor limit to $MAX_FD" + esac +fi + +# Collect all arguments for the java command, stacking in reverse order: +# * args from the command line +# * the main class name +# * -classpath +# * -D...appname settings +# * --module-path (only if needed) +# * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. + +# For Cygwin or MSYS, switch paths to Windows format before running java +if "$cygwin" || "$msys" ; then + APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) + CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) + + JAVACMD=$( cygpath --unix "$JAVACMD" ) + + # Now convert the arguments - kludge to limit ourselves to /bin/sh + for arg do + if + case $arg in #( + -*) false ;; # don't mess with options #( + /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath + [ -e "$t" ] ;; #( + *) false ;; + esac + then + arg=$( cygpath --path --ignore --mixed "$arg" ) + fi + # Roll the args list around exactly as many times as the number of + # args, so each arg winds up back in the position where it started, but + # possibly modified. + # + # NB: a `for` loop captures its iteration list before it begins, so + # changing the positional parameters here affects neither the number of + # iterations, nor the values presented in `arg`. + shift # remove old arg + set -- "$@" "$arg" # push replacement arg + done +fi + +# Collect all arguments for the java command; +# * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of +# shell script including quotes and variable substitutions, so put them in +# double quotes to make sure that they get re-expanded; and +# * put everything else in single quotes, so that it's not re-expanded. + +set -- \ + "-Dorg.gradle.appname=$APP_BASE_NAME" \ + -classpath "$CLASSPATH" \ + org.gradle.wrapper.GradleWrapperMain \ + "$@" + +# Use "xargs" to parse quoted args. +# +# With -n1 it outputs one arg per line, with the quotes and backslashes removed. +# +# In Bash we could simply go: +# +# readarray ARGS < <( xargs -n1 <<<"$var" ) && +# set -- "${ARGS[@]}" "$@" +# +# but POSIX shell has neither arrays nor command substitution, so instead we +# post-process each arg (as a line of input to sed) to backslash-escape any +# character that might be a shell metacharacter, then use eval to reverse +# that process (while maintaining the separation between arguments), and wrap +# the whole thing up as a single "set" statement. +# +# This will of course break if any of these variables contains a newline or +# an unmatched quote. +# + +eval "set -- $( + printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | + xargs -n1 | + sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | + tr '\n' ' ' + )" '"$@"' + +exec "$JAVACMD" "$@" diff --git a/third_party/flatbuffers/kotlin/gradlew.bat b/third_party/flatbuffers/kotlin/gradlew.bat new file mode 100644 index 00000000000..107acd32c4e --- /dev/null +++ b/third_party/flatbuffers/kotlin/gradlew.bat @@ -0,0 +1,89 @@ +@rem +@rem Copyright 2015 the original author or authors. +@rem +@rem Licensed under the Apache License, Version 2.0 (the "License"); +@rem you may not use this file except in compliance with the License. +@rem You may obtain a copy of the License at +@rem +@rem https://www.apache.org/licenses/LICENSE-2.0 +@rem +@rem Unless required by applicable law or agreed to in writing, software +@rem distributed under the License is distributed on an "AS IS" BASIS, +@rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +@rem See the License for the specific language governing permissions and +@rem limitations under the License. +@rem + +@if "%DEBUG%" == "" @echo off +@rem ########################################################################## +@rem +@rem Gradle startup script for Windows +@rem +@rem ########################################################################## + +@rem Set local scope for the variables with windows NT shell +if "%OS%"=="Windows_NT" setlocal + +set DIRNAME=%~dp0 +if "%DIRNAME%" == "" set DIRNAME=. +set APP_BASE_NAME=%~n0 +set APP_HOME=%DIRNAME% + +@rem Resolve any "." and ".." in APP_HOME to make it shorter. +for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi + +@rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. +set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" + +@rem Find java.exe +if defined JAVA_HOME goto findJavaFromJavaHome + +set JAVA_EXE=java.exe +%JAVA_EXE% -version >NUL 2>&1 +if "%ERRORLEVEL%" == "0" goto execute + +echo. +echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:findJavaFromJavaHome +set JAVA_HOME=%JAVA_HOME:"=% +set JAVA_EXE=%JAVA_HOME%/bin/java.exe + +if exist "%JAVA_EXE%" goto execute + +echo. +echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% +echo. +echo Please set the JAVA_HOME variable in your environment to match the +echo location of your Java installation. + +goto fail + +:execute +@rem Setup the command line + +set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar + + +@rem Execute Gradle +"%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* + +:end +@rem End local scope for the variables with windows NT shell +if "%ERRORLEVEL%"=="0" goto mainEnd + +:fail +rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of +rem the _cmd.exe /c_ return code! +if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 +exit /b 1 + +:mainEnd +if "%OS%"=="Windows_NT" endlocal + +:omega diff --git a/third_party/flatbuffers/kotlin/settings.gradle.kts b/third_party/flatbuffers/kotlin/settings.gradle.kts new file mode 100644 index 00000000000..9b6981eebe0 --- /dev/null +++ b/third_party/flatbuffers/kotlin/settings.gradle.kts @@ -0,0 +1,4 @@ +rootProject.name = "flatbuffers-kotlin" +includeBuild("convention-plugins") +include("flatbuffers-kotlin") +include("benchmark") diff --git a/third_party/flatbuffers/kotlin/spotless/spotless.kt b/third_party/flatbuffers/kotlin/spotless/spotless.kt new file mode 100644 index 00000000000..6363ca0e36b --- /dev/null +++ b/third_party/flatbuffers/kotlin/spotless/spotless.kt @@ -0,0 +1,15 @@ +/* + * Copyright $YEAR Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ diff --git a/third_party/flatbuffers/net/FlatBuffers/FlatBufferConstants.cs b/third_party/flatbuffers/net/FlatBuffers/FlatBufferConstants.cs index d7fee534895..53b84fa864d 100644 --- a/third_party/flatbuffers/net/FlatBuffers/FlatBufferConstants.cs +++ b/third_party/flatbuffers/net/FlatBuffers/FlatBufferConstants.cs @@ -32,6 +32,6 @@ the runtime and generated code are modified in sync. Changes to the C# implementation need to be sure to change the version here and in the code generator on every possible incompatible change */ - public static void FLATBUFFERS_24_3_25() {} + public static void FLATBUFFERS_25_2_10() {} } } diff --git a/third_party/flatbuffers/net/FlatBuffers/Google.FlatBuffers.csproj b/third_party/flatbuffers/net/FlatBuffers/Google.FlatBuffers.csproj index 7789de1b119..7a8702fc11d 100644 --- a/third_party/flatbuffers/net/FlatBuffers/Google.FlatBuffers.csproj +++ b/third_party/flatbuffers/net/FlatBuffers/Google.FlatBuffers.csproj @@ -1,9 +1,9 @@  - netstandard2.1;net6.0;net8.0 + netstandard2.0;netstandard2.1;net6.0;net8.0 A cross-platform memory efficient serialization library - 24.3.25 + 25.2.10 Google LLC https://github.com/google/flatbuffers https://github.com/google/flatbuffers diff --git a/third_party/flatbuffers/nim/flatbuffers.nimble b/third_party/flatbuffers/nim/flatbuffers.nimble new file mode 100644 index 00000000000..df16be26a09 --- /dev/null +++ b/third_party/flatbuffers/nim/flatbuffers.nimble @@ -0,0 +1,7 @@ +version = "2.0.8" +author = "flatbuffers" +description = "Flatbuffers" +license = "Apache 2.0" +srcDir = "flatbuffers" + +requires "nim >= 1.4.0" diff --git a/third_party/flatbuffers/nim/flatbuffers/flatbuffers.nim b/third_party/flatbuffers/nim/flatbuffers/flatbuffers.nim new file mode 100644 index 00000000000..b9532877e76 --- /dev/null +++ b/third_party/flatbuffers/nim/flatbuffers/flatbuffers.nim @@ -0,0 +1,7 @@ +import + src/[ + builder, + struct, + table + ] +export flatbuffers.builder, flatbuffers.table, flatbuffers.struct diff --git a/third_party/flatbuffers/nim/flatbuffers/src/builder.nim b/third_party/flatbuffers/nim/flatbuffers/src/builder.nim new file mode 100644 index 00000000000..62ac2edb0be --- /dev/null +++ b/third_party/flatbuffers/nim/flatbuffers/src/builder.nim @@ -0,0 +1,262 @@ +import math +import table + + +const MAX_BUFFER_SIZE* = 2^31 + + +type Builder* = ref object of RootObj + bytes*: seq[byte] + minalign*: int + current_vtable*: seq[uoffset] + objectEnd*: uoffset + vtables*: seq[uoffset] #? + head*: uoffset + nested*: bool + finished*: bool + vectorNumElems*: uoffset + +using this: var Builder + +func newBuilder*(size: int): Builder = + result = new Builder + result.bytes.setLen(size) + result.minalign = 1 + result.head = size.uoffset + result.nested = false + result.finished = false + result.vectorNumElems = 0 + +proc FinishedBytes*(this): seq[byte] = + if not this.finished: + quit("Builder not finished, Incorrect use of FinishedBytes(): must call 'Finish' first.") + result = this.bytes[this.head..^1] + +proc Output*(this): seq[byte] = + if not this.finished: + quit("Builder not finished, Incorrect use of Output(): must call 'Finish' first.") + + result = this.bytes[this.head..^1] + +func Offset*(this): uoffset = + result = this.bytes.len.uoffset - this.head + +proc StartObject*(this; numfields: int) = + if this.nested: + quit("builder is nested") + + this.current_vtable.setLen(numfields) + for i in this.current_vtable.mitems(): + i = 0 + this.objectEnd = this.Offset() + this.nested = true + +proc GrowByteBuffer*(this) = + if this.bytes.len == MAX_BUFFER_SIZE: + quit("flatbuffers: cannot grow buffer beyond 2 gigabytes") + let oldLen = this.bytes.len + var newLen = min(this.bytes.len * 2, MAX_BUFFER_SIZE) + if newLen == 0: + newLen = 1 + this.bytes.setLen(newLen) + var j = this.bytes.len - 1 + while j >= 0: + if j >= newLen - oldLen: + this.bytes[j] = this.bytes[j - (newLen - oldLen)] + else: + this.bytes[j] = 0 + dec(j) + +proc Place*[T](this; x: T) = + this.head -= uoffset x.sizeof + WriteVal(this.bytes, this.head, x) + +func Pad*(this; n: int) = + for i in 0.. this.minalign: + this.minalign = size + var alignsize = (not (this.bytes.len - this.head.int + additionalBytes)) + 1 + alignsize = alignsize and (size - 1) + + while this.head.int < alignsize + size + additionalBytes: + let oldbufSize = this.bytes.len + this.GrowByteBuffer() + this.head = (this.head.int + this.bytes.len - oldbufSize).uoffset + this.Pad(alignsize) + +proc PrependOffsetRelative*[T: Offsets](this; off: T) = + when T is voffset: + this.Prep(T.sizeof, 0) + if not off.uoffset <= this.Offset: + quit("flatbuffers: Offset arithmetic error.") + this.Place(off) + else: + this.Prep(T.sizeof, 0) + if not off.uoffset <= this.Offset: + quit("flatbuffers: Offset arithmetic error.") + let off2: T = this.Offset.T - off + sizeof(T).T + this.Place(off2) + + +proc Prepend*[T](this; x: T) = + this.Prep(x.sizeof, 0) + this.Place(x) + +proc Slot*(this; slotnum: int) = + this.current_vtable[slotnum] = this.Offset + +proc PrependSlot*[T](this; o: int; x, d: T) = + if x != d: + when T is uoffset or T is soffset or T is voffset: + this.PrependOffsetRelative(x) + else: + this.Prepend(x) + this.Slot(o) + +proc AssertStuctInline(this; obj: uoffset) = + if obj != this.Offset: + quit("flatbuffers: Tried to write a Struct at an Offset that is different from the current Offset of the Builder.") + +proc PrependStructSlot*(this; o: int; x: uoffset; d: uoffset) = + if x != d: + this.AssertStuctInline(x) + this.Slot(o) + +proc Add*[T](this; n: T) = + this.Prep(T.sizeof, 0) + WriteVal(this.bytes, this.head, n) + +proc VtableEqual*(a: seq[uoffset]; objectStart: uoffset; b: seq[byte]): bool = + if a.len * voffset.sizeof != b.len: + return false + + var i = 0 + while i < a.len: + var seq = b[i * voffset.sizeof..<(i + 1) * voffset.sizeof] + let x = GetVal[voffset](addr seq) + + if x == 0 and a[i] == 0: + inc i + continue + + let y = objectStart.soffset - a[i].soffset + if x.soffset != y: + return false + inc i + return true + +proc WriteVtable*(this): uoffset = + this.PrependOffsetRelative(0.soffset) + + let objectOffset = this.Offset + var existingVtable = uoffset 0 + + var i = this.current_vtable.len - 1 + while i >= 0 and this.current_vtable[i] == 0: dec i + + this.current_vtable = this.current_vtable[0..i] + for i in countdown(this.vtables.len - 1, 0): + let + vt2Offset: uoffset = this.vtables[i] + vt2Start: int = this.bytes.len - int vt2Offset + + var seq = this.bytes[vt2Start.._buffer = $bytes; + + return $bb; + } + + /** + * @param $size + */ + public function __construct($size) + { + $this->_buffer = str_repeat("\0", $size); + } + + /** + * @return int + */ + public function capacity() + { + return strlen($this->_buffer); + } + + /** + * @return int + */ + public function getPosition() + { + return $this->_pos; + } + + /** + * @param $pos + */ + public function setPosition($pos) + { + $this->_pos = $pos; + } + + /** + * + */ + public function reset() + { + $this->_pos = 0; + } + + /** + * @return int + */ + public function length() + { + return strlen($this->_buffer); + } + + /** + * @return string + */ + public function data() + { + return substr($this->_buffer, $this->_pos); + } + + /** + * @return bool + */ + public static function isLittleEndian() + { + if (ByteBuffer::$_is_little_endian === null) { + ByteBuffer::$_is_little_endian = unpack('S', "\x01\x00")[1] === 1; + } + + return ByteBuffer::$_is_little_endian; + } + + /** + * write little endian value to the buffer. + * + * @param $offset + * @param $count byte length + * @param $data actual values + */ + public function writeLittleEndian($offset, $count, $data) + { + if (ByteBuffer::isLittleEndian()) { + for ($i = 0; $i < $count; $i++) { + $this->_buffer[$offset + $i] = chr($data >> $i * 8); + } + } else { + for ($i = 0; $i < $count; $i++) { + $this->_buffer[$offset + $count - 1 - $i] = chr($data >> $i * 8); + } + } + } + + /** + * read little endian value from the buffer + * + * @param $offset + * @param $count acutal size + * @return int + */ + public function readLittleEndian($offset, $count, $force_bigendian = false) + { + $this->assertOffsetAndLength($offset, $count); + $r = 0; + + if (ByteBuffer::isLittleEndian() && $force_bigendian == false) { + for ($i = 0; $i < $count; $i++) { + $r |= ord($this->_buffer[$offset + $i]) << $i * 8; + } + } else { + for ($i = 0; $i < $count; $i++) { + $r |= ord($this->_buffer[$offset + $count -1 - $i]) << $i * 8; + } + } + + return $r; + } + + /** + * @param $offset + * @param $length + */ + public function assertOffsetAndLength($offset, $length) + { + if ($offset < 0 || + $offset >= strlen($this->_buffer) || + $offset + $length > strlen($this->_buffer)) { + throw new \OutOfRangeException(sprintf("offset: %d, length: %d, buffer; %d", $offset, $length, strlen($this->_buffer))); + } + } + + /** + * @param $offset + * @param $value + * @return mixed + */ + public function putSbyte($offset, $value) + { + self::validateValue(-128, 127, $value, "sbyte"); + + $length = strlen($value); + $this->assertOffsetAndLength($offset, $length); + return $this->_buffer[$offset] = $value; + } + + /** + * @param $offset + * @param $value + * @return mixed + */ + public function putByte($offset, $value) + { + self::validateValue(0, 255, $value, "byte"); + + $length = strlen($value); + $this->assertOffsetAndLength($offset, $length); + return $this->_buffer[$offset] = $value; + } + + /** + * @param $offset + * @param $value + */ + public function put($offset, $value) + { + $length = strlen($value); + $this->assertOffsetAndLength($offset, $length); + for ($i = 0; $i < $length; $i++) { + $this->_buffer[$offset + $i] = $value[$i]; + } + } + + /** + * @param $offset + * @param $value + */ + public function putShort($offset, $value) + { + self::validateValue(-32768, 32767, $value, "short"); + + $this->assertOffsetAndLength($offset, 2); + $this->writeLittleEndian($offset, 2, $value); + } + + /** + * @param $offset + * @param $value + */ + public function putUshort($offset, $value) + { + self::validateValue(0, 65535, $value, "short"); + + $this->assertOffsetAndLength($offset, 2); + $this->writeLittleEndian($offset, 2, $value); + } + + /** + * @param $offset + * @param $value + */ + public function putInt($offset, $value) + { + // 2147483647 = (1 << 31) -1 = Maximum signed 32-bit int + // -2147483648 = -1 << 31 = Minimum signed 32-bit int + self::validateValue(-2147483648, 2147483647, $value, "int"); + + $this->assertOffsetAndLength($offset, 4); + $this->writeLittleEndian($offset, 4, $value); + } + + /** + * @param $offset + * @param $value + */ + public function putUint($offset, $value) + { + // NOTE: We can't put big integer value. this is PHP limitation. + // 4294967295 = (1 << 32) -1 = Maximum unsigned 32-bin int + self::validateValue(0, 4294967295, $value, "uint", " php has big numbers limitation. check your PHP_INT_MAX"); + + $this->assertOffsetAndLength($offset, 4); + $this->writeLittleEndian($offset, 4, $value); + } + + /** + * @param $offset + * @param $value + */ + public function putLong($offset, $value) + { + // NOTE: We can't put big integer value. this is PHP limitation. + self::validateValue(~PHP_INT_MAX, PHP_INT_MAX, $value, "long", " php has big numbers limitation. check your PHP_INT_MAX"); + + $this->assertOffsetAndLength($offset, 8); + $this->writeLittleEndian($offset, 8, $value); + } + + /** + * @param $offset + * @param $value + */ + public function putUlong($offset, $value) + { + // NOTE: We can't put big integer value. this is PHP limitation. + self::validateValue(0, PHP_INT_MAX, $value, "long", " php has big numbers limitation. check your PHP_INT_MAX"); + + $this->assertOffsetAndLength($offset, 8); + $this->writeLittleEndian($offset, 8, $value); + } + + /** + * @param $offset + * @param $value + */ + public function putFloat($offset, $value) + { + $this->assertOffsetAndLength($offset, 4); + + $floathelper = pack("f", $value); + $v = unpack("V", $floathelper); + $this->writeLittleEndian($offset, 4, $v[1]); + } + + /** + * @param $offset + * @param $value + */ + public function putDouble($offset, $value) + { + $this->assertOffsetAndLength($offset, 8); + + $floathelper = pack("d", $value); + $v = unpack("V*", $floathelper); + + $this->writeLittleEndian($offset, 4, $v[1]); + $this->writeLittleEndian($offset + 4, 4, $v[2]); + } + + /** + * @param $index + * @return mixed + */ + public function getByte($index) + { + return ord($this->_buffer[$index]); + } + + /** + * @param $index + * @return mixed + */ + public function getSbyte($index) + { + $v = unpack("c", $this->_buffer[$index]); + return $v[1]; + } + + /** + * @param $buffer + */ + public function getX(&$buffer) + { + for ($i = $this->_pos, $j = 0; $j < strlen($buffer); $i++, $j++) { + $buffer[$j] = $this->_buffer[$i]; + } + } + + /** + * @param $index + * @return mixed + */ + public function get($index) + { + $this->assertOffsetAndLength($index, 1); + return $this->_buffer[$index]; + } + + + /** + * @param $index + * @return mixed + */ + public function getBool($index) + { + return (bool)ord($this->_buffer[$index]); + } + + /** + * @param $index + * @return int + */ + public function getShort($index) + { + $result = $this->readLittleEndian($index, 2); + + $sign = $index + (ByteBuffer::isLittleEndian() ? 1 : 0); + $issigned = isset($this->_buffer[$sign]) && ord($this->_buffer[$sign]) & 0x80; + + // 65536 = 1 << 16 = Maximum unsigned 16-bit int + return $issigned ? $result - 65536 : $result; + } + + /** + * @param $index + * @return int + */ + public function getUShort($index) + { + return $this->readLittleEndian($index, 2); + } + + /** + * @param $index + * @return int + */ + public function getInt($index) + { + $result = $this->readLittleEndian($index, 4); + + $sign = $index + (ByteBuffer::isLittleEndian() ? 3 : 0); + $issigned = isset($this->_buffer[$sign]) && ord($this->_buffer[$sign]) & 0x80; + + if (PHP_INT_SIZE > 4) { + // 4294967296 = 1 << 32 = Maximum unsigned 32-bit int + return $issigned ? $result - 4294967296 : $result; + } else { + // 32bit / Windows treated number as signed integer. + return $result; + } + } + + /** + * @param $index + * @return int + */ + public function getUint($index) + { + return $this->readLittleEndian($index, 4); + } + + /** + * @param $index + * @return int + */ + public function getLong($index) + { + return $this->readLittleEndian($index, 8); + } + + /** + * @param $index + * @return int + */ + public function getUlong($index) + { + return $this->readLittleEndian($index, 8); + } + + /** + * @param $index + * @return mixed + */ + public function getFloat($index) + { + $i = $this->readLittleEndian($index, 4); + + return self::convertHelper(self::__FLOAT, $i); + } + + /** + * @param $index + * @return float + */ + public function getDouble($index) + { + $i = $this->readLittleEndian($index, 4); + $i2 = $this->readLittleEndian($index + 4, 4); + + return self::convertHelper(self::__DOUBLE, $i, $i2); + } + + const __SHORT = 1; + const __INT = 2; + const __LONG = 3; + const __FLOAT = 4; + const __DOUBLE = 5; + private static function convertHelper($type, $value, $value2 = null) { + // readLittleEndian construct unsigned integer value from bytes. we have to encode this value to + // correct bytes, and decode as expected types with `unpack` function. + // then it returns correct type value. + // see also: http://php.net/manual/en/function.pack.php + + switch ($type) { + case self::__FLOAT: + $inthelper = pack("V", $value); + $v = unpack("f", $inthelper); + return $v[1]; + break; + case self::__DOUBLE: + $inthelper = pack("VV", $value, $value2); + $v = unpack("d", $inthelper); + return $v[1]; + break; + default: + throw new \Exception(sprintf("unexpected type %d specified", $type)); + } + } + + private static function validateValue($min, $max, $value, $type, $additional_notes = "") { + if ( + !( + ($type === "byte" && $min <= ord($value) && ord($value) <= $max) || + ($min <= $value && $value <= $max) + ) + ) { + throw new \InvalidArgumentException(sprintf("bad number %s for type %s.%s", $value, $type, $additional_notes)); + } + } +} diff --git a/third_party/flatbuffers/php/Constants.php b/third_party/flatbuffers/php/Constants.php new file mode 100644 index 00000000000..ef3730d4281 --- /dev/null +++ b/third_party/flatbuffers/php/Constants.php @@ -0,0 +1,25 @@ +space = $initial_size; + $this->bb = $this->newByteBuffer($initial_size); + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * create new bytebuffer + * + * @param $size + * @return ByteBuffer + */ + private function newByteBuffer($size) + { + return new ByteBuffer($size); + } + + /** + * Returns the current ByteBuffer offset. + * + * @return int + */ + public function offset() + { + return $this->bb->capacity() - $this->space; + } + + /** + * padding buffer + * + * @param $byte_size + */ + public function pad($byte_size) + { + for ($i = 0; $i < $byte_size; $i++) { + $this->bb->putByte(--$this->space, "\0"); + } + } + + /** + * prepare bytebuffer + * + * @param $size + * @param $additional_bytes + * @throws \Exception + */ + public function prep($size, $additional_bytes) + { + if ($size > $this->minalign) { + $this->minalign = $size; + } + + $align_size = ((~($this->bb->capacity() - $this->space + $additional_bytes)) + 1) & ($size - 1); + while ($this->space < $align_size + $size + $additional_bytes) { + $old_buf_size = $this->bb->capacity(); + $this->bb = $this->growByteBuffer($this->bb); + $this->space += $this->bb->capacity() - $old_buf_size; + } + + $this->pad($align_size); + } + + /** + * @param ByteBuffer $bb + * @return ByteBuffer + * @throws \Exception + */ + private static function growByteBuffer(ByteBuffer $bb) + { + $old_buf_size = $bb->capacity(); + if (($old_buf_size & 0xC0000000) != 0) { + throw new \Exception("FlatBuffers: cannot grow buffer beyond 2 gigabytes"); + } + $new_buf_size = $old_buf_size << 1; + + $bb->setPosition(0); + $nbb = new ByteBuffer($new_buf_size); + + $nbb->setPosition($new_buf_size - $old_buf_size); + + // TODO(chobie): is this little bit faster? + //$nbb->_buffer = substr_replace($nbb->_buffer, $bb->_buffer, $new_buf_size - $old_buf_size, strlen($bb->_buffer)); + for ($i = $new_buf_size - $old_buf_size, $j = 0; $j < strlen($bb->_buffer); $i++, $j++) { + $nbb->_buffer[$i] = $bb->_buffer[$j]; + } + + return $nbb; + } + + /** + * @param $x + */ + public function putBool($x) + { + $this->bb->put($this->space -= 1, chr((int)(bool)($x))); + } + + /** + * @param $x + */ + public function putByte($x) + { + $this->bb->put($this->space -= 1, chr($x)); + } + + /** + * @param $x + */ + public function putSbyte($x) + { + $this->bb->put($this->space -= 1, chr($x)); + } + + /** + * @param $x + */ + public function putShort($x) + { + $this->bb->putShort($this->space -= 2, $x); + } + + /** + * @param $x + */ + public function putUshort($x) + { + $this->bb->putUshort($this->space -= 2, $x); + } + + /** + * @param $x + */ + public function putInt($x) + { + $this->bb->putInt($this->space -= 4, $x); + } + + /** + * @param $x + */ + public function putUint($x) + { + if ($x > PHP_INT_MAX) { + throw new \InvalidArgumentException("your platform can't handle uint correctly. use 64bit machine."); + } + + $this->bb->putUint($this->space -= 4, $x); + } + + /** + * @param $x + */ + public function putLong($x) + { + if ($x > PHP_INT_MAX) { + throw new \InvalidArgumentException("Your platform can't handle long correctly. Use a 64bit machine."); + } + + $this->bb->putLong($this->space -= 8, $x); + } + + /** + * @param $x + */ + public function putUlong($x) + { + if ($x > PHP_INT_MAX) { + throw new \InvalidArgumentException("Your platform can't handle ulong correctly. This is a php limitation. Please wait for the extension release."); + } + + $this->bb->putUlong($this->space -= 8, $x); + } + + /** + * @param $x + */ + public function putFloat($x) + { + $this->bb->putFloat($this->space -= 4, $x); + } + + /** + * @param $x + */ + public function putDouble($x) + { + $this->bb->putDouble($this->space -= 8, $x); + } + + /** + * @param $off + */ + public function putOffset($off) + { + $new_off = $this->offset() - $off + Constants::SIZEOF_INT; + $this->putInt($new_off); + } + /// @endcond + + /** + * Add a `bool` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `bool` to add to the buffer. + */ + public function addBool($x) + { + $this->prep(1, 0); + $this->putBool($x); + } + + /** + * Add a `byte` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `byte` to add to the buffer. + */ + public function addByte($x) + { + $this->prep(1, 0); + $this->putByte($x); + } + + /** + * Add a `signed byte` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `signed byte` to add to the buffer. + */ + public function addSbyte($x) + { + $this->prep(1, 0); + $this->putSbyte($x); + } + + /** + * Add a `short` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `short` to add to the buffer. + */ + public function addShort($x) + { + $this->prep(2, 0); + $this->putShort($x); + } + + /** + * Add an `unsigned short` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `unsigned short` to add to the buffer. + */ + public function addUshort($x) + { + $this->prep(2, 0); + $this->putUshort($x); + } + + /** + * Add an `int` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `int` to add to the buffer. + */ + public function addInt($x) + { + $this->prep(4, 0); + $this->putInt($x); + } + + /** + * Add an `unsigned int` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `unsigned int` to add to the buffer. + */ + public function addUint($x) + { + $this->prep(4, 0); + $this->putUint($x); + } + + /** + * Add a `long` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `long` to add to the buffer. + */ + public function addLong($x) + { + $this->prep(8, 0); + $this->putLong($x); + } + + /** + * Add an `unsigned long` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `unsigned long` to add to the buffer. + */ + public function addUlong($x) + { + $this->prep(8, 0); + $this->putUlong($x); + } + + /** + * Add a `float` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `float` to add to the buffer. + */ + public function addFloat($x) + { + $this->prep(4, 0); + $this->putFloat($x); + } + + /** + * Add a `double` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param $x The `double` to add to the buffer. + */ + public function addDouble($x) + { + $this->prep(8, 0); + $this->putDouble($x); + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * @param $o + * @param $x + * @param $d + */ + public function addBoolX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addBool($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addByteX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addByte($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addSbyteX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addSbyte($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addShortX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addShort($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addUshortX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addUshort($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addIntX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addInt($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addUintX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addUint($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addLongX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addLong($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addUlongX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addUlong($x); + $this->slot($o); + } + } + + + /** + * @param $o + * @param $x + * @param $d + */ + public function addFloatX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addFloat($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + */ + public function addDoubleX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addDouble($x); + $this->slot($o); + } + } + + /** + * @param $o + * @param $x + * @param $d + * @throws \Exception + */ + public function addOffsetX($o, $x, $d) + { + if ($this->force_defaults || $x != $d) { + $this->addOffset($x); + $this->slot($o); + } + } + /// @endcond + + /** + * Adds on offset, relative to where it will be written. + * @param $off The offset to add to the buffer. + * @throws \Exception Throws an exception if `$off` is greater than the underlying ByteBuffer's + * offest. + */ + public function addOffset($off) + { + $this->prep(Constants::SIZEOF_INT, 0); // Ensure alignment is already done + if ($off > $this->offset()) { + throw new \Exception(""); + } + $this->putOffset($off); + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * @param $elem_size + * @param $num_elems + * @param $alignment + * @throws \Exception + */ + public function startVector($elem_size, $num_elems, $alignment) + { + $this->notNested(); + $this->vector_num_elems = $num_elems; + $this->prep(Constants::SIZEOF_INT, $elem_size * $num_elems); + $this->prep($alignment, $elem_size * $num_elems); // Just in case alignemnt > int; + } + + /** + * @return int + */ + public function endVector() + { + $this->putUint($this->vector_num_elems); + return $this->offset(); + } + + protected function is_utf8($bytes) + { + if (function_exists('mb_detect_encoding')) { + return (bool) mb_detect_encoding($bytes, 'UTF-8', true); + } + + $len = strlen($bytes); + if ($len < 1) { + /* NOTE: always return 1 when passed string is null */ + return true; + } + + for ($j = 0, $i = 0; $i < $len; $i++) { + // check ACII + if ($bytes[$j] == "\x09" || + $bytes[$j] == "\x0A" || + $bytes[$j] == "\x0D" || + ($bytes[$j] >= "\x20" && $bytes[$j] <= "\x7E")) { + $j++; + continue; + } + + /* non-overlong 2-byte */ + if ((($i+1) <= $len) && + ($bytes[$j] >= "\xC2" && $bytes[$j] <= "\xDF" && + ($bytes[$j+1] >= "\x80" && $bytes[$j+1] <= "\xBF"))) { + $j += 2; + $i++; + continue; + } + + /* excluding overlongs */ + if ((($i + 2) <= $len) && + $bytes[$j] == "\xE0" && + ($bytes[$j+1] >= "\xA0" && $bytes[$j+1] <= "\xBF" && + ($bytes[$j+2] >= "\x80" && $bytes[$j+2] <= "\xBF"))) { + $bytes += 3; + $i +=2; + continue; + } + + /* straight 3-byte */ + if ((($i+2) <= $len) && + (($bytes[$j] >= "\xE1" && $bytes[$j] <= "\xEC") || + $bytes[$j] == "\xEE" || + $bytes[$j] = "\xEF") && + ($bytes[$j+1] >= "\x80" && $bytes[$j+1] <= "\xBF") && + ($bytes[$j+2] >= "\x80" && $bytes[$j+2] <= "\xBF")) { + $j += 3; + $i += 2; + continue; + } + + /* excluding surrogates */ + if ((($i+2) <= $len) && + $bytes[$j] == "\xED" && + ($bytes[$j+1] >= "\x80" && $bytes[$j+1] <= "\x9f" && + ($bytes[$j+2] >= "\x80" && $bytes[$j+2] <= "\xBF"))) { + $j += 3; + $i += 2; + continue; + } + + /* planes 1-3 */ + if ((($i + 3) <= $len) && + $bytes[$j] == "\xF0" && + ($bytes[$j+1] >= "\x90" && $bytes[$j+1] <= "\xBF") && + ($bytes[$j+2] >= "\x80" && $bytes[$j+2] <= "\xBF") && + ($bytes[$j+3] >= "\x80" && $bytes[$j+3] <= "\xBF")) { + $j += 4; + $i += 3; + continue; + } + + + /* planes 4-15 */ + if ((($i+3) <= $len) && + $bytes[$j] >= "\xF1" && $bytes[$j] <= "\xF3" && + $bytes[$j+1] >= "\x80" && $bytes[$j+1] <= "\xBF" && + $bytes[$j+2] >= "\x80" && $bytes[$j+2] <= "\xBF" && + $bytes[$j+3] >= "\x80" && $bytes[$j+3] <= "\xBF" + ) { + $j += 4; + $i += 3; + continue; + } + + /* plane 16 */ + if ((($i+3) <= $len) && + $bytes[$j] == "\xF4" && + ($bytes[$j+1] >= "\x80" && $bytes[$j+1] <= "\x8F") && + ($bytes[$j+2] >= "\x80" && $bytes[$j+2] <= "\xBF") && + ($bytes[$j+3] >= "\x80" && $bytes[$j+3] <= "\xBF") + ) { + $bytes += 4; + $i += 3; + continue; + } + + + return false; + } + + return true; + } + /// @endcond + + /** + * Encode the string `$s` in the buffer using UTF-8. + * @param string $s The string to encode. + * @return int The offset in the buffer where the encoded string starts. + * @throws InvalidArgumentException Thrown if the input string `$s` is not + * UTF-8. + */ + public function createString($s) + { + if (!$this->is_utf8($s)) { + throw new \InvalidArgumentException("string must be utf-8 encoded value."); + } + + $this->notNested(); + $this->addByte(0); // null terminated + $this->startVector(1, strlen($s), 1); + $this->space -= strlen($s); + for ($i = $this->space, $j = 0 ; $j < strlen($s) ; $i++, $j++) { + $this->bb->_buffer[$i] = $s[$j]; + } + return $this->endVector(); + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * @throws \Exception + */ + public function notNested() + { + if ($this->nested) { + throw new \Exception("FlatBuffers; object serialization must not be nested"); + } + } + + /** + * @param $obj + * @throws \Exception + */ + public function nested($obj) + { + if ($obj != $this->offset()) { + throw new \Exception("FlatBuffers: struct must be serialized inline"); + } + } + + /** + * @param $numfields + * @throws \Exception + */ + public function startObject($numfields) + { + $this->notNested(); + if ($this->vtable == null || count($this->vtable) < $numfields) { + $this->vtable = array(); + } + + $this->vtable_in_use = $numfields; + for ($i = 0; $i < $numfields; $i++) { + $this->vtable[$i] = 0; + } + + $this->nested = true; + $this->object_start = $this->offset(); + } + + /** + * @param $voffset + * @param $x + * @param $d + * @throws \Exception + */ + public function addStructX($voffset, $x, $d) + { + if ($x != $d) { + $this->nested($x); + $this->slot($voffset); + } + } + + /** + * @param $voffset + * @param $x + * @param $d + * @throws \Exception + */ + public function addStruct($voffset, $x, $d) + { + if ($x != $d) { + $this->nested($x); + $this->slot($voffset); + } + } + + /** + * @param $voffset + */ + public function slot($voffset) + { + $this->vtable[$voffset] = $this->offset(); + } + + /** + * @return int + * @throws \Exception + */ + public function endObject() + { + if ($this->vtable == null || !$this->nested) { + throw new \Exception("FlatBuffers: endObject called without startObject"); + } + + $this->addInt(0); + $vtableloc = $this->offset(); + + $i = $this->vtable_in_use -1; + // Trim trailing zeroes. + for (; $i >= 0 && $this->vtable[$i] == 0; $i--) {} + $trimmed_size = $i + 1; + for (; $i >= 0; $i--) { + $off = ($this->vtable[$i] != 0) ? $vtableloc - $this->vtable[$i] : 0; + $this->addShort($off); + } + + $standard_fields = 2; // the fields below + $this->addShort($vtableloc - $this->object_start); + $this->addShort(($trimmed_size + $standard_fields) * Constants::SIZEOF_SHORT); + + // search for an existing vtable that matches the current one. + $existing_vtable = 0; + + for ($i = 0; $i < $this->num_vtables; $i++) { + $vt1 = $this->bb->capacity() - $this->vtables[$i]; + $vt2 = $this->space; + + $len = $this->bb->getShort($vt1); + + if ($len == $this->bb->getShort($vt2)) { + for ($j = Constants::SIZEOF_SHORT; $j < $len; $j += Constants::SIZEOF_SHORT) { + if ($this->bb->getShort($vt1 + $j) != $this->bb->getShort($vt2 + $j)) { + continue 2; + } + } + $existing_vtable = $this->vtables[$i]; + break; + } + } + + if ($existing_vtable != 0) { + // Found a match: + // Remove the current vtable + $this->space = $this->bb->capacity() - $vtableloc; + $this->bb->putInt($this->space, $existing_vtable - $vtableloc); + } else { + // No Match: + // Add the location of the current vtable to the list of vtables + if ($this->num_vtables == count($this->vtables)) { + $vtables = $this->vtables; + $this->vtables = array(); + // copy of + for ($i = 0; $i < count($vtables) * 2; $i++) { + $this->vtables[$i] = ($i < count($vtables)) ? $vtables[$i] : 0; + } + } + $this->vtables[$this->num_vtables++] = $this->offset(); + $this->bb->putInt($this->bb->capacity() - $vtableloc, $this->offset() - $vtableloc); + } + + $this->nested = false; + $this->vtable = null; + return $vtableloc; + } + + /** + * @param $table + * @param $field + * @throws \Exception + */ + public function required($table, $field) + { + $table_start = $this->bb->capacity() - $table; + $vtable_start = $table_start - $this->bb->getInt($table_start); + $ok = $this->bb->getShort($vtable_start + $field) != 0; + + if (!$ok) { + throw new \Exception("FlatBuffers: field " . $field . " must be set"); + } + } + /// @endcond + + /** + * Finalize a buffer, pointing to the given `$root_table`. + * @param $root_table An offest to be added to the buffer. + * @param $file_identifier A FlatBuffer file identifier to be added to the + * buffer before `$root_table`. This defaults to `null`. + * @throws InvalidArgumentException Thrown if an invalid `$identifier` is + * given, where its length is not equal to + * `Constants::FILE_IDENTIFIER_LENGTH`. + */ + public function finish($root_table, $identifier = null) + { + if ($identifier == null) { + $this->prep($this->minalign, Constants::SIZEOF_INT); + $this->addOffset($root_table); + $this->bb->setPosition($this->space); + } else { + $this->prep($this->minalign, Constants::SIZEOF_INT + Constants::FILE_IDENTIFIER_LENGTH); + if (strlen($identifier) != Constants::FILE_IDENTIFIER_LENGTH) { + throw new \InvalidArgumentException( + sprintf("FlatBuffers: file identifier must be length %d", + Constants::FILE_IDENTIFIER_LENGTH)); + } + + for ($i = Constants::FILE_IDENTIFIER_LENGTH - 1; $i >= 0; + $i--) { + $this->addByte(ord($identifier[$i])); + } + $this->finish($root_table); + } + } + + /** + * In order to save space, fields that are set to their default value don't + * get serialized into the buffer. + * @param bool $forceDefaults When set to `true`, always serializes default + * values. + */ + public function forceDefaults($forceDefaults) + { + $this->force_defaults = $forceDefaults; + } + + /** + * Get the ByteBuffer representing the FlatBuffer. + * @return ByteBuffer The ByteBuffer containing the FlatBuffer data. + */ + public function dataBuffer() + { + return $this->bb; + } + + /// @cond FLATBUFFERS_INTERNAL + /** + * @return int + */ + public function dataStart() + { + return $this->space; + } + /// @endcond + + /** + * Utility function to copy and return the FlatBuffer data from the + * underlying ByteBuffer. + * @return string A string (representing a byte[]) that contains a copy + * of the FlatBuffer data. + */ + public function sizedByteArray() + { + $start = $this->space; + $length = $this->bb->capacity() - $this->space; + + $result = str_repeat("\0", $length); + $this->bb->setPosition($start); + $this->bb->getX($result); + + return $result; + } +} + +/// @} diff --git a/third_party/flatbuffers/php/Struct.php b/third_party/flatbuffers/php/Struct.php new file mode 100644 index 00000000000..cd7652e7d0c --- /dev/null +++ b/third_party/flatbuffers/php/Struct.php @@ -0,0 +1,41 @@ +bb_pos = $pos; + } + + public function setByteBuffer($bb) + { + $this->bb = $bb; + } +} diff --git a/third_party/flatbuffers/php/Table.php b/third_party/flatbuffers/php/Table.php new file mode 100644 index 00000000000..bf6fe21d79d --- /dev/null +++ b/third_party/flatbuffers/php/Table.php @@ -0,0 +1,145 @@ +bb_pos = $pos; + } + + public function setByteBuffer($bb) + { + $this->bb = $bb; + } + + /** + * returns actual vtable offset + * + * @param $vtable_offset + * @return int offset > 0 means exist value. 0 means not exist + */ + protected function __offset($vtable_offset) + { + $vtable = $this->bb_pos - $this->bb->getInt($this->bb_pos); + return $vtable_offset < $this->bb->getShort($vtable) ? $this->bb->getShort($vtable + $vtable_offset) : 0; + } + + /** + * @param $offset + * @return mixed + */ + protected function __indirect($offset) + { + return $offset + $this->bb->getInt($offset); + } + + /** + * fetch utf8 encoded string. + * + * @param $offset + * @return string + */ + protected function __string($offset) + { + $offset += $this->bb->getInt($offset); + $len = $this->bb->getInt($offset); + $startPos = $offset + Constants::SIZEOF_INT; + return substr($this->bb->_buffer, $startPos, $len); + } + + /** + * @param $offset + * @return int + */ + protected function __vector_len($offset) + { + $offset += $this->bb_pos; + $offset += $this->bb->getInt($offset); + return $this->bb->getInt($offset); + } + + /** + * @param $offset + * @return int + */ + protected function __vector($offset) + { + $offset += $this->bb_pos; + // data starts after the length + return $offset + $this->bb->getInt($offset) + Constants::SIZEOF_INT; + } + + protected function __vector_as_bytes($vector_offset, $elem_size=1) + { + $o = $this->__offset($vector_offset); + if ($o == 0) { + return null; + } + + return substr($this->bb->_buffer, $this->__vector($o), $this->__vector_len($o) * $elem_size); + } + + /** + * @param Table $table + * @param int $offset + * @return Table + */ + protected function __union($table, $offset) + { + $offset += $this->bb_pos; + $table->setByteBufferPos($offset + $this->bb->getInt($offset)); + $table->setByteBuffer($this->bb); + return $table; + } + + /** + * @param ByteBuffer $bb + * @param string $ident + * @return bool + * @throws \ArgumentException + */ + protected static function __has_identifier($bb, $ident) + { + if (strlen($ident) != Constants::FILE_IDENTIFIER_LENGTH) { + throw new \ArgumentException("FlatBuffers: file identifier must be length " . Constants::FILE_IDENTIFIER_LENGTH); + } + + for ($i = 0; $i < 4; $i++) { + if ($ident[$i] != $bb->get($bb->getPosition() + Constants::SIZEOF_INT + $i)) { + return false; + } + } + + return true; + } +} diff --git a/third_party/flatbuffers/python/.gitignore b/third_party/flatbuffers/python/.gitignore new file mode 100644 index 00000000000..a7719469a3a --- /dev/null +++ b/third_party/flatbuffers/python/.gitignore @@ -0,0 +1,2 @@ +/dist/ +/*.egg-info/ diff --git a/third_party/flatbuffers/python/__init__.py b/third_party/flatbuffers/python/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/python/flatbuffers/__init__.py b/third_party/flatbuffers/python/flatbuffers/__init__.py new file mode 100644 index 00000000000..74dc7ee58ca --- /dev/null +++ b/third_party/flatbuffers/python/flatbuffers/__init__.py @@ -0,0 +1,19 @@ +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from .builder import Builder +from .table import Table +from .compat import range_func as compat_range +from ._version import __version__ +from . import util diff --git a/third_party/flatbuffers/python/flatbuffers/_version.py b/third_party/flatbuffers/python/flatbuffers/_version.py new file mode 100644 index 00000000000..a54de437010 --- /dev/null +++ b/third_party/flatbuffers/python/flatbuffers/_version.py @@ -0,0 +1,17 @@ +# Copyright 2019 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# Placeholder, to be updated during the release process +# by the setup.py +__version__ = u"25.2.10" diff --git a/third_party/flatbuffers/python/flatbuffers/builder.py b/third_party/flatbuffers/python/flatbuffers/builder.py new file mode 100644 index 00000000000..c39cd283aed --- /dev/null +++ b/third_party/flatbuffers/python/flatbuffers/builder.py @@ -0,0 +1,824 @@ +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from . import number_types as N +from .number_types import (UOffsetTFlags, SOffsetTFlags, VOffsetTFlags) + +from . import encode +from . import packer + +from . import compat +from .compat import range_func +from .compat import memoryview_type +from .compat import import_numpy, NumpyRequiredForThisFeature + +import warnings + +np = import_numpy() +## @file +## @addtogroup flatbuffers_python_api +## @{ + +## @cond FLATBUFFERS_INTERNAL +class OffsetArithmeticError(RuntimeError): + """ + Error caused by an Offset arithmetic error. Probably caused by bad + writing of fields. This is considered an unreachable situation in + normal circumstances. + """ + pass + + +class IsNotNestedError(RuntimeError): + """ + Error caused by using a Builder to write Object data when not inside + an Object. + """ + pass + + +class IsNestedError(RuntimeError): + """ + Error caused by using a Builder to begin an Object when an Object is + already being built. + """ + pass + + +class StructIsNotInlineError(RuntimeError): + """ + Error caused by using a Builder to write a Struct at a location that + is not the current Offset. + """ + pass + + +class BuilderSizeError(RuntimeError): + """ + Error caused by causing a Builder to exceed the hardcoded limit of 2 + gigabytes. + """ + pass + +class BuilderNotFinishedError(RuntimeError): + """ + Error caused by not calling `Finish` before calling `Output`. + """ + pass + +class EndVectorLengthMismatched(RuntimeError): + """ + The number of elements passed to EndVector does not match the number + specified in StartVector. + """ + pass + + +# VtableMetadataFields is the count of metadata fields in each vtable. +VtableMetadataFields = 2 +## @endcond + +class Builder(object): + """ A Builder is used to construct one or more FlatBuffers. + + Typically, Builder objects will be used from code generated by the `flatc` + compiler. + + A Builder constructs byte buffers in a last-first manner for simplicity and + performance during reading. + + Internally, a Builder is a state machine for creating FlatBuffer objects. + + It holds the following internal state: + - Bytes: an array of bytes. + - current_vtable: a list of integers. + - vtables: a hash of vtable entries. + + Attributes: + Bytes: The internal `bytearray` for the Builder. + finished: A boolean determining if the Builder has been finalized. + """ + + ## @cond FLATBUFFERS_INTENRAL + __slots__ = ("Bytes", "current_vtable", "head", "minalign", "objectEnd", + "vtables", "nested", "forceDefaults", "finished", "vectorNumElems", + "sharedStrings") + + """Maximum buffer size constant, in bytes. + + Builder will never allow it's buffer grow over this size. + Currently equals 2Gb. + """ + MAX_BUFFER_SIZE = 2**31 + ## @endcond + + def __init__(self, initialSize=1024): + """Initializes a Builder of size `initial_size`. + + The internal buffer is grown as needed. + """ + + if not (0 <= initialSize <= Builder.MAX_BUFFER_SIZE): + msg = "flatbuffers: Cannot create Builder larger than 2 gigabytes." + raise BuilderSizeError(msg) + + self.Bytes = bytearray(initialSize) + ## @cond FLATBUFFERS_INTERNAL + self.current_vtable = None + self.head = UOffsetTFlags.py_type(initialSize) + self.minalign = 1 + self.objectEnd = None + self.vtables = {} + self.nested = False + self.forceDefaults = False + self.sharedStrings = {} + ## @endcond + self.finished = False + + def Clear(self) -> None: + ## @cond FLATBUFFERS_INTERNAL + self.current_vtable = None + self.head = UOffsetTFlags.py_type(len(self.Bytes)) + self.minalign = 1 + self.objectEnd = None + self.vtables = {} + self.nested = False + self.forceDefaults = False + self.sharedStrings = {} + self.vectorNumElems = None + ## @endcond + self.finished = False + + def Output(self): + """Return the portion of the buffer that has been used for writing data. + + This is the typical way to access the FlatBuffer data inside the + builder. If you try to access `Builder.Bytes` directly, you would need + to manually index it with `Head()`, since the buffer is constructed + backwards. + + It raises BuilderNotFinishedError if the buffer has not been finished + with `Finish`. + """ + + if not self.finished: + raise BuilderNotFinishedError() + + return self.Bytes[self.Head():] + + ## @cond FLATBUFFERS_INTERNAL + def StartObject(self, numfields): + """StartObject initializes bookkeeping for writing a new object.""" + + self.assertNotNested() + + # use 32-bit offsets so that arithmetic doesn't overflow. + self.current_vtable = [0 for _ in range_func(numfields)] + self.objectEnd = self.Offset() + self.nested = True + + def WriteVtable(self): + """ + WriteVtable serializes the vtable for the current object, if needed. + + Before writing out the vtable, this checks pre-existing vtables for + equality to this one. If an equal vtable is found, point the object to + the existing vtable and return. + + Because vtable values are sensitive to alignment of object data, not + all logically-equal vtables will be deduplicated. + + A vtable has the following format: + + + * N, where N is the number of fields + in the schema for this type. Includes deprecated fields. + Thus, a vtable is made of 2 + N elements, each VOffsetT bytes wide. + + An object has the following format: + + + + """ + + # Prepend a zero scalar to the object. Later in this function we'll + # write an offset here that points to the object's vtable: + self.PrependSOffsetTRelative(0) + + objectOffset = self.Offset() + + vtKey = [] + trim = True + for elem in reversed(self.current_vtable): + if elem == 0: + if trim: + continue + else: + elem = objectOffset - elem + trim = False + + vtKey.append(elem) + + vtKey = tuple(vtKey) + vt2Offset = self.vtables.get(vtKey) + if vt2Offset is None: + # Did not find a vtable, so write this one to the buffer. + + # Write out the current vtable in reverse , because + # serialization occurs in last-first order: + i = len(self.current_vtable) - 1 + trailing = 0 + trim = True + while i >= 0: + off = 0 + elem = self.current_vtable[i] + i -= 1 + + if elem == 0: + if trim: + trailing += 1 + continue + else: + # Forward reference to field; + # use 32bit number to ensure no overflow: + off = objectOffset - elem + trim = False + + self.PrependVOffsetT(off) + + # The two metadata fields are written last. + + # First, store the object bytesize: + objectSize = UOffsetTFlags.py_type(objectOffset - self.objectEnd) + self.PrependVOffsetT(VOffsetTFlags.py_type(objectSize)) + + # Second, store the vtable bytesize: + vBytes = len(self.current_vtable) - trailing + VtableMetadataFields + vBytes *= N.VOffsetTFlags.bytewidth + self.PrependVOffsetT(VOffsetTFlags.py_type(vBytes)) + + # Next, write the offset to the new vtable in the + # already-allocated SOffsetT at the beginning of this object: + objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset) + encode.Write(packer.soffset, self.Bytes, objectStart, + SOffsetTFlags.py_type(self.Offset() - objectOffset)) + + # Finally, store this vtable in memory for future + # deduplication: + self.vtables[vtKey] = self.Offset() + else: + # Found a duplicate vtable. + objectStart = SOffsetTFlags.py_type(len(self.Bytes) - objectOffset) + self.head = UOffsetTFlags.py_type(objectStart) + + # Write the offset to the found vtable in the + # already-allocated SOffsetT at the beginning of this object: + encode.Write(packer.soffset, self.Bytes, self.Head(), + SOffsetTFlags.py_type(vt2Offset - objectOffset)) + + self.current_vtable = None + return objectOffset + + def EndObject(self): + """EndObject writes data necessary to finish object construction.""" + self.assertNested() + self.nested = False + return self.WriteVtable() + + def growByteBuffer(self): + """Doubles the size of the byteslice, and copies the old data towards + the end of the new buffer (since we build the buffer backwards).""" + if len(self.Bytes) == Builder.MAX_BUFFER_SIZE: + msg = "flatbuffers: cannot grow buffer beyond 2 gigabytes" + raise BuilderSizeError(msg) + + newSize = min(len(self.Bytes) * 2, Builder.MAX_BUFFER_SIZE) + if newSize == 0: + newSize = 1 + bytes2 = bytearray(newSize) + bytes2[newSize-len(self.Bytes):] = self.Bytes + self.Bytes = bytes2 + ## @endcond + + def Head(self): + """Get the start of useful data in the underlying byte buffer. + + Note: unlike other functions, this value is interpreted as from the + left. + """ + ## @cond FLATBUFFERS_INTERNAL + return self.head + ## @endcond + + ## @cond FLATBUFFERS_INTERNAL + def Offset(self): + """Offset relative to the end of the buffer.""" + return UOffsetTFlags.py_type(len(self.Bytes) - self.Head()) + + def Pad(self, n): + """Pad places zeros at the current offset.""" + for i in range_func(n): + self.Place(0, N.Uint8Flags) + + def Prep(self, size, additionalBytes): + """ + Prep prepares to write an element of `size` after `additional_bytes` + have been written, e.g. if you write a string, you need to align + such the int length field is aligned to SizeInt32, and the string + data follows it directly. + If all you need to do is align, `additionalBytes` will be 0. + """ + + # Track the biggest thing we've ever aligned to. + if size > self.minalign: + self.minalign = size + + # Find the amount of alignment needed such that `size` is properly + # aligned after `additionalBytes`: + alignSize = (~(len(self.Bytes) - self.Head() + additionalBytes)) + 1 + alignSize &= (size - 1) + + # Reallocate the buffer if needed: + while self.Head() < alignSize+size+additionalBytes: + oldBufSize = len(self.Bytes) + self.growByteBuffer() + updated_head = self.head + len(self.Bytes) - oldBufSize + self.head = UOffsetTFlags.py_type(updated_head) + self.Pad(alignSize) + + def PrependSOffsetTRelative(self, off): + """ + PrependSOffsetTRelative prepends an SOffsetT, relative to where it + will be written. + """ + + # Ensure alignment is already done: + self.Prep(N.SOffsetTFlags.bytewidth, 0) + if not (off <= self.Offset()): + msg = "flatbuffers: Offset arithmetic error." + raise OffsetArithmeticError(msg) + off2 = self.Offset() - off + N.SOffsetTFlags.bytewidth + self.PlaceSOffsetT(off2) + ## @endcond + + def PrependUOffsetTRelative(self, off): + """Prepends an unsigned offset into vector data, relative to where it + will be written. + """ + + # Ensure alignment is already done: + self.Prep(N.UOffsetTFlags.bytewidth, 0) + if not (off <= self.Offset()): + msg = "flatbuffers: Offset arithmetic error." + raise OffsetArithmeticError(msg) + off2 = self.Offset() - off + N.UOffsetTFlags.bytewidth + self.PlaceUOffsetT(off2) + + ## @cond FLATBUFFERS_INTERNAL + def StartVector(self, elemSize, numElems, alignment): + """ + StartVector initializes bookkeeping for writing a new vector. + + A vector has the following format: + - + - +, where T is the type of elements of this vector. + """ + + self.assertNotNested() + self.nested = True + self.vectorNumElems = numElems + self.Prep(N.Uint32Flags.bytewidth, elemSize*numElems) + self.Prep(alignment, elemSize*numElems) # In case alignment > int. + return self.Offset() + ## @endcond + + def EndVector(self, numElems = None): + """EndVector writes data necessary to finish vector construction.""" + + self.assertNested() + ## @cond FLATBUFFERS_INTERNAL + self.nested = False + ## @endcond + + if numElems: + warnings.warn("numElems is deprecated.", + DeprecationWarning, stacklevel=2) + if numElems != self.vectorNumElems: + raise EndVectorLengthMismatched(); + + # we already made space for this, so write without PrependUint32 + self.PlaceUOffsetT(self.vectorNumElems) + self.vectorNumElems = None + return self.Offset() + + def CreateSharedString(self, s, encoding='utf-8', errors='strict'): + """ + CreateSharedString checks if the string is already written to the buffer + before calling CreateString. + """ + + if s in self.sharedStrings: + return self.sharedStrings[s] + + off = self.CreateString(s, encoding, errors) + self.sharedStrings[s] = off + + return off + + def CreateString(self, s, encoding='utf-8', errors='strict'): + """CreateString writes a null-terminated byte string as a vector.""" + + self.assertNotNested() + ## @cond FLATBUFFERS_INTERNAL + self.nested = True + ## @endcond + + if isinstance(s, compat.string_types): + x = s.encode(encoding, errors) + elif isinstance(s, compat.binary_types): + x = s + else: + raise TypeError("non-string passed to CreateString") + + self.Prep(N.UOffsetTFlags.bytewidth, (len(x)+1)*N.Uint8Flags.bytewidth) + self.Place(0, N.Uint8Flags) + + l = UOffsetTFlags.py_type(len(s)) + ## @cond FLATBUFFERS_INTERNAL + self.head = UOffsetTFlags.py_type(self.Head() - l) + ## @endcond + self.Bytes[self.Head():self.Head()+l] = x + + self.vectorNumElems = len(x) + return self.EndVector() + + def CreateByteVector(self, x): + """CreateString writes a byte vector.""" + + self.assertNotNested() + ## @cond FLATBUFFERS_INTERNAL + self.nested = True + ## @endcond + + if not isinstance(x, compat.binary_types): + raise TypeError("non-byte vector passed to CreateByteVector") + + self.Prep(N.UOffsetTFlags.bytewidth, len(x)*N.Uint8Flags.bytewidth) + + l = UOffsetTFlags.py_type(len(x)) + ## @cond FLATBUFFERS_INTERNAL + self.head = UOffsetTFlags.py_type(self.Head() - l) + ## @endcond + self.Bytes[self.Head():self.Head()+l] = x + + self.vectorNumElems = len(x) + return self.EndVector() + + def CreateNumpyVector(self, x): + """CreateNumpyVector writes a numpy array into the buffer.""" + + if np is None: + # Numpy is required for this feature + raise NumpyRequiredForThisFeature("Numpy was not found.") + + if not isinstance(x, np.ndarray): + raise TypeError("non-numpy-ndarray passed to CreateNumpyVector") + + if x.dtype.kind not in ['b', 'i', 'u', 'f']: + raise TypeError("numpy-ndarray holds elements of unsupported datatype") + + if x.ndim > 1: + raise TypeError("multidimensional-ndarray passed to CreateNumpyVector") + + self.StartVector(x.itemsize, x.size, x.dtype.alignment) + + # Ensure little endian byte ordering + if x.dtype.str[0] == "<": + x_lend = x + else: + x_lend = x.byteswap(inplace=False) + + # Calculate total length + l = UOffsetTFlags.py_type(x_lend.itemsize * x_lend.size) + ## @cond FLATBUFFERS_INTERNAL + self.head = UOffsetTFlags.py_type(self.Head() - l) + ## @endcond + + # tobytes ensures c_contiguous ordering + self.Bytes[self.Head():self.Head()+l] = x_lend.tobytes(order='C') + + self.vectorNumElems = x.size + return self.EndVector() + + ## @cond FLATBUFFERS_INTERNAL + def assertNested(self): + """ + Check that we are in the process of building an object. + """ + + if not self.nested: + raise IsNotNestedError() + + def assertNotNested(self): + """ + Check that no other objects are being built while making this + object. If not, raise an exception. + """ + + if self.nested: + raise IsNestedError() + + def assertStructIsInline(self, obj): + """ + Structs are always stored inline, so need to be created right + where they are used. You'll get this error if you created it + elsewhere. + """ + + N.enforce_number(obj, N.UOffsetTFlags) + if obj != self.Offset(): + msg = ("flatbuffers: Tried to write a Struct at an Offset that " + "is different from the current Offset of the Builder.") + raise StructIsNotInlineError(msg) + + def Slot(self, slotnum): + """ + Slot sets the vtable key `voffset` to the current location in the + buffer. + + """ + self.assertNested() + self.current_vtable[slotnum] = self.Offset() + ## @endcond + + def __Finish(self, rootTable, sizePrefix, file_identifier=None): + """Finish finalizes a buffer, pointing to the given `rootTable`.""" + N.enforce_number(rootTable, N.UOffsetTFlags) + + prepSize = N.UOffsetTFlags.bytewidth + if file_identifier is not None: + prepSize += N.Int32Flags.bytewidth + if sizePrefix: + prepSize += N.Int32Flags.bytewidth + self.Prep(self.minalign, prepSize) + + if file_identifier is not None: + self.Prep(N.UOffsetTFlags.bytewidth, encode.FILE_IDENTIFIER_LENGTH) + + # Convert bytes object file_identifier to an array of 4 8-bit integers, + # and use big-endian to enforce size compliance. + # https://docs.python.org/2/library/struct.html#format-characters + file_identifier = N.struct.unpack(">BBBB", file_identifier) + for i in range(encode.FILE_IDENTIFIER_LENGTH-1, -1, -1): + # Place the bytes of the file_identifer in reverse order: + self.Place(file_identifier[i], N.Uint8Flags) + + self.PrependUOffsetTRelative(rootTable) + if sizePrefix: + size = len(self.Bytes) - self.Head() + N.enforce_number(size, N.Int32Flags) + self.PrependInt32(size) + self.finished = True + return self.Head() + + def Finish(self, rootTable, file_identifier=None): + """Finish finalizes a buffer, pointing to the given `rootTable`.""" + return self.__Finish(rootTable, False, file_identifier=file_identifier) + + def FinishSizePrefixed(self, rootTable, file_identifier=None): + """ + Finish finalizes a buffer, pointing to the given `rootTable`, + with the size prefixed. + """ + return self.__Finish(rootTable, True, file_identifier=file_identifier) + + ## @cond FLATBUFFERS_INTERNAL + def Prepend(self, flags, off): + self.Prep(flags.bytewidth, 0) + self.Place(off, flags) + + def PrependSlot(self, flags, o, x, d): + if x is not None: + N.enforce_number(x, flags) + if d is not None: + N.enforce_number(d, flags) + if x != d or (self.forceDefaults and d is not None): + self.Prepend(flags, x) + self.Slot(o) + + def PrependBoolSlot(self, *args): self.PrependSlot(N.BoolFlags, *args) + + def PrependByteSlot(self, *args): self.PrependSlot(N.Uint8Flags, *args) + + def PrependUint8Slot(self, *args): self.PrependSlot(N.Uint8Flags, *args) + + def PrependUint16Slot(self, *args): self.PrependSlot(N.Uint16Flags, *args) + + def PrependUint32Slot(self, *args): self.PrependSlot(N.Uint32Flags, *args) + + def PrependUint64Slot(self, *args): self.PrependSlot(N.Uint64Flags, *args) + + def PrependInt8Slot(self, *args): self.PrependSlot(N.Int8Flags, *args) + + def PrependInt16Slot(self, *args): self.PrependSlot(N.Int16Flags, *args) + + def PrependInt32Slot(self, *args): self.PrependSlot(N.Int32Flags, *args) + + def PrependInt64Slot(self, *args): self.PrependSlot(N.Int64Flags, *args) + + def PrependFloat32Slot(self, *args): self.PrependSlot(N.Float32Flags, + *args) + + def PrependFloat64Slot(self, *args): self.PrependSlot(N.Float64Flags, + *args) + + def PrependUOffsetTRelativeSlot(self, o, x, d): + """ + PrependUOffsetTRelativeSlot prepends an UOffsetT onto the object at + vtable slot `o`. If value `x` equals default `d`, then the slot will + be set to zero and no other data will be written. + """ + + if x != d or self.forceDefaults: + self.PrependUOffsetTRelative(x) + self.Slot(o) + + def PrependStructSlot(self, v, x, d): + """ + PrependStructSlot prepends a struct onto the object at vtable slot `o`. + Structs are stored inline, so nothing additional is being added. + In generated code, `d` is always 0. + """ + + N.enforce_number(d, N.UOffsetTFlags) + if x != d: + self.assertStructIsInline(x) + self.Slot(v) + + ## @endcond + + def PrependBool(self, x): + """Prepend a `bool` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.BoolFlags, x) + + def PrependByte(self, x): + """Prepend a `byte` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Uint8Flags, x) + + def PrependUint8(self, x): + """Prepend an `uint8` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Uint8Flags, x) + + def PrependUint16(self, x): + """Prepend an `uint16` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Uint16Flags, x) + + def PrependUint32(self, x): + """Prepend an `uint32` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Uint32Flags, x) + + def PrependUint64(self, x): + """Prepend an `uint64` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Uint64Flags, x) + + def PrependInt8(self, x): + """Prepend an `int8` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Int8Flags, x) + + def PrependInt16(self, x): + """Prepend an `int16` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Int16Flags, x) + + def PrependInt32(self, x): + """Prepend an `int32` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Int32Flags, x) + + def PrependInt64(self, x): + """Prepend an `int64` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Int64Flags, x) + + def PrependFloat32(self, x): + """Prepend a `float32` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Float32Flags, x) + + def PrependFloat64(self, x): + """Prepend a `float64` to the Builder buffer. + + Note: aligns and checks for space. + """ + self.Prepend(N.Float64Flags, x) + + def ForceDefaults(self, forceDefaults): + """ + In order to save space, fields that are set to their default value + don't get serialized into the buffer. Forcing defaults provides a + way to manually disable this optimization. When set to `True`, will + always serialize default values. + """ + self.forceDefaults = forceDefaults + +############################################################## + + ## @cond FLATBUFFERS_INTERNAL + def PrependVOffsetT(self, x): self.Prepend(N.VOffsetTFlags, x) + + def Place(self, x, flags): + """ + Place prepends a value specified by `flags` to the Builder, + without checking for available space. + """ + + N.enforce_number(x, flags) + self.head = self.head - flags.bytewidth + encode.Write(flags.packer_type, self.Bytes, self.Head(), x) + + def PlaceVOffsetT(self, x): + """PlaceVOffsetT prepends a VOffsetT to the Builder, without checking + for space. + """ + N.enforce_number(x, N.VOffsetTFlags) + self.head = self.head - N.VOffsetTFlags.bytewidth + encode.Write(packer.voffset, self.Bytes, self.Head(), x) + + def PlaceSOffsetT(self, x): + """PlaceSOffsetT prepends a SOffsetT to the Builder, without checking + for space. + """ + N.enforce_number(x, N.SOffsetTFlags) + self.head = self.head - N.SOffsetTFlags.bytewidth + encode.Write(packer.soffset, self.Bytes, self.Head(), x) + + def PlaceUOffsetT(self, x): + """PlaceUOffsetT prepends a UOffsetT to the Builder, without checking + for space. + """ + N.enforce_number(x, N.UOffsetTFlags) + self.head = self.head - N.UOffsetTFlags.bytewidth + encode.Write(packer.uoffset, self.Bytes, self.Head(), x) + ## @endcond + +## @cond FLATBUFFERS_INTERNAL +def vtableEqual(a, objectStart, b): + """vtableEqual compares an unwritten vtable to a written vtable.""" + + N.enforce_number(objectStart, N.UOffsetTFlags) + + if len(a) * N.VOffsetTFlags.bytewidth != len(b): + return False + + for i, elem in enumerate(a): + x = encode.Get(packer.voffset, b, i * N.VOffsetTFlags.bytewidth) + + # Skip vtable entries that indicate a default value. + if x == 0 and elem == 0: + pass + else: + y = objectStart - elem + if x != y: + return False + return True +## @endcond +## @} diff --git a/third_party/flatbuffers/python/flatbuffers/compat.py b/third_party/flatbuffers/python/flatbuffers/compat.py new file mode 100644 index 00000000000..0244c9787ee --- /dev/null +++ b/third_party/flatbuffers/python/flatbuffers/compat.py @@ -0,0 +1,86 @@ +# Copyright 2016 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" A tiny version of `six` to help with backwards compability. Also includes + compatibility helpers for numpy. """ + +import sys + +PY2 = sys.version_info[0] == 2 +PY26 = sys.version_info[0:2] == (2, 6) +PY27 = sys.version_info[0:2] == (2, 7) +PY275 = sys.version_info[0:3] >= (2, 7, 5) +PY3 = sys.version_info[0] == 3 +PY34 = sys.version_info[0:2] >= (3, 4) + +if PY3: + import importlib.machinery + string_types = (str,) + binary_types = (bytes,bytearray) + range_func = range + memoryview_type = memoryview + struct_bool_decl = "?" +else: + import imp + string_types = (unicode,) + if PY26 or PY27: + binary_types = (str,bytearray) + else: + binary_types = (str,) + range_func = xrange + if PY26 or (PY27 and not PY275): + memoryview_type = buffer + struct_bool_decl = "= 0 + + if value < (1 << 8): + return BitWidth.W8 + elif value < (1 << 16): + return BitWidth.W16 + elif value < (1 << 32): + return BitWidth.W32 + elif value < (1 << 64): + return BitWidth.W64 + else: + raise ValueError('value is too big to encode: %s' % value) + + @staticmethod + def I(value): + """Returns the minimum `BitWidth` to encode signed integer value.""" + # -2^(n-1) <= value < 2^(n-1) + # -2^n <= 2 * value < 2^n + # 2 * value < 2^n, when value >= 0 or 2 * (-value) <= 2^n, when value < 0 + # 2 * value < 2^n, when value >= 0 or 2 * (-value) - 1 < 2^n, when value < 0 + # + # if value >= 0: + # return BitWidth.U(2 * value) + # else: + # return BitWidth.U(2 * (-value) - 1) # ~x = -x - 1 + value *= 2 + return BitWidth.U(value if value >= 0 else ~value) + + @staticmethod + def F(value): + """Returns the `BitWidth` to encode floating point value.""" + if struct.unpack(' 0: + i = first + step = count // 2 + i += step + if pred(values[i], value): + i += 1 + first = i + count -= step + 1 + else: + count = step + return first + + +# https://en.cppreference.com/w/cpp/algorithm/binary_search +def _BinarySearch(values, value, pred=lambda x, y: x < y): + """Implementation of C++ std::binary_search() algorithm.""" + index = _LowerBound(values, value, pred) + if index != len(values) and not pred(value, values[index]): + return index + return -1 + + +class Type(enum.IntEnum): + """Supported types of encoded data. + + These are used as the upper 6 bits of a type field to indicate the actual + type. + """ + NULL = 0 + INT = 1 + UINT = 2 + FLOAT = 3 + # Types above stored inline, types below store an offset. + KEY = 4 + STRING = 5 + INDIRECT_INT = 6 + INDIRECT_UINT = 7 + INDIRECT_FLOAT = 8 + MAP = 9 + VECTOR = 10 # Untyped. + + VECTOR_INT = 11 # Typed any size (stores no type table). + VECTOR_UINT = 12 + VECTOR_FLOAT = 13 + VECTOR_KEY = 14 + # DEPRECATED, use VECTOR or VECTOR_KEY instead. + # Read test.cpp/FlexBuffersDeprecatedTest() for details on why. + VECTOR_STRING_DEPRECATED = 15 + + VECTOR_INT2 = 16 # Typed tuple (no type table, no size field). + VECTOR_UINT2 = 17 + VECTOR_FLOAT2 = 18 + VECTOR_INT3 = 19 # Typed triple (no type table, no size field). + VECTOR_UINT3 = 20 + VECTOR_FLOAT3 = 21 + VECTOR_INT4 = 22 # Typed quad (no type table, no size field). + VECTOR_UINT4 = 23 + VECTOR_FLOAT4 = 24 + + BLOB = 25 + BOOL = 26 + VECTOR_BOOL = 36 # To do the same type of conversion of type to vector type + + @staticmethod + def Pack(type_, bit_width): + return (int(type_) << 2) | bit_width + + @staticmethod + def Unpack(packed_type): + return 1 << (packed_type & 0b11), Type(packed_type >> 2) + + @staticmethod + def IsInline(type_): + return type_ <= Type.FLOAT or type_ == Type.BOOL + + @staticmethod + def IsTypedVector(type_): + return Type.VECTOR_INT <= type_ <= Type.VECTOR_STRING_DEPRECATED or \ + type_ == Type.VECTOR_BOOL + + @staticmethod + def IsTypedVectorElementType(type_): + return Type.INT <= type_ <= Type.STRING or type_ == Type.BOOL + + @staticmethod + def ToTypedVectorElementType(type_): + if not Type.IsTypedVector(type_): + raise ValueError('must be typed vector type') + + return Type(type_ - Type.VECTOR_INT + Type.INT) + + @staticmethod + def IsFixedTypedVector(type_): + return Type.VECTOR_INT2 <= type_ <= Type.VECTOR_FLOAT4 + + @staticmethod + def IsFixedTypedVectorElementType(type_): + return Type.INT <= type_ <= Type.FLOAT + + @staticmethod + def ToFixedTypedVectorElementType(type_): + if not Type.IsFixedTypedVector(type_): + raise ValueError('must be fixed typed vector type') + + # 3 types each, starting from length 2. + fixed_type = type_ - Type.VECTOR_INT2 + return Type(fixed_type % 3 + Type.INT), fixed_type // 3 + 2 + + @staticmethod + def ToTypedVector(element_type, fixed_len=0): + """Converts element type to corresponding vector type. + + Args: + element_type: vector element type + fixed_len: number of elements: 0 for typed vector; 2, 3, or 4 for fixed + typed vector. + + Returns: + Typed vector type or fixed typed vector type. + """ + if fixed_len == 0: + if not Type.IsTypedVectorElementType(element_type): + raise ValueError('must be typed vector element type') + else: + if not Type.IsFixedTypedVectorElementType(element_type): + raise ValueError('must be fixed typed vector element type') + + offset = element_type - Type.INT + if fixed_len == 0: + return Type(offset + Type.VECTOR_INT) # TypedVector + elif fixed_len == 2: + return Type(offset + Type.VECTOR_INT2) # FixedTypedVector + elif fixed_len == 3: + return Type(offset + Type.VECTOR_INT3) # FixedTypedVector + elif fixed_len == 4: + return Type(offset + Type.VECTOR_INT4) # FixedTypedVector + else: + raise ValueError('unsupported fixed_len: %s' % fixed_len) + + +class Buf: + """Class to access underlying buffer object starting from the given offset.""" + + def __init__(self, buf, offset): + self._buf = buf + self._offset = offset if offset >= 0 else len(buf) + offset + self._length = len(buf) - self._offset + + def __getitem__(self, key): + if isinstance(key, slice): + return self._buf[_ShiftSlice(key, self._offset, self._length)] + elif isinstance(key, int): + return self._buf[self._offset + key] + else: + raise TypeError('invalid key type') + + def __setitem__(self, key, value): + if isinstance(key, slice): + self._buf[_ShiftSlice(key, self._offset, self._length)] = value + elif isinstance(key, int): + self._buf[self._offset + key] = key + else: + raise TypeError('invalid key type') + + def __repr__(self): + return 'buf[%d:]' % self._offset + + def Find(self, sub): + """Returns the lowest index where the sub subsequence is found.""" + return self._buf[self._offset:].find(sub) + + def Slice(self, offset): + """Returns new `Buf` which starts from the given offset.""" + return Buf(self._buf, self._offset + offset) + + def Indirect(self, offset, byte_width): + """Return new `Buf` based on the encoded offset (indirect encoding).""" + return self.Slice(offset - _Unpack(U, self[offset:offset + byte_width])) + + +class Object: + """Base class for all non-trivial data accessors.""" + __slots__ = '_buf', '_byte_width' + + def __init__(self, buf, byte_width): + self._buf = buf + self._byte_width = byte_width + + @property + def ByteWidth(self): + return self._byte_width + + +class Sized(Object): + """Base class for all data accessors which need to read encoded size.""" + __slots__ = '_size', + + def __init__(self, buf, byte_width, size=0): + super().__init__(buf, byte_width) + if size == 0: + self._size = _Unpack(U, self.SizeBytes) + else: + self._size = size + + @property + def SizeBytes(self): + return self._buf[-self._byte_width:0] + + def __len__(self): + return self._size + + +class Blob(Sized): + """Data accessor for the encoded blob bytes.""" + __slots__ = () + + @property + def Bytes(self): + return self._buf[0:len(self)] + + def __repr__(self): + return 'Blob(%s, size=%d)' % (self._buf, len(self)) + + +class String(Sized): + """Data accessor for the encoded string bytes.""" + __slots__ = () + + @property + def Bytes(self): + return self._buf[0:len(self)] + + def Mutate(self, value): + """Mutates underlying string bytes in place. + + Args: + value: New string to replace the existing one. New string must have less + or equal UTF-8-encoded bytes than the existing one to successfully + mutate underlying byte buffer. + + Returns: + Whether the value was mutated or not. + """ + encoded = value.encode('utf-8') + n = len(encoded) + if n <= len(self): + self._buf[-self._byte_width:0] = _Pack(U, n, self._byte_width) + self._buf[0:n] = encoded + self._buf[n:len(self)] = bytearray(len(self) - n) + return True + return False + + def __str__(self): + return self.Bytes.decode('utf-8') + + def __repr__(self): + return 'String(%s, size=%d)' % (self._buf, len(self)) + + +class Key(Object): + """Data accessor for the encoded key bytes.""" + __slots__ = () + + def __init__(self, buf, byte_width): + assert byte_width == 1 + super().__init__(buf, byte_width) + + @property + def Bytes(self): + return self._buf[0:len(self)] + + def __len__(self): + return self._buf.Find(0) + + def __str__(self): + return self.Bytes.decode('ascii') + + def __repr__(self): + return 'Key(%s, size=%d)' % (self._buf, len(self)) + + +class Vector(Sized): + """Data accessor for the encoded vector bytes.""" + __slots__ = () + + def __getitem__(self, index): + if index < 0 or index >= len(self): + raise IndexError('vector index %s is out of [0, %d) range' % \ + (index, len(self))) + + packed_type = self._buf[len(self) * self._byte_width + index] + buf = self._buf.Slice(index * self._byte_width) + return Ref.PackedType(buf, self._byte_width, packed_type) + + @property + def Value(self): + """Returns the underlying encoded data as a list object.""" + return [e.Value for e in self] + + def __repr__(self): + return 'Vector(%s, byte_width=%d, size=%d)' % \ + (self._buf, self._byte_width, self._size) + + +class TypedVector(Sized): + """Data accessor for the encoded typed vector or fixed typed vector bytes.""" + __slots__ = '_element_type', '_size' + + def __init__(self, buf, byte_width, element_type, size=0): + super().__init__(buf, byte_width, size) + + if element_type == Type.STRING: + # These can't be accessed as strings, since we don't know the bit-width + # of the size field, see the declaration of + # FBT_VECTOR_STRING_DEPRECATED above for details. + # We change the type here to be keys, which are a subtype of strings, + # and will ignore the size field. This will truncate strings with + # embedded nulls. + element_type = Type.KEY + + self._element_type = element_type + + @property + def Bytes(self): + return self._buf[:self._byte_width * len(self)] + + @property + def ElementType(self): + return self._element_type + + def __getitem__(self, index): + if index < 0 or index >= len(self): + raise IndexError('vector index %s is out of [0, %d) range' % \ + (index, len(self))) + + buf = self._buf.Slice(index * self._byte_width) + return Ref(buf, self._byte_width, 1, self._element_type) + + @property + def Value(self): + """Returns underlying data as list object.""" + if not self: + return [] + + if self._element_type is Type.BOOL: + return [bool(e) for e in _UnpackVector(U, self.Bytes, len(self))] + elif self._element_type is Type.INT: + return list(_UnpackVector(I, self.Bytes, len(self))) + elif self._element_type is Type.UINT: + return list(_UnpackVector(U, self.Bytes, len(self))) + elif self._element_type is Type.FLOAT: + return list(_UnpackVector(F, self.Bytes, len(self))) + elif self._element_type is Type.KEY: + return [e.AsKey for e in self] + elif self._element_type is Type.STRING: + return [e.AsString for e in self] + else: + raise TypeError('unsupported element_type: %s' % self._element_type) + + def __repr__(self): + return 'TypedVector(%s, byte_width=%d, element_type=%s, size=%d)' % \ + (self._buf, self._byte_width, self._element_type, self._size) + + +class Map(Vector): + """Data accessor for the encoded map bytes.""" + + @staticmethod + def CompareKeys(a, b): + if isinstance(a, Ref): + a = a.AsKeyBytes + if isinstance(b, Ref): + b = b.AsKeyBytes + return a < b + + def __getitem__(self, key): + if isinstance(key, int): + return super().__getitem__(key) + + index = _BinarySearch(self.Keys, key.encode('ascii'), self.CompareKeys) + if index != -1: + return super().__getitem__(index) + + raise KeyError(key) + + @property + def Keys(self): + byte_width = _Unpack(U, self._buf[-2 * self._byte_width:-self._byte_width]) + buf = self._buf.Indirect(-3 * self._byte_width, self._byte_width) + return TypedVector(buf, byte_width, Type.KEY) + + @property + def Values(self): + return Vector(self._buf, self._byte_width) + + @property + def Value(self): + return {k.Value: v.Value for k, v in zip(self.Keys, self.Values)} + + def __repr__(self): + return 'Map(%s, size=%d)' % (self._buf, len(self)) + + +class Ref: + """Data accessor for the encoded data bytes.""" + __slots__ = '_buf', '_parent_width', '_byte_width', '_type' + + @staticmethod + def PackedType(buf, parent_width, packed_type): + byte_width, type_ = Type.Unpack(packed_type) + return Ref(buf, parent_width, byte_width, type_) + + def __init__(self, buf, parent_width, byte_width, type_): + self._buf = buf + self._parent_width = parent_width + self._byte_width = byte_width + self._type = type_ + + def __repr__(self): + return 'Ref(%s, parent_width=%d, byte_width=%d, type_=%s)' % \ + (self._buf, self._parent_width, self._byte_width, self._type) + + @property + def _Bytes(self): + return self._buf[:self._parent_width] + + def _ConvertError(self, target_type): + raise TypeError('cannot convert %s to %s' % (self._type, target_type)) + + def _Indirect(self): + return self._buf.Indirect(0, self._parent_width) + + @property + def IsNull(self): + return self._type is Type.NULL + + @property + def IsBool(self): + return self._type is Type.BOOL + + @property + def AsBool(self): + if self._type is Type.BOOL: + return bool(_Unpack(U, self._Bytes)) + else: + return self.AsInt != 0 + + def MutateBool(self, value): + """Mutates underlying boolean value bytes in place. + + Args: + value: New boolean value. + + Returns: + Whether the value was mutated or not. + """ + return self.IsBool and \ + _Mutate(U, self._buf, value, self._parent_width, BitWidth.W8) + + @property + def IsNumeric(self): + return self.IsInt or self.IsFloat + + @property + def IsInt(self): + return self._type in (Type.INT, Type.INDIRECT_INT, Type.UINT, + Type.INDIRECT_UINT) + + @property + def AsInt(self): + """Returns current reference as integer value.""" + if self.IsNull: + return 0 + elif self.IsBool: + return int(self.AsBool) + elif self._type is Type.INT: + return _Unpack(I, self._Bytes) + elif self._type is Type.INDIRECT_INT: + return _Unpack(I, self._Indirect()[:self._byte_width]) + if self._type is Type.UINT: + return _Unpack(U, self._Bytes) + elif self._type is Type.INDIRECT_UINT: + return _Unpack(U, self._Indirect()[:self._byte_width]) + elif self.IsString: + return len(self.AsString) + elif self.IsKey: + return len(self.AsKey) + elif self.IsBlob: + return len(self.AsBlob) + elif self.IsVector: + return len(self.AsVector) + elif self.IsTypedVector: + return len(self.AsTypedVector) + elif self.IsFixedTypedVector: + return len(self.AsFixedTypedVector) + else: + raise self._ConvertError(Type.INT) + + def MutateInt(self, value): + """Mutates underlying integer value bytes in place. + + Args: + value: New integer value. It must fit to the byte size of the existing + encoded value. + + Returns: + Whether the value was mutated or not. + """ + if self._type is Type.INT: + return _Mutate(I, self._buf, value, self._parent_width, BitWidth.I(value)) + elif self._type is Type.INDIRECT_INT: + return _Mutate(I, self._Indirect(), value, self._byte_width, + BitWidth.I(value)) + elif self._type is Type.UINT: + return _Mutate(U, self._buf, value, self._parent_width, BitWidth.U(value)) + elif self._type is Type.INDIRECT_UINT: + return _Mutate(U, self._Indirect(), value, self._byte_width, + BitWidth.U(value)) + else: + return False + + @property + def IsFloat(self): + return self._type in (Type.FLOAT, Type.INDIRECT_FLOAT) + + @property + def AsFloat(self): + """Returns current reference as floating point value.""" + if self.IsNull: + return 0.0 + elif self.IsBool: + return float(self.AsBool) + elif self.IsInt: + return float(self.AsInt) + elif self._type is Type.FLOAT: + return _Unpack(F, self._Bytes) + elif self._type is Type.INDIRECT_FLOAT: + return _Unpack(F, self._Indirect()[:self._byte_width]) + elif self.IsString: + return float(self.AsString) + elif self.IsVector: + return float(len(self.AsVector)) + elif self.IsTypedVector(): + return float(len(self.AsTypedVector)) + elif self.IsFixedTypedVector(): + return float(len(self.FixedTypedVector)) + else: + raise self._ConvertError(Type.FLOAT) + + def MutateFloat(self, value): + """Mutates underlying floating point value bytes in place. + + Args: + value: New float value. It must fit to the byte size of the existing + encoded value. + + Returns: + Whether the value was mutated or not. + """ + if self._type is Type.FLOAT: + return _Mutate(F, self._buf, value, self._parent_width, + BitWidth.B(self._parent_width)) + elif self._type is Type.INDIRECT_FLOAT: + return _Mutate(F, self._Indirect(), value, self._byte_width, + BitWidth.B(self._byte_width)) + else: + return False + + @property + def IsKey(self): + return self._type is Type.KEY + + @property + def AsKeyBytes(self): + if self.IsKey: + return Key(self._Indirect(), self._byte_width).Bytes + else: + raise self._ConvertError(Type.KEY) + + @property + def AsKey(self): + if self.IsKey: + return str(Key(self._Indirect(), self._byte_width)) + else: + raise self._ConvertError(Type.KEY) + + @property + def IsString(self): + return self._type is Type.STRING + + @property + def AsStringBytes(self): + if self.IsString: + return String(self._Indirect(), self._byte_width).Bytes + elif self.IsKey: + return self.AsKeyBytes + else: + raise self._ConvertError(Type.STRING) + + @property + def AsString(self): + if self.IsString: + return str(String(self._Indirect(), self._byte_width)) + elif self.IsKey: + return self.AsKey + else: + raise self._ConvertError(Type.STRING) + + def MutateString(self, value): + return String(self._Indirect(), self._byte_width).Mutate(value) + + @property + def IsBlob(self): + return self._type is Type.BLOB + + @property + def AsBlob(self): + if self.IsBlob: + return Blob(self._Indirect(), self._byte_width).Bytes + else: + raise self._ConvertError(Type.BLOB) + + @property + def IsAnyVector(self): + return self.IsVector or self.IsTypedVector or self.IsFixedTypedVector() + + @property + def IsVector(self): + return self._type in (Type.VECTOR, Type.MAP) + + @property + def AsVector(self): + if self.IsVector: + return Vector(self._Indirect(), self._byte_width) + else: + raise self._ConvertError(Type.VECTOR) + + @property + def IsTypedVector(self): + return Type.IsTypedVector(self._type) + + @property + def AsTypedVector(self): + if self.IsTypedVector: + return TypedVector(self._Indirect(), self._byte_width, + Type.ToTypedVectorElementType(self._type)) + else: + raise self._ConvertError('TYPED_VECTOR') + + @property + def IsFixedTypedVector(self): + return Type.IsFixedTypedVector(self._type) + + @property + def AsFixedTypedVector(self): + if self.IsFixedTypedVector: + element_type, size = Type.ToFixedTypedVectorElementType(self._type) + return TypedVector(self._Indirect(), self._byte_width, element_type, size) + else: + raise self._ConvertError('FIXED_TYPED_VECTOR') + + @property + def IsMap(self): + return self._type is Type.MAP + + @property + def AsMap(self): + if self.IsMap: + return Map(self._Indirect(), self._byte_width) + else: + raise self._ConvertError(Type.MAP) + + @property + def Value(self): + """Converts current reference to value of corresponding type. + + This is equivalent to calling `AsInt` for integer values, `AsFloat` for + floating point values, etc. + + Returns: + Value of corresponding type. + """ + if self.IsNull: + return None + elif self.IsBool: + return self.AsBool + elif self.IsInt: + return self.AsInt + elif self.IsFloat: + return self.AsFloat + elif self.IsString: + return self.AsString + elif self.IsKey: + return self.AsKey + elif self.IsBlob: + return self.AsBlob + elif self.IsMap: + return self.AsMap.Value + elif self.IsVector: + return self.AsVector.Value + elif self.IsTypedVector: + return self.AsTypedVector.Value + elif self.IsFixedTypedVector: + return self.AsFixedTypedVector.Value + else: + raise TypeError('cannot convert %r to value' % self) + + +def _IsIterable(obj): + try: + iter(obj) + return True + except TypeError: + return False + + +class Value: + """Class to represent given value during the encoding process.""" + + @staticmethod + def Null(): + return Value(0, Type.NULL, BitWidth.W8) + + @staticmethod + def Bool(value): + return Value(value, Type.BOOL, BitWidth.W8) + + @staticmethod + def Int(value, bit_width): + return Value(value, Type.INT, bit_width) + + @staticmethod + def UInt(value, bit_width): + return Value(value, Type.UINT, bit_width) + + @staticmethod + def Float(value, bit_width): + return Value(value, Type.FLOAT, bit_width) + + @staticmethod + def Key(offset): + return Value(offset, Type.KEY, BitWidth.W8) + + def __init__(self, value, type_, min_bit_width): + self._value = value + self._type = type_ + + # For scalars: of itself, for vector: of its elements, for string: length. + self._min_bit_width = min_bit_width + + @property + def Value(self): + return self._value + + @property + def Type(self): + return self._type + + @property + def MinBitWidth(self): + return self._min_bit_width + + def StoredPackedType(self, parent_bit_width=BitWidth.W8): + return Type.Pack(self._type, self.StoredWidth(parent_bit_width)) + + # We have an absolute offset, but want to store a relative offset + # elem_index elements beyond the current buffer end. Since whether + # the relative offset fits in a certain byte_width depends on + # the size of the elements before it (and their alignment), we have + # to test for each size in turn. + def ElemWidth(self, buf_size, elem_index=0): + if Type.IsInline(self._type): + return self._min_bit_width + for byte_width in 1, 2, 4, 8: + offset_loc = buf_size + _PaddingBytes(buf_size, byte_width) + \ + elem_index * byte_width + bit_width = BitWidth.U(offset_loc - self._value) + if byte_width == (1 << bit_width): + return bit_width + raise ValueError('relative offset is too big') + + def StoredWidth(self, parent_bit_width=BitWidth.W8): + if Type.IsInline(self._type): + return max(self._min_bit_width, parent_bit_width) + return self._min_bit_width + + def __repr__(self): + return 'Value(%s, %s, %s)' % (self._value, self._type, self._min_bit_width) + + def __str__(self): + return str(self._value) + + +def InMap(func): + def wrapper(self, *args, **kwargs): + if isinstance(args[0], str): + self.Key(args[0]) + func(self, *args[1:], **kwargs) + else: + func(self, *args, **kwargs) + return wrapper + + +def InMapForString(func): + def wrapper(self, *args): + if len(args) == 1: + func(self, args[0]) + elif len(args) == 2: + self.Key(args[0]) + func(self, args[1]) + else: + raise ValueError('invalid number of arguments') + return wrapper + + +class Pool: + """Collection of (data, offset) pairs sorted by data for quick access.""" + + def __init__(self): + self._pool = [] # sorted list of (data, offset) tuples + + def FindOrInsert(self, data, offset): + do = data, offset + index = _BinarySearch(self._pool, do, lambda a, b: a[0] < b[0]) + if index != -1: + _, offset = self._pool[index] + return offset + self._pool.insert(index, do) + return None + + def Clear(self): + self._pool = [] + + @property + def Elements(self): + return [data for data, _ in self._pool] + + +class Builder: + """Helper class to encode structural data into flexbuffers format.""" + + def __init__(self, + share_strings=False, + share_keys=True, + force_min_bit_width=BitWidth.W8): + self._share_strings = share_strings + self._share_keys = share_keys + self._force_min_bit_width = force_min_bit_width + + self._string_pool = Pool() + self._key_pool = Pool() + + self._finished = False + self._buf = bytearray() + self._stack = [] + + def __len__(self): + return len(self._buf) + + @property + def StringPool(self): + return self._string_pool + + @property + def KeyPool(self): + return self._key_pool + + def Clear(self): + self._string_pool.Clear() + self._key_pool.Clear() + self._finished = False + self._buf = bytearray() + self._stack = [] + + def Finish(self): + """Finishes encoding process and returns underlying buffer.""" + if self._finished: + raise RuntimeError('builder has been already finished') + + # If you hit this exception, you likely have objects that were never + # included in a parent. You need to have exactly one root to finish a + # buffer. Check your Start/End calls are matched, and all objects are inside + # some other object. + if len(self._stack) != 1: + raise RuntimeError('internal stack size must be one') + + value = self._stack[0] + byte_width = self._Align(value.ElemWidth(len(self._buf))) + self._WriteAny(value, byte_width=byte_width) # Root value + self._Write(U, value.StoredPackedType(), byte_width=1) # Root type + self._Write(U, byte_width, byte_width=1) # Root size + + self.finished = True + return self._buf + + def _ReadKey(self, offset): + key = self._buf[offset:] + return key[:key.find(0)] + + def _Align(self, alignment): + byte_width = 1 << alignment + self._buf.extend(b'\x00' * _PaddingBytes(len(self._buf), byte_width)) + return byte_width + + def _Write(self, fmt, value, byte_width): + self._buf.extend(_Pack(fmt, value, byte_width)) + + def _WriteVector(self, fmt, values, byte_width): + self._buf.extend(_PackVector(fmt, values, byte_width)) + + def _WriteOffset(self, offset, byte_width): + relative_offset = len(self._buf) - offset + assert byte_width == 8 or relative_offset < (1 << (8 * byte_width)) + self._Write(U, relative_offset, byte_width) + + def _WriteAny(self, value, byte_width): + fmt = { + Type.NULL: U, Type.BOOL: U, Type.INT: I, Type.UINT: U, Type.FLOAT: F + }.get(value.Type) + if fmt: + self._Write(fmt, value.Value, byte_width) + else: + self._WriteOffset(value.Value, byte_width) + + def _WriteBlob(self, data, append_zero, type_): + bit_width = BitWidth.U(len(data)) + byte_width = self._Align(bit_width) + self._Write(U, len(data), byte_width) + loc = len(self._buf) + self._buf.extend(data) + if append_zero: + self._buf.append(0) + self._stack.append(Value(loc, type_, bit_width)) + return loc + + def _WriteScalarVector(self, element_type, byte_width, elements, fixed): + """Writes scalar vector elements to the underlying buffer.""" + bit_width = BitWidth.B(byte_width) + # If you get this exception, you're trying to write a vector with a size + # field that is bigger than the scalars you're trying to write (e.g. a + # byte vector > 255 elements). For such types, write a "blob" instead. + if BitWidth.U(len(elements)) > bit_width: + raise ValueError('too many elements for the given byte_width') + + self._Align(bit_width) + if not fixed: + self._Write(U, len(elements), byte_width) + + loc = len(self._buf) + + fmt = {Type.INT: I, Type.UINT: U, Type.FLOAT: F}.get(element_type) + if not fmt: + raise TypeError('unsupported element_type') + self._WriteVector(fmt, elements, byte_width) + + type_ = Type.ToTypedVector(element_type, len(elements) if fixed else 0) + self._stack.append(Value(loc, type_, bit_width)) + return loc + + def _CreateVector(self, elements, typed, fixed, keys=None): + """Writes vector elements to the underlying buffer.""" + length = len(elements) + + if fixed and not typed: + raise ValueError('fixed vector must be typed') + + # Figure out smallest bit width we can store this vector with. + bit_width = max(self._force_min_bit_width, BitWidth.U(length)) + prefix_elems = 1 # Vector size + if keys: + bit_width = max(bit_width, keys.ElemWidth(len(self._buf))) + prefix_elems += 2 # Offset to the keys vector and its byte width. + + vector_type = Type.KEY + # Check bit widths and types for all elements. + for i, e in enumerate(elements): + bit_width = max(bit_width, e.ElemWidth(len(self._buf), prefix_elems + i)) + + if typed: + if i == 0: + vector_type = e.Type + else: + if vector_type != e.Type: + raise RuntimeError('typed vector elements must be of the same type') + + if fixed and not Type.IsFixedTypedVectorElementType(vector_type): + raise RuntimeError('must be fixed typed vector element type') + + byte_width = self._Align(bit_width) + # Write vector. First the keys width/offset if available, and size. + if keys: + self._WriteOffset(keys.Value, byte_width) + self._Write(U, 1 << keys.MinBitWidth, byte_width) + + if not fixed: + self._Write(U, length, byte_width) + + # Then the actual data. + loc = len(self._buf) + for e in elements: + self._WriteAny(e, byte_width) + + # Then the types. + if not typed: + for e in elements: + self._buf.append(e.StoredPackedType(bit_width)) + + if keys: + type_ = Type.MAP + else: + if typed: + type_ = Type.ToTypedVector(vector_type, length if fixed else 0) + else: + type_ = Type.VECTOR + + return Value(loc, type_, bit_width) + + def _PushIndirect(self, value, type_, bit_width): + byte_width = self._Align(bit_width) + loc = len(self._buf) + fmt = { + Type.INDIRECT_INT: I, + Type.INDIRECT_UINT: U, + Type.INDIRECT_FLOAT: F + }[type_] + self._Write(fmt, value, byte_width) + self._stack.append(Value(loc, type_, bit_width)) + + @InMapForString + def String(self, value): + """Encodes string value.""" + reset_to = len(self._buf) + encoded = value.encode('utf-8') + loc = self._WriteBlob(encoded, append_zero=True, type_=Type.STRING) + if self._share_strings: + prev_loc = self._string_pool.FindOrInsert(encoded, loc) + if prev_loc is not None: + del self._buf[reset_to:] + self._stack[-1]._value = loc = prev_loc # pylint: disable=protected-access + + return loc + + @InMap + def Blob(self, value): + """Encodes binary blob value. + + Args: + value: A byte/bytearray value to encode + + Returns: + Offset of the encoded value in underlying the byte buffer. + """ + return self._WriteBlob(value, append_zero=False, type_=Type.BLOB) + + def Key(self, value): + """Encodes key value. + + Args: + value: A byte/bytearray/str value to encode. Byte object must not contain + zero bytes. String object must be convertible to ASCII. + + Returns: + Offset of the encoded value in the underlying byte buffer. + """ + if isinstance(value, (bytes, bytearray)): + encoded = value + else: + encoded = value.encode('ascii') + + if 0 in encoded: + raise ValueError('key contains zero byte') + + loc = len(self._buf) + self._buf.extend(encoded) + self._buf.append(0) + if self._share_keys: + prev_loc = self._key_pool.FindOrInsert(encoded, loc) + if prev_loc is not None: + del self._buf[loc:] + loc = prev_loc + + self._stack.append(Value.Key(loc)) + return loc + + def Null(self, key=None): + """Encodes None value.""" + if key: + self.Key(key) + self._stack.append(Value.Null()) + + @InMap + def Bool(self, value): + """Encodes boolean value. + + Args: + value: A boolean value. + """ + self._stack.append(Value.Bool(value)) + + @InMap + def Int(self, value, byte_width=0): + """Encodes signed integer value. + + Args: + value: A signed integer value. + byte_width: Number of bytes to use: 1, 2, 4, or 8. + """ + bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width) + self._stack.append(Value.Int(value, bit_width)) + + @InMap + def IndirectInt(self, value, byte_width=0): + """Encodes signed integer value indirectly. + + Args: + value: A signed integer value. + byte_width: Number of bytes to use: 1, 2, 4, or 8. + """ + bit_width = BitWidth.I(value) if byte_width == 0 else BitWidth.B(byte_width) + self._PushIndirect(value, Type.INDIRECT_INT, bit_width) + + @InMap + def UInt(self, value, byte_width=0): + """Encodes unsigned integer value. + + Args: + value: An unsigned integer value. + byte_width: Number of bytes to use: 1, 2, 4, or 8. + """ + bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width) + self._stack.append(Value.UInt(value, bit_width)) + + @InMap + def IndirectUInt(self, value, byte_width=0): + """Encodes unsigned integer value indirectly. + + Args: + value: An unsigned integer value. + byte_width: Number of bytes to use: 1, 2, 4, or 8. + """ + bit_width = BitWidth.U(value) if byte_width == 0 else BitWidth.B(byte_width) + self._PushIndirect(value, Type.INDIRECT_UINT, bit_width) + + @InMap + def Float(self, value, byte_width=0): + """Encodes floating point value. + + Args: + value: A floating point value. + byte_width: Number of bytes to use: 4 or 8. + """ + bit_width = BitWidth.F(value) if byte_width == 0 else BitWidth.B(byte_width) + self._stack.append(Value.Float(value, bit_width)) + + @InMap + def IndirectFloat(self, value, byte_width=0): + """Encodes floating point value indirectly. + + Args: + value: A floating point value. + byte_width: Number of bytes to use: 4 or 8. + """ + bit_width = BitWidth.F(value) if byte_width == 0 else BitWidth.B(byte_width) + self._PushIndirect(value, Type.INDIRECT_FLOAT, bit_width) + + def _StartVector(self): + """Starts vector construction.""" + return len(self._stack) + + def _EndVector(self, start, typed, fixed): + """Finishes vector construction by encodung its elements.""" + vec = self._CreateVector(self._stack[start:], typed, fixed) + del self._stack[start:] + self._stack.append(vec) + return vec.Value + + @contextlib.contextmanager + def Vector(self, key=None): + if key: + self.Key(key) + + try: + start = self._StartVector() + yield self + finally: + self._EndVector(start, typed=False, fixed=False) + + @InMap + def VectorFromElements(self, elements): + """Encodes sequence of any elements as a vector. + + Args: + elements: sequence of elements, they may have different types. + """ + with self.Vector(): + for e in elements: + self.Add(e) + + @contextlib.contextmanager + def TypedVector(self, key=None): + if key: + self.Key(key) + + try: + start = self._StartVector() + yield self + finally: + self._EndVector(start, typed=True, fixed=False) + + @InMap + def TypedVectorFromElements(self, elements, element_type=None): + """Encodes sequence of elements of the same type as typed vector. + + Args: + elements: Sequence of elements, they must be of the same type. + element_type: Suggested element type. Setting it to None means determining + correct value automatically based on the given elements. + """ + if isinstance(elements, array.array): + if elements.typecode == 'f': + self._WriteScalarVector(Type.FLOAT, 4, elements, fixed=False) + elif elements.typecode == 'd': + self._WriteScalarVector(Type.FLOAT, 8, elements, fixed=False) + elif elements.typecode in ('b', 'h', 'i', 'l', 'q'): + self._WriteScalarVector( + Type.INT, elements.itemsize, elements, fixed=False) + elif elements.typecode in ('B', 'H', 'I', 'L', 'Q'): + self._WriteScalarVector( + Type.UINT, elements.itemsize, elements, fixed=False) + else: + raise ValueError('unsupported array typecode: %s' % elements.typecode) + else: + add = self.Add if element_type is None else self.Adder(element_type) + with self.TypedVector(): + for e in elements: + add(e) + + @InMap + def FixedTypedVectorFromElements(self, + elements, + element_type=None, + byte_width=0): + """Encodes sequence of elements of the same type as fixed typed vector. + + Args: + elements: Sequence of elements, they must be of the same type. Allowed + types are `Type.INT`, `Type.UINT`, `Type.FLOAT`. Allowed number of + elements are 2, 3, or 4. + element_type: Suggested element type. Setting it to None means determining + correct value automatically based on the given elements. + byte_width: Number of bytes to use per element. For `Type.INT` and + `Type.UINT`: 1, 2, 4, or 8. For `Type.FLOAT`: 4 or 8. Setting it to 0 + means determining correct value automatically based on the given + elements. + """ + if not 2 <= len(elements) <= 4: + raise ValueError('only 2, 3, or 4 elements are supported') + + types = {type(e) for e in elements} + if len(types) != 1: + raise TypeError('all elements must be of the same type') + + type_, = types + + if element_type is None: + element_type = {int: Type.INT, float: Type.FLOAT}.get(type_) + if not element_type: + raise TypeError('unsupported element_type: %s' % type_) + + if byte_width == 0: + width = { + Type.UINT: BitWidth.U, + Type.INT: BitWidth.I, + Type.FLOAT: BitWidth.F + }[element_type] + byte_width = 1 << max(width(e) for e in elements) + + self._WriteScalarVector(element_type, byte_width, elements, fixed=True) + + def _StartMap(self): + """Starts map construction.""" + return len(self._stack) + + def _EndMap(self, start): + """Finishes map construction by encodung its elements.""" + # Interleaved keys and values on the stack. + stack = self._stack[start:] + + if len(stack) % 2 != 0: + raise RuntimeError('must be even number of keys and values') + + for key in stack[::2]: + if key.Type is not Type.KEY: + raise RuntimeError('all map keys must be of %s type' % Type.KEY) + + pairs = zip(stack[::2], stack[1::2]) # [(key, value), ...] + pairs = sorted(pairs, key=lambda pair: self._ReadKey(pair[0].Value)) + + del self._stack[start:] + for pair in pairs: + self._stack.extend(pair) + + keys = self._CreateVector(self._stack[start::2], typed=True, fixed=False) + values = self._CreateVector( + self._stack[start + 1::2], typed=False, fixed=False, keys=keys) + + del self._stack[start:] + self._stack.append(values) + return values.Value + + @contextlib.contextmanager + def Map(self, key=None): + if key: + self.Key(key) + + try: + start = self._StartMap() + yield self + finally: + self._EndMap(start) + + def MapFromElements(self, elements): + start = self._StartMap() + for k, v in elements.items(): + self.Key(k) + self.Add(v) + self._EndMap(start) + + def Adder(self, type_): + return { + Type.BOOL: self.Bool, + Type.INT: self.Int, + Type.INDIRECT_INT: self.IndirectInt, + Type.UINT: self.UInt, + Type.INDIRECT_UINT: self.IndirectUInt, + Type.FLOAT: self.Float, + Type.INDIRECT_FLOAT: self.IndirectFloat, + Type.KEY: self.Key, + Type.BLOB: self.Blob, + Type.STRING: self.String, + }[type_] + + @InMapForString + def Add(self, value): + """Encodes value of any supported type.""" + if value is None: + self.Null() + elif isinstance(value, bool): + self.Bool(value) + elif isinstance(value, int): + self.Int(value) + elif isinstance(value, float): + self.Float(value) + elif isinstance(value, str): + self.String(value) + elif isinstance(value, (bytes, bytearray)): + self.Blob(value) + elif isinstance(value, dict): + with self.Map(): + for k, v in value.items(): + self.Key(k) + self.Add(v) + elif isinstance(value, array.array): + self.TypedVectorFromElements(value) + elif _IsIterable(value): + self.VectorFromElements(value) + else: + raise TypeError('unsupported python type: %s' % type(value)) + + @property + def LastValue(self): + return self._stack[-1] + + @InMap + def ReuseValue(self, value): + self._stack.append(value) + + +def GetRoot(buf): + """Returns root `Ref` object for the given buffer.""" + if len(buf) < 3: + raise ValueError('buffer is too small') + byte_width = buf[-1] + return Ref.PackedType( + Buf(buf, -(2 + byte_width)), byte_width, packed_type=buf[-2]) + + +def Dumps(obj): + """Returns bytearray with the encoded python object.""" + fbb = Builder() + fbb.Add(obj) + return fbb.Finish() + + +def Loads(buf): + """Returns python object decoded from the buffer.""" + return GetRoot(buf).Value diff --git a/third_party/flatbuffers/python/flatbuffers/number_types.py b/third_party/flatbuffers/python/flatbuffers/number_types.py new file mode 100644 index 00000000000..47942ffb2c2 --- /dev/null +++ b/third_party/flatbuffers/python/flatbuffers/number_types.py @@ -0,0 +1,181 @@ +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import collections +import struct + +from . import packer +from .compat import import_numpy, NumpyRequiredForThisFeature + +np = import_numpy() + +# For reference, see: +# https://docs.python.org/2/library/ctypes.html#ctypes-fundamental-data-types-2 + +# These classes could be collections.namedtuple instances, but those are new +# in 2.6 and we want to work towards 2.5 compatability. + +class BoolFlags(object): + bytewidth = 1 + min_val = False + max_val = True + py_type = bool + name = "bool" + packer_type = packer.boolean + + +class Uint8Flags(object): + bytewidth = 1 + min_val = 0 + max_val = (2**8) - 1 + py_type = int + name = "uint8" + packer_type = packer.uint8 + + +class Uint16Flags(object): + bytewidth = 2 + min_val = 0 + max_val = (2**16) - 1 + py_type = int + name = "uint16" + packer_type = packer.uint16 + + +class Uint32Flags(object): + bytewidth = 4 + min_val = 0 + max_val = (2**32) - 1 + py_type = int + name = "uint32" + packer_type = packer.uint32 + + +class Uint64Flags(object): + bytewidth = 8 + min_val = 0 + max_val = (2**64) - 1 + py_type = int + name = "uint64" + packer_type = packer.uint64 + + +class Int8Flags(object): + bytewidth = 1 + min_val = -(2**7) + max_val = (2**7) - 1 + py_type = int + name = "int8" + packer_type = packer.int8 + + +class Int16Flags(object): + bytewidth = 2 + min_val = -(2**15) + max_val = (2**15) - 1 + py_type = int + name = "int16" + packer_type = packer.int16 + + +class Int32Flags(object): + bytewidth = 4 + min_val = -(2**31) + max_val = (2**31) - 1 + py_type = int + name = "int32" + packer_type = packer.int32 + + +class Int64Flags(object): + bytewidth = 8 + min_val = -(2**63) + max_val = (2**63) - 1 + py_type = int + name = "int64" + packer_type = packer.int64 + + +class Float32Flags(object): + bytewidth = 4 + min_val = None + max_val = None + py_type = float + name = "float32" + packer_type = packer.float32 + + +class Float64Flags(object): + bytewidth = 8 + min_val = None + max_val = None + py_type = float + name = "float64" + packer_type = packer.float64 + + +class SOffsetTFlags(Int32Flags): + pass + + +class UOffsetTFlags(Uint32Flags): + pass + + +class VOffsetTFlags(Uint16Flags): + pass + + +def valid_number(n, flags): + if flags.min_val is None and flags.max_val is None: + return True + return flags.min_val <= n <= flags.max_val + + +def enforce_number(n, flags): + if flags.min_val is None and flags.max_val is None: + return + if not flags.min_val <= n <= flags.max_val: + raise TypeError("bad number %s for type %s" % (str(n), flags.name)) + + +def float32_to_uint32(n): + packed = struct.pack("<1f", n) + (converted,) = struct.unpack("<1L", packed) + return converted + + +def uint32_to_float32(n): + packed = struct.pack("<1L", n) + (unpacked,) = struct.unpack("<1f", packed) + return unpacked + + +def float64_to_uint64(n): + packed = struct.pack("<1d", n) + (converted,) = struct.unpack("<1Q", packed) + return converted + + +def uint64_to_float64(n): + packed = struct.pack("<1Q", n) + (unpacked,) = struct.unpack("<1d", packed) + return unpacked + + +def to_numpy_type(number_type): + if np is not None: + return np.dtype(number_type.name).newbyteorder('<') + else: + raise NumpyRequiredForThisFeature('Numpy was not found.') diff --git a/third_party/flatbuffers/python/flatbuffers/packer.py b/third_party/flatbuffers/python/flatbuffers/packer.py new file mode 100644 index 00000000000..20ee9f11680 --- /dev/null +++ b/third_party/flatbuffers/python/flatbuffers/packer.py @@ -0,0 +1,42 @@ +# Copyright 2016 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +""" +Provide pre-compiled struct packers for encoding and decoding. + +See: https://docs.python.org/2/library/struct.html#format-characters +""" + +import struct +from . import compat + + +boolean = struct.Struct(compat.struct_bool_decl) + +uint8 = struct.Struct("`_ ' + 'serialization format.'), + packages=['flatbuffers'], + include_package_data=True, + requires=[], + description='The FlatBuffers serialization format for Python', + classifiers=[ + 'Intended Audience :: Developers', + 'License :: OSI Approved :: Apache Software License', + 'Operating System :: OS Independent', + 'Programming Language :: Python', + 'Programming Language :: Python :: 2', + 'Programming Language :: Python :: 3', + 'Topic :: Software Development :: Libraries :: Python Modules', + ], + project_urls={ + 'Documentation': 'https://google.github.io/flatbuffers/', + 'Source': 'https://github.com/google/flatbuffers', + }, +) diff --git a/third_party/flatbuffers/reflection/BUILD.bazel b/third_party/flatbuffers/reflection/BUILD.bazel index 4bdada5b8b9..ec14e5263a6 100644 --- a/third_party/flatbuffers/reflection/BUILD.bazel +++ b/third_party/flatbuffers/reflection/BUILD.bazel @@ -7,6 +7,12 @@ filegroup( visibility = ["//visibility:public"], ) +# flatbuffer_ts_library() only supports .fbs file but not filegroups +exports_files( + srcs = ["reflection.fbs"], + visibility = ["//reflection/ts:__pkg__"], +) + filegroup( name = "reflection_fbs_schema", srcs = ["reflection.fbs"], diff --git a/third_party/flatbuffers/reflection/ts/BUILD.bazel b/third_party/flatbuffers/reflection/ts/BUILD.bazel index 0b3dfbe9af3..ca9701d2a14 100644 --- a/third_party/flatbuffers/reflection/ts/BUILD.bazel +++ b/third_party/flatbuffers/reflection/ts/BUILD.bazel @@ -1,15 +1,8 @@ load("//:typescript.bzl", "flatbuffer_ts_library") -genrule( - name = "copy_schema_to_folder", - srcs = ["//reflection:reflection_fbs_schema"], - outs = ["reflection.fbs"], - cmd = "cp $< $@", -) - flatbuffer_ts_library( name = "reflection_ts_fbs", - srcs = [":reflection.fbs"], + srcs = ["//reflection:reflection.fbs"], gen_reflections = True, visibility = ["//visibility:public"], ) diff --git a/third_party/flatbuffers/rust/flatbuffers/Cargo.toml b/third_party/flatbuffers/rust/flatbuffers/Cargo.toml new file mode 100644 index 00000000000..241ac2b99b8 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/Cargo.toml @@ -0,0 +1,24 @@ +[package] +name = "flatbuffers" +version = "25.2.10" +edition = "2018" +authors = ["Robert Winslow ", "FlatBuffers Maintainers"] +license = "Apache-2.0" +description = "Official FlatBuffers Rust runtime library." +homepage = "https://google.github.io/flatbuffers/" +repository = "https://github.com/google/flatbuffers" +keywords = ["flatbuffers", "serialization", "zero-copy"] +categories = ["encoding", "data-structures", "memory-management"] +rust = "1.51" + +[features] +default = ["std"] +std = [] +serialize = ["serde"] + +[dependencies] +bitflags = "2.8.0" +serde = { version = "1.0", optional = true } + +[build-dependencies] +rustc_version = "0.4.0" diff --git a/third_party/flatbuffers/rust/flatbuffers/README.md b/third_party/flatbuffers/rust/flatbuffers/README.md new file mode 100644 index 00000000000..4d7a5be3d15 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/README.md @@ -0,0 +1,15 @@ +# Flatbuffers + +FlatBuffers is a cross platform serialization library architected for maximum +memory efficiency. It allows you to directly access serialized data without +parsing/unpacking it first, while still having great forwards/backwards +compatibility. It was originally created at Google for game development and +other performance-critical applications. + +## See our +* [Tutorial](https://google.github.io/flatbuffers/flatbuffers_guide_tutorial.html) +* [Landing Page](https://google.github.io/flatbuffers/) +* [Rust sample binary](https://github.com/google/flatbuffers/blob/master/samples/sample_binary.rs) +* [Schema**less** format, Flexbuffers](https://crates.io/crates/flexbuffers) +* [Github](https://github.com/google/flatbuffers) + diff --git a/third_party/flatbuffers/rust/flatbuffers/build.rs b/third_party/flatbuffers/rust/flatbuffers/build.rs new file mode 100644 index 00000000000..c13ed1da485 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/build.rs @@ -0,0 +1,12 @@ +use rustc_version::{version_meta, Channel}; + +fn main() { + let version_meta = version_meta().unwrap(); + + // To use nightly features we declare this and then we can use + // #[cfg(nightly)] + // for nightly only features + if version_meta.channel == Channel::Nightly { + println!("cargo:rustc-cfg=nightly") + } +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/array.rs b/third_party/flatbuffers/rust/flatbuffers/src/array.rs new file mode 100644 index 00000000000..089557440ce --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/array.rs @@ -0,0 +1,163 @@ +/* + * Copyright 2021 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use crate::follow::Follow; +use crate::vector::VectorIter; +use crate::EndianScalar; +use core::fmt::{Debug, Formatter, Result}; +use core::marker::PhantomData; +use core::mem::size_of; + +#[derive(Copy, Clone)] +pub struct Array<'a, T: 'a, const N: usize>(&'a [u8], PhantomData); + +impl<'a, T: 'a, const N: usize> Debug for Array<'a, T, N> +where + T: 'a + Follow<'a>, + >::Inner: Debug, +{ + fn fmt(&self, f: &mut Formatter) -> Result { + f.debug_list().entries(self.iter()).finish() + } +} + +#[allow(clippy::len_without_is_empty)] +#[allow(clippy::from_over_into)] // TODO(caspern): Go from From to Into. +impl<'a, T: 'a, const N: usize> Array<'a, T, N> { + /// # Safety + /// + /// buf must be a contiguous array of `T` + /// + /// # Panics + /// + /// Panics if `buf.len()` is not `size_of::() * N` + #[inline(always)] + pub unsafe fn new(buf: &'a [u8]) -> Self { + assert_eq!(size_of::() * N, buf.len()); + + Array(buf, PhantomData) + } + + #[inline(always)] + pub const fn len(&self) -> usize { + N + } + pub fn as_ptr(&self) -> *const u8 { + self.0.as_ptr() + } +} + +impl<'a, T: Follow<'a> + 'a, const N: usize> Array<'a, T, N> { + #[inline(always)] + pub fn get(&self, idx: usize) -> T::Inner { + assert!(idx < N); + let sz = size_of::(); + // Safety: + // self.0 was valid for length `N` on construction and have verified `idx < N` + unsafe { T::follow(self.0, sz * idx) } + } + + #[inline(always)] + pub fn iter(&self) -> VectorIter<'a, T> { + // Safety: + // self.0 was valid for length N on construction + unsafe { VectorIter::from_slice(self.0, self.len()) } + } +} + +impl<'a, T: Follow<'a> + Debug, const N: usize> From> for [T::Inner; N] { + fn from(array: Array<'a, T, N>) -> Self { + array_init(|i| array.get(i)) + } +} + +/// Implement Follow for all possible Arrays that have Follow-able elements. +impl<'a, T: Follow<'a> + 'a, const N: usize> Follow<'a> for Array<'a, T, N> { + type Inner = Array<'a, T, N>; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Array::new(&buf[loc..loc + N * size_of::()]) + } +} + +/// Place an array of EndianScalar into the provided mutable byte slice. Performs +/// endian conversion, if necessary. +/// # Safety +/// Caller must ensure `s.len() >= size_of::<[T; N]>()` +pub unsafe fn emplace_scalar_array( + buf: &mut [u8], + loc: usize, + src: &[T; N], +) { + let mut buf_ptr = buf[loc..].as_mut_ptr(); + for item in src.iter() { + let item_le = item.to_little_endian(); + core::ptr::copy_nonoverlapping( + &item_le as *const T::Scalar as *const u8, + buf_ptr, + size_of::(), + ); + buf_ptr = buf_ptr.add(size_of::()); + } +} + +impl<'a, T: Follow<'a> + 'a, const N: usize> IntoIterator for Array<'a, T, N> { + type Item = T::Inner; + type IntoIter = VectorIter<'a, T>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +#[inline] +pub fn array_init(mut initializer: F) -> [T; N] +where + F: FnMut(usize) -> T, +{ + let mut array: core::mem::MaybeUninit<[T; N]> = core::mem::MaybeUninit::uninit(); + let mut ptr_i = array.as_mut_ptr() as *mut T; + + // Safety: + // array is aligned by T, and has length N + unsafe { + for i in 0..N { + let value_i = initializer(i); + ptr_i.write(value_i); + ptr_i = ptr_i.add(1); + } + array.assume_init() + } +} + +#[cfg(feature = "serialize")] +impl<'a, T: 'a, const N: usize> serde::ser::Serialize for Array<'a, T, N> +where + T: 'a + Follow<'a>, + >::Inner: serde::ser::Serialize, +{ + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::ser::Serializer, + { + use serde::ser::SerializeSeq; + let mut seq = serializer.serialize_seq(Some(self.len()))?; + for element in self.iter() { + seq.serialize_element(&element)?; + } + seq.end() + } +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/builder.rs b/third_party/flatbuffers/rust/flatbuffers/src/builder.rs new file mode 100644 index 00000000000..a6e6818101f --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/builder.rs @@ -0,0 +1,954 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#[cfg(not(feature = "std"))] +use alloc::{vec, vec::Vec}; +use core::cmp::max; +use core::convert::Infallible; +use core::fmt::{Debug, Display}; +use core::iter::{DoubleEndedIterator, ExactSizeIterator}; +use core::marker::PhantomData; +use core::ops::{Add, AddAssign, Deref, DerefMut, Index, IndexMut, Sub, SubAssign}; +use core::ptr::write_bytes; + +use crate::endian_scalar::emplace_scalar; +use crate::primitives::*; +use crate::push::{Push, PushAlignment}; +use crate::read_scalar; +use crate::table::Table; +use crate::vector::Vector; +use crate::vtable::{field_index_to_field_offset, VTable}; +use crate::vtable_writer::VTableWriter; + +/// Trait to implement custom allocation strategies for [`FlatBufferBuilder`]. +/// +/// An implementation can be used with [`FlatBufferBuilder::new_in`], enabling a custom allocation +/// strategy for the [`FlatBufferBuilder`]. +/// +/// # Safety +/// +/// The implementation of the allocator must match the defined behavior as described by the +/// comments. +pub unsafe trait Allocator: DerefMut { + /// A type describing allocation failures + type Error: Display + Debug; + /// Grows the buffer, with the old contents being moved to the end. + /// + /// NOTE: While not unsound, an implementation that doesn't grow the + /// internal buffer will get stuck in an infinite loop. + fn grow_downwards(&mut self) -> Result<(), Self::Error>; + + /// Returns the size of the internal buffer in bytes. + fn len(&self) -> usize; +} + +/// Default [`FlatBufferBuilder`] allocator backed by a [`Vec`]. +#[derive(Default)] +pub struct DefaultAllocator(Vec); + +impl DefaultAllocator { + /// Builds the allocator from an existing buffer. + pub fn from_vec(buffer: Vec) -> Self { + Self(buffer) + } +} + +impl Deref for DefaultAllocator { + type Target = [u8]; + + fn deref(&self) -> &Self::Target { + &self.0 + } +} + +impl DerefMut for DefaultAllocator { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.0 + } +} + +// SAFETY: The methods are implemented as described by the documentation. +unsafe impl Allocator for DefaultAllocator { + type Error = Infallible; + fn grow_downwards(&mut self) -> Result<(), Self::Error> { + let old_len = self.0.len(); + let new_len = max(1, old_len * 2); + + self.0.resize(new_len, 0); + + if new_len == 1 { + return Ok(()); + } + + // calculate the midpoint, and safely copy the old end data to the new + // end position: + let middle = new_len / 2; + { + let (left, right) = &mut self.0[..].split_at_mut(middle); + right.copy_from_slice(left); + } + // finally, zero out the old end data. + { + let ptr = self.0[..middle].as_mut_ptr(); + // Safety: + // ptr is byte aligned and of length middle + unsafe { + write_bytes(ptr, 0, middle); + } + } + Ok(()) + } + + fn len(&self) -> usize { + self.0.len() + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct FieldLoc { + off: UOffsetT, + id: VOffsetT, +} + +/// FlatBufferBuilder builds a FlatBuffer through manipulating its internal +/// state. It has an owned `Vec` that grows as needed (up to the hardcoded +/// limit of 2GiB, which is set by the FlatBuffers format). +#[derive(Clone, Debug, Eq, PartialEq)] +pub struct FlatBufferBuilder<'fbb, A: Allocator = DefaultAllocator> { + allocator: A, + head: ReverseIndex, + + field_locs: Vec, + written_vtable_revpos: Vec, + + nested: bool, + finished: bool, + + min_align: usize, + force_defaults: bool, + strings_pool: Vec>, + + _phantom: PhantomData<&'fbb ()>, +} + +impl<'fbb> FlatBufferBuilder<'fbb, DefaultAllocator> { + /// Create a FlatBufferBuilder that is ready for writing. + pub fn new() -> Self { + Self::with_capacity(0) + } + #[deprecated(note = "replaced with `with_capacity`", since = "0.8.5")] + pub fn new_with_capacity(size: usize) -> Self { + Self::with_capacity(size) + } + /// Create a FlatBufferBuilder that is ready for writing, with a + /// ready-to-use capacity of the provided size. + /// + /// The maximum valid value is `FLATBUFFERS_MAX_BUFFER_SIZE`. + pub fn with_capacity(size: usize) -> Self { + Self::from_vec(vec![0; size]) + } + /// Create a FlatBufferBuilder that is ready for writing, reusing + /// an existing vector. + pub fn from_vec(buffer: Vec) -> Self { + // we need to check the size here because we create the backing buffer + // directly, bypassing the typical way of using grow_allocator: + assert!( + buffer.len() <= FLATBUFFERS_MAX_BUFFER_SIZE, + "cannot initialize buffer bigger than 2 gigabytes" + ); + let allocator = DefaultAllocator::from_vec(buffer); + Self::new_in(allocator) + } + + /// Destroy the FlatBufferBuilder, returning its internal byte vector + /// and the index into it that represents the start of valid data. + pub fn collapse(self) -> (Vec, usize) { + let index = self.head.to_forward_index(&self.allocator); + (self.allocator.0, index) + } +} + +impl<'fbb, A: Allocator> FlatBufferBuilder<'fbb, A> { + /// Create a [`FlatBufferBuilder`] that is ready for writing with a custom [`Allocator`]. + pub fn new_in(allocator: A) -> Self { + let head = ReverseIndex::end(); + FlatBufferBuilder { + allocator, + head, + + field_locs: Vec::new(), + written_vtable_revpos: Vec::new(), + + nested: false, + finished: false, + + min_align: 0, + force_defaults: false, + strings_pool: Vec::new(), + + _phantom: PhantomData, + } + } + + /// Destroy the [`FlatBufferBuilder`], returning its [`Allocator`] and the index + /// into it that represents the start of valid data. + pub fn collapse_in(self) -> (A, usize) { + let index = self.head.to_forward_index(&self.allocator); + (self.allocator, index) + } + + /// Reset the FlatBufferBuilder internal state. Use this method after a + /// call to a `finish` function in order to re-use a FlatBufferBuilder. + /// + /// This function is the only way to reset the `finished` state and start + /// again. + /// + /// If you are using a FlatBufferBuilder repeatedly, make sure to use this + /// function, because it re-uses the FlatBufferBuilder's existing + /// heap-allocated `Vec` internal buffer. This offers significant speed + /// improvements as compared to creating a new FlatBufferBuilder for every + /// new object. + pub fn reset(&mut self) { + // memset only the part of the buffer that could be dirty: + self.allocator[self.head.range_to_end()] + .iter_mut() + .for_each(|x| *x = 0); + + self.head = ReverseIndex::end(); + self.written_vtable_revpos.clear(); + + self.nested = false; + self.finished = false; + + self.min_align = 0; + self.strings_pool.clear(); + } + + /// Push a Push'able value onto the front of the in-progress data. + /// + /// This function uses traits to provide a unified API for writing + /// scalars, tables, vectors, and WIPOffsets. + #[inline] + pub fn push(&mut self, x: P) -> WIPOffset { + let sz = P::size(); + self.align(sz, P::alignment()); + self.make_space(sz); + { + let (dst, rest) = self.allocator[self.head.range_to_end()].split_at_mut(sz); + // Safety: + // Called make_space above + unsafe { x.push(dst, rest.len()) }; + } + WIPOffset::new(self.used_space() as UOffsetT) + } + + /// Push a Push'able value onto the front of the in-progress data, and + /// store a reference to it in the in-progress vtable. If the value matches + /// the default, then this is a no-op. + #[inline] + pub fn push_slot(&mut self, slotoff: VOffsetT, x: X, default: X) { + self.assert_nested("push_slot"); + if x != default || self.force_defaults { + self.push_slot_always(slotoff, x); + } + } + + /// Push a Push'able value onto the front of the in-progress data, and + /// store a reference to it in the in-progress vtable. + #[inline] + pub fn push_slot_always(&mut self, slotoff: VOffsetT, x: X) { + self.assert_nested("push_slot_always"); + let off = self.push(x); + self.track_field(slotoff, off.value()); + } + + /// Retrieve the number of vtables that have been serialized into the + /// FlatBuffer. This is primarily used to check vtable deduplication. + #[inline] + pub fn num_written_vtables(&self) -> usize { + self.written_vtable_revpos.len() + } + + /// Start a Table write. + /// + /// Asserts that the builder is not in a nested state. + /// + /// Users probably want to use `push_slot` to add values after calling this. + #[inline] + pub fn start_table(&mut self) -> WIPOffset { + self.assert_not_nested( + "start_table can not be called when a table or vector is under construction", + ); + self.nested = true; + + WIPOffset::new(self.used_space() as UOffsetT) + } + + /// End a Table write. + /// + /// Asserts that the builder is in a nested state. + #[inline] + pub fn end_table( + &mut self, + off: WIPOffset, + ) -> WIPOffset { + self.assert_nested("end_table"); + + let o = self.write_vtable(off); + + self.nested = false; + self.field_locs.clear(); + + WIPOffset::new(o.value()) + } + + /// Start a Vector write. + /// + /// Asserts that the builder is not in a nested state. + /// + /// Most users will prefer to call `create_vector`. + /// Speed optimizing users who choose to create vectors manually using this + /// function will want to use `push` to add values. + #[inline] + pub fn start_vector(&mut self, num_items: usize) { + self.assert_not_nested( + "start_vector can not be called when a table or vector is under construction", + ); + self.nested = true; + self.align(num_items * T::size(), T::alignment().max_of(SIZE_UOFFSET)); + } + + /// End a Vector write. + /// + /// Note that the `num_elems` parameter is the number of written items, not + /// the byte count. + /// + /// Asserts that the builder is in a nested state. + #[inline] + pub fn end_vector(&mut self, num_elems: usize) -> WIPOffset> { + self.assert_nested("end_vector"); + self.nested = false; + let o = self.push::(num_elems as UOffsetT); + WIPOffset::new(o.value()) + } + + #[inline] + pub fn create_shared_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { + self.assert_not_nested( + "create_shared_string can not be called when a table or vector is under construction", + ); + + // Saves a ref to allocator since rust doesnt like us refrencing it + // in the binary_search_by code. + let buf = &self.allocator; + + let found = self.strings_pool.binary_search_by(|offset| { + let ptr = offset.value() as usize; + // Gets The pointer to the size of the string + let str_memory = &buf[buf.len() - ptr..]; + // Gets the size of the written string from buffer + let size = + u32::from_le_bytes([str_memory[0], str_memory[1], str_memory[2], str_memory[3]]) + as usize; + // Size of the string size + let string_size: usize = 4; + // Fetches actual string bytes from index of string after string size + // to the size of string plus string size + let iter = str_memory[string_size..size + string_size].iter(); + // Compares bytes of fetched string and current writable string + iter.cloned().cmp(s.bytes()) + }); + + match found { + Ok(index) => self.strings_pool[index], + Err(index) => { + let address = WIPOffset::new(self.create_byte_string(s.as_bytes()).value()); + self.strings_pool.insert(index, address); + address + } + } + } + + /// Create a utf8 string. + /// + /// The wire format represents this as a zero-terminated byte vector. + #[inline] + pub fn create_string<'a: 'b, 'b>(&'a mut self, s: &'b str) -> WIPOffset<&'fbb str> { + self.assert_not_nested( + "create_string can not be called when a table or vector is under construction", + ); + WIPOffset::new(self.create_byte_string(s.as_bytes()).value()) + } + + /// Create a zero-terminated byte vector. + #[inline] + pub fn create_byte_string(&mut self, data: &[u8]) -> WIPOffset<&'fbb [u8]> { + self.assert_not_nested( + "create_byte_string can not be called when a table or vector is under construction", + ); + self.align(data.len() + 1, PushAlignment::new(SIZE_UOFFSET)); + self.push(0u8); + self.push_bytes_unprefixed(data); + self.push(data.len() as UOffsetT); + WIPOffset::new(self.used_space() as UOffsetT) + } + + /// Create a vector of Push-able objects. + /// + /// Speed-sensitive users may wish to reduce memory usage by creating the + /// vector manually: use `start_vector`, `push`, and `end_vector`. + #[inline] + pub fn create_vector<'a: 'b, 'b, T: Push + 'b>( + &'a mut self, + items: &'b [T], + ) -> WIPOffset> { + let elem_size = T::size(); + let slice_size = items.len() * elem_size; + self.align(slice_size, T::alignment().max_of(SIZE_UOFFSET)); + self.ensure_capacity(slice_size + UOffsetT::size()); + + self.head -= slice_size; + let mut written_len = self.head.distance_to_end(); + + let buf = &mut self.allocator[self.head.range_to(self.head + slice_size)]; + for (item, out) in items.iter().zip(buf.chunks_exact_mut(elem_size)) { + written_len -= elem_size; + + // Safety: + // Called ensure_capacity and aligned to T above + unsafe { item.push(out, written_len) }; + } + + WIPOffset::new(self.push::(items.len() as UOffsetT).value()) + } + + /// Create a vector of Push-able objects. + /// + /// Speed-sensitive users may wish to reduce memory usage by creating the + /// vector manually: use `start_vector`, `push`, and `end_vector`. + #[inline] + pub fn create_vector_from_iter( + &mut self, + items: impl ExactSizeIterator + DoubleEndedIterator, + ) -> WIPOffset> { + let elem_size = T::size(); + self.align(items.len() * elem_size, T::alignment().max_of(SIZE_UOFFSET)); + let mut actual = 0; + for item in items.rev() { + self.push(item); + actual += 1; + } + WIPOffset::new(self.push::(actual).value()) + } + + /// Set whether default values are stored. + /// + /// In order to save space, fields that are set to their default value + /// aren't stored in the buffer. Setting `force_defaults` to `true` + /// disables this optimization. + /// + /// By default, `force_defaults` is `false`. + #[inline] + pub fn force_defaults(&mut self, force_defaults: bool) { + self.force_defaults = force_defaults; + } + + /// Get the byte slice for the data that has been written, regardless of + /// whether it has been finished. + #[inline] + pub fn unfinished_data(&self) -> &[u8] { + &self.allocator[self.head.range_to_end()] + } + /// Get the byte slice for the data that has been written after a call to + /// one of the `finish` functions. + /// # Panics + /// Panics if the buffer is not finished. + #[inline] + pub fn finished_data(&self) -> &[u8] { + self.assert_finished("finished_bytes cannot be called when the buffer is not yet finished"); + &self.allocator[self.head.range_to_end()] + } + /// Returns a mutable view of a finished buffer and location of where the flatbuffer starts. + /// Note that modifying the flatbuffer data may corrupt it. + /// # Panics + /// Panics if the flatbuffer is not finished. + #[inline] + pub fn mut_finished_buffer(&mut self) -> (&mut [u8], usize) { + let index = self.head.to_forward_index(&self.allocator); + (&mut self.allocator[..], index) + } + /// Assert that a field is present in the just-finished Table. + /// + /// This is somewhat low-level and is mostly used by the generated code. + #[inline] + pub fn required( + &self, + tab_revloc: WIPOffset, + slot_byte_loc: VOffsetT, + assert_msg_name: &'static str, + ) { + let idx = self.used_space() - tab_revloc.value() as usize; + + // Safety: + // The value of TableFinishedWIPOffset is the offset from the end of the allocator + // to an SOffsetT pointing to a valid VTable + // + // `self.allocator.len() = self.used_space() + self.head` + // `self.allocator.len() - tab_revloc = self.used_space() - tab_revloc + self.head` + // `self.allocator.len() - tab_revloc = idx + self.head` + let tab = unsafe { Table::new(&self.allocator[self.head.range_to_end()], idx) }; + let o = tab.vtable().get(slot_byte_loc) as usize; + assert!(o != 0, "missing required field {}", assert_msg_name); + } + + /// Finalize the FlatBuffer by: aligning it, pushing an optional file + /// identifier on to it, pushing a size prefix on to it, and marking the + /// internal state of the FlatBufferBuilder as `finished`. Afterwards, + /// users can call `finished_data` to get the resulting data. + #[inline] + pub fn finish_size_prefixed(&mut self, root: WIPOffset, file_identifier: Option<&str>) { + self.finish_with_opts(root, file_identifier, true); + } + + /// Finalize the FlatBuffer by: aligning it, pushing an optional file + /// identifier on to it, and marking the internal state of the + /// FlatBufferBuilder as `finished`. Afterwards, users can call + /// `finished_data` to get the resulting data. + #[inline] + pub fn finish(&mut self, root: WIPOffset, file_identifier: Option<&str>) { + self.finish_with_opts(root, file_identifier, false); + } + + /// Finalize the FlatBuffer by: aligning it and marking the internal state + /// of the FlatBufferBuilder as `finished`. Afterwards, users can call + /// `finished_data` to get the resulting data. + #[inline] + pub fn finish_minimal(&mut self, root: WIPOffset) { + self.finish_with_opts(root, None, false); + } + + #[inline] + fn used_space(&self) -> usize { + self.head.distance_to_end() + } + + #[inline] + fn track_field(&mut self, slot_off: VOffsetT, off: UOffsetT) { + let fl = FieldLoc { id: slot_off, off }; + self.field_locs.push(fl); + } + + /// Write the VTable, if it is new. + fn write_vtable( + &mut self, + table_tail_revloc: WIPOffset, + ) -> WIPOffset { + self.assert_nested("write_vtable"); + + // Write the vtable offset, which is the start of any Table. + // We fill its value later. + let object_revloc_to_vtable: WIPOffset = + WIPOffset::new(self.push::(0xF0F0_F0F0).value()); + + // Layout of the data this function will create when a new vtable is + // needed. + // -------------------------------------------------------------------- + // vtable starts here + // | x, x -- vtable len (bytes) [u16] + // | x, x -- object inline len (bytes) [u16] + // | x, x -- zero, or num bytes from start of object to field #0 [u16] + // | ... + // | x, x -- zero, or num bytes from start of object to field #n-1 [u16] + // vtable ends here + // table starts here + // | x, x, x, x -- offset (negative direction) to the vtable [i32] + // | aka "vtableoffset" + // | -- table inline data begins here, we don't touch it -- + // table ends here -- aka "table_start" + // -------------------------------------------------------------------- + // + // Layout of the data this function will create when we re-use an + // existing vtable. + // + // We always serialize this particular vtable, then compare it to the + // other vtables we know about to see if there is a duplicate. If there + // is, then we erase the serialized vtable we just made. + // We serialize it first so that we are able to do byte-by-byte + // comparisons with already-serialized vtables. This 1) saves + // bookkeeping space (we only keep revlocs to existing vtables), 2) + // allows us to convert to little-endian once, then do + // fast memcmp comparisons, and 3) by ensuring we are comparing real + // serialized vtables, we can be more assured that we are doing the + // comparisons correctly. + // + // -------------------------------------------------------------------- + // table starts here + // | x, x, x, x -- offset (negative direction) to an existing vtable [i32] + // | aka "vtableoffset" + // | -- table inline data begins here, we don't touch it -- + // table starts here: aka "table_start" + // -------------------------------------------------------------------- + + // fill the WIP vtable with zeros: + let vtable_byte_len = get_vtable_byte_len(&self.field_locs); + self.make_space(vtable_byte_len); + + // compute the length of the table (not vtable!) in bytes: + let table_object_size = object_revloc_to_vtable.value() - table_tail_revloc.value(); + debug_assert!(table_object_size < 0x10000); // vTable use 16bit offsets. + + // Write the VTable (we may delete it afterwards, if it is a duplicate): + let vt_start_pos = self.head; + let vt_end_pos = self.head + vtable_byte_len; + { + // write the vtable header: + let vtfw = + &mut VTableWriter::init(&mut self.allocator[vt_start_pos.range_to(vt_end_pos)]); + vtfw.write_vtable_byte_length(vtable_byte_len as VOffsetT); + vtfw.write_object_inline_size(table_object_size as VOffsetT); + + // serialize every FieldLoc to the vtable: + for &fl in self.field_locs.iter() { + let pos: VOffsetT = (object_revloc_to_vtable.value() - fl.off) as VOffsetT; + vtfw.write_field_offset(fl.id, pos); + } + } + let new_vt_bytes = &self.allocator[vt_start_pos.range_to(vt_end_pos)]; + let found = self + .written_vtable_revpos + .binary_search_by(|old_vtable_revpos: &UOffsetT| { + let old_vtable_pos = self.allocator.len() - *old_vtable_revpos as usize; + // Safety: + // Already written vtables are valid by construction + let old_vtable = unsafe { VTable::init(&self.allocator, old_vtable_pos) }; + new_vt_bytes.cmp(old_vtable.as_bytes()) + }); + let final_vtable_revpos = match found { + Ok(i) => { + // The new vtable is a duplicate so clear it. + VTableWriter::init(&mut self.allocator[vt_start_pos.range_to(vt_end_pos)]).clear(); + self.head += vtable_byte_len; + self.written_vtable_revpos[i] + } + Err(i) => { + // This is a new vtable. Add it to the cache. + let new_vt_revpos = self.used_space() as UOffsetT; + self.written_vtable_revpos.insert(i, new_vt_revpos); + new_vt_revpos + } + }; + // Write signed offset from table to its vtable. + let table_pos = self.allocator.len() - object_revloc_to_vtable.value() as usize; + if cfg!(debug_assertions) { + // Safety: + // Verified slice length + let tmp_soffset_to_vt = unsafe { + read_scalar::(&self.allocator[table_pos..table_pos + SIZE_UOFFSET]) + }; + assert_eq!(tmp_soffset_to_vt, 0xF0F0_F0F0); + } + + let buf = &mut self.allocator[table_pos..table_pos + SIZE_SOFFSET]; + // Safety: + // Verified length of buf above + unsafe { + emplace_scalar::( + buf, + final_vtable_revpos as SOffsetT - object_revloc_to_vtable.value() as SOffsetT, + ); + } + + self.field_locs.clear(); + + object_revloc_to_vtable + } + + // Only call this when you know it is safe to double the size of the buffer. + #[inline] + fn grow_allocator(&mut self) { + let starting_active_size = self.used_space(); + self.allocator + .grow_downwards() + .expect("Flatbuffer allocation failure"); + + let ending_active_size = self.used_space(); + debug_assert_eq!(starting_active_size, ending_active_size); + } + + // with or without a size prefix changes how we load the data, so finish* + // functions are split along those lines. + fn finish_with_opts( + &mut self, + root: WIPOffset, + file_identifier: Option<&str>, + size_prefixed: bool, + ) { + self.assert_not_finished("buffer cannot be finished when it is already finished"); + self.assert_not_nested( + "buffer cannot be finished when a table or vector is under construction", + ); + self.written_vtable_revpos.clear(); + + let to_align = { + // for the root offset: + let a = SIZE_UOFFSET; + // for the size prefix: + let b = if size_prefixed { SIZE_UOFFSET } else { 0 }; + // for the file identifier (a string that is not zero-terminated): + let c = if file_identifier.is_some() { + FILE_IDENTIFIER_LENGTH + } else { + 0 + }; + a + b + c + }; + + { + let ma = PushAlignment::new(self.min_align); + self.align(to_align, ma); + } + + if let Some(ident) = file_identifier { + debug_assert_eq!(ident.len(), FILE_IDENTIFIER_LENGTH); + self.push_bytes_unprefixed(ident.as_bytes()); + } + + self.push(root); + + if size_prefixed { + let sz = self.used_space() as UOffsetT; + self.push::(sz); + } + self.finished = true; + } + + #[inline] + fn align(&mut self, len: usize, alignment: PushAlignment) { + self.track_min_align(alignment.value()); + let s = self.used_space() as usize; + self.make_space(padding_bytes(s + len, alignment.value())); + } + + #[inline] + fn track_min_align(&mut self, alignment: usize) { + self.min_align = max(self.min_align, alignment); + } + + #[inline] + fn push_bytes_unprefixed(&mut self, x: &[u8]) -> UOffsetT { + let n = self.make_space(x.len()); + self.allocator[n.range_to(n + x.len())].copy_from_slice(x); + + n.to_forward_index(&self.allocator) as UOffsetT + } + + #[inline] + fn make_space(&mut self, want: usize) -> ReverseIndex { + self.ensure_capacity(want); + self.head -= want; + self.head + } + + #[inline] + fn ensure_capacity(&mut self, want: usize) -> usize { + if self.unused_ready_space() >= want { + return want; + } + assert!( + want <= FLATBUFFERS_MAX_BUFFER_SIZE, + "cannot grow buffer beyond 2 gigabytes" + ); + + while self.unused_ready_space() < want { + self.grow_allocator(); + } + want + } + #[inline] + fn unused_ready_space(&self) -> usize { + self.allocator.len() - self.head.distance_to_end() + } + #[inline] + fn assert_nested(&self, fn_name: &'static str) { + // we don't assert that self.field_locs.len() >0 because the vtable + // could be empty (e.g. for empty tables, or for all-default values). + debug_assert!( + self.nested, + "incorrect FlatBufferBuilder usage: {} must be called while in a nested state", + fn_name + ); + } + #[inline] + fn assert_not_nested(&self, msg: &'static str) { + debug_assert!(!self.nested, "{}", msg); + } + #[inline] + fn assert_finished(&self, msg: &'static str) { + debug_assert!(self.finished, "{}", msg); + } + #[inline] + fn assert_not_finished(&self, msg: &'static str) { + debug_assert!(!self.finished, "{}", msg); + } +} + +/// Compute the length of the vtable needed to represent the provided FieldLocs. +/// If there are no FieldLocs, then provide the minimum number of bytes +/// required: enough to write the VTable header. +#[inline] +fn get_vtable_byte_len(field_locs: &[FieldLoc]) -> usize { + let max_voffset = field_locs.iter().map(|fl| fl.id).max(); + match max_voffset { + None => field_index_to_field_offset(0) as usize, + Some(mv) => mv as usize + SIZE_VOFFSET, + } +} + +#[inline] +fn padding_bytes(buf_size: usize, scalar_size: usize) -> usize { + // ((!buf_size) + 1) & (scalar_size - 1) + (!buf_size).wrapping_add(1) & (scalar_size.wrapping_sub(1)) +} + +impl<'fbb> Default for FlatBufferBuilder<'fbb> { + fn default() -> Self { + Self::with_capacity(0) + } +} + +/// An index that indexes from the reverse of a slice. +/// +/// Note that while the internal representation is an index +/// from the end of a buffer, operations like `Add` and `Sub` +/// behave like a regular index: +/// +/// # Examples +/// +/// ```ignore +/// let buf = [0, 1, 2, 3, 4, 5]; +/// let idx = ReverseIndex::end() - 2; +/// assert_eq!(&buf[idx.range_to_end()], &[4, 5]); +/// assert_eq!(idx.to_forward_index(&buf), 4); +/// ``` +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct ReverseIndex(usize); + +impl ReverseIndex { + /// Returns an index set to the end. + /// + /// Note: Indexing this will result in an out of bounds error. + pub fn end() -> Self { + Self(0) + } + + /// Returns a struct equivalent to the range `self..` + pub fn range_to_end(self) -> ReverseIndexRange { + ReverseIndexRange(self, ReverseIndex::end()) + } + + /// Returns a struct equivalent to the range `self..end` + pub fn range_to(self, end: ReverseIndex) -> ReverseIndexRange { + ReverseIndexRange(self, end) + } + + /// Transforms this reverse index into a regular index for the given buffer. + pub fn to_forward_index(self, buf: &[T]) -> usize { + buf.len() - self.0 + } + + /// Returns the number of elements until the end of the range. + pub fn distance_to_end(&self) -> usize { + self.0 + } +} + +impl Sub for ReverseIndex { + type Output = Self; + + fn sub(self, rhs: usize) -> Self::Output { + Self(self.0 + rhs) + } +} + +impl SubAssign for ReverseIndex { + fn sub_assign(&mut self, rhs: usize) { + *self = *self - rhs; + } +} + +impl Add for ReverseIndex { + type Output = Self; + + fn add(self, rhs: usize) -> Self::Output { + Self(self.0 - rhs) + } +} + +impl AddAssign for ReverseIndex { + fn add_assign(&mut self, rhs: usize) { + *self = *self + rhs; + } +} +impl Index for [T] { + type Output = T; + + fn index(&self, index: ReverseIndex) -> &Self::Output { + let index = index.to_forward_index(self); + &self[index] + } +} + +impl IndexMut for [T] { + fn index_mut(&mut self, index: ReverseIndex) -> &mut Self::Output { + let index = index.to_forward_index(self); + &mut self[index] + } +} + +#[derive(Clone, Copy, Debug, Eq, PartialEq)] +struct ReverseIndexRange(ReverseIndex, ReverseIndex); + +impl Index for [T] { + type Output = [T]; + + fn index(&self, index: ReverseIndexRange) -> &Self::Output { + let start = index.0.to_forward_index(self); + let end = index.1.to_forward_index(self); + &self[start..end] + } +} + +impl IndexMut for [T] { + fn index_mut(&mut self, index: ReverseIndexRange) -> &mut Self::Output { + let start = index.0.to_forward_index(self); + let end = index.1.to_forward_index(self); + &mut self[start..end] + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn reverse_index_test() { + let buf = [0, 1, 2, 3, 4, 5]; + let idx = ReverseIndex::end() - 2; + assert_eq!(&buf[idx.range_to_end()], &[4, 5]); + assert_eq!(&buf[idx.range_to(idx + 1)], &[4]); + assert_eq!(idx.to_forward_index(&buf), 4); + } +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/endian_scalar.rs b/third_party/flatbuffers/rust/flatbuffers/src/endian_scalar.rs new file mode 100644 index 00000000000..48cb83e2f9d --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/endian_scalar.rs @@ -0,0 +1,184 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#![allow(clippy::wrong_self_convention)] + +use core::mem::size_of; + +mod private { + /// Types that are trivially transmutable are those where any combination of bits + /// represents a valid value of that type + /// + /// For example integral types are TriviallyTransmutable as all bit patterns are valid, + /// however, `bool` is not trivially transmutable as only `0` and `1` are valid + pub trait TriviallyTransmutable {} + + impl TriviallyTransmutable for i8 {} + impl TriviallyTransmutable for i16 {} + impl TriviallyTransmutable for i32 {} + impl TriviallyTransmutable for i64 {} + impl TriviallyTransmutable for u8 {} + impl TriviallyTransmutable for u16 {} + impl TriviallyTransmutable for u32 {} + impl TriviallyTransmutable for u64 {} +} + +/// Trait for values that must be stored in little-endian byte order, but +/// might be represented in memory as big-endian. Every type that implements +/// EndianScalar is a valid FlatBuffers scalar value. +/// +/// The Rust stdlib does not provide a trait to represent scalars, so this trait +/// serves that purpose, too. +/// +/// Note that we do not use the num-traits crate for this, because it provides +/// "too much". For example, num-traits provides i128 support, but that is an +/// invalid FlatBuffers type. +pub trait EndianScalar: Sized + PartialEq + Copy + Clone { + type Scalar: private::TriviallyTransmutable; + + fn to_little_endian(self) -> Self::Scalar; + + fn from_little_endian(v: Self::Scalar) -> Self; +} + +/// Macro for implementing an endian conversion using the stdlib `to_le` and +/// `from_le` functions. This is used for integer types. It is not used for +/// floats, because the `to_le` and `from_le` are not implemented for them in +/// the stdlib. +macro_rules! impl_endian_scalar { + ($ty:ident) => { + impl EndianScalar for $ty { + type Scalar = Self; + + #[inline] + fn to_little_endian(self) -> Self::Scalar { + Self::to_le(self) + } + #[inline] + fn from_little_endian(v: Self::Scalar) -> Self { + Self::from_le(v) + } + } + }; +} + +impl_endian_scalar!(u8); +impl_endian_scalar!(i8); +impl_endian_scalar!(u16); +impl_endian_scalar!(u32); +impl_endian_scalar!(u64); +impl_endian_scalar!(i16); +impl_endian_scalar!(i32); +impl_endian_scalar!(i64); + +impl EndianScalar for bool { + type Scalar = u8; + + fn to_little_endian(self) -> Self::Scalar { + self as u8 + } + + fn from_little_endian(v: Self::Scalar) -> Self { + v != 0 + } +} + +impl EndianScalar for f32 { + type Scalar = u32; + /// Convert f32 from host endian-ness to little-endian. + #[inline] + fn to_little_endian(self) -> u32 { + // Floats and Ints have the same endianness on all supported platforms. + // + self.to_bits().to_le() + } + /// Convert f32 from little-endian to host endian-ness. + #[inline] + fn from_little_endian(v: u32) -> Self { + // Floats and Ints have the same endianness on all supported platforms. + // + f32::from_bits(u32::from_le(v)) + } +} + +impl EndianScalar for f64 { + type Scalar = u64; + + /// Convert f64 from host endian-ness to little-endian. + #[inline] + fn to_little_endian(self) -> u64 { + // Floats and Ints have the same endianness on all supported platforms. + // + self.to_bits().to_le() + } + /// Convert f64 from little-endian to host endian-ness. + #[inline] + fn from_little_endian(v: u64) -> Self { + // Floats and Ints have the same endianness on all supported platforms. + // + f64::from_bits(u64::from_le(v)) + } +} + +/// Place an EndianScalar into the provided mutable byte slice. Performs +/// endian conversion, if necessary. +/// # Safety +/// Caller must ensure `s.len() >= size_of::()` +#[inline] +pub unsafe fn emplace_scalar(s: &mut [u8], x: T) { + let size = size_of::(); + debug_assert!( + s.len() >= size, + "insufficient capacity for emplace_scalar, needed {} got {}", + size, + s.len() + ); + + let x_le = x.to_little_endian(); + core::ptr::copy_nonoverlapping( + &x_le as *const T::Scalar as *const u8, + s.as_mut_ptr() as *mut u8, + size, + ); +} + +/// Read an EndianScalar from the provided byte slice at the specified location. +/// Performs endian conversion, if necessary. +/// # Safety +/// Caller must ensure `s.len() >= loc + size_of::()`. +#[inline] +pub unsafe fn read_scalar_at(s: &[u8], loc: usize) -> T { + read_scalar(&s[loc..]) +} + +/// Read an EndianScalar from the provided byte slice. Performs endian +/// conversion, if necessary. +/// # Safety +/// Caller must ensure `s.len() > size_of::()`. +#[inline] +pub unsafe fn read_scalar(s: &[u8]) -> T { + let size = size_of::(); + debug_assert!( + s.len() >= size, + "insufficient capacity for emplace_scalar, needed {} got {}", + size, + s.len() + ); + + let mut mem = core::mem::MaybeUninit::::uninit(); + // Since [u8] has alignment 1, we copy it into T which may have higher alignment. + core::ptr::copy_nonoverlapping(s.as_ptr(), mem.as_mut_ptr() as *mut u8, size); + T::from_little_endian(mem.assume_init()) +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/follow.rs b/third_party/flatbuffers/rust/flatbuffers/src/follow.rs new file mode 100644 index 00000000000..74884875942 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/follow.rs @@ -0,0 +1,63 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use core::marker::PhantomData; + +/// Follow is a trait that allows us to access FlatBuffers in a declarative, +/// type safe, and fast way. They compile down to almost no code (after +/// optimizations). Conceptually, Follow lifts the offset-based access +/// patterns of FlatBuffers data into the type system. This trait is used +/// pervasively at read time, to access tables, vtables, vectors, strings, and +/// all other data. At this time, Follow is not utilized much on the write +/// path. +/// +/// Writing a new Follow implementation primarily involves deciding whether +/// you want to return data (of the type Self::Inner) or do you want to +/// continue traversing the FlatBuffer. +pub trait Follow<'buf> { + type Inner; + /// # Safety + /// + /// `buf[loc..]` must contain a valid value of `Self` and anything it + /// transitively refers to by offset must also be valid + unsafe fn follow(buf: &'buf [u8], loc: usize) -> Self::Inner; +} + +/// FollowStart wraps a Follow impl in a struct type. This can make certain +/// programming patterns more ergonomic. +#[derive(Debug, Default)] +pub struct FollowStart(PhantomData); +impl<'a, T: Follow<'a> + 'a> FollowStart { + #[inline] + pub fn new() -> Self { + Self(PhantomData) + } + + /// # Safety + /// + /// `buf[loc..]` must contain a valid value of `T` + #[inline] + pub unsafe fn self_follow(&'a self, buf: &'a [u8], loc: usize) -> T::Inner { + T::follow(buf, loc) + } +} +impl<'a, T: Follow<'a>> Follow<'a> for FollowStart { + type Inner = T::Inner; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + T::follow(buf, loc) + } +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/get_root.rs b/third_party/flatbuffers/rust/flatbuffers/src/get_root.rs new file mode 100644 index 00000000000..372d02f73c5 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/get_root.rs @@ -0,0 +1,111 @@ +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use crate::{ + Follow, ForwardsUOffset, InvalidFlatbuffer, SkipSizePrefix, Verifiable, Verifier, + VerifierOptions, +}; + +/// Gets the root of the Flatbuffer, verifying it first with default options. +/// Note that verification is an experimental feature and may not be maximally performant or +/// catch every error (though that is the goal). See the `_unchecked` variants for previous +/// behavior. +pub fn root<'buf, T>(data: &'buf [u8]) -> Result +where + T: 'buf + Follow<'buf> + Verifiable, +{ + let opts = VerifierOptions::default(); + root_with_opts::(&opts, data) +} + +#[inline] +/// Gets the root of the Flatbuffer, verifying it first with given options. +/// Note that verification is an experimental feature and may not be maximally performant or +/// catch every error (though that is the goal). See the `_unchecked` variants for previous +/// behavior. +pub fn root_with_opts<'opts, 'buf, T>( + opts: &'opts VerifierOptions, + data: &'buf [u8], +) -> Result +where + T: 'buf + Follow<'buf> + Verifiable, +{ + let mut v = Verifier::new(opts, data); + >::run_verifier(&mut v, 0)?; + // Safety: + // Run verifier above + Ok(unsafe { root_unchecked::(data) }) +} + +#[inline] +/// Gets the root of a size prefixed Flatbuffer, verifying it first with default options. +/// Note that verification is an experimental feature and may not be maximally performant or +/// catch every error (though that is the goal). See the `_unchecked` variants for previous +/// behavior. +pub fn size_prefixed_root<'buf, T>(data: &'buf [u8]) -> Result +where + T: 'buf + Follow<'buf> + Verifiable, +{ + let opts = VerifierOptions::default(); + size_prefixed_root_with_opts::(&opts, data) +} + +#[inline] +/// Gets the root of a size prefixed Flatbuffer, verifying it first with given options. +/// Note that verification is an experimental feature and may not be maximally performant or +/// catch every error (though that is the goal). See the `_unchecked` variants for previous +/// behavior. +pub fn size_prefixed_root_with_opts<'opts, 'buf, T>( + opts: &'opts VerifierOptions, + data: &'buf [u8], +) -> Result +where + T: 'buf + Follow<'buf> + Verifiable, +{ + let mut v = Verifier::new(opts, data); + >>::run_verifier(&mut v, 0)?; + // Safety: + // Run verifier above + Ok(unsafe { size_prefixed_root_unchecked::(data) }) +} + +#[inline] +/// Gets root for a trusted Flatbuffer. +/// # Safety +/// Flatbuffers accessors do not perform validation checks before accessing. Unlike the other +/// `root` functions, this does not validate the flatbuffer before returning the accessor. Users +/// must trust `data` contains a valid flatbuffer (e.g. b/c it was built by your software). Reading +/// unchecked buffers may cause panics or even UB. +pub unsafe fn root_unchecked<'buf, T>(data: &'buf [u8]) -> T::Inner +where + T: Follow<'buf> + 'buf, +{ + >::follow(data, 0) +} + +#[inline] +/// Gets root for a trusted, size prefixed, Flatbuffer. +/// # Safety +/// Flatbuffers accessors do not perform validation checks before accessing. Unlike the other +/// `root` functions, this does not validate the flatbuffer before returning the accessor. Users +/// must trust `data` contains a valid flatbuffer (e.g. b/c it was built by your software). Reading +/// unchecked buffers may cause panics or even UB. +pub unsafe fn size_prefixed_root_unchecked<'buf, T>(data: &'buf [u8]) -> T::Inner +where + T: Follow<'buf> + 'buf, +{ + >>::follow(data, 0) +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/lib.rs b/third_party/flatbuffers/rust/flatbuffers/src/lib.rs new file mode 100644 index 00000000000..9ed308024fb --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/lib.rs @@ -0,0 +1,66 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +//! # FlatBuffers +//! +//! A library for memory-efficient serialization of data. +//! +//! This crate provides runtime support for the FlatBuffers format in the Rust programming language. +//! To use this crate, first generate code with the `flatc` compiler, as described here: +//! Then, include that code into your project. +//! Finally, add this crate to your `Cargo.toml`. +//! +//! At this time, Rust support is experimental, and APIs may change between minor versions. +//! +//! At this time, to generate Rust code, you will need the latest `master` version of `flatc`, available from here: +//! (On OSX, you can install FlatBuffers from `HEAD` with the Homebrew package manager.) + +#![cfg_attr(not(feature = "std"), no_std)] +#![cfg_attr(all(nightly, not(feature = "std")), feature(error_in_core))] + +#[cfg(not(feature = "std"))] +extern crate alloc; + +mod array; +mod builder; +mod endian_scalar; +mod follow; +mod get_root; +mod primitives; +mod push; +mod table; +mod vector; +mod verifier; +mod vtable; +mod vtable_writer; + +pub use crate::array::{array_init, emplace_scalar_array, Array}; +pub use crate::builder::{Allocator, DefaultAllocator, FlatBufferBuilder}; +pub use crate::endian_scalar::{emplace_scalar, read_scalar, read_scalar_at, EndianScalar}; +pub use crate::follow::{Follow, FollowStart}; +pub use crate::primitives::*; +pub use crate::push::{Push, PushAlignment}; +pub use crate::table::{buffer_has_identifier, Table}; +pub use crate::vector::{follow_cast_ref, Vector, VectorIter}; +pub use crate::verifier::{ + ErrorTraceDetail, InvalidFlatbuffer, SimpleToVerifyInSlice, TableVerifier, Verifiable, Verifier, + VerifierOptions, +}; +pub use crate::vtable::field_index_to_field_offset; +pub use bitflags; +pub use get_root::*; + +// TODO(rw): Split fill ops in builder into fill_small, fill_big like in C++. diff --git a/third_party/flatbuffers/rust/flatbuffers/src/primitives.rs b/third_party/flatbuffers/rust/flatbuffers/src/primitives.rs new file mode 100644 index 00000000000..ac35511da94 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/primitives.rs @@ -0,0 +1,323 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use core::marker::PhantomData; +use core::mem::size_of; +use core::ops::Deref; + +use crate::endian_scalar::{emplace_scalar, read_scalar, read_scalar_at}; +use crate::follow::Follow; +use crate::push::Push; + +pub const FLATBUFFERS_MAX_BUFFER_SIZE: usize = (1u64 << 31) as usize; + +pub const FILE_IDENTIFIER_LENGTH: usize = 4; + +pub const VTABLE_METADATA_FIELDS: usize = 2; + +pub const SIZE_U8: usize = size_of::(); +pub const SIZE_I8: usize = size_of::(); + +pub const SIZE_U16: usize = size_of::(); +pub const SIZE_I16: usize = size_of::(); + +pub const SIZE_U32: usize = size_of::(); +pub const SIZE_I32: usize = size_of::(); + +pub const SIZE_U64: usize = size_of::(); +pub const SIZE_I64: usize = size_of::(); + +pub const SIZE_F32: usize = size_of::(); +pub const SIZE_F64: usize = size_of::(); + +pub const SIZE_SOFFSET: usize = SIZE_I32; +pub const SIZE_UOFFSET: usize = SIZE_U32; +pub const SIZE_VOFFSET: usize = SIZE_I16; + +pub const SIZE_SIZEPREFIX: usize = SIZE_UOFFSET; + +/// SOffsetT is a relative pointer from tables to their vtables. +pub type SOffsetT = i32; + +/// UOffsetT is used represent both for relative pointers and lengths of vectors. +pub type UOffsetT = u32; + +/// VOffsetT is a relative pointer in vtables to point from tables to field data. +pub type VOffsetT = u16; + +/// TableFinishedWIPOffset marks a WIPOffset as being for a finished table. +#[derive(Clone, Copy)] +pub struct TableFinishedWIPOffset {} + +/// TableUnfinishedWIPOffset marks a WIPOffset as being for an unfinished table. +#[derive(Clone, Copy)] +pub struct TableUnfinishedWIPOffset {} + +/// UnionWIPOffset marks a WIPOffset as being for a union value. +#[derive(Clone, Copy)] +pub struct UnionWIPOffset {} + +/// VTableWIPOffset marks a WIPOffset as being for a vtable. +#[derive(Clone, Copy)] +pub struct VTableWIPOffset {} + +/// WIPOffset contains an UOffsetT with a special meaning: it is the location of +/// data relative to the *end* of an in-progress FlatBuffer. The +/// FlatBufferBuilder uses this to track the location of objects in an absolute +/// way. The impl of Push converts a WIPOffset into a ForwardsUOffset. +#[derive(Debug)] +pub struct WIPOffset(UOffsetT, PhantomData); + +// We cannot use derive for these two impls, as the derived impls would only +// implement `Copy` and `Clone` for `T: Copy` and `T: Clone` respectively. +// However `WIPOffset` can always be copied, no matter that `T` you +// have. +impl Copy for WIPOffset {} +impl Clone for WIPOffset { + #[inline(always)] + fn clone(&self) -> Self { + *self + } +} + +impl Eq for WIPOffset {} + +impl PartialEq for WIPOffset { + fn eq(&self, o: &WIPOffset) -> bool { + self.value() == o.value() + } +} + +impl Deref for WIPOffset { + type Target = UOffsetT; + #[inline] + fn deref(&self) -> &UOffsetT { + &self.0 + } +} +impl<'a, T: 'a> WIPOffset { + /// Create a new WIPOffset. + #[inline] + pub fn new(o: UOffsetT) -> WIPOffset { + WIPOffset(o, PhantomData) + } + + /// Return a wrapped value that brings its meaning as a union WIPOffset + /// into the type system. + #[inline(always)] + pub fn as_union_value(self) -> WIPOffset { + WIPOffset::new(self.0) + } + /// Get the underlying value. + #[inline(always)] + pub fn value(self) -> UOffsetT { + self.0 + } +} + +impl Push for WIPOffset { + type Output = ForwardsUOffset; + + #[inline(always)] + unsafe fn push(&self, dst: &mut [u8], written_len: usize) { + let n = (SIZE_UOFFSET + written_len - self.value() as usize) as UOffsetT; + emplace_scalar::(dst, n); + } +} + +impl Push for ForwardsUOffset { + type Output = Self; + + #[inline(always)] + unsafe fn push(&self, dst: &mut [u8], written_len: usize) { + self.value().push(dst, written_len); + } +} + +/// ForwardsUOffset is used by Follow to traverse a FlatBuffer: the pointer +/// is incremented by the value contained in this type. +#[derive(Debug)] +pub struct ForwardsUOffset(UOffsetT, PhantomData); + +// We cannot use derive for these two impls, as the derived impls would only +// implement `Copy` and `Clone` for `T: Copy` and `T: Clone` respectively. +// However `ForwardsUOffset` can always be copied, no matter that `T` you +// have. +impl Copy for ForwardsUOffset {} +impl Clone for ForwardsUOffset { + #[inline(always)] + fn clone(&self) -> Self { + *self + } +} + +impl ForwardsUOffset { + #[inline(always)] + pub fn value(self) -> UOffsetT { + self.0 + } +} + +impl<'a, T: Follow<'a>> Follow<'a> for ForwardsUOffset { + type Inner = T::Inner; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let slice = &buf[loc..loc + SIZE_UOFFSET]; + let off = read_scalar::(slice) as usize; + T::follow(buf, loc + off) + } +} + +/// ForwardsVOffset is used by Follow to traverse a FlatBuffer: the pointer +/// is incremented by the value contained in this type. +#[derive(Debug)] +pub struct ForwardsVOffset(VOffsetT, PhantomData); +impl ForwardsVOffset { + #[inline(always)] + pub fn value(&self) -> VOffsetT { + self.0 + } +} + +impl<'a, T: Follow<'a>> Follow<'a> for ForwardsVOffset { + type Inner = T::Inner; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let slice = &buf[loc..loc + SIZE_VOFFSET]; + let off = read_scalar::(slice) as usize; + T::follow(buf, loc + off) + } +} + +impl Push for ForwardsVOffset { + type Output = Self; + + #[inline] + unsafe fn push(&self, dst: &mut [u8], written_len: usize) { + self.value().push(dst, written_len); + } +} + +/// ForwardsSOffset is used by Follow to traverse a FlatBuffer: the pointer +/// is incremented by the *negative* of the value contained in this type. +#[derive(Debug)] +pub struct BackwardsSOffset(SOffsetT, PhantomData); +impl BackwardsSOffset { + #[inline(always)] + pub fn value(&self) -> SOffsetT { + self.0 + } +} + +impl<'a, T: Follow<'a>> Follow<'a> for BackwardsSOffset { + type Inner = T::Inner; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let slice = &buf[loc..loc + SIZE_SOFFSET]; + let off = read_scalar::(slice); + T::follow(buf, (loc as SOffsetT - off) as usize) + } +} + +impl Push for BackwardsSOffset { + type Output = Self; + + #[inline] + unsafe fn push(&self, dst: &mut [u8], written_len: usize) { + self.value().push(dst, written_len); + } +} + +/// SkipSizePrefix is used by Follow to traverse a FlatBuffer: the pointer is +/// incremented by a fixed constant in order to skip over the size prefix value. +pub struct SkipSizePrefix(PhantomData); +impl<'a, T: Follow<'a> + 'a> Follow<'a> for SkipSizePrefix { + type Inner = T::Inner; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + T::follow(buf, loc + SIZE_SIZEPREFIX) + } +} + +/// SkipRootOffset is used by Follow to traverse a FlatBuffer: the pointer is +/// incremented by a fixed constant in order to skip over the root offset value. +pub struct SkipRootOffset(PhantomData); +impl<'a, T: Follow<'a> + 'a> Follow<'a> for SkipRootOffset { + type Inner = T::Inner; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + T::follow(buf, loc + SIZE_UOFFSET) + } +} + +/// FileIdentifier is used by Follow to traverse a FlatBuffer: the pointer is +/// dereferenced into a byte slice, whose bytes are the file identifer value. +pub struct FileIdentifier; +impl<'a> Follow<'a> for FileIdentifier { + type Inner = &'a [u8]; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + &buf[loc..loc + FILE_IDENTIFIER_LENGTH] + } +} + +/// SkipFileIdentifier is used by Follow to traverse a FlatBuffer: the pointer +/// is incremented by a fixed constant in order to skip over the file +/// identifier value. +pub struct SkipFileIdentifier(PhantomData); +impl<'a, T: Follow<'a> + 'a> Follow<'a> for SkipFileIdentifier { + type Inner = T::Inner; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + T::follow(buf, loc + FILE_IDENTIFIER_LENGTH) + } +} + +impl<'a> Follow<'a> for bool { + type Inner = bool; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + read_scalar_at::(buf, loc) != 0 + } +} + +/// Follow trait impls for primitive types. +/// +/// Ideally, these would be implemented as a single impl using trait bounds on +/// EndianScalar, but implementing Follow that way causes a conflict with +/// other impls. +macro_rules! impl_follow_for_endian_scalar { + ($ty:ident) => { + impl<'a> Follow<'a> for $ty { + type Inner = $ty; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + read_scalar_at::<$ty>(buf, loc) + } + } + }; +} + +impl_follow_for_endian_scalar!(u8); +impl_follow_for_endian_scalar!(u16); +impl_follow_for_endian_scalar!(u32); +impl_follow_for_endian_scalar!(u64); +impl_follow_for_endian_scalar!(i8); +impl_follow_for_endian_scalar!(i16); +impl_follow_for_endian_scalar!(i32); +impl_follow_for_endian_scalar!(i64); +impl_follow_for_endian_scalar!(f32); +impl_follow_for_endian_scalar!(f64); diff --git a/third_party/flatbuffers/rust/flatbuffers/src/push.rs b/third_party/flatbuffers/rust/flatbuffers/src/push.rs new file mode 100644 index 00000000000..20bacd8e2e5 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/push.rs @@ -0,0 +1,100 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use core::cmp::max; +use core::mem::{align_of, size_of}; + +use crate::endian_scalar::emplace_scalar; + +/// Trait to abstract over functionality needed to write values (either owned +/// or referenced). Used in FlatBufferBuilder and implemented for generated +/// types. +pub trait Push: Sized { + type Output; + + /// # Safety + /// + /// dst is aligned to [`Self::alignment`] and has length greater than or equal to [`Self::size`] + unsafe fn push(&self, dst: &mut [u8], written_len: usize); + #[inline] + fn size() -> usize { + size_of::() + } + #[inline] + fn alignment() -> PushAlignment { + PushAlignment::new(align_of::()) + } +} + +impl<'a, T: Push> Push for &'a T { + type Output = T::Output; + + unsafe fn push(&self, dst: &mut [u8], written_len: usize) { + T::push(self, dst, written_len) + } + + fn size() -> usize { + T::size() + } + + fn alignment() -> PushAlignment { + T::alignment() + } +} + +/// Ensure Push alignment calculations are typesafe (because this helps reduce +/// implementation issues when using FlatBufferBuilder::align). +pub struct PushAlignment(usize); +impl PushAlignment { + #[inline] + pub fn new(x: usize) -> Self { + PushAlignment(x) + } + #[inline] + pub fn value(&self) -> usize { + self.0 + } + #[inline] + pub fn max_of(&self, o: usize) -> Self { + PushAlignment::new(max(self.0, o)) + } +} + +/// Macro to implement Push for EndianScalar types. +macro_rules! impl_push_for_endian_scalar { + ($ty:ident) => { + impl Push for $ty { + type Output = $ty; + + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + emplace_scalar::<$ty>(dst, *self); + } + } + }; +} + +impl_push_for_endian_scalar!(bool); +impl_push_for_endian_scalar!(u8); +impl_push_for_endian_scalar!(i8); +impl_push_for_endian_scalar!(u16); +impl_push_for_endian_scalar!(i16); +impl_push_for_endian_scalar!(u32); +impl_push_for_endian_scalar!(i32); +impl_push_for_endian_scalar!(u64); +impl_push_for_endian_scalar!(i64); +impl_push_for_endian_scalar!(f32); +impl_push_for_endian_scalar!(f64); diff --git a/third_party/flatbuffers/rust/flatbuffers/src/table.rs b/third_party/flatbuffers/rust/flatbuffers/src/table.rs new file mode 100644 index 00000000000..d3c296bb316 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/table.rs @@ -0,0 +1,99 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use crate::follow::Follow; +use crate::primitives::*; +use crate::vtable::VTable; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Table<'a> { + buf: &'a [u8], + loc: usize, +} + +impl<'a> Table<'a> { + #[inline] + pub fn buf(&self) -> &'a [u8] { + self.buf + } + + #[inline] + pub fn loc(&self) -> usize { + self.loc + } + + /// # Safety + /// + /// `buf` must contain a `soffset_t` at `loc`, which points to a valid vtable + #[inline] + pub unsafe fn new(buf: &'a [u8], loc: usize) -> Self { + Table { buf, loc } + } + + #[inline] + pub fn vtable(&self) -> VTable<'a> { + // Safety: + // Table::new is created with a valid buf and location + unsafe { >>::follow(self.buf, self.loc) } + } + + /// Retrieves the value at the provided `slot_byte_loc` returning `default` + /// if no value present + /// + /// # Safety + /// + /// The value of the corresponding slot must have type T + #[inline] + pub unsafe fn get + 'a>( + &self, + slot_byte_loc: VOffsetT, + default: Option, + ) -> Option { + let o = self.vtable().get(slot_byte_loc) as usize; + if o == 0 { + return default; + } + Some(::follow(self.buf, self.loc + o)) + } +} + +impl<'a> Follow<'a> for Table<'a> { + type Inner = Table<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Table { buf, loc } + } +} + +/// Returns true if data contains a prefix of `ident` +#[inline] +pub fn buffer_has_identifier(data: &[u8], ident: &str, size_prefixed: bool) -> bool { + assert_eq!(ident.len(), FILE_IDENTIFIER_LENGTH); + + let got = if size_prefixed { + assert!(data.len() >= SIZE_SIZEPREFIX + SIZE_UOFFSET + FILE_IDENTIFIER_LENGTH); + // Safety: + // Verified data has sufficient bytes + unsafe { >>::follow(data, 0) } + } else { + assert!(data.len() >= SIZE_UOFFSET + FILE_IDENTIFIER_LENGTH); + // Safety: + // Verified data has sufficient bytes + unsafe { >::follow(data, 0) } + }; + + ident.as_bytes() == got +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/vector.rs b/third_party/flatbuffers/rust/flatbuffers/src/vector.rs new file mode 100644 index 00000000000..e1569510c85 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/vector.rs @@ -0,0 +1,341 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use core::cmp::Ordering; +use core::fmt::{Debug, Formatter, Result}; +use core::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator}; +use core::marker::PhantomData; +use core::mem::{align_of, size_of}; +use core::str::from_utf8_unchecked; + +use crate::endian_scalar::read_scalar_at; +use crate::follow::Follow; +use crate::primitives::*; + +pub struct Vector<'a, T: 'a>(&'a [u8], usize, PhantomData); + +impl<'a, T: 'a> Default for Vector<'a, T> { + fn default() -> Self { + // Static, length 0 vector. + // Note that derived default causes UB due to issues in read_scalar_at /facepalm. + Self( + &[0; core::mem::size_of::()], + 0, + Default::default(), + ) + } +} + +impl<'a, T> Debug for Vector<'a, T> +where + T: 'a + Follow<'a>, + >::Inner: Debug, +{ + fn fmt(&self, f: &mut Formatter) -> Result { + f.debug_list().entries(self.iter()).finish() + } +} + +// We cannot use derive for these two impls, as it would only implement Copy +// and Clone for `T: Copy` and `T: Clone` respectively. However `Vector<'a, T>` +// can always be copied, no matter that `T` you have. +impl<'a, T> Copy for Vector<'a, T> {} + +impl<'a, T> Clone for Vector<'a, T> { + fn clone(&self) -> Self { + *self + } +} + +impl<'a, T: 'a> Vector<'a, T> { + /// # Safety + /// + /// `buf` contains a valid vector at `loc` consisting of + /// + /// - UOffsetT element count + /// - Consecutive list of `T` elements + #[inline(always)] + pub unsafe fn new(buf: &'a [u8], loc: usize) -> Self { + Vector(buf, loc, PhantomData) + } + + #[inline(always)] + pub fn len(&self) -> usize { + // Safety: + // Valid vector at time of construction starting with UOffsetT element count + unsafe { read_scalar_at::(self.0, self.1) as usize } + } + + #[inline(always)] + pub fn is_empty(&self) -> bool { + self.len() == 0 + } + + #[inline(always)] + pub fn bytes(&self) -> &'a [u8] { + let sz = size_of::(); + let len = self.len(); + &self.0[self.1 + SIZE_UOFFSET..self.1 + SIZE_UOFFSET + sz * len] + } +} + +impl<'a, T: Follow<'a> + 'a> Vector<'a, T> { + #[inline(always)] + pub fn get(&self, idx: usize) -> T::Inner { + assert!(idx < self.len()); + let sz = size_of::(); + debug_assert!(sz > 0); + // Safety: + // Valid vector at time of construction, verified that idx < element count + unsafe { T::follow(self.0, self.1 as usize + SIZE_UOFFSET + sz * idx) } + } + + #[inline(always)] + pub fn lookup_by_key( + &self, + key: K, + f: fn(&>::Inner, &K) -> Ordering, + ) -> Option { + if self.is_empty() { + return None; + } + + let mut left: usize = 0; + let mut right = self.len() - 1; + + while left <= right { + let mid = (left + right) / 2; + let value = self.get(mid); + match f(&value, &key) { + Ordering::Equal => return Some(value), + Ordering::Less => left = mid + 1, + Ordering::Greater => { + if mid == 0 { + return None; + } + right = mid - 1; + }, + } + } + + None + } + + #[inline(always)] + pub fn iter(&self) -> VectorIter<'a, T> { + VectorIter::from_vector(*self) + } +} + +/// # Safety +/// +/// `buf` must contain a value of T at `loc` and have alignment of 1 +pub unsafe fn follow_cast_ref<'a, T: Sized + 'a>(buf: &'a [u8], loc: usize) -> &'a T { + assert_eq!(align_of::(), 1); + let sz = size_of::(); + let buf = &buf[loc..loc + sz]; + let ptr = buf.as_ptr() as *const T; + // SAFETY + // buf contains a value at loc of type T and T has no alignment requirements + &*ptr +} + +impl<'a> Follow<'a> for &'a str { + type Inner = &'a str; + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let len = read_scalar_at::(buf, loc) as usize; + let slice = &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len]; + from_utf8_unchecked(slice) + } +} + +impl<'a> Follow<'a> for &'a [u8] { + type Inner = &'a [u8]; + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let len = read_scalar_at::(buf, loc) as usize; + &buf[loc + SIZE_UOFFSET..loc + SIZE_UOFFSET + len] + } +} + +/// Implement Follow for all possible Vectors that have Follow-able elements. +impl<'a, T: Follow<'a> + 'a> Follow<'a> for Vector<'a, T> { + type Inner = Vector<'a, T>; + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Vector::new(buf, loc) + } +} + +/// An iterator over a `Vector`. +#[derive(Debug)] +pub struct VectorIter<'a, T: 'a> { + buf: &'a [u8], + loc: usize, + remaining: usize, + phantom: PhantomData, +} + +impl<'a, T: 'a> VectorIter<'a, T> { + #[inline] + pub fn from_vector(inner: Vector<'a, T>) -> Self { + VectorIter { + buf: inner.0, + // inner.1 is the location of the data for the vector. + // The first SIZE_UOFFSET bytes is the length. We skip + // that to get to the actual vector content. + loc: inner.1 + SIZE_UOFFSET, + remaining: inner.len(), + phantom: PhantomData, + } + } + + /// Creates a new `VectorIter` from the provided slice + /// + /// # Safety + /// + /// buf must contain a contiguous sequence of `items_num` values of `T` + /// + #[inline] + pub unsafe fn from_slice(buf: &'a [u8], items_num: usize) -> Self { + VectorIter { + buf, + loc: 0, + remaining: items_num, + phantom: PhantomData, + } + } +} + +impl<'a, T: Follow<'a> + 'a> Clone for VectorIter<'a, T> { + #[inline] + fn clone(&self) -> Self { + VectorIter { + buf: self.buf, + loc: self.loc, + remaining: self.remaining, + phantom: self.phantom, + } + } +} + +impl<'a, T: Follow<'a> + 'a> Iterator for VectorIter<'a, T> { + type Item = T::Inner; + + #[inline] + fn next(&mut self) -> Option { + let sz = size_of::(); + debug_assert!(sz > 0); + + if self.remaining == 0 { + None + } else { + // Safety: + // VectorIter can only be created from a contiguous sequence of `items_num` + // And remaining is initialized to `items_num` + let result = unsafe { T::follow(self.buf, self.loc) }; + self.loc += sz; + self.remaining -= 1; + Some(result) + } + } + + #[inline] + fn nth(&mut self, n: usize) -> Option { + let sz = size_of::(); + debug_assert!(sz > 0); + + self.remaining = self.remaining.saturating_sub(n); + + // Note that this might overflow, but that is okay because + // in that case self.remaining will have been set to zero. + self.loc = self.loc.wrapping_add(sz * n); + + self.next() + } + + #[inline] + fn size_hint(&self) -> (usize, Option) { + (self.remaining, Some(self.remaining)) + } +} + +impl<'a, T: Follow<'a> + 'a> DoubleEndedIterator for VectorIter<'a, T> { + #[inline] + fn next_back(&mut self) -> Option { + let sz = size_of::(); + debug_assert!(sz > 0); + + if self.remaining == 0 { + None + } else { + self.remaining -= 1; + // Safety: + // VectorIter can only be created from a contiguous sequence of `items_num` + // And remaining is initialized to `items_num` + Some(unsafe { T::follow(self.buf, self.loc + sz * self.remaining) }) + } + } + + #[inline] + fn nth_back(&mut self, n: usize) -> Option { + self.remaining = self.remaining.saturating_sub(n); + self.next_back() + } +} + +impl<'a, T: 'a + Follow<'a>> ExactSizeIterator for VectorIter<'a, T> { + #[inline] + fn len(&self) -> usize { + self.remaining + } +} + +impl<'a, T: 'a + Follow<'a>> FusedIterator for VectorIter<'a, T> {} + +impl<'a, T: Follow<'a> + 'a> IntoIterator for Vector<'a, T> { + type Item = T::Inner; + type IntoIter = VectorIter<'a, T>; + #[inline] + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +impl<'a, 'b, T: Follow<'a> + 'a> IntoIterator for &'b Vector<'a, T> { + type Item = T::Inner; + type IntoIter = VectorIter<'a, T>; + fn into_iter(self) -> Self::IntoIter { + self.iter() + } +} + +#[cfg(feature = "serialize")] +impl<'a, T> serde::ser::Serialize for Vector<'a, T> +where + T: 'a + Follow<'a>, + >::Inner: serde::ser::Serialize, +{ + fn serialize(&self, serializer: S) -> std::result::Result + where + S: serde::ser::Serializer, + { + use serde::ser::SerializeSeq; + let mut seq = serializer.serialize_seq(Some(self.len()))?; + for element in self { + seq.serialize_element(&element)?; + } + seq.end() + } +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/verifier.rs b/third_party/flatbuffers/rust/flatbuffers/src/verifier.rs new file mode 100644 index 00000000000..c4c55f587d0 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/verifier.rs @@ -0,0 +1,699 @@ +use crate::follow::Follow; +use crate::{ForwardsUOffset, SOffsetT, SkipSizePrefix, UOffsetT, VOffsetT, Vector, SIZE_UOFFSET}; +#[cfg(not(feature = "std"))] +use alloc::vec::Vec; +use core::ops::Range; +use core::option::Option; + +#[cfg(not(feature = "std"))] +use alloc::borrow::Cow; +#[cfg(feature = "std")] +use std::borrow::Cow; + +#[cfg(all(nightly, not(feature = "std")))] +use core::error::Error; +#[cfg(feature = "std")] +use std::error::Error; + +/// Traces the location of data errors. Not populated for Dos detecting errors. +/// Useful for MissingRequiredField and Utf8Error in particular, though +/// the other errors should not be producible by correct flatbuffers implementations. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum ErrorTraceDetail { + VectorElement { + index: usize, + position: usize, + }, + TableField { + field_name: Cow<'static, str>, + position: usize, + }, + UnionVariant { + variant: Cow<'static, str>, + position: usize, + }, +} + +#[derive(PartialEq, Eq, Default, Debug, Clone)] +pub struct ErrorTrace(Vec); + +impl core::convert::AsRef<[ErrorTraceDetail]> for ErrorTrace { + #[inline] + fn as_ref(&self) -> &[ErrorTraceDetail] { + &self.0 + } +} + +/// Describes how a flatuffer is invalid and, for data errors, roughly where. No extra tracing +/// information is given for DoS detecting errors since it will probably be a lot. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum InvalidFlatbuffer { + MissingRequiredField { + required: Cow<'static, str>, + error_trace: ErrorTrace, + }, + InconsistentUnion { + field: Cow<'static, str>, + field_type: Cow<'static, str>, + error_trace: ErrorTrace, + }, + Utf8Error { + error: core::str::Utf8Error, + range: Range, + error_trace: ErrorTrace, + }, + MissingNullTerminator { + range: Range, + error_trace: ErrorTrace, + }, + Unaligned { + position: usize, + unaligned_type: Cow<'static, str>, + error_trace: ErrorTrace, + }, + RangeOutOfBounds { + range: Range, + error_trace: ErrorTrace, + }, + SignedOffsetOutOfBounds { + soffset: SOffsetT, + position: usize, + error_trace: ErrorTrace, + }, + // Dos detecting errors. These do not get error traces since it will probably be very large. + TooManyTables, + ApparentSizeTooLarge, + DepthLimitReached, +} + +#[cfg(any(nightly, feature = "std"))] +impl Error for InvalidFlatbuffer { + fn source(&self) -> Option<&(dyn Error + 'static)> { + if let InvalidFlatbuffer::Utf8Error { error: source, .. } = self { + Some(source) + } else { + None + } + } +} + +impl core::fmt::Display for InvalidFlatbuffer { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + match self { + InvalidFlatbuffer::MissingRequiredField { + required, + error_trace, + } => { + writeln!(f, "Missing required field `{}`.\n{}", required, error_trace)?; + } + InvalidFlatbuffer::InconsistentUnion { + field, + field_type, + error_trace, + } => { + writeln!( + f, + "Exactly one of union discriminant (`{}`) and value (`{}`) are present.\n{}", + field_type, field, error_trace + )?; + } + InvalidFlatbuffer::Utf8Error { + error, + range, + error_trace, + } => { + writeln!( + f, + "Utf8 error for string in {:?}: {}\n{}", + range, error, error_trace + )?; + } + InvalidFlatbuffer::MissingNullTerminator { range, error_trace } => { + writeln!( + f, + "String in range [{}, {}) is missing its null terminator.\n{}", + range.start, range.end, error_trace + )?; + } + InvalidFlatbuffer::Unaligned { + position, + unaligned_type, + error_trace, + } => { + writeln!( + f, + "Type `{}` at position {} is unaligned.\n{}", + unaligned_type, position, error_trace + )?; + } + InvalidFlatbuffer::RangeOutOfBounds { range, error_trace } => { + writeln!( + f, + "Range [{}, {}) is out of bounds.\n{}", + range.start, range.end, error_trace + )?; + } + InvalidFlatbuffer::SignedOffsetOutOfBounds { + soffset, + position, + error_trace, + } => { + writeln!( + f, + "Signed offset at position {} has value {} which points out of bounds.\n{}", + position, soffset, error_trace + )?; + } + InvalidFlatbuffer::TooManyTables {} => { + writeln!(f, "Too many tables.")?; + } + InvalidFlatbuffer::ApparentSizeTooLarge {} => { + writeln!(f, "Apparent size too large.")?; + } + InvalidFlatbuffer::DepthLimitReached {} => { + writeln!(f, "Nested table depth limit reached.")?; + } + } + Ok(()) + } +} + +impl core::fmt::Display for ErrorTrace { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + use ErrorTraceDetail::*; + for e in self.0.iter() { + match e { + VectorElement { index, position } => { + writeln!( + f, + "\twhile verifying vector element {:?} at position {:?}", + index, position + )?; + } + TableField { + field_name, + position, + } => { + writeln!( + f, + "\twhile verifying table field `{}` at position {:?}", + field_name, position + )?; + } + UnionVariant { variant, position } => { + writeln!( + f, + "\t while verifying union variant `{}` at position {:?}", + variant, position + )?; + } + } + } + Ok(()) + } +} + +pub type Result = core::result::Result; + +impl InvalidFlatbuffer { + fn new_range_oob(start: usize, end: usize) -> Result { + Err(Self::RangeOutOfBounds { + range: Range { start, end }, + error_trace: Default::default(), + }) + } + pub fn new_inconsistent_union( + field: impl Into>, + field_type: impl Into>, + ) -> Result { + Err(Self::InconsistentUnion { + field: field.into(), + field_type: field_type.into(), + error_trace: Default::default(), + }) + } + pub fn new_missing_required(required: impl Into>) -> Result { + Err(Self::MissingRequiredField { + required: required.into(), + error_trace: Default::default(), + }) + } +} + +/// Records the path to the verifier detail if the error is a data error and not a DoS error. +fn append_trace(mut res: Result, d: ErrorTraceDetail) -> Result { + if let Err(e) = res.as_mut() { + use InvalidFlatbuffer::*; + if let MissingRequiredField { error_trace, .. } + | Unaligned { error_trace, .. } + | RangeOutOfBounds { error_trace, .. } + | InconsistentUnion { error_trace, .. } + | Utf8Error { error_trace, .. } + | MissingNullTerminator { error_trace, .. } + | SignedOffsetOutOfBounds { error_trace, .. } = e + { + error_trace.0.push(d) + } + } + res +} + +/// Adds a TableField trace detail if `res` is a data error. +fn trace_field(res: Result, field_name: Cow<'static, str>, position: usize) -> Result { + append_trace( + res, + ErrorTraceDetail::TableField { + field_name, + position, + }, + ) +} + +/// Adds a TableField trace detail if `res` is a data error. +fn trace_elem(res: Result, index: usize, position: usize) -> Result { + append_trace(res, ErrorTraceDetail::VectorElement { index, position }) +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct VerifierOptions { + /// Maximum depth of nested tables allowed in a valid flatbuffer. + pub max_depth: usize, + /// Maximum number of tables allowed in a valid flatbuffer. + pub max_tables: usize, + /// Maximum "apparent" size of the message if the Flatbuffer object DAG is expanded into a + /// tree. + pub max_apparent_size: usize, + /// Ignore errors where a string is missing its null terminator. + /// This is mostly a problem if the message will be sent to a client using old c-strings. + pub ignore_missing_null_terminator: bool, + // probably want an option to ignore utf8 errors since strings come from c++ + // options to error un-recognized enums and unions? possible footgun. + // Ignore nested flatbuffers, etc? +} + +impl Default for VerifierOptions { + fn default() -> Self { + Self { + max_depth: 64, + max_tables: 1_000_000, + // size_ might do something different. + max_apparent_size: 1 << 31, + ignore_missing_null_terminator: false, + } + } +} + +/// Carries the verification state. Should not be reused between tables. +#[derive(Debug)] +pub struct Verifier<'opts, 'buf> { + buffer: &'buf [u8], + opts: &'opts VerifierOptions, + depth: usize, + num_tables: usize, + apparent_size: usize, +} + +impl<'opts, 'buf> Verifier<'opts, 'buf> { + pub fn new(opts: &'opts VerifierOptions, buffer: &'buf [u8]) -> Self { + Self { + opts, + buffer, + depth: 0, + num_tables: 0, + apparent_size: 0, + } + } + /// Resets verifier internal state. + #[inline] + pub fn reset(&mut self) { + self.depth = 0; + self.num_tables = 0; + self.num_tables = 0; + } + /// Checks `pos` is aligned to T's alignment. This does not mean `buffer[pos]` is aligned w.r.t + /// memory since `buffer: &[u8]` has alignment 1. + /// + /// ### WARNING + /// + /// This does not work for flatbuffers-structs as they have alignment 1 according to + /// `core::mem::align_of` but are meant to have higher alignment within a Flatbuffer w.r.t. + /// `buffer[0]`. TODO(caspern). + /// + /// Note this does not impact soundness as this crate does not assume alignment of structs + #[inline] + pub fn is_aligned(&self, pos: usize) -> Result<()> { + if pos % core::mem::align_of::() == 0 { + Ok(()) + } else { + Err(InvalidFlatbuffer::Unaligned { + unaligned_type: Cow::Borrowed(core::any::type_name::()), + position: pos, + error_trace: Default::default(), + }) + } + } + #[inline] + pub fn range_in_buffer(&mut self, pos: usize, size: usize) -> Result<()> { + let end = pos.saturating_add(size); + if end > self.buffer.len() { + return InvalidFlatbuffer::new_range_oob(pos, end); + } + self.apparent_size += size; + if self.apparent_size > self.opts.max_apparent_size { + return Err(InvalidFlatbuffer::ApparentSizeTooLarge); + } + Ok(()) + } + /// Check that there really is a T in there. + #[inline] + pub fn in_buffer(&mut self, pos: usize) -> Result<()> { + self.is_aligned::(pos)?; + self.range_in_buffer(pos, core::mem::size_of::()) + } + #[inline] + pub fn get_u8(&mut self, pos: usize) -> Result { + self.in_buffer::(pos)?; + Ok(u8::from_le_bytes([self.buffer[pos]])) + } + #[inline] + fn get_u16(&mut self, pos: usize) -> Result { + self.in_buffer::(pos)?; + Ok(u16::from_le_bytes([self.buffer[pos], self.buffer[pos + 1]])) + } + #[inline] + pub fn get_uoffset(&mut self, pos: usize) -> Result { + self.in_buffer::(pos)?; + Ok(u32::from_le_bytes([ + self.buffer[pos], + self.buffer[pos + 1], + self.buffer[pos + 2], + self.buffer[pos + 3], + ])) + } + #[inline] + fn deref_soffset(&mut self, pos: usize) -> Result { + self.in_buffer::(pos)?; + let offset = SOffsetT::from_le_bytes([ + self.buffer[pos], + self.buffer[pos + 1], + self.buffer[pos + 2], + self.buffer[pos + 3], + ]); + + // signed offsets are subtracted. + let derefed = if offset > 0 { + pos.checked_sub(offset.unsigned_abs() as usize) + } else { + pos.checked_add(offset.unsigned_abs() as usize) + }; + if let Some(x) = derefed { + if x < self.buffer.len() { + return Ok(x); + } + } + Err(InvalidFlatbuffer::SignedOffsetOutOfBounds { + soffset: offset, + position: pos, + error_trace: Default::default(), + }) + } + #[inline] + pub fn visit_table<'ver>( + &'ver mut self, + table_pos: usize, + ) -> Result> { + let vtable_pos = self.deref_soffset(table_pos)?; + let vtable_len = self.get_u16(vtable_pos)? as usize; + self.is_aligned::(vtable_pos.saturating_add(vtable_len))?; // i.e. vtable_len is even. + self.range_in_buffer(vtable_pos, vtable_len)?; + // Check bounds. + self.num_tables += 1; + if self.num_tables > self.opts.max_tables { + return Err(InvalidFlatbuffer::TooManyTables); + } + self.depth += 1; + if self.depth > self.opts.max_depth { + return Err(InvalidFlatbuffer::DepthLimitReached); + } + Ok(TableVerifier { + pos: table_pos, + vtable: vtable_pos, + vtable_len, + verifier: self, + }) + } + + /// Runs the union variant's type's verifier assuming the variant is at the given position, + /// tracing the error. + pub fn verify_union_variant( + &mut self, + variant: impl Into>, + position: usize, + ) -> Result<()> { + let res = T::run_verifier(self, position); + append_trace( + res, + ErrorTraceDetail::UnionVariant { + variant: variant.into(), + position, + }, + ) + } +} + +// Cache table metadata in usize so we don't have to cast types or jump around so much. +// We will visit every field anyway. +pub struct TableVerifier<'ver, 'opts, 'buf> { + // Absolute position of table in buffer + pos: usize, + // Absolute position of vtable in buffer. + vtable: usize, + // Length of vtable. + vtable_len: usize, + // Verifier struct which holds the surrounding state and options. + verifier: &'ver mut Verifier<'opts, 'buf>, +} + +impl<'ver, 'opts, 'buf> TableVerifier<'ver, 'opts, 'buf> { + pub fn deref(&mut self, field: VOffsetT) -> Result> { + let field = field as usize; + if field < self.vtable_len { + let field_offset = self.verifier.get_u16(self.vtable.saturating_add(field))?; + if field_offset > 0 { + // Field is present. + let field_pos = self.pos.saturating_add(field_offset as usize); + return Ok(Some(field_pos)); + } + } + Ok(None) + } + + #[inline] + pub fn verifier(&mut self) -> &mut Verifier<'opts, 'buf> { + self.verifier + } + + #[inline] + pub fn visit_field( + mut self, + field_name: impl Into>, + field: VOffsetT, + required: bool, + ) -> Result { + if let Some(field_pos) = self.deref(field)? { + trace_field( + T::run_verifier(self.verifier, field_pos), + field_name.into(), + field_pos, + )?; + return Ok(self); + } + if required { + InvalidFlatbuffer::new_missing_required(field_name.into()) + } else { + Ok(self) + } + } + #[inline] + /// Union verification is complicated. The schemas passes this function the metadata of the + /// union's key (discriminant) and value fields, and a callback. The function verifies and + /// reads the key, then invokes the callback to perform data-dependent verification. + pub fn visit_union( + mut self, + key_field_name: impl Into>, + key_field_voff: VOffsetT, + val_field_name: impl Into>, + val_field_voff: VOffsetT, + required: bool, + verify_union: UnionVerifier, + ) -> Result + where + Key: Follow<'buf> + Verifiable, + UnionVerifier: + (core::ops::FnOnce(>::Inner, &mut Verifier, usize) -> Result<()>), + // NOTE: >::Inner == Key + { + // TODO(caspern): how to trace vtable errors? + let val_pos = self.deref(val_field_voff)?; + let key_pos = self.deref(key_field_voff)?; + match (key_pos, val_pos) { + (None, None) => { + if required { + InvalidFlatbuffer::new_missing_required(val_field_name.into()) + } else { + Ok(self) + } + } + (Some(k), Some(v)) => { + trace_field( + Key::run_verifier(self.verifier, k), + key_field_name.into(), + k, + )?; + // Safety: + // Run verifier on `k` above + let discriminant = unsafe { Key::follow(self.verifier.buffer, k) }; + trace_field( + verify_union(discriminant, self.verifier, v), + val_field_name.into(), + v, + )?; + Ok(self) + } + _ => InvalidFlatbuffer::new_inconsistent_union(key_field_name.into(), val_field_name.into()), + } + } + pub fn finish(self) -> &'ver mut Verifier<'opts, 'buf> { + self.verifier.depth -= 1; + self.verifier + } +} + +// Needs to be implemented for Tables and maybe structs. +// Unions need some special treatment. +pub trait Verifiable { + /// Runs the verifier for this type, assuming its at position `pos` in the verifier's buffer. + /// Should not need to be called directly. + fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()>; +} + +// Verify the uoffset and then pass verifier to the type being pointed to. +impl Verifiable for ForwardsUOffset { + #[inline] + fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> { + let offset = v.get_uoffset(pos)? as usize; + let next_pos = offset.saturating_add(pos); + T::run_verifier(v, next_pos) + } +} + +/// Checks and returns the range containing the flatbuffers vector. +fn verify_vector_range(v: &mut Verifier, pos: usize) -> Result> { + let len = v.get_uoffset(pos)? as usize; + let start = pos.saturating_add(SIZE_UOFFSET); + v.is_aligned::(start)?; + let size = len.saturating_mul(core::mem::size_of::()); + let end = start.saturating_add(size); + v.range_in_buffer(start, size)?; + Ok(core::ops::Range { start, end }) +} + +pub trait SimpleToVerifyInSlice {} + +impl SimpleToVerifyInSlice for bool {} + +impl SimpleToVerifyInSlice for i8 {} + +impl SimpleToVerifyInSlice for u8 {} + +impl SimpleToVerifyInSlice for i16 {} + +impl SimpleToVerifyInSlice for u16 {} + +impl SimpleToVerifyInSlice for i32 {} + +impl SimpleToVerifyInSlice for u32 {} + +impl SimpleToVerifyInSlice for f32 {} + +impl SimpleToVerifyInSlice for i64 {} + +impl SimpleToVerifyInSlice for u64 {} + +impl SimpleToVerifyInSlice for f64 {} + +impl Verifiable for Vector<'_, T> { + fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> { + verify_vector_range::(v, pos)?; + Ok(()) + } +} + +impl Verifiable for SkipSizePrefix { + #[inline] + fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> { + T::run_verifier(v, pos.saturating_add(crate::SIZE_SIZEPREFIX)) + } +} + +impl Verifiable for Vector<'_, ForwardsUOffset> { + #[inline] + fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> { + let range = verify_vector_range::>(v, pos)?; + let size = core::mem::size_of::>(); + for (i, element_pos) in range.step_by(size).enumerate() { + trace_elem( + >::run_verifier(v, element_pos), + i, + element_pos, + )?; + } + Ok(()) + } +} + +impl<'a> Verifiable for &'a str { + #[inline] + fn run_verifier(v: &mut Verifier, pos: usize) -> Result<()> { + let range = verify_vector_range::(v, pos)?; + let has_null_terminator = v.buffer.get(range.end).map(|&b| b == 0).unwrap_or(false); + let s = core::str::from_utf8(&v.buffer[range.clone()]); + if let Err(error) = s { + return Err(InvalidFlatbuffer::Utf8Error { + error, + range, + error_trace: Default::default(), + }); + } + if !v.opts.ignore_missing_null_terminator && !has_null_terminator { + return Err(InvalidFlatbuffer::MissingNullTerminator { + range, + error_trace: Default::default(), + }); + } + Ok(()) + } +} + +// Verify VectorOfTables, Unions, Arrays, Structs... +macro_rules! impl_verifiable_for { + ($T: ty) => { + impl Verifiable for $T { + #[inline] + fn run_verifier<'opts, 'buf>(v: &mut Verifier<'opts, 'buf>, pos: usize) -> Result<()> { + v.in_buffer::<$T>(pos) + } + } + }; +} +impl_verifiable_for!(bool); +impl_verifiable_for!(u8); +impl_verifiable_for!(i8); +impl_verifiable_for!(u16); +impl_verifiable_for!(i16); +impl_verifiable_for!(u32); +impl_verifiable_for!(i32); +impl_verifiable_for!(f32); +impl_verifiable_for!(u64); +impl_verifiable_for!(i64); +impl_verifiable_for!(f64); diff --git a/third_party/flatbuffers/rust/flatbuffers/src/vtable.rs b/third_party/flatbuffers/rust/flatbuffers/src/vtable.rs new file mode 100644 index 00000000000..1516153d529 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/vtable.rs @@ -0,0 +1,115 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use crate::endian_scalar::read_scalar_at; +use crate::follow::Follow; +use crate::primitives::*; + +/// VTable encapsulates read-only usage of a vtable. It is only to be used +/// by generated code. +#[derive(Debug)] +pub struct VTable<'a> { + buf: &'a [u8], + loc: usize, +} + +impl<'a> PartialEq for VTable<'a> { + fn eq(&self, other: &VTable) -> bool { + self.as_bytes().eq(other.as_bytes()) + } +} + +impl<'a> VTable<'a> { + /// SAFETY + /// `buf` must contain a valid vtable at `loc` + /// + /// This consists of a number of `VOffsetT` + /// - size of vtable in bytes including size element + /// - size of object in bytes including the vtable offset + /// - n fields where n is the number of fields in the table's schema when the code was compiled + pub unsafe fn init(buf: &'a [u8], loc: usize) -> Self { + VTable { buf, loc } + } + + pub fn num_fields(&self) -> usize { + (self.num_bytes() / SIZE_VOFFSET) - 2 + } + + pub fn num_bytes(&self) -> usize { + // Safety: + // Valid VTable at time of construction + unsafe { read_scalar_at::(self.buf, self.loc) as usize } + } + + pub fn object_inline_num_bytes(&self) -> usize { + // Safety: + // Valid VTable at time of construction + let n = unsafe { read_scalar_at::(self.buf, self.loc + SIZE_VOFFSET) }; + n as usize + } + + pub fn get_field(&self, idx: usize) -> VOffsetT { + // TODO(rw): distinguish between None and 0? + if idx > self.num_fields() { + return 0; + } + + // Safety: + // Valid VTable at time of construction + unsafe { + read_scalar_at::( + self.buf, + self.loc + SIZE_VOFFSET + SIZE_VOFFSET + SIZE_VOFFSET * idx, + ) + } + } + + pub fn get(&self, byte_loc: VOffsetT) -> VOffsetT { + // TODO(rw): distinguish between None and 0? + if byte_loc as usize + 2 > self.num_bytes() { + return 0; + } + // Safety: + // byte_loc is within bounds of vtable, which was valid at time of construction + unsafe { read_scalar_at::(self.buf, self.loc + byte_loc as usize) } + } + + pub fn as_bytes(&self) -> &[u8] { + let len = self.num_bytes(); + &self.buf[self.loc..self.loc + len] + } +} + +#[allow(dead_code)] +pub fn field_index_to_field_offset(field_id: VOffsetT) -> VOffsetT { + // Should correspond to what end_table() below builds up. + let fixed_fields = 2; // Vtable size and Object Size. + ((field_id + fixed_fields) * (SIZE_VOFFSET as VOffsetT)) as VOffsetT +} + +#[allow(dead_code)] +pub fn field_offset_to_field_index(field_o: VOffsetT) -> VOffsetT { + debug_assert!(field_o >= 2); + let fixed_fields = 2; // VTable size and Object Size. + (field_o / (SIZE_VOFFSET as VOffsetT)) - fixed_fields +} + +impl<'a> Follow<'a> for VTable<'a> { + type Inner = VTable<'a>; + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + VTable::init(buf, loc) + } +} diff --git a/third_party/flatbuffers/rust/flatbuffers/src/vtable_writer.rs b/third_party/flatbuffers/rust/flatbuffers/src/vtable_writer.rs new file mode 100644 index 00000000000..4bcde9adca3 --- /dev/null +++ b/third_party/flatbuffers/rust/flatbuffers/src/vtable_writer.rs @@ -0,0 +1,92 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use core::ptr::write_bytes; + +use crate::endian_scalar::emplace_scalar; +use crate::primitives::*; + +/// VTableWriter compartmentalizes actions needed to create a vtable. +#[derive(Debug)] +pub struct VTableWriter<'a> { + buf: &'a mut [u8], +} + +impl<'a> VTableWriter<'a> { + #[inline(always)] + pub fn init(buf: &'a mut [u8]) -> Self { + VTableWriter { buf } + } + + /// Writes the vtable length (in bytes) into the vtable. + /// + /// Note that callers already need to have computed this to initialize + /// a VTableWriter. + /// + /// In debug mode, asserts that the length of the underlying data is equal + /// to the provided value. + #[inline(always)] + pub fn write_vtable_byte_length(&mut self, n: VOffsetT) { + let buf = &mut self.buf[..SIZE_VOFFSET]; + // Safety: + // Validated range above + unsafe { + emplace_scalar::(buf, n); + } + debug_assert_eq!(n as usize, self.buf.len()); + } + + /// Writes an object length (in bytes) into the vtable. + #[inline(always)] + pub fn write_object_inline_size(&mut self, n: VOffsetT) { + let buf = &mut self.buf[SIZE_VOFFSET..2 * SIZE_VOFFSET]; + // Safety: + // Validated range above + unsafe { + emplace_scalar::(buf, n); + } + } + + /// Writes an object field offset into the vtable. + /// + /// Note that this expects field offsets (which are like pointers), not + /// field ids (which are like array indices). + #[inline(always)] + pub fn write_field_offset(&mut self, vtable_offset: VOffsetT, object_data_offset: VOffsetT) { + let idx = vtable_offset as usize; + let buf = &mut self.buf[idx..idx + SIZE_VOFFSET]; + // Safety: + // Validated range above + unsafe { + emplace_scalar::(buf, object_data_offset); + } + } + + /// Clears all data in this VTableWriter. Used to cleanly undo a + /// vtable write. + #[inline(always)] + pub fn clear(&mut self) { + // This is the closest thing to memset in Rust right now. + let len = self.buf.len(); + let p = self.buf.as_mut_ptr() as *mut u8; + + // Safety: + // p is byte aligned and of length `len` + unsafe { + write_bytes(p, 0, len); + } + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/.gitignore b/third_party/flatbuffers/rust/flexbuffers/.gitignore new file mode 100644 index 00000000000..693699042b1 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/.gitignore @@ -0,0 +1,3 @@ +/target +**/*.rs.bk +Cargo.lock diff --git a/third_party/flatbuffers/rust/flexbuffers/Cargo.toml b/third_party/flatbuffers/rust/flexbuffers/Cargo.toml new file mode 100644 index 00000000000..a7d03c08ac4 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/Cargo.toml @@ -0,0 +1,28 @@ +[package] +name = "flexbuffers" +version = "25.2.10" +authors = ["Casper Neo ", "FlatBuffers Maintainers"] +edition = "2018" +license = "Apache-2.0" +description = "Official FlexBuffers Rust runtime library." +homepage = "https://google.github.io/flatbuffers/flexbuffers" +repository = "https://github.com/google/flatbuffers" +keywords = ["flatbuffers", "flexbuffers", "serialization", "zero-copy"] +categories = ["encoding", "data-structures", "memory-management"] + +[features] +# Sets serde::Serializer::is_human_readable() to true. +# The default was changed from true to false in version "0.2.1". +# You basically never need this to be true unless writing data for old binaries. +serialize_human_readable = [] +# Sets serde::Deserializer::is_human_readable() to true. +# The default was changed from true to false in version "0.2.1". +# You basically never need this to be true unless reading data from old binaries. +deserialize_human_readable = [] + +[dependencies] +serde = "1.0.119" +serde_derive = "1.0.119" +byteorder = "1.4.2" +num_enum = "0.5.1" +bitflags = "1.2.1" diff --git a/third_party/flatbuffers/rust/flexbuffers/README.md b/third_party/flatbuffers/rust/flexbuffers/README.md new file mode 100644 index 00000000000..0b3331b6e6b --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/README.md @@ -0,0 +1,22 @@ +# Flexbuffers + +[Flexbuffers](https://google.github.io/flatbuffers/flexbuffers.html) is a +schema-less binary format developed at Google. FlexBuffers can be accessed +without parsing, copying, or allocation. This is a huge win for efficiency, +memory friendly-ness, and allows for unique use cases such as mmap-ing large +amounts of free-form data. + +FlexBuffers' design and implementation allows for a very compact encoding, +with automatic sizing of containers to their smallest possible representation +(8/16/32/64 bits). Many values and offsets can be encoded in just 8 bits. + +FlexBuffers supports [Serde](https://serde.rs/) for automatically serializing +Rust data structures into its binary format. + +## See Examples for Usage: +* [Example](https://github.com/google/flatbuffers/blob/master/samples/sample_flexbuffers.rs) +* [Serde Example](https://github.com/google/flatbuffers/blob/master/samples/sample_flexbuffers_serde.rs) +* [Documentation](https://docs.rs/flexbuffers) + +Flexbuffers is the schema-less cousin of +[Flatbuffers](https://google.github.io/flatbuffers/). diff --git a/third_party/flatbuffers/rust/flexbuffers/src/bitwidth.rs b/third_party/flatbuffers/rust/flexbuffers/src/bitwidth.rs new file mode 100644 index 00000000000..8e0bfedbe83 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/bitwidth.rs @@ -0,0 +1,113 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::bitwidth::BitWidth::*; +use std::slice::Iter; + +/// Represents the size of Flexbuffers data. +/// +/// Flexbuffers automatically compresses numbers to the smallest possible width +/// (`250u64` is stored as `250u8`). +#[derive( + Debug, + Clone, + Copy, + PartialEq, + Eq, + PartialOrd, + Serialize, + Deserialize, + Ord, + num_enum::TryFromPrimitive, +)] +#[repr(u8)] +pub enum BitWidth { + W8 = 0, + W16 = 1, + W32 = 2, + W64 = 3, +} +impl BitWidth { + pub(crate) fn iter() -> Iter<'static, Self> { + [W8, W16, W32, W64].iter() + } + pub fn n_bytes(self) -> usize { + 1 << self as usize + } + pub fn from_nbytes(n: impl std::convert::Into) -> Option { + match n.into() { + 1 => Some(W8), + 2 => Some(W16), + 4 => Some(W32), + 8 => Some(W64), + _ => None, + } + } +} + +impl Default for BitWidth { + fn default() -> Self { + W8 + } +} + +// TODO(cneo): Overloading with `from` is probably not the most readable idea in hindsight. +macro_rules! impl_bitwidth_from { + ($from: ident, $w64: ident, $w32: ident, $w16: ident, $w8: ident) => { + impl From<$from> for BitWidth { + fn from(x: $from) -> BitWidth { + let x = x as $w64; + if x >= $w8::min_value() as $w64 && x <= $w8::max_value() as $w64 { + return W8; + } + if x >= $w16::min_value() as $w64 && x <= $w16::max_value() as $w64 { + return W16; + } + if x >= $w32::min_value() as $w64 && x <= $w32::max_value() as $w64 { + return W32; + } + W64 + } + } + }; +} +impl_bitwidth_from!(u64, u64, u32, u16, u8); +impl_bitwidth_from!(usize, u64, u32, u16, u8); +impl_bitwidth_from!(i64, i64, i32, i16, i8); + +#[allow(clippy::float_cmp)] +impl From for BitWidth { + fn from(x: f64) -> BitWidth { + if x != x as f32 as f64 { + W64 + } else { + W32 + } + } +} +impl From for BitWidth { + fn from(_: f32) -> BitWidth { + W32 + } +} + +/// Zero pad `v` until `T` will be byte aligned when pushed. +pub fn align(buffer: &mut Vec, width: BitWidth) { + let bytes = 1 << width as u8; + let alignment = (bytes - buffer.len() % bytes) % bytes; + // Profiling reveals the loop is faster than Vec::resize. + for _ in 0..alignment as usize { + buffer.push(0); + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/buffer.rs b/third_party/flatbuffers/rust/flexbuffers/src/buffer.rs new file mode 100644 index 00000000000..ad522deccf2 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/buffer.rs @@ -0,0 +1,80 @@ +use std::ops::{Deref, Range}; + +/// The underlying buffer that is used by a flexbuffer Reader. +/// +/// This allows for custom buffer implementations as long as they can be viewed as a &[u8]. +pub trait Buffer: Deref + Sized { + // The `BufferString` allows for a buffer to return a custom string which will have the + // lifetime of the underlying buffer. A simple `std::str::from_utf8` wouldn't work since that + // returns a &str, which is then owned by the callee (cannot be returned from a function). + // + // Example: During deserialization a `BufferString` is returned, allowing the deserializer + // to "borrow" the given str - b/c there is a "lifetime" guarantee, so to speak, from the + // underlying buffer. + /// A BufferString which will live at least as long as the Buffer itself. + /// + /// Deref's to UTF-8 `str`, and only generated from the `buffer_str` function Result. + type BufferString: Deref + Sized + serde::ser::Serialize; + + /// This method returns an instance of type Self. This allows for lifetimes to be tracked + /// in cases of deserialization. + /// + /// It also lets custom buffers manage reference counts. + /// + /// Returns None if: + /// - range start is greater than end + /// - range end is out of bounds + /// + /// This operation should be fast -> O(1), ideally with no heap allocations. + fn slice(&self, range: Range) -> Option; + + /// Creates a shallow copy of the given buffer, similar to `slice`. + /// + /// This operation should be fast -> O(1), ideally with no heap allocations. + #[inline] + fn shallow_copy(&self) -> Self { + self.slice(0..self.len()).unwrap() + } + + /// Creates an empty instance of a `Buffer`. This is different than `Default` b/c it + /// guarantees that the buffer instance will have length zero. + /// + /// Most impls shold be able to implement this via `Default`. + fn empty() -> Self; + + /// Based off of the `empty` function, allows override for optimization purposes. + #[inline] + fn empty_str() -> Self::BufferString { + Self::empty().buffer_str().unwrap() + } + + /// Attempts to convert the given buffer to a custom string type. + /// + /// This should fail if the type does not have valid UTF-8 bytes, and must be zero copy. + fn buffer_str(&self) -> Result; +} + +impl<'de> Buffer for &'de [u8] { + type BufferString = &'de str; + + #[inline] + fn slice(&self, range: Range) -> Option { + self.get(range) + } + + #[inline] + fn empty() -> Self { + &[] + } + + /// Based off of the `empty` function, allows override for optimization purposes. + #[inline] + fn empty_str() -> Self::BufferString { + "" + } + + #[inline] + fn buffer_str(&self) -> Result { + std::str::from_utf8(self) + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/builder/map.rs b/third_party/flatbuffers/rust/flexbuffers/src/builder/map.rs new file mode 100644 index 00000000000..73194c7bf96 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/builder/map.rs @@ -0,0 +1,117 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::{Builder, Pushable, Value, VectorBuilder}; + +/// Builds a Flexbuffer map, returned by a [Builder](struct.Builder.html). +/// +/// ## Side effect when dropped: +/// When this is dropped, or `end_map` is called, the map is +/// commited to the buffer. If this map is the root of the flexbuffer, then the +/// root is written and the flexbuffer is complete. +/// ## Panics: +/// - Duplicate keys will result in a panic in both debug and release mode. +/// - Keys with internal nulls results in a panic in debug mode and result in silent truncaction +/// in release mode. +pub struct MapBuilder<'a> { + pub(super) builder: &'a mut Builder, + // If the root is this map then start == None. Otherwise start is the + // number of values in the 'values stack' before adding this map. + pub(super) start: Option, +} +impl<'a> MapBuilder<'a> { + /// Push `p` onto this map with key `key`. + /// This will panic (in debug mode) if `key` contains internal nulls. + #[inline] + pub fn push(&mut self, key: &str, p: P) { + self.builder.push_key(key); + self.builder.push(p); + } + /// Starts a nested vector that will be pushed onto this map + /// with key `key` when it is dropped. + /// + /// This will panic (in debug mode) if `key` contains internal nulls. + #[inline] + pub fn start_vector(&mut self, key: &str) -> VectorBuilder { + // Push the key that refers to this nested vector. + self.builder.push_key(key); + // Nested vector. + let start = Some(self.builder.values.len()); + VectorBuilder { + builder: self.builder, + start, + } + } + /// Starts a nested map which that will be pushed onto this map + /// with key `key` when it is dropped. + /// + /// This will panic (in debug mode) if `key` contains internal nulls. + #[inline] + pub fn start_map(&mut self, key: &str) -> MapBuilder { + // Push the key that refers to this nested vector. + self.builder.push_key(key); + // Nested map. + let start = Some(self.builder.values.len()); + MapBuilder { + builder: self.builder, + start, + } + } + /// `end_map` sorts the map by key and writes it to the buffer. This happens anyway + /// when the map builder is dropped. + #[inline] + pub fn end_map(self) {} +} +impl<'a> Drop for MapBuilder<'a> { + #[inline] + fn drop(&mut self) { + self.builder.end_map_or_vector(true, self.start); + } +} + +// Read known keys / strings as iterators over bytes -- skipping utf8 validation and strlen. +pub(super) fn get_key(buffer: &[u8], address: usize) -> impl Iterator { + buffer[address..].iter().take_while(|&&b| b != b'\0') +} + +// `values` is assumed to be of the format [key1, value1, ..., keyN, valueN]. +// The keys refer to cstrings in `buffer`. When this function returns, +// `values` is sorted in place by key. +pub(super) fn sort_map_by_keys(values: &mut [Value], buffer: &[u8]) { + debug_assert_eq!(values.len() % 2, 0); + debug_assert!(values.iter().step_by(2).all(Value::is_key)); + let raw_pairs = values.as_mut_ptr() as *mut [Value; 2]; + let pairs_len = values.len() / 2; + // Unsafe code needed to treat the slice as key-value pairs when sorting in place. This is + // preferred over custom sorting or adding another dependency. By construction, this part + // of the values stack must be alternating (key, value) pairs. The public API must not be + // able to trigger the above debug_assets that protect this unsafe usage. + let pairs: &mut [[Value; 2]] = unsafe { std::slice::from_raw_parts_mut(raw_pairs, pairs_len) }; + #[rustfmt::skip] + pairs.sort_unstable_by(|[key1, _], [key2, _]| { + if let Value::Key(a1) = *key1 { + if let Value::Key(a2) = *key2 { + let s1 = get_key(buffer, a1); + let s2 = get_key(buffer, a2); + let ord = s1.cmp(s2); + if ord == std::cmp::Ordering::Equal { + let dup: String = get_key(buffer, a1).map(|&b| b as char).collect(); + panic!("Duplicated key in map {:?}", dup); + } + return ord; + } + } + unreachable!(); + }); +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/builder/mod.rs b/third_party/flatbuffers/rust/flexbuffers/src/builder/mod.rs new file mode 100644 index 00000000000..97838c21c4c --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/builder/mod.rs @@ -0,0 +1,401 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::bitwidth::{align, BitWidth}; +mod value; +use crate::FlexBufferType; +use std::cmp::max; +use value::{find_vector_type, store_value, Value}; +mod map; +mod push; +mod ser; +mod vector; +use map::sort_map_by_keys; +pub use map::MapBuilder; +pub use push::Pushable; +pub use ser::{Error, FlexbufferSerializer}; +pub use vector::VectorBuilder; + +macro_rules! push_slice { + ($push_name: ident, $scalar: ty, $Val: ident, $new_vec: ident) => { + fn $push_name(&mut self, xs: S) + where + T: Into<$scalar> + Copy, + S: AsRef<[T]>, + { + let mut value = Value::$new_vec(xs.as_ref().len()); + let mut width = xs + .as_ref() + .iter() + .map(|x| BitWidth::from((*x).into())) + .max() + .unwrap_or_default(); + if !value.is_fixed_length_vector() { + let length = Value::UInt(xs.as_ref().len() as u64); + width = std::cmp::max(width, length.width_or_child_width()); + align(&mut self.buffer, width); + store_value(&mut self.buffer, length, width); + } else { + align(&mut self.buffer, width); + } + let address = self.buffer.len(); + for &x in xs.as_ref().iter() { + store_value(&mut self.buffer, Value::$Val(x.into()), width); + } + value.set_address_or_panic(address); + value.set_child_width_or_panic(width); + self.values.push(value); + } + }; +} +macro_rules! push_indirect { + ($push_name: ident, $scalar: ty, $Direct: ident, $Indirect: ident) => { + fn $push_name>(&mut self, x: T) { + let x = Value::$Direct(x.into()); + let child_width = x.width_or_child_width(); + let address = self.buffer.len(); + store_value(&mut self.buffer, x, child_width); + self.values.push(Value::Reference { + address, + child_width, + fxb_type: FlexBufferType::$Indirect, + }); + } + }; +} + +bitflags! { + /// Options for sharing data within a flexbuffer. + /// + /// These increase serialization time but decrease the size of the resulting buffer. By + /// default, `SHARE_KEYS`. You may wish to turn on `SHARE_STRINGS` if you know your data has + /// many duplicate strings or `SHARE_KEY_VECTORS` if your data has many maps with identical + /// keys. + /// + /// ## Not Yet Implemented + /// - `SHARE_STRINGS` + /// - `SHARE_KEY_VECTORS` + pub struct BuilderOptions: u8 { + const SHARE_NONE = 0; + const SHARE_KEYS = 1; + const SHARE_STRINGS = 2; + const SHARE_KEYS_AND_STRINGS = 3; + const SHARE_KEY_VECTORS = 4; + const SHARE_ALL = 7; + } +} +impl Default for BuilderOptions { + fn default() -> Self { + Self::SHARE_KEYS + } +} + +#[derive(Debug, Clone, Copy)] +// Address of a Key inside of the buffer. +struct CachedKey(usize); + +/// **Use this struct to build a Flexbuffer.** +/// +/// Flexbuffers may only have a single root value, which may be constructed +/// with one of the following functions. +/// * `build_singleton` will push 1 value to the buffer and serialize it as the root. +/// * `start_vector` returns a `VectorBuilder`, into which many (potentially +/// heterogenous) values can be pushed. The vector itself is the root and is serialized +/// when the `VectorBuilder` is dropped (or `end` is called). +/// * `start_map` returns a `MapBuilder`, which is similar to a `VectorBuilder` except +/// every value must be pushed with an associated key. The map is serialized when the +/// `MapBuilder` is dropped (or `end` is called). +/// +/// These functions reset and overwrite the Builder which means, while there are no +/// active `MapBuilder` or `VectorBuilder`, the internal buffer is empty or contains a +/// finished Flexbuffer. The internal buffer is accessed with `view`. +#[derive(Debug, Clone)] +pub struct Builder { + buffer: Vec, + values: Vec, + key_pool: Option>, +} +impl Default for Builder { + fn default() -> Self { + let opts = Default::default(); + Builder::new(opts) + } +} + +impl<'a> Builder { + pub fn new(opts: BuilderOptions) -> Self { + let key_pool = if opts.contains(BuilderOptions::SHARE_KEYS) { + Some(vec![]) + } else { + None + }; + Builder { + key_pool, + values: Vec::new(), + buffer: Vec::new(), + } + } + /// Shows the internal flexbuffer. It will either be empty or populated with the most + /// recently built flexbuffer. + pub fn view(&self) -> &[u8] { + &self.buffer + } + /// Returns the internal buffer, replacing it with a new vector. The returned buffer will + /// either be empty or populated with the most recently built flexbuffer. + pub fn take_buffer(&mut self) -> Vec { + let mut b = Vec::new(); + std::mem::swap(&mut self.buffer, &mut b); + b + } + /// Resets the internal state. Automatically called before building a new flexbuffer. + pub fn reset(&mut self) { + self.buffer.clear(); + self.values.clear(); + if let Some(pool) = self.key_pool.as_mut() { + pool.clear(); + } + } + fn push_key(&mut self, key: &str) { + debug_assert!( + key.bytes().all(|b| b != b'\0'), + "Keys must not have internal nulls." + ); + // Search key pool if there is one. + let found = self.key_pool.as_ref().map(|pool| { + pool.binary_search_by(|&CachedKey(addr)| { + let old_key = map::get_key(&self.buffer, addr); + old_key.cloned().cmp(key.bytes()) + }) + }); + let address = if let Some(Ok(idx)) = found { + // Found key in key pool. + self.key_pool.as_ref().unwrap()[idx].0 + } else { + // Key not in pool (or no pool). + let address = self.buffer.len(); + self.buffer.extend_from_slice(key.as_bytes()); + self.buffer.push(b'\0'); + address + }; + if let Some(Err(idx)) = found { + // Insert into key pool. + let pool = self.key_pool.as_mut().unwrap(); + pool.insert(idx, CachedKey(address)); + } + self.values.push(Value::Key(address)); + } + fn push_uint>(&mut self, x: T) { + self.values.push(Value::UInt(x.into())); + } + fn push_int>(&mut self, x: T) { + self.values.push(Value::Int(x.into())); + } + fn push_float>(&mut self, x: T) { + self.values.push(Value::Float(x.into())); + } + fn push_null(&mut self) { + self.values.push(Value::Null); + } + fn push_bool(&mut self, x: bool) { + self.values.push(Value::Bool(x)); + } + fn store_blob(&mut self, xs: &[u8]) -> Value { + let length = Value::UInt(xs.len() as u64); + let width = length.width_or_child_width(); + align(&mut self.buffer, width); + store_value(&mut self.buffer, length, width); + let address = self.buffer.len(); + self.buffer.extend_from_slice(xs); + Value::Reference { + fxb_type: FlexBufferType::Blob, + address, + child_width: width, + } + } + fn push_str(&mut self, x: &str) { + let mut string = self.store_blob(x.as_bytes()); + self.buffer.push(b'\0'); + string.set_fxb_type_or_panic(FlexBufferType::String); + self.values.push(string); + } + fn push_blob(&mut self, x: &[u8]) { + let blob = self.store_blob(x); + self.values.push(blob); + } + fn push_bools(&mut self, xs: &[bool]) { + let length = Value::UInt(xs.len() as u64); + let width = length.width_or_child_width(); + align(&mut self.buffer, width); + store_value(&mut self.buffer, length, width); + let address = self.buffer.len(); + for &b in xs.iter() { + self.buffer.push(b as u8); + self.buffer.resize(self.buffer.len() + width as usize, 0); + } + self.values.push(Value::Reference { + fxb_type: FlexBufferType::VectorBool, + address, + child_width: width, + }); + } + + push_slice!(push_uints, u64, UInt, new_uint_vector); + push_slice!(push_ints, i64, Int, new_int_vector); + push_slice!(push_floats, f64, Float, new_float_vector); + push_indirect!(push_indirect_int, i64, Int, IndirectInt); + push_indirect!(push_indirect_uint, u64, UInt, IndirectUInt); + push_indirect!(push_indirect_float, f64, Float, IndirectFloat); + + /// Resets the builder and starts a new flexbuffer with a vector at the root. + /// The exact Flexbuffer vector type is dynamically inferred. + pub fn start_vector(&'a mut self) -> VectorBuilder<'a> { + self.reset(); + VectorBuilder { + builder: self, + start: None, + } + } + /// Resets the builder and builds a new flexbuffer with a map at the root. + pub fn start_map(&'a mut self) -> MapBuilder<'a> { + self.reset(); + MapBuilder { + builder: self, + start: None, + } + } + /// Resets the builder and builds a new flexbuffer with the pushed value at the root. + pub fn build_singleton(&mut self, p: P) { + self.reset(); + p.push_to_builder(self); + let root = self.values.pop().unwrap(); + store_root(&mut self.buffer, root); + } + fn push(&mut self, p: P) { + p.push_to_builder(self); + } + /// Stores the values past `previous_end` as a map or vector depending on `is_map`. + /// If `previous_end` is None then this was a root map / vector and the last value + /// is stored as the root. + fn end_map_or_vector(&mut self, is_map: bool, previous_end: Option) { + let split = previous_end.unwrap_or(0); + let value = if is_map { + let key_vals = &mut self.values[split..]; + sort_map_by_keys(key_vals, &self.buffer); + let key_vector = store_vector(&mut self.buffer, key_vals, StoreOption::MapKeys); + store_vector(&mut self.buffer, key_vals, StoreOption::Map(key_vector)) + } else { + store_vector(&mut self.buffer, &self.values[split..], StoreOption::Vector) + }; + self.values.truncate(split); + if previous_end.is_some() { + self.values.push(value); + } else { + store_root(&mut self.buffer, value); + } + } +} + +/// Builds a Flexbuffer with the single pushed value as the root. +pub fn singleton(p: P) -> Vec { + let mut b = Builder::default(); + b.build_singleton(p); + let Builder { buffer, .. } = b; + buffer +} + +/// Stores the root value, root type and root width. +/// This should be called to finish the Flexbuffer. +fn store_root(buffer: &mut Vec, root: Value) { + let root_width = root.width_in_vector(buffer.len(), 0); + align(buffer, root_width); + store_value(buffer, root, root_width); + buffer.push(root.packed_type(root_width)); + buffer.push(root_width.n_bytes() as u8); +} + +pub enum StoreOption { + Vector, + Map(Value), + MapKeys, +} +/// Writes a Flexbuffer Vector or Map. +/// StoreOption::Map(Keys) must be a Value::Key or this will panic. +// #[inline(always)] +pub fn store_vector(buffer: &mut Vec, values: &[Value], opt: StoreOption) -> Value { + let (skip, stride) = match opt { + StoreOption::Vector => (0, 1), + StoreOption::MapKeys => (0, 2), + StoreOption::Map(_) => (1, 2), + }; + let iter_values = || values.iter().skip(skip).step_by(stride); + + // Figure out vector type and how long is the prefix. + let mut result = if let StoreOption::Map(_) = opt { + Value::new_map() + } else { + find_vector_type(iter_values()) + }; + let length_slot = if !result.is_fixed_length_vector() { + let length = iter_values().count(); + Some(Value::UInt(length as u64)) + } else { + None + }; + // Measure required width and align to it. + let mut width = BitWidth::W8; + if let StoreOption::Map(keys) = opt { + width = max(width, keys.width_in_vector(buffer.len(), 0)) + } + if let Some(l) = length_slot { + width = max(width, l.width_or_child_width()); + } + let prefix_length = result.prefix_length(); + for (i, &val) in iter_values().enumerate() { + width = max(width, val.width_in_vector(buffer.len(), i + prefix_length)); + } + align(buffer, width); + #[allow(deprecated)] + { + debug_assert_ne!( + result.fxb_type(), + FlexBufferType::VectorString, + "VectorString is deprecated and cannot be written.\ + (https://github.com/google/flatbuffers/issues/5627)" + ); + } + // Write Prefix. + if let StoreOption::Map(keys) = opt { + let key_width = Value::UInt(keys.width_or_child_width().n_bytes() as u64); + store_value(buffer, keys, width); + store_value(buffer, key_width, width); + } + if let Some(len) = length_slot { + store_value(buffer, len, width); + } + // Write data. + let address = buffer.len(); + for &v in iter_values() { + store_value(buffer, v, width); + } + // Write types + if result.is_typed_vector_or_map() { + for v in iter_values() { + buffer.push(v.packed_type(width)); + } + } + // Return Value representing this Vector. + result.set_address_or_panic(address); + result.set_child_width_or_panic(width); + result +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/builder/push.rs b/third_party/flatbuffers/rust/flexbuffers/src/builder/push.rs new file mode 100644 index 00000000000..5cb584d6021 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/builder/push.rs @@ -0,0 +1,168 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::builder::Builder; +use crate::private::Sealed; +use crate::{Blob, Buffer, IndirectFloat, IndirectInt, IndirectUInt}; + +impl Sealed for Blob {} +impl Sealed for () {} + +// TODO: String interning +// TODO: Pushable for Map types? + +/// Types that implement the Pushable trait can be written into a Flexbuffer. +/// +/// All Rust's standard numbers, `u8, u16, u32, u64, i8, i16, i32, i64, f32, f64`, +/// can all be pushed. They are `FlexBufferType::{UInt, Int, Float}`. +/// Flexbuffers chooses the smallest width that can represent the given number. +/// Strings can pe pushed, they become `FlexBufferType::String` and are stored +/// with both a length and null terminator. +/// +/// * For convenience and speed push typed vectors using rust arrays and slices. +/// Doing so will immediately serialize the data, skipping the `Builder`'s +/// internal cache. +/// +/// * Pushable cannot not be implemented by any downstream crates. +pub trait Pushable: Sealed + Sized { + fn push_to_builder(self, _: &mut Builder) {} +} + +impl Pushable for () { + fn push_to_builder(self, builder: &mut Builder) { + builder.push_null(); + } +} + +impl Pushable for Blob { + fn push_to_builder(self, builder: &mut Builder) { + builder.push_blob(&self.0); + } +} + +macro_rules! forward_to_builder { + ($T: ty, $method: ident) => { + impl Sealed for $T {} + impl Pushable for $T { + fn push_to_builder(self, builder: &mut Builder) { + builder.$method(self); + } + } + }; + ($T: ty, $method: ident, $asT: ty) => { + impl Sealed for $T {} + impl Pushable for $T { + fn push_to_builder(self, builder: &mut Builder) { + builder.$method(self as $asT); + } + } + }; +} +forward_to_builder!(&str, push_str); +forward_to_builder!(bool, push_bool); +forward_to_builder!(u8, push_uint); +forward_to_builder!(u16, push_uint); +forward_to_builder!(u32, push_uint); +forward_to_builder!(u64, push_uint); +forward_to_builder!(i8, push_int); +forward_to_builder!(i16, push_int); +forward_to_builder!(i32, push_int); +forward_to_builder!(i64, push_int); +forward_to_builder!(f32, push_float); +forward_to_builder!(f64, push_float); +forward_to_builder!(&[u8], push_uints); +forward_to_builder!(&[u16], push_uints); +forward_to_builder!(&[u32], push_uints); +forward_to_builder!(&[u64], push_uints); +forward_to_builder!(&[i8], push_ints); +forward_to_builder!(&[i16], push_ints); +forward_to_builder!(&[i32], push_ints); +forward_to_builder!(&[i64], push_ints); +forward_to_builder!(&[f32], push_floats); +forward_to_builder!(&[f64], push_floats); +forward_to_builder!(&[bool], push_bools); +forward_to_builder!(&Vec, push_uints); +forward_to_builder!(&Vec, push_uints); +forward_to_builder!(&Vec, push_uints); +forward_to_builder!(&Vec, push_uints); +forward_to_builder!(&Vec, push_ints); +forward_to_builder!(&Vec, push_ints); +forward_to_builder!(&Vec, push_ints); +forward_to_builder!(&Vec, push_ints); +forward_to_builder!(&Vec, push_floats); +forward_to_builder!(&Vec, push_floats); +forward_to_builder!(&Vec, push_bools); + +macro_rules! impl_indirects { + ($Indirect: ident, $method: ident) => { + impl Sealed for $Indirect {} + impl Pushable for $Indirect { + fn push_to_builder(self, builder: &mut Builder) { + builder.$method(self.0); + } + } + }; +} +impl_indirects!(IndirectInt, push_indirect_int); +impl_indirects!(IndirectUInt, push_indirect_uint); +impl_indirects!(IndirectFloat, push_indirect_float); + +macro_rules! impl_arrays { + ($num: expr) => { + forward_to_builder!(&[u8; $num], push_uints, &[u8]); + forward_to_builder!(&[u16; $num], push_uints, &[u16]); + forward_to_builder!(&[u32; $num], push_uints, &[u32]); + forward_to_builder!(&[u64; $num], push_uints, &[u64]); + forward_to_builder!(&[i8; $num], push_ints, &[i8]); + forward_to_builder!(&[i16; $num], push_ints, &[i16]); + forward_to_builder!(&[i32; $num], push_ints, &[i32]); + forward_to_builder!(&[i64; $num], push_ints, &[i64]); + forward_to_builder!(&[f32; $num], push_floats, &[f32]); + forward_to_builder!(&[f64; $num], push_floats, &[f64]); + forward_to_builder!(&[bool; $num], push_bools, &[bool]); + }; +} +impl_arrays!(0); +impl_arrays!(1); +impl_arrays!(2); +impl_arrays!(3); +impl_arrays!(4); +impl_arrays!(5); +impl_arrays!(6); +// impl_arrays!(7); +// impl_arrays!(8); +// impl_arrays!(9); +// impl_arrays!(10); +// impl_arrays!(11); +// impl_arrays!(12); +// impl_arrays!(13); +// impl_arrays!(14); +// impl_arrays!(15); +// impl_arrays!(16); +// impl_arrays!(17); +// impl_arrays!(18); +// impl_arrays!(19); +// impl_arrays!(20); +// impl_arrays!(21); +// impl_arrays!(22); +// impl_arrays!(23); +// impl_arrays!(24); +// impl_arrays!(25); +// impl_arrays!(26); +// impl_arrays!(27); +// impl_arrays!(28); +// impl_arrays!(29); +// impl_arrays!(30); +// impl_arrays!(31); +// impl_arrays!(32); diff --git a/third_party/flatbuffers/rust/flexbuffers/src/builder/ser.rs b/third_party/flatbuffers/rust/flexbuffers/src/builder/ser.rs new file mode 100644 index 00000000000..4d8fe53e382 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/builder/ser.rs @@ -0,0 +1,537 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::Builder; +use serde::ser; +use serde::ser::*; +use std::fmt::Display; + +// This struct internally tracks the nested vectors representing +// nested structs and such. +// TODO: Add an option field names in a map. +/// Flexbuffer Serializer. This should be used to serialize structs. +#[derive(Debug, Default)] +pub struct FlexbufferSerializer { + builder: Builder, + nesting: Vec>, +} +impl FlexbufferSerializer { + pub fn new() -> Self { + Self::default() + } + pub fn view(&self) -> &[u8] { + self.builder.view() + } + pub fn take_buffer(&mut self) -> Vec { + self.builder.take_buffer() + } + pub fn reset(&mut self) { + self.builder.reset(); + self.nesting.clear(); + } + fn finish_if_not_nested(&mut self) -> Result<(), Error> { + if self.nesting.is_empty() { + assert_eq!(self.builder.values.len(), 1); + let root = self.builder.values.pop().unwrap(); + super::store_root(&mut self.builder.buffer, root); + } + Ok(()) + } + fn start_vector(&mut self) { + let previous_end = if self.nesting.is_empty() { + None + } else { + Some(self.builder.values.len()) + }; + self.nesting.push(previous_end); + } + fn start_map(&mut self) { + let previous_end = if self.nesting.is_empty() { + None + } else { + Some(self.builder.values.len()) + }; + self.nesting.push(previous_end); + } + fn end_vector(&mut self) -> Result<(), Error> { + let previous_end = self.nesting.pop().unwrap(); + self.builder.end_map_or_vector(false, previous_end); + Ok(()) + } + fn end_map(&mut self) -> Result<(), Error> { + let previous_end = self.nesting.pop().unwrap(); + self.builder.end_map_or_vector(true, previous_end); + Ok(()) + } +} + +#[derive(Debug)] +/// Errors that may happen with Serde. +pub enum Error { + /// Only `str` and `String` can be serialized as keys in serde maps. + KeyMustBeString, + Serde(String), +} + +impl std::fmt::Display for Error { + fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { + write!(f, "{:?}", self) + } +} +impl std::error::Error for Error {} +impl ser::Error for Error { + fn custom(msg: T) -> Self + where + T: Display, + { + Self::Serde(format!("{}", msg)) + } +} +impl ser::SerializeSeq for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_vector() + } +} +// This is unlike a flexbuffers map which requires CString like keys. +// Its implemented as alternating keys and values (hopefully). +impl ser::SerializeMap for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_key(&mut self, key: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + key.serialize(MapKeySerializer(self)) + } + fn serialize_value(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_map() + } +} +impl ser::SerializeTuple for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_element(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_vector() + } +} +impl ser::SerializeTupleStruct for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_vector() + } +} +impl ser::SerializeStruct for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_field( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: Serialize, + { + self.builder.push_key(key); + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_map() + } +} +impl ser::SerializeTupleVariant for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_field(&mut self, value: &T) -> Result<(), Self::Error> + where + T: Serialize, + { + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_vector()?; + self.end_map() + } +} +impl ser::SerializeStructVariant for &mut FlexbufferSerializer { + type Ok = (); + type Error = Error; + fn serialize_field( + &mut self, + key: &'static str, + value: &T, + ) -> Result<(), Self::Error> + where + T: Serialize, + { + self.builder.push_key(key); + value.serialize(&mut **self) + } + fn end(self) -> Result { + self.end_map()?; + self.end_map() + } + // TODO: skip field? +} + +impl<'a> ser::Serializer for &'a mut FlexbufferSerializer { + type SerializeSeq = &'a mut FlexbufferSerializer; + type SerializeTuple = &'a mut FlexbufferSerializer; + type SerializeTupleStruct = &'a mut FlexbufferSerializer; + type SerializeTupleVariant = &'a mut FlexbufferSerializer; + type SerializeMap = &'a mut FlexbufferSerializer; + type SerializeStruct = &'a mut FlexbufferSerializer; + type SerializeStructVariant = &'a mut FlexbufferSerializer; + type Ok = (); + type Error = Error; + fn is_human_readable(&self) -> bool { + cfg!(serialize_human_readable) + } + fn serialize_bool(self, v: bool) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_i8(self, v: i8) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_i16(self, v: i16) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_i32(self, v: i32) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_i64(self, v: i64) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_u8(self, v: u8) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_u16(self, v: u16) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_u32(self, v: u32) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_u64(self, v: u64) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_f32(self, v: f32) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_f64(self, v: f64) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_char(self, v: char) -> Result { + self.builder.push(v as u8); + self.finish_if_not_nested() + } + fn serialize_str(self, v: &str) -> Result { + self.builder.push(v); + self.finish_if_not_nested() + } + fn serialize_bytes(self, v: &[u8]) -> Result { + self.builder.push(crate::Blob(v)); + self.finish_if_not_nested() + } + fn serialize_none(self) -> Result { + self.builder.push(()); + self.finish_if_not_nested() + } + fn serialize_some(self, t: &T) -> Result + where + T: Serialize, + { + t.serialize(self) + } + fn serialize_unit(self) -> Result { + self.builder.push(()); + self.finish_if_not_nested() + } + fn serialize_unit_struct(self, _name: &'static str) -> Result { + self.builder.push(()); + self.finish_if_not_nested() + } + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result { + self.builder.push(variant); + self.finish_if_not_nested() + } + fn serialize_newtype_struct( + self, + _name: &'static str, + value: &T, + ) -> Result + where + T: Serialize, + { + value.serialize(self) + } + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + value: &T, + ) -> Result + where + T: Serialize, + { + self.start_map(); + self.builder.push_key(variant); + value.serialize(&mut *self)?; + self.end_map() + } + fn serialize_seq(self, _len: Option) -> Result { + self.start_vector(); + Ok(self) + } + fn serialize_tuple(self, _len: usize) -> Result { + self.start_vector(); + Ok(self) + } + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + self.start_map(); + Ok(self) + } + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + _len: usize, + ) -> Result { + self.start_map(); + self.builder.push_key(variant); + self.start_vector(); + Ok(self) + } + fn serialize_map(self, _len: Option) -> Result { + self.start_map(); + Ok(self) + } + fn serialize_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + self.start_map(); + Ok(self) + } + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + _len: usize, + ) -> Result { + self.start_map(); + self.builder.push_key(variant); + self.start_map(); + Ok(self) + } +} + +fn key_must_be_a_string() -> Result { + Err(Error::KeyMustBeString) +} +struct MapKeySerializer<'a>(&'a mut FlexbufferSerializer); +impl<'a> Serializer for MapKeySerializer<'a> { + type Ok = (); + type Error = Error; + #[inline] + fn serialize_str(self, value: &str) -> Result<(), Error> { + self.0.builder.push_key(value); + Ok(()) + } + #[inline] + fn serialize_unit_variant( + self, + _name: &'static str, + _variant_index: u32, + variant: &'static str, + ) -> Result<(), Error> { + self.0.builder.push_key(variant); + Ok(()) + } + #[inline] + fn serialize_newtype_struct( + self, + _name: &'static str, + value: &T, + ) -> Result<(), Error> + where + T: Serialize, + { + value.serialize(self) + } + type SerializeSeq = Impossible<(), Error>; + type SerializeTuple = Impossible<(), Error>; + type SerializeTupleStruct = Impossible<(), Error>; + type SerializeTupleVariant = Impossible<(), Error>; + type SerializeMap = Impossible<(), Error>; + type SerializeStruct = Impossible<(), Error>; + type SerializeStructVariant = Impossible<(), Error>; + + fn serialize_bool(self, _value: bool) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_i8(self, _value: i8) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_i16(self, _value: i16) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_i32(self, _value: i32) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_i64(self, _value: i64) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_u8(self, _value: u8) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_u16(self, _value: u16) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_u32(self, _value: u32) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_u64(self, _value: u64) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_f32(self, _value: f32) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_f64(self, _value: f64) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_char(self, _value: char) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_bytes(self, _value: &[u8]) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_unit(self) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_unit_struct(self, _name: &'static str) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_newtype_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _value: &T, + ) -> Result<(), Error> + where + T: Serialize, + { + key_must_be_a_string() + } + fn serialize_none(self) -> Result<(), Error> { + key_must_be_a_string() + } + fn serialize_some(self, _value: &T) -> Result<(), Error> + where + T: Serialize, + { + key_must_be_a_string() + } + fn serialize_seq(self, _len: Option) -> Result { + key_must_be_a_string() + } + fn serialize_tuple(self, _len: usize) -> Result { + key_must_be_a_string() + } + fn serialize_tuple_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + key_must_be_a_string() + } + fn serialize_tuple_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + key_must_be_a_string() + } + fn serialize_map(self, _len: Option) -> Result { + key_must_be_a_string() + } + fn serialize_struct( + self, + _name: &'static str, + _len: usize, + ) -> Result { + key_must_be_a_string() + } + fn serialize_struct_variant( + self, + _name: &'static str, + _variant_index: u32, + _variant: &'static str, + _len: usize, + ) -> Result { + key_must_be_a_string() + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/builder/value.rs b/third_party/flatbuffers/rust/flexbuffers/src/builder/value.rs new file mode 100644 index 00000000000..88ff7b9859e --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/builder/value.rs @@ -0,0 +1,307 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use byteorder::{LittleEndian, WriteBytesExt}; + +use crate::bitwidth::BitWidth; +use crate::bitwidth::BitWidth::*; +use crate::flexbuffer_type::FlexBufferType; +use crate::flexbuffer_type::FlexBufferType::*; + +/// Internal representation of FlexBuffer Types and Data before writing. +/// These get placed on the builder's stack and are eventually commited. +#[derive(Debug, Clone, Copy, PartialEq)] +pub enum Value { + // Inline types + Null, + Int(i64), + UInt(u64), + Float(f64), + Bool(bool), + /// Null termintated, c_string. Only used with `Map`s. + Key(usize), + /// The other ~20 or so types. + Reference { + address: usize, + child_width: BitWidth, + fxb_type: FlexBufferType, + }, +} + +macro_rules! new_typed_vector { + ($name: ident, $v2: ident, $v3: ident, $v4: ident, $vn: ident) => { + /// Returns a typed vector, fixed length if possible. + /// Address and child width are zero initialized and must be set. + pub fn $name(n: usize) -> Value { + let address = 0; + let child_width = W8; + match n { + 2 => Value::Reference { + address, + child_width, + fxb_type: $v2, + }, + 3 => Value::Reference { + address, + child_width, + fxb_type: $v3, + }, + 4 => Value::Reference { + address, + child_width, + fxb_type: $v4, + }, + _ => Value::Reference { + address, + child_width, + fxb_type: $vn, + }, + } + } + }; +} + +impl Value { + pub fn new_vector() -> Self { + Value::Reference { + address: 0, + child_width: W8, + fxb_type: Vector, + } + } + pub fn new_map() -> Self { + Value::Reference { + address: 0, + child_width: W8, + fxb_type: Map, + } + } + new_typed_vector!( + new_int_vector, + VectorInt2, + VectorInt3, + VectorInt4, + VectorInt + ); + new_typed_vector!( + new_uint_vector, + VectorUInt2, + VectorUInt3, + VectorUInt4, + VectorUInt + ); + new_typed_vector!( + new_float_vector, + VectorFloat2, + VectorFloat3, + VectorFloat4, + VectorFloat + ); + pub fn fxb_type(&self) -> FlexBufferType { + match *self { + Value::Null => Null, + Value::Int(_) => Int, + Value::UInt(_) => UInt, + Value::Float(_) => Float, + Value::Bool(_) => Bool, + Value::Key(_) => Key, + Value::Reference { fxb_type, .. } => fxb_type, + } + } + pub fn is_fixed_length_vector(&self) -> bool { + self.fxb_type().is_fixed_length_vector() + } + pub fn is_inline(&self) -> bool { + self.fxb_type().is_inline() + } + pub fn is_reference(&self) -> bool { + !self.is_inline() + } + pub fn is_key(&self) -> bool { + if let Value::Key(_) = self { + true + } else { + false + } + } + pub fn is_typed_vector_or_map(&self) -> bool { + if let Value::Reference { fxb_type, .. } = self { + fxb_type.is_heterogenous() + } else { + false + } + } + pub fn prefix_length(&self) -> usize { + if self.is_fixed_length_vector() || self.is_inline() { + return 0; + } + if let Value::Reference { fxb_type, .. } = self { + if *fxb_type == Map { + return 3; + } + } + 1 + } + pub fn set_fxb_type_or_panic(&mut self, new_type: FlexBufferType) { + if let Value::Reference { fxb_type, .. } = self { + *fxb_type = new_type; + } else { + panic!("`set_fxb_type_or_panic` called on {:?}", self) + } + } + pub fn set_child_width_or_panic(&mut self, new_width: BitWidth) { + if let Value::Reference { child_width, .. } = self { + *child_width = new_width; + } else { + panic!("`set_child_width_or_panic` called on {:?}", self); + } + } + pub fn get_address(&self) -> Option { + if let Value::Reference { address, .. } | Value::Key(address) = self { + Some(*address) + } else { + None + } + } + pub fn set_address_or_panic(&mut self, new_address: usize) { + if let Value::Reference { address, .. } | Value::Key(address) = self { + *address = new_address; + } else { + panic!("`set_address_or_panic` called on {:?}", self); + } + } + /// For inline types - the width of the value to be stored. + /// For reference types, the width of the referred. + /// Note Key types always refer to 8 bit data. + pub fn width_or_child_width(&self) -> BitWidth { + match *self { + Value::Int(x) => x.into(), + Value::UInt(x) => x.into(), + Value::Float(x) => x.into(), + Value::Key(_) | Value::Bool(_) | Value::Null => W8, + Value::Reference { child_width, .. } => child_width, + } + } + pub fn relative_address(self, written_at: usize) -> Option { + self.get_address().map(|address| { + let offset = written_at + .checked_sub(address) + .expect("Error: References may only refer backwards in buffer."); + Value::UInt(offset as u64) + }) + } + /// Computes the minimum required width of `value` when stored in a vector + /// starting at `vector_start` at index `idx` (this index includes the prefix). + /// `Value::Reference{..}` variants require location information because + /// offsets are relative. + pub fn width_in_vector(self, vector_start: usize, idx: usize) -> BitWidth { + match self { + Value::Bool(_) => W8, + Value::Null => W8, + Value::Int(x) => x.into(), + Value::UInt(x) => x.into(), + Value::Float(x) => x.into(), + _ => { + debug_assert!(self.is_reference()); + for &width in BitWidth::iter() { + let bytes = width as usize + 1; + let alignment = (bytes - vector_start % bytes) % bytes; + let written_at = vector_start + alignment + idx * bytes; + // This match must always succeed. + if let Some(Value::UInt(offset)) = self.relative_address(written_at) { + if BitWidth::from(offset) == width { + return width; + } + } + } + unreachable!() + } + } + } + pub fn packed_type(self, parent_width: BitWidth) -> u8 { + let width = if self.is_inline() { + std::cmp::max(parent_width, self.width_or_child_width()) + } else { + self.width_or_child_width() + }; + (self.fxb_type() as u8) << 2 | width as u8 + } +} + +pub fn find_vector_type<'a, T>(mut values: T) -> Value +where + T: std::iter::Iterator, +{ + let first = values.next(); + if first.is_none() { + return Value::new_vector(); + } + let mut len = 1; + let init = first.unwrap().fxb_type(); + for v in values { + if v.fxb_type() != init { + return Value::new_vector(); + } + len += 1; + } + let vector_type = match init { + Bool => VectorBool, + UInt => return Value::new_uint_vector(len), + Int => return Value::new_int_vector(len), + Float => return Value::new_float_vector(len), + Key => VectorKey, + // Note that VectorString is deprecated for writing + _ => return Value::new_vector(), + }; + Value::Reference { + address: 0, + child_width: W8, + fxb_type: vector_type, + } +} + +#[inline] +pub fn store_value(buffer: &mut Vec, mut value: Value, width: BitWidth) { + // Remap to number types. + use Value::*; + if let Some(offset) = value.relative_address(buffer.len()) { + value = offset; + } else { + value = match value { + Bool(x) => UInt(x.into()), + Null => UInt(0), // Should this be 0 bytes? + _ => value, + } + } + let write_result = match (value, width) { + (UInt(x), W8) => buffer.write_u8(x as u8), + (UInt(x), W16) => buffer.write_u16::(x as u16), + (UInt(x), W32) => buffer.write_u32::(x as u32), + (UInt(x), W64) => buffer.write_u64::(x), + (Int(x), W8) => buffer.write_i8(x as i8), + (Int(x), W16) => buffer.write_i16::(x as i16), + (Int(x), W32) => buffer.write_i32::(x as i32), + (Int(x), W64) => buffer.write_i64::(x), + (Float(x), W32) => buffer.write_f32::(x as f32), + (Float(x), W64) => buffer.write_f64::(x), + (Float(_), _) => unreachable!("Error: Flatbuffers does not support 8 and 16 bit floats."), + _ => unreachable!("Variant not considered: {:?}", value), + }; + write_result.unwrap_or_else(|err| { + panic!( + "Error writing value {:?} with width {:?}: {:?}", + value, width, err + ) + }); +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/builder/vector.rs b/third_party/flatbuffers/rust/flexbuffers/src/builder/vector.rs new file mode 100644 index 00000000000..375d49e2aa7 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/builder/vector.rs @@ -0,0 +1,65 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::{Builder, MapBuilder, Pushable}; + +/// Builds a Flexbuffer vector, returned by a [Builder](struct.Builder.html). +/// +/// ## Side effect when dropped: +/// When this is dropped, or `end_vector` is called, the vector is +/// commited to the buffer. If this vector is the root of the flexbuffer, then the +/// root is written and the flexbuffer is complete. The FlexBufferType of this vector +/// is determined by the pushed values when this is dropped. The most compact vector type is +/// automatically chosen. +pub struct VectorBuilder<'a> { + pub(crate) builder: &'a mut Builder, + // If the root is this vector then start == None. Otherwise start is the + // number of values in the 'values stack' before adding this vector. + pub(crate) start: Option, +} +impl<'a> VectorBuilder<'a> { + /// Pushes `p` onto the vector. + #[inline] + pub fn push(&mut self, p: P) { + self.builder.push(p); + } + /// Starts a nested vector that will be pushed onto this vector when it is dropped. + #[inline] + pub fn start_vector(&mut self) -> VectorBuilder { + let start = Some(self.builder.values.len()); + VectorBuilder { + builder: self.builder, + start, + } + } + /// Starts a nested map that will be pushed onto this vector when it is dropped. + #[inline] + pub fn start_map(&mut self) -> MapBuilder { + let start = Some(self.builder.values.len()); + MapBuilder { + builder: self.builder, + start, + } + } + /// `end_vector` determines the type of the vector and writes it to the buffer. + /// This will happen automatically if the VectorBuilder is dropped. + #[inline] + pub fn end_vector(self) {} +} +impl<'a> Drop for VectorBuilder<'a> { + #[inline] + fn drop(&mut self) { + self.builder.end_map_or_vector(false, self.start); + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/flexbuffer_type.rs b/third_party/flatbuffers/rust/flexbuffers/src/flexbuffer_type.rs new file mode 100644 index 00000000000..eda51955d00 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/flexbuffer_type.rs @@ -0,0 +1,240 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. +#![allow(deprecated)] +/// Represents all the valid types in a flexbuffer. +/// +/// Flexbuffers supports +/// heterogenous maps, heterogenous vectors, typed vectors, and fixed length +/// typed vectors for some lengths and types. Rust types are converted into +/// Flexbuffers via the [Pushable](trait.Pushable.html) trait. +/// +/// For exact details see the [internals document]( +/// https://google.github.io/flatbuffers/flatbuffers_internals.html) +/// +/// ### Notes: +/// * In the binary format, Each element of a `Map` or (heterogenous) `Vector` +/// is stored with a byte describing its FlexBufferType and BitWidth. +/// +/// * Typed vectors do not store this extra type information and fixed length +/// typed vectors do not store length. Whether a vector is stored as a typed +/// vector or fixed length typed vector is determined dymaically from the +/// given data. +/// +/// * Indirect numbers are stored as an offset instead of inline. Using +/// indirect numbers instead of their inline counterparts in maps and typed +/// vectors can reduce the minimum element width and therefore bytes used. + +#[repr(u8)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize, num_enum::TryFromPrimitive)] +pub enum FlexBufferType { + /// Nulls are represented with `()` in Rust. + Null = 0, + /// Variable width signed integer: `i8, i16, i32, i64` + Int = 1, + /// Variable width unsigned integer: `u8, u16, u32, u64` + UInt = 2, + /// Variable width floating point: `f32, f64` + Float = 3, + Bool = 26, + /// Null termintated, utf8 string. Typically used with `Map`s. + Key = 4, + /// Stored with a unsigned integer length, then UTF-8 bytes, and an extra null terminator that + /// is not counted with the length. + String = 5, + /// An Int, stored by offset rather than inline. Indirect types can keep the bitwidth of a + /// vector or map small when the inline value would have increased the bitwidth. + IndirectInt = 6, + /// A UInt, stored by offset rather than inline. Indirect types can keep the bitwidth of a + /// vector or map small when the inline value would have increased the bitwidth. + IndirectUInt = 7, + /// A Float, stored by offset rather than inline. Indirect types can keep the bitwidth of a + /// vector or map small when the inline value would have increased the bitwidth. + IndirectFloat = 8, + /// Maps are like Vectors except elements are associated with, and sorted by, keys. + Map = 9, + /// Heterogenous Vector (stored with a type table). + Vector = 10, + /// Homogenous Vector of Ints. + VectorInt = 11, + /// Homogenous Vector of UInts. + VectorUInt = 12, + /// Homogenous Vector of Floats. + VectorFloat = 13, + /// Homogenous Vector of Keys. + VectorKey = 14, + /// Homogenous Vector of Strings. + #[deprecated( + note = "Please use Vector or VectorKey instead. See https://github.com/google/flatbuffers/issues/5627" + )] + VectorString = 15, + /// Since the elements of a vector use the same `BitWidth` as the length, + /// Blob is more efficient for >255 element boolean vectors. + VectorBool = 36, + /// Homogenous vector of two Ints + VectorInt2 = 16, + /// Homogenous vector of two UInts + VectorUInt2 = 17, + /// Homogenous vector of two Floats + VectorFloat2 = 18, + /// Homogenous vector of three Ints + VectorInt3 = 19, + /// Homogenous vector of three UInts + VectorUInt3 = 20, + /// Homogenous vector of three Floats + VectorFloat3 = 21, + /// Homogenous vector of four Ints + VectorInt4 = 22, + /// Homogenous vector of four UInts + VectorUInt4 = 23, + /// Homogenous vector of four Floats + VectorFloat4 = 24, + /// An array of bytes. Stored with a variable width length. + Blob = 25, +} +use FlexBufferType::*; + +impl Default for FlexBufferType { + fn default() -> Self { + Null + } +} + +macro_rules! is_ty { + ($is_T: ident, $FTy: ident) => { + #[inline(always)] + pub fn $is_T(self) -> bool { + self == $FTy + } + }; +} + +impl FlexBufferType { + /// Returns true for flexbuffer types that are stored inline. + pub fn is_inline(self) -> bool { + match self { + Null | Int | UInt | Float | Bool => true, + _ => false, + } + } + /// Returns true for flexbuffer types that are stored by offset. + pub fn is_reference(self) -> bool { + !self.is_inline() + } + /// Returns true if called on a map, vector, typed vector, or fixed length typed vector. + pub fn is_vector(self) -> bool { + let d = self as u8; + (9..25).contains(&d) || self == VectorBool + } + /// True iff the binary format stores the length. + /// This applies to Blob, String, Maps, and Vectors of variable length. + pub fn has_length_slot(self) -> bool { + !self.is_fixed_length_vector() && self.is_vector() || self == String || self == Blob + } + /// Returns true if called on a fixed length typed vector. + pub fn is_fixed_length_vector(self) -> bool { + self.fixed_length_vector_length().is_some() + } + /// If called on a fixed type vector, returns the type of the elements. + pub fn typed_vector_type(self) -> Option { + match self { + VectorInt | VectorInt2 | VectorInt3 | VectorInt4 => Some(Int), + VectorUInt | VectorUInt2 | VectorUInt3 | VectorUInt4 => Some(UInt), + VectorFloat | VectorFloat2 | VectorFloat3 | VectorFloat4 => Some(Float), + VectorKey => Some(Key), + // Treat them as keys because we do not know width of length slot. + // see deprecation link. + VectorString => Some(Key), + VectorBool => Some(Bool), + _ => None, + } + } + /// Return the length of the fixed length vector or None. + pub fn fixed_length_vector_length(self) -> Option { + match self { + VectorInt2 | VectorUInt2 | VectorFloat2 => Some(2), + VectorInt3 | VectorUInt3 | VectorFloat3 => Some(3), + VectorInt4 | VectorUInt4 | VectorFloat4 => Some(4), + _ => None, + } + } + /// Returns true if self is a Map or Vector. Typed vectors are not heterogenous. + pub fn is_heterogenous(self) -> bool { + self == Map || self == Vector + } + /// If `self` is an indirect scalar, remap it to the scalar. Otherwise do nothing. + pub fn to_direct(self) -> Option { + match self { + IndirectInt => Some(Int), + IndirectUInt => Some(UInt), + IndirectFloat => Some(Float), + _ => None, + } + } + // returns true if and only if the flexbuffer type is `Null`. + is_ty!(is_null, Null); + // returns true if and only if the flexbuffer type is `Int`. + is_ty!(is_int, Int); + // returns true if and only if the flexbuffer type is `UInt`. + is_ty!(is_uint, UInt); + // returns true if and only if the flexbuffer type is `Float`. + is_ty!(is_float, Float); + // returns true if and only if the flexbuffer type is `Bool`. + is_ty!(is_bool, Bool); + // returns true if and only if the flexbuffer type is `Key`. + is_ty!(is_key, Key); + // returns true if and only if the flexbuffer type is `String`. + is_ty!(is_string, String); + // returns true if and only if the flexbuffer type is `IndirectInt`. + is_ty!(is_indirect_int, IndirectInt); + // returns true if and only if the flexbuffer type is `IndirectUInt`. + is_ty!(is_indirect_uint, IndirectUInt); + // returns true if and only if the flexbuffer type is `IndirectFloat`. + is_ty!(is_indirect_float, IndirectFloat); + // returns true if and only if the flexbuffer type is `Map`. + is_ty!(is_map, Map); + // returns true if and only if the flexbuffer type is `Vector`. + is_ty!(is_heterogenous_vector, Vector); + // returns true if and only if the flexbuffer type is `VectorInt`. + is_ty!(is_vector_int, VectorInt); + // returns true if and only if the flexbuffer type is `VectorUInt`. + is_ty!(is_vector_uint, VectorUInt); + // returns true if and only if the flexbuffer type is `VectorFloat`. + is_ty!(is_vector_float, VectorFloat); + // returns true if and only if the flexbuffer type is `VectorKey`. + is_ty!(is_vector_key, VectorKey); + // returns true if and only if the flexbuffer type is `VectorString`. + is_ty!(is_vector_string, VectorString); + // returns true if and only if the flexbuffer type is `VectorBool`. + is_ty!(is_vector_bool, VectorBool); + // returns true if and only if the flexbuffer type is `VectorInt2`. + is_ty!(is_vector_int2, VectorInt2); + // returns true if and only if the flexbuffer type is `VectorUInt2`. + is_ty!(is_vector_uint2, VectorUInt2); + // returns true if and only if the flexbuffer type is `VectorFloat2`. + is_ty!(is_vector_float2, VectorFloat2); + // returns true if and only if the flexbuffer type is `VectorInt3`. + is_ty!(is_vector_int3, VectorInt3); + // returns true if and only if the flexbuffer type is `VectorUInt3`. + is_ty!(is_vector_uint3, VectorUInt3); + // returns true if and only if the flexbuffer type is `VectorFloat3`. + is_ty!(is_vector_float3, VectorFloat3); + // returns true if and only if the flexbuffer type is `VectorInt4`. + is_ty!(is_vector_int4, VectorInt4); + // returns true if and only if the flexbuffer type is `VectorUInt4`. + is_ty!(is_vector_uint4, VectorUInt4); + // returns true if and only if the flexbuffer type is `VectorFloat4`. + is_ty!(is_vector_float4, VectorFloat4); + // returns true if and only if the flexbuffer type is `Blob`. + is_ty!(is_blob, Blob); +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/lib.rs b/third_party/flatbuffers/rust/flexbuffers/src/lib.rs new file mode 100644 index 00000000000..760ab16efa5 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/lib.rs @@ -0,0 +1,116 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +//! Flexbuffers is a high performance schemaless binary data format designed at Google. +//! It is complementary to the schema-ed format [Flatbuffers](http://docs.rs/flatbuffers/). +//! See [Flexbuffer Internals](https://google.github.io/flatbuffers/flatbuffers_internals.html) +//! for details on the binary format. +//! +//! See the examples for usage: +//! * [Example](https://github.com/google/flatbuffers/blob/master/samples/sample_flexbuffers.rs) +//! * [Serde Example](https://github.com/google/flatbuffers/blob/master/samples/sample_flexbuffers_serde.rs) +//! +//! This rust implementation is in progress and, until the 1.0 release, breaking API changes may +//! happen between minor versions. +// TODO(cneo): serde stuff are behind a default-on feature flag +// Reader to Json is behind a default-off feature flag +// Serializable structs are Pushable +// Serde with maps - field names and type names. + +// Until flat/flexbuffers is on Rust v1.42, we cannot use the previously unstable matches! macro. +#![allow(unknown_lints)] +#![allow(clippy::match_like_matches_macro)] + +#[macro_use] +extern crate bitflags; +extern crate byteorder; +#[macro_use] +extern crate serde_derive; +extern crate num_enum; +extern crate serde; + +mod bitwidth; +mod buffer; +mod builder; +mod flexbuffer_type; +mod reader; + +pub use bitwidth::BitWidth; +pub use buffer::Buffer; +pub use builder::Error as SerializationError; +pub use builder::{ + singleton, Builder, BuilderOptions, FlexbufferSerializer, MapBuilder, Pushable, VectorBuilder, +}; +pub use flexbuffer_type::FlexBufferType; +pub use reader::Error as ReaderError; +pub use reader::{DeserializationError, MapReader, Reader, ReaderIterator, VectorReader}; +use serde::{Deserialize, Serialize}; + +mod private { + pub trait Sealed {} +} + +/// Serialize as a flexbuffer into a vector. +pub fn to_vec(x: T) -> Result, SerializationError> { + let mut s = FlexbufferSerializer::new(); + x.serialize(&mut s)?; + Ok(s.take_buffer()) +} + +/// Deserialize a type from a flexbuffer. +pub fn from_slice<'de, T: Deserialize<'de>>(buf: &'de [u8]) -> Result { + let r = Reader::get_root(buf)?; + T::deserialize(r) +} + +/// Deserialize a type from a flexbuffer. +pub fn from_buffer<'de, T: Deserialize<'de>, B: Buffer>( + buf: &'de B, +) -> Result { + let r = Reader::get_root(buf as &'de [u8])?; + T::deserialize(r) +} + +/// This struct, when pushed will be serialized as a `FlexBufferType::Blob`. +/// +/// A `Blob` is a variable width `length` followed by that many bytes of data. +#[derive(Debug, PartialEq, Eq)] +pub struct Blob(pub B); + +impl Clone for Blob { + fn clone(&self) -> Self { + Blob(self.0.shallow_copy()) + } +} + +/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectUInt`. +/// +/// It is an unsigned integer stored by reference in the flexbuffer. This can reduce the +/// size of vectors and maps containing the `IndirectUInt`. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct IndirectUInt(pub u64); + +/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectInt`. +/// +/// It is a signed integer stored by reference in the flexbuffer. This can reduce the +/// size of vectors and maps containing the `IndirectInt`. +#[derive(Debug, Copy, Clone, PartialEq, Eq)] +pub struct IndirectInt(pub i64); + +/// This struct, when pushed, will be serialized as a `FlexBufferType::IndirectFloat`. +/// +/// It is a floating point stored by reference in the flexbuffer. This can reduce the +/// size of vectors and maps containing the `IndirectFloat`. +#[derive(Debug, Copy, Clone, PartialEq)] +pub struct IndirectFloat(pub f64); diff --git a/third_party/flatbuffers/rust/flexbuffers/src/reader/de.rs b/third_party/flatbuffers/rust/flexbuffers/src/reader/de.rs new file mode 100644 index 00000000000..ed2b8158e79 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/reader/de.rs @@ -0,0 +1,271 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::Error; +use crate::{FlexBufferType, Reader, ReaderIterator}; +use serde::de::{ + DeserializeSeed, Deserializer, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, + VariantAccess, Visitor, +}; + +/// Errors that may happen when deserializing a flexbuffer with serde. +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum DeserializationError { + Reader(Error), + Serde(String), +} + +impl std::error::Error for DeserializationError {} +impl std::fmt::Display for DeserializationError { + fn fmt(&self, f: &mut std::fmt::Formatter) -> Result<(), std::fmt::Error> { + match self { + Self::Reader(r) => write!(f, "Flexbuffer Read Error: {:?}", r), + Self::Serde(s) => write!(f, "Serde Error: {}", s), + } + } +} + +impl serde::de::Error for DeserializationError { + fn custom(msg: T) -> Self + where + T: std::fmt::Display, + { + Self::Serde(format!("{}", msg)) + } +} + +impl std::convert::From for DeserializationError { + fn from(e: super::Error) -> Self { + Self::Reader(e) + } +} + +impl<'de> SeqAccess<'de> for ReaderIterator<&'de [u8]> { + type Error = DeserializationError; + + fn next_element_seed( + &mut self, + seed: T, + ) -> Result>::Value>, Self::Error> + where + T: DeserializeSeed<'de>, + { + if let Some(elem) = self.next() { + seed.deserialize(elem).map(Some) + } else { + Ok(None) + } + } + + fn size_hint(&self) -> Option { + Some(self.len()) + } +} + +struct EnumReader<'de> { + variant: &'de str, + value: Option>, +} + +impl<'de> EnumAccess<'de> for EnumReader<'de> { + type Error = DeserializationError; + type Variant = Reader<&'de [u8]>; + + fn variant_seed(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> + where + V: DeserializeSeed<'de>, + { + seed.deserialize(self.variant.into_deserializer()) + .map(|v| (v, self.value.unwrap_or_default())) + } +} + +struct MapAccessor<'de> { + keys: ReaderIterator<&'de [u8]>, + vals: ReaderIterator<&'de [u8]>, +} + +impl<'de> MapAccess<'de> for MapAccessor<'de> { + type Error = DeserializationError; + + fn next_key_seed(&mut self, seed: K) -> Result, Self::Error> + where + K: DeserializeSeed<'de>, + { + if let Some(k) = self.keys.next() { + seed.deserialize(k).map(Some) + } else { + Ok(None) + } + } + + fn next_value_seed(&mut self, seed: V) -> Result + where + V: DeserializeSeed<'de>, + { + let val = self.vals.next().ok_or(Error::IndexOutOfBounds)?; + seed.deserialize(val) + } +} + +impl<'de> VariantAccess<'de> for Reader<&'de [u8]> { + type Error = DeserializationError; + + fn unit_variant(self) -> Result<(), Self::Error> { + Ok(()) + } + + fn newtype_variant_seed(self, seed: T) -> Result + where + T: DeserializeSeed<'de>, + { + seed.deserialize(self) + } + + // Tuple variants have an internally tagged representation. They are vectors where Index 0 is + // the discriminant and index N is field N-1. + fn tuple_variant(self, _len: usize, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_seq(self.as_vector().iter()) + } + + // Struct variants have an internally tagged representation. They are vectors where Index 0 is + // the discriminant and index N is field N-1. + fn struct_variant( + self, + _fields: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let m = self.get_map()?; + visitor.visit_map(MapAccessor { + keys: m.keys_vector().iter(), + vals: m.iter_values(), + }) + } +} + +impl<'de> Deserializer<'de> for Reader<&'de [u8]> { + type Error = DeserializationError; + fn is_human_readable(&self) -> bool { + cfg!(deserialize_human_readable) + } + + fn deserialize_any(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + use crate::BitWidth::*; + use crate::FlexBufferType::*; + match (self.flexbuffer_type(), self.bitwidth()) { + (Bool, _) => visitor.visit_bool(self.as_bool()), + (UInt, W8) => visitor.visit_u8(self.as_u8()), + (UInt, W16) => visitor.visit_u16(self.as_u16()), + (UInt, W32) => visitor.visit_u32(self.as_u32()), + (UInt, W64) => visitor.visit_u64(self.as_u64()), + (Int, W8) => visitor.visit_i8(self.as_i8()), + (Int, W16) => visitor.visit_i16(self.as_i16()), + (Int, W32) => visitor.visit_i32(self.as_i32()), + (Int, W64) => visitor.visit_i64(self.as_i64()), + (Float, W32) => visitor.visit_f32(self.as_f32()), + (Float, W64) => visitor.visit_f64(self.as_f64()), + (Float, _) => Err(Error::InvalidPackedType.into()), // f8 and f16 are not supported. + (Null, _) => visitor.visit_unit(), + (String, _) | (Key, _) => visitor.visit_borrowed_str(self.as_str()), + (Blob, _) => visitor.visit_borrowed_bytes(self.get_blob()?.0), + (Map, _) => { + let m = self.get_map()?; + visitor.visit_map(MapAccessor { + keys: m.keys_vector().iter(), + vals: m.iter_values(), + }) + } + (ty, _) if ty.is_vector() => visitor.visit_seq(self.as_vector().iter()), + (ty, bw) => unreachable!("TODO deserialize_any {:?} {:?}.", ty, bw), + } + } + + serde::forward_to_deserialize_any! { + bool i8 i16 i32 i64 u8 u16 u32 u64 f32 f64 str unit unit_struct bytes + ignored_any map identifier struct tuple tuple_struct seq string + } + + fn deserialize_char(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_char(self.as_u8() as char) + } + + fn deserialize_byte_buf(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + visitor.visit_byte_buf(self.get_blob()?.0.to_vec()) + } + + fn deserialize_option(self, visitor: V) -> Result + where + V: Visitor<'de>, + { + if self.flexbuffer_type() == FlexBufferType::Null { + visitor.visit_none() + } else { + visitor.visit_some(self) + } + } + + fn deserialize_newtype_struct( + self, + _name: &'static str, + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + visitor.visit_newtype_struct(self) + } + + fn deserialize_enum( + self, + _name: &'static str, + _variants: &'static [&'static str], + visitor: V, + ) -> Result + where + V: Visitor<'de>, + { + let (variant, value) = match self.fxb_type { + FlexBufferType::String => (self.as_str(), None), + FlexBufferType::Map => { + let m = self.get_map()?; + let variant = m.keys_vector().idx(0).get_key()?; + let value = Some(m.idx(0)); + (variant, value) + } + _ => { + return Err(Error::UnexpectedFlexbufferType { + expected: FlexBufferType::Map, + actual: self.fxb_type, + } + .into()); + } + }; + visitor.visit_enum(EnumReader { variant, value }) + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/reader/iter.rs b/third_party/flatbuffers/rust/flexbuffers/src/reader/iter.rs new file mode 100644 index 00000000000..267a01f1cc8 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/reader/iter.rs @@ -0,0 +1,67 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::{Buffer, Reader, VectorReader}; +use std::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator}; + +/// Iterates over a flexbuffer vector, typed vector, or map. Yields [Readers](struct.Reader.html). +/// +/// If any error occurs, the Reader is defaulted to a Null flexbuffer Reader. +pub struct ReaderIterator { + pub(super) reader: VectorReader, + pub(super) front: usize, + end: usize, +} + +impl ReaderIterator { + pub(super) fn new(reader: VectorReader) -> Self { + let end = reader.len(); + ReaderIterator { + reader, + front: 0, + end, + } + } +} + +impl Iterator for ReaderIterator { + type Item = Reader; + fn next(&mut self) -> Option { + if self.front < self.end { + let r = self.reader.idx(self.front); + self.front += 1; + Some(r) + } else { + None + } + } + fn size_hint(&self) -> (usize, Option) { + let remaining = self.end - self.front; + (remaining, Some(remaining)) + } +} + +impl DoubleEndedIterator for ReaderIterator { + fn next_back(&mut self) -> Option { + if self.front < self.end { + self.end -= 1; + Some(self.reader.idx(self.end)) + } else { + None + } + } +} + +impl ExactSizeIterator for ReaderIterator {} +impl FusedIterator for ReaderIterator {} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/reader/map.rs b/third_party/flatbuffers/rust/flexbuffers/src/reader/map.rs new file mode 100644 index 00000000000..7d6ada8abed --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/reader/map.rs @@ -0,0 +1,192 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::{deref_offset, unpack_type, Error, Reader, ReaderIterator, VectorReader}; +use crate::BitWidth; +use crate::Buffer; +use std::cmp::Ordering; +use std::iter::{DoubleEndedIterator, ExactSizeIterator, FusedIterator, Iterator}; + +/// Allows indexing on a flexbuffer map. +/// +/// MapReaders may be indexed with strings or usizes. `index` returns a result type, +/// which may indicate failure due to a missing key or bad data, `idx` returns an Null Reader in +/// cases of error. +pub struct MapReader { + pub(super) buffer: B, + pub(super) values_address: usize, + pub(super) keys_address: usize, + pub(super) values_width: BitWidth, + pub(super) keys_width: BitWidth, + pub(super) length: usize, +} + +impl Clone for MapReader { + fn clone(&self) -> Self { + MapReader { + buffer: self.buffer.shallow_copy(), + ..*self + } + } +} + +impl Default for MapReader { + fn default() -> Self { + MapReader { + buffer: B::empty(), + values_address: usize::default(), + keys_address: usize::default(), + values_width: BitWidth::default(), + keys_width: BitWidth::default(), + length: usize::default(), + } + } +} + +// manual implementation of Debug because buffer slice can't be automatically displayed +impl std::fmt::Debug for MapReader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // skips buffer field + f.debug_struct("MapReader") + .field("values_address", &self.values_address) + .field("keys_address", &self.keys_address) + .field("values_width", &self.values_width) + .field("keys_width", &self.keys_width) + .field("length", &self.length) + .finish() + } +} + +impl MapReader { + /// Returns the number of key/value pairs are in the map. + pub fn len(&self) -> usize { + self.length + } + + /// Returns true if the map has zero key/value pairs. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + + // Using &CStr will eagerly compute the length of the key. &str needs length info AND utf8 + // validation. This version is faster than both. + fn lazy_strcmp(&self, key_addr: usize, key: &str) -> Ordering { + // TODO: Can we know this won't OOB and panic? + let k = self.buffer[key_addr..].iter().take_while(|&&b| b != b'\0'); + k.cmp(key.as_bytes().iter()) + } + + /// Returns the index of a given key in the map. + pub fn index_key(&self, key: &str) -> Option { + let (mut low, mut high) = (0, self.length); + while low < high { + let i = (low + high) / 2; + let key_offset_address = self.keys_address + i * self.keys_width.n_bytes(); + let key_address = + deref_offset(&self.buffer, key_offset_address, self.keys_width).ok()?; + match self.lazy_strcmp(key_address, key) { + Ordering::Equal => return Some(i), + Ordering::Less => low = if i == low { i + 1 } else { i }, + Ordering::Greater => high = i, + } + } + None + } + + /// Index into a map with a key or usize. + pub fn index(&self, i: I) -> Result, Error> { + i.index_map_reader(self) + } + + /// Index into a map with a key or usize. If any errors occur a Null reader is returned. + pub fn idx(&self, i: I) -> Reader { + i.index_map_reader(self).unwrap_or_default() + } + + fn usize_index(&self, i: usize) -> Result, Error> { + if i >= self.length { + return Err(Error::IndexOutOfBounds); + } + let data_address = self.values_address + self.values_width.n_bytes() * i; + let type_address = self.values_address + self.values_width.n_bytes() * self.length + i; + let (fxb_type, width) = self + .buffer + .get(type_address) + .ok_or(Error::FlexbufferOutOfBounds) + .and_then(|&b| unpack_type(b))?; + Reader::new( + self.buffer.shallow_copy(), + data_address, + fxb_type, + width, + self.values_width, + ) + } + + fn key_index(&self, k: &str) -> Result, Error> { + let i = self.index_key(k).ok_or(Error::KeyNotFound)?; + self.usize_index(i) + } + + /// Iterate over the values of the map. + pub fn iter_values(&self) -> ReaderIterator { + ReaderIterator::new(VectorReader { + reader: Reader { + buffer: self.buffer.shallow_copy(), + fxb_type: crate::FlexBufferType::Map, + width: self.values_width, + address: self.values_address, + }, + length: self.length, + }) + } + + /// Iterate over the keys of the map. + pub fn iter_keys( + &self, + ) -> impl Iterator + DoubleEndedIterator + ExactSizeIterator + FusedIterator + { + self.keys_vector().iter().map(|k| k.as_str()) + } + + pub fn keys_vector(&self) -> VectorReader { + VectorReader { + reader: Reader { + buffer: self.buffer.shallow_copy(), + fxb_type: crate::FlexBufferType::VectorKey, + width: self.keys_width, + address: self.keys_address, + }, + length: self.length, + } + } +} + +pub trait MapReaderIndexer { + fn index_map_reader(self, r: &MapReader) -> Result, Error>; +} + +impl MapReaderIndexer for usize { + #[inline] + fn index_map_reader(self, r: &MapReader) -> Result, Error> { + r.usize_index(self) + } +} + +impl MapReaderIndexer for &str { + #[inline] + fn index_map_reader(self, r: &MapReader) -> Result, Error> { + r.key_index(self) + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/reader/mod.rs b/third_party/flatbuffers/rust/flexbuffers/src/reader/mod.rs new file mode 100644 index 00000000000..8e9c247c255 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/reader/mod.rs @@ -0,0 +1,676 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::bitwidth::BitWidth; +use crate::flexbuffer_type::FlexBufferType; +use crate::{Blob, Buffer}; +use std::convert::{TryFrom, TryInto}; +use std::fmt; +use std::ops::Rem; +use std::str::FromStr; +mod de; +mod iter; +mod map; +mod serialize; +mod vector; +pub use de::DeserializationError; +pub use iter::ReaderIterator; +pub use map::{MapReader, MapReaderIndexer}; +pub use vector::VectorReader; + +/// All the possible errors when reading a flexbuffer. +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +pub enum Error { + /// One of the following data errors occured: + /// + /// * The read flexbuffer had an offset that pointed outside the flexbuffer. + /// * The 'negative indicies' where length and map keys are stored were out of bounds + /// * The buffer was too small to contain a flexbuffer root. + FlexbufferOutOfBounds, + /// Failed to parse a valid FlexbufferType and Bitwidth from a type byte. + InvalidPackedType, + /// Flexbuffer type of the read data does not match function used. + UnexpectedFlexbufferType { + expected: FlexBufferType, + actual: FlexBufferType, + }, + /// BitWidth type of the read data does not match function used. + UnexpectedBitWidth { + expected: BitWidth, + actual: BitWidth, + }, + /// Read a flexbuffer offset or length that overflowed usize. + ReadUsizeOverflowed, + /// Tried to index a type that's not one of the Flexbuffer vector types. + CannotIndexAsVector, + /// Tried to index a Flexbuffer vector or map out of bounds. + IndexOutOfBounds, + /// A Map was indexed with a key that it did not contain. + KeyNotFound, + /// Failed to parse a Utf8 string. + /// The Option will be `None` if and only if this Error was deserialized. + // NOTE: std::str::Utf8Error does not implement Serialize, Deserialize, nor Default. We tell + // serde to skip the field and default to None. We prefer to have the boxed error so it can be + // used with std::error::Error::source, though another (worse) option could be to drop that + // information. + Utf8Error(#[serde(skip)] Option>), + /// get_slice failed because the given data buffer is misaligned. + AlignmentError, + InvalidRootWidth, + InvalidMapKeysVectorWidth, +} +impl std::convert::From for Error { + fn from(e: std::str::Utf8Error) -> Self { + Self::Utf8Error(Some(Box::new(e))) + } +} +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Self::UnexpectedBitWidth { expected, actual } => write!( + f, + "Error reading flexbuffer: Expected bitwidth: {:?}, found bitwidth: {:?}", + expected, actual + ), + Self::UnexpectedFlexbufferType { expected, actual } => write!( + f, + "Error reading flexbuffer: Expected type: {:?}, found type: {:?}", + expected, actual + ), + _ => write!(f, "Error reading flexbuffer: {:?}", self), + } + } +} +impl std::error::Error for Error { + fn source(&self) -> Option<&(dyn std::error::Error + 'static)> { + if let Self::Utf8Error(Some(e)) = self { + Some(e) + } else { + None + } + } +} + +pub trait ReadLE: crate::private::Sealed + std::marker::Sized { + const VECTOR_TYPE: FlexBufferType; + const WIDTH: BitWidth; +} +macro_rules! rle { + ($T: ty, $VECTOR_TYPE: ident, $WIDTH: ident) => { + impl ReadLE for $T { + const VECTOR_TYPE: FlexBufferType = FlexBufferType::$VECTOR_TYPE; + const WIDTH: BitWidth = BitWidth::$WIDTH; + } + }; +} +rle!(u8, VectorUInt, W8); +rle!(u16, VectorUInt, W16); +rle!(u32, VectorUInt, W32); +rle!(u64, VectorUInt, W64); +rle!(i8, VectorInt, W8); +rle!(i16, VectorInt, W16); +rle!(i32, VectorInt, W32); +rle!(i64, VectorInt, W64); +rle!(f32, VectorFloat, W32); +rle!(f64, VectorFloat, W64); + +macro_rules! as_default { + ($as: ident, $get: ident, $T: ty) => { + pub fn $as(&self) -> $T { + self.$get().unwrap_or_default() + } + }; +} + +/// `Reader`s allow access to data stored in a Flexbuffer. +/// +/// Each reader represents a single address in the buffer so data is read lazily. Start a reader +/// by calling `get_root` on your flexbuffer `&[u8]`. +/// +/// - The `get_T` methods return a `Result`. They return an OK value if and only if the +/// flexbuffer type matches `T`. This is analogous to the behavior of Rust's json library, though +/// with Result instead of Option. +/// - The `as_T` methods will try their best to return to a value of type `T` +/// (by casting or even parsing a string if necessary) but ultimately returns `T::default` if it +/// fails. This behavior is analogous to that of flexbuffers C++. +pub struct Reader { + fxb_type: FlexBufferType, + width: BitWidth, + address: usize, + buffer: B, +} + +impl Clone for Reader { + fn clone(&self) -> Self { + Reader { + fxb_type: self.fxb_type, + width: self.width, + address: self.address, + buffer: self.buffer.shallow_copy(), + } + } +} + +impl Default for Reader { + fn default() -> Self { + Reader { + fxb_type: FlexBufferType::default(), + width: BitWidth::default(), + address: usize::default(), + buffer: B::empty(), + } + } +} + +// manual implementation of Debug because buffer slice can't be automatically displayed +impl std::fmt::Debug for Reader { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + // skips buffer field + f.debug_struct("Reader") + .field("fxb_type", &self.fxb_type) + .field("width", &self.width) + .field("address", &self.address) + .finish() + } +} + +macro_rules! try_cast_fn { + ($name: ident, $full_width: ident, $Ty: ident) => { + pub fn $name(&self) -> $Ty { + self.$full_width().try_into().unwrap_or_default() + } + }; +} + +fn safe_sub(a: usize, b: usize) -> Result { + a.checked_sub(b).ok_or(Error::FlexbufferOutOfBounds) +} + +fn deref_offset(buffer: &[u8], address: usize, width: BitWidth) -> Result { + let off = read_usize(buffer, address, width); + safe_sub(address, off) +} + +impl Reader { + fn new( + buffer: B, + mut address: usize, + mut fxb_type: FlexBufferType, + width: BitWidth, + parent_width: BitWidth, + ) -> Result { + if fxb_type.is_reference() { + address = deref_offset(&buffer, address, parent_width)?; + // Indirects were dereferenced. + if let Some(t) = fxb_type.to_direct() { + fxb_type = t; + } + } + Ok(Reader { + address, + fxb_type, + width, + buffer, + }) + } + + /// Parses the flexbuffer from the given buffer. Assumes the flexbuffer root is the last byte + /// of the buffer. + pub fn get_root(buffer: B) -> Result { + let end = buffer.len(); + if end < 3 { + return Err(Error::FlexbufferOutOfBounds); + } + // Last byte is the root width. + let root_width = BitWidth::from_nbytes(buffer[end - 1]).ok_or(Error::InvalidRootWidth)?; + // Second last byte is root type. + let (fxb_type, width) = unpack_type(buffer[end - 2])?; + // Location of root data. (BitWidth bits before root type) + let address = safe_sub(end - 2, root_width.n_bytes())?; + Self::new(buffer, address, fxb_type, width, root_width) + } + + /// Convenience function to get the underlying buffer. By using `shallow_copy`, this preserves + /// the lifetime that the underlying buffer has. + pub fn buffer(&self) -> B { + self.buffer.shallow_copy() + } + + /// Returns the FlexBufferType of this Reader. + pub fn flexbuffer_type(&self) -> FlexBufferType { + self.fxb_type + } + + /// Returns the bitwidth of this Reader. + pub fn bitwidth(&self) -> BitWidth { + self.width + } + + /// Returns the length of the Flexbuffer. If the type has no length, or if an error occurs, + /// 0 is returned. + pub fn length(&self) -> usize { + if let Some(len) = self.fxb_type.fixed_length_vector_length() { + len + } else if self.fxb_type.has_length_slot() && self.address >= self.width.n_bytes() { + read_usize( + &self.buffer, + self.address - self.width.n_bytes(), + self.width, + ) + } else { + 0 + } + } + /// Returns true if the flexbuffer is aligned to 8 bytes. This guarantees, for valid + /// flexbuffers, that the data is correctly aligned in memory and slices can be read directly + /// e.g. with `get_f64s` or `get_i16s`. + #[inline] + pub fn is_aligned(&self) -> bool { + (self.buffer.as_ptr() as usize).rem(8) == 0 + } + + as_default!(as_vector, get_vector, VectorReader); + as_default!(as_map, get_map, MapReader); + + fn expect_type(&self, ty: FlexBufferType) -> Result<(), Error> { + if self.fxb_type == ty { + Ok(()) + } else { + Err(Error::UnexpectedFlexbufferType { + expected: ty, + actual: self.fxb_type, + }) + } + } + fn expect_bw(&self, bw: BitWidth) -> Result<(), Error> { + if self.width == bw { + Ok(()) + } else { + Err(Error::UnexpectedBitWidth { + expected: bw, + actual: self.width, + }) + } + } + + /// Directly reads a slice of type `T` where `T` is one of `u8,u16,u32,u64,i8,i16,i32,i64,f32,f64`. + /// Returns Err if the type, bitwidth, or memory alignment does not match. Since the bitwidth is + /// dynamic, its better to use a VectorReader unless you know your data and performance is critical. + #[cfg(target_endian = "little")] + #[deprecated( + since = "0.3.0", + note = "This function is unsafe - if this functionality is needed use `Reader::buffer::align_to`" + )] + pub fn get_slice(&self) -> Result<&[T], Error> { + if self.flexbuffer_type().typed_vector_type() != T::VECTOR_TYPE.typed_vector_type() { + self.expect_type(T::VECTOR_TYPE)?; + } + if self.bitwidth().n_bytes() != std::mem::size_of::() { + self.expect_bw(T::WIDTH)?; + } + let end = self.address + self.length() * std::mem::size_of::(); + let slice: &[u8] = self + .buffer + .get(self.address..end) + .ok_or(Error::FlexbufferOutOfBounds)?; + + // `align_to` is required because the point of this function is to directly hand back a + // slice of scalars. This can fail because Rust's default allocator is not 16byte aligned + // (though in practice this only happens for small buffers). + let (pre, mid, suf) = unsafe { slice.align_to::() }; + if pre.is_empty() && suf.is_empty() { + Ok(mid) + } else { + Err(Error::AlignmentError) + } + } + + /// Returns the value of the reader if it is a boolean. + /// Otherwise Returns error. + pub fn get_bool(&self) -> Result { + self.expect_type(FlexBufferType::Bool)?; + Ok( + self.buffer[self.address..self.address + self.width.n_bytes()] + .iter() + .any(|&b| b != 0), + ) + } + + /// Gets the length of the key if this type is a key. + /// + /// Otherwise, returns an error. + #[inline] + fn get_key_len(&self) -> Result { + self.expect_type(FlexBufferType::Key)?; + let (length, _) = self.buffer[self.address..] + .iter() + .enumerate() + .find(|(_, &b)| b == b'\0') + .unwrap_or((0, &0)); + Ok(length) + } + + /// Retrieves the string value up until the first `\0` character. + pub fn get_key(&self) -> Result { + let bytes = self + .buffer + .slice(self.address..self.address + self.get_key_len()?) + .ok_or(Error::IndexOutOfBounds)?; + Ok(bytes.buffer_str()?) + } + + pub fn get_blob(&self) -> Result, Error> { + self.expect_type(FlexBufferType::Blob)?; + Ok(Blob( + self.buffer + .slice(self.address..self.address + self.length()) + .ok_or(Error::IndexOutOfBounds)?, + )) + } + + pub fn as_blob(&self) -> Blob { + self.get_blob().unwrap_or_else(|_| Blob(B::empty())) + } + + /// Retrieves str pointer, errors if invalid UTF-8, or the provided index + /// is out of bounds. + pub fn get_str(&self) -> Result { + self.expect_type(FlexBufferType::String)?; + let bytes = self + .buffer + .slice(self.address..self.address + self.length()); + Ok(bytes.ok_or(Error::ReadUsizeOverflowed)?.buffer_str()?) + } + + fn get_map_info(&self) -> Result<(usize, BitWidth), Error> { + self.expect_type(FlexBufferType::Map)?; + if 3 * self.width.n_bytes() >= self.address { + return Err(Error::FlexbufferOutOfBounds); + } + let keys_offset_address = self.address - 3 * self.width.n_bytes(); + let keys_width = { + let kw_addr = self.address - 2 * self.width.n_bytes(); + let kw = read_usize(&self.buffer, kw_addr, self.width); + BitWidth::from_nbytes(kw).ok_or(Error::InvalidMapKeysVectorWidth) + }?; + Ok((keys_offset_address, keys_width)) + } + + pub fn get_map(&self) -> Result, Error> { + let (keys_offset_address, keys_width) = self.get_map_info()?; + let keys_address = deref_offset(&self.buffer, keys_offset_address, self.width)?; + // TODO(cneo): Check that vectors length equals keys length. + Ok(MapReader { + buffer: self.buffer.shallow_copy(), + values_address: self.address, + values_width: self.width, + keys_address, + keys_width, + length: self.length(), + }) + } + + /// Tries to read a FlexBufferType::UInt. Returns Err if the type is not a UInt or if the + /// address is out of bounds. + pub fn get_u64(&self) -> Result { + self.expect_type(FlexBufferType::UInt)?; + let cursor = self + .buffer + .get(self.address..self.address + self.width.n_bytes()); + match self.width { + BitWidth::W8 => cursor.map(|s| s[0] as u8).map(Into::into), + BitWidth::W16 => cursor + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .map(Into::into), + BitWidth::W32 => cursor + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .map(Into::into), + BitWidth::W64 => cursor + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes), + } + .ok_or(Error::FlexbufferOutOfBounds) + } + /// Tries to read a FlexBufferType::Int. Returns Err if the type is not a UInt or if the + /// address is out of bounds. + pub fn get_i64(&self) -> Result { + self.expect_type(FlexBufferType::Int)?; + let cursor = self + .buffer + .get(self.address..self.address + self.width.n_bytes()); + match self.width { + BitWidth::W8 => cursor.map(|s| s[0] as i8).map(Into::into), + BitWidth::W16 => cursor + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .map(Into::into), + BitWidth::W32 => cursor + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .map(Into::into), + BitWidth::W64 => cursor + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes), + } + .ok_or(Error::FlexbufferOutOfBounds) + } + /// Tries to read a FlexBufferType::Float. Returns Err if the type is not a UInt, if the + /// address is out of bounds, or if its a f16 or f8 (not currently supported). + pub fn get_f64(&self) -> Result { + self.expect_type(FlexBufferType::Float)?; + let cursor = self + .buffer + .get(self.address..self.address + self.width.n_bytes()); + match self.width { + BitWidth::W8 | BitWidth::W16 => return Err(Error::InvalidPackedType), + BitWidth::W32 => cursor + .and_then(|s| s.try_into().ok()) + .map(f32_from_le_bytes) + .map(Into::into), + BitWidth::W64 => cursor + .and_then(|s| s.try_into().ok()) + .map(f64_from_le_bytes), + } + .ok_or(Error::FlexbufferOutOfBounds) + } + pub fn as_bool(&self) -> bool { + use FlexBufferType::*; + match self.fxb_type { + Bool => self.get_bool().unwrap_or_default(), + UInt => self.as_u64() != 0, + Int => self.as_i64() != 0, + Float => self.as_f64().abs() > std::f64::EPSILON, + String | Key => !self.as_str().is_empty(), + Null => false, + Blob => self.length() != 0, + ty if ty.is_vector() => self.length() != 0, + _ => unreachable!(), + } + } + /// Returns a u64, casting if necessary. For Maps and Vectors, their length is + /// returned. If anything fails, 0 is returned. + pub fn as_u64(&self) -> u64 { + match self.fxb_type { + FlexBufferType::UInt => self.get_u64().unwrap_or_default(), + FlexBufferType::Int => self + .get_i64() + .unwrap_or_default() + .try_into() + .unwrap_or_default(), + FlexBufferType::Float => self.get_f64().unwrap_or_default() as u64, + FlexBufferType::String => { + if let Ok(s) = self.get_str() { + if let Ok(f) = u64::from_str(&s) { + return f; + } + } + 0 + } + _ if self.fxb_type.is_vector() => self.length() as u64, + _ => 0, + } + } + try_cast_fn!(as_u32, as_u64, u32); + try_cast_fn!(as_u16, as_u64, u16); + try_cast_fn!(as_u8, as_u64, u8); + + /// Returns an i64, casting if necessary. For Maps and Vectors, their length is + /// returned. If anything fails, 0 is returned. + pub fn as_i64(&self) -> i64 { + match self.fxb_type { + FlexBufferType::Int => self.get_i64().unwrap_or_default(), + FlexBufferType::UInt => self + .get_u64() + .unwrap_or_default() + .try_into() + .unwrap_or_default(), + FlexBufferType::Float => self.get_f64().unwrap_or_default() as i64, + FlexBufferType::String => { + if let Ok(s) = self.get_str() { + if let Ok(f) = i64::from_str(&s) { + return f; + } + } + 0 + } + _ if self.fxb_type.is_vector() => self.length() as i64, + _ => 0, + } + } + try_cast_fn!(as_i32, as_i64, i32); + try_cast_fn!(as_i16, as_i64, i16); + try_cast_fn!(as_i8, as_i64, i8); + + /// Returns an f64, casting if necessary. For Maps and Vectors, their length is + /// returned. If anything fails, 0 is returned. + pub fn as_f64(&self) -> f64 { + match self.fxb_type { + FlexBufferType::Int => self.get_i64().unwrap_or_default() as f64, + FlexBufferType::UInt => self.get_u64().unwrap_or_default() as f64, + FlexBufferType::Float => self.get_f64().unwrap_or_default(), + FlexBufferType::String => { + if let Ok(s) = self.get_str() { + if let Ok(f) = f64::from_str(&s) { + return f; + } + } + 0.0 + } + _ if self.fxb_type.is_vector() => self.length() as f64, + _ => 0.0, + } + } + pub fn as_f32(&self) -> f32 { + self.as_f64() as f32 + } + + /// Returns empty string if you're not trying to read a string. + pub fn as_str(&self) -> B::BufferString { + match self.fxb_type { + FlexBufferType::String => self.get_str().unwrap_or_else(|_| B::empty_str()), + FlexBufferType::Key => self.get_key().unwrap_or_else(|_| B::empty_str()), + _ => B::empty_str(), + } + } + + pub fn get_vector(&self) -> Result, Error> { + if !self.fxb_type.is_vector() { + self.expect_type(FlexBufferType::Vector)?; + }; + Ok(VectorReader { + reader: self.clone(), + length: self.length(), + }) + } +} + +impl fmt::Display for Reader { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + use FlexBufferType::*; + match self.flexbuffer_type() { + Null => write!(f, "null"), + UInt => write!(f, "{}", self.as_u64()), + Int => write!(f, "{}", self.as_i64()), + Float => write!(f, "{}", self.as_f64()), + Key | String => write!(f, "{:?}", &self.as_str() as &str), + Bool => write!(f, "{}", self.as_bool()), + Blob => write!(f, "blob"), + Map => { + write!(f, "{{")?; + let m = self.as_map(); + let mut pairs = m.iter_keys().zip(m.iter_values()); + if let Some((k, v)) = pairs.next() { + write!(f, "{:?}: {}", &k as &str, v)?; + for (k, v) in pairs { + write!(f, ", {:?}: {}", &k as &str, v)?; + } + } + write!(f, "}}") + } + t if t.is_vector() => { + write!(f, "[")?; + let mut elems = self.as_vector().iter(); + if let Some(first) = elems.next() { + write!(f, "{}", first)?; + for e in elems { + write!(f, ", {}", e)?; + } + } + write!(f, "]") + } + _ => unreachable!("Display not implemented for {:?}", self), + } + } +} + +// TODO(cneo): Use ::from_le_bytes when we move past rustc 1.39. +fn f32_from_le_bytes(bytes: [u8; 4]) -> f32 { + let bits = ::from_le_bytes(bytes); + ::from_bits(bits) +} + +fn f64_from_le_bytes(bytes: [u8; 8]) -> f64 { + let bits = ::from_le_bytes(bytes); + ::from_bits(bits) +} + +fn read_usize(buffer: &[u8], address: usize, width: BitWidth) -> usize { + let cursor = &buffer[address..]; + match width { + BitWidth::W8 => cursor[0] as usize, + BitWidth::W16 => cursor + .get(0..2) + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .unwrap_or_default() as usize, + BitWidth::W32 => cursor + .get(0..4) + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .unwrap_or_default() as usize, + BitWidth::W64 => cursor + .get(0..8) + .and_then(|s| s.try_into().ok()) + .map(::from_le_bytes) + .unwrap_or_default() as usize, + } +} + +fn unpack_type(ty: u8) -> Result<(FlexBufferType, BitWidth), Error> { + let w = BitWidth::try_from(ty & 3u8).map_err(|_| Error::InvalidPackedType)?; + let t = FlexBufferType::try_from(ty >> 2).map_err(|_| Error::InvalidPackedType)?; + Ok((t, w)) +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/reader/serialize.rs b/third_party/flatbuffers/rust/flexbuffers/src/reader/serialize.rs new file mode 100644 index 00000000000..b129da1260e --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/reader/serialize.rs @@ -0,0 +1,76 @@ +// Copyright 2021 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use crate::reader::Reader; +use crate::Buffer; +use crate::{BitWidth::*, FlexBufferType::*}; +use serde::ser; +use serde::ser::{SerializeMap, SerializeSeq}; + +impl ser::Serialize for &Reader { + fn serialize(&self, serializer: S) -> Result + where + S: ser::Serializer, + { + #[allow(deprecated)] + match (self.flexbuffer_type(), self.bitwidth()) { + (Null, _) => serializer.serialize_unit(), + (Int, W8) | (IndirectInt, W8) => serializer.serialize_i8(self.as_i8()), + (Int, W16) | (IndirectInt, W16) => serializer.serialize_i16(self.as_i16()), + (Int, W32) | (IndirectInt, W32) => serializer.serialize_i32(self.as_i32()), + (Int, W64) | (IndirectInt, W64) => serializer.serialize_i64(self.as_i64()), + (UInt, W8) | (IndirectUInt, W8) => serializer.serialize_u8(self.as_u8()), + (UInt, W16) | (IndirectUInt, W16) => serializer.serialize_u16(self.as_u16()), + (UInt, W32) | (IndirectUInt, W32) => serializer.serialize_u32(self.as_u32()), + (UInt, W64) | (IndirectUInt, W64) => serializer.serialize_u64(self.as_u64()), + (Float, W32) | (IndirectFloat, W32) => serializer.serialize_f32(self.as_f32()), + (Float, _) | (IndirectFloat, _) => serializer.serialize_f64(self.as_f64()), + (Bool, _) => serializer.serialize_bool(self.as_bool()), + (Key, _) | (String, _) => serializer.serialize_str(&self.as_str()), + (Map, _) => { + let m = self.as_map(); + let mut map_serializer = serializer.serialize_map(Some(m.len()))?; + for (k, v) in m.iter_keys().zip(m.iter_values()) { + map_serializer.serialize_key(&&k)?; + map_serializer.serialize_value(&&v)?; + } + map_serializer.end() + } + (Vector, _) + | (VectorInt, _) + | (VectorUInt, _) + | (VectorFloat, _) + | (VectorKey, _) + | (VectorString, _) + | (VectorBool, _) + | (VectorInt2, _) + | (VectorUInt2, _) + | (VectorFloat2, _) + | (VectorInt3, _) + | (VectorUInt3, _) + | (VectorFloat3, _) + | (VectorInt4, _) + | (VectorUInt4, _) + | (VectorFloat4, _) => { + let v = self.as_vector(); + let mut seq_serializer = serializer.serialize_seq(Some(v.len()))?; + for x in v.iter() { + seq_serializer.serialize_element(&&x)?; + } + seq_serializer.end() + } + (Blob, _) => serializer.serialize_bytes(&self.as_blob().0), + } + } +} diff --git a/third_party/flatbuffers/rust/flexbuffers/src/reader/vector.rs b/third_party/flatbuffers/rust/flexbuffers/src/reader/vector.rs new file mode 100644 index 00000000000..6b97e1057f2 --- /dev/null +++ b/third_party/flatbuffers/rust/flexbuffers/src/reader/vector.rs @@ -0,0 +1,92 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use super::{unpack_type, Error, Reader, ReaderIterator}; +use crate::{BitWidth, Buffer, FlexBufferType}; + +/// Allows indexing on any flexbuffer vector type, (heterogenous vector, typed vector, or fixed +/// length typed vector). +/// +/// VectorReaders may be indexed with usize, `index` returns a result type +/// which may indicate failure due to indexing out of bounds or bad data. `idx` returns a +/// Null Reader in the event of any failure. +pub struct VectorReader { + pub(super) reader: Reader, + // Cache the length because read_usize can be slow. + pub(super) length: usize, +} + +impl Clone for VectorReader { + fn clone(&self) -> Self { + VectorReader { + reader: self.reader.clone(), + ..*self + } + } +} + +impl Default for VectorReader { + fn default() -> Self { + VectorReader { + reader: Reader::default(), + length: usize::default(), + } + } +} + +impl VectorReader { + /// Returns the number of elements in the vector. + pub fn len(&self) -> usize { + self.length + } + /// Returns true if there are 0 elements in the vector. + pub fn is_empty(&self) -> bool { + self.length == 0 + } + fn get_elem_type(&self, i: usize) -> Result<(FlexBufferType, BitWidth), Error> { + if let Some(ty) = self.reader.fxb_type.typed_vector_type() { + Ok((ty, self.reader.width)) + } else { + let types_addr = self.reader.address + self.length * self.reader.width.n_bytes(); + self.reader + .buffer + .get(types_addr + i) + .ok_or(Error::FlexbufferOutOfBounds) + .and_then(|&t| unpack_type(t)) + } + } + /// Index into a flexbuffer vector. Any errors are defaulted to Null Readers. + pub fn idx(&self, i: usize) -> Reader { + self.index(i).unwrap_or_default() + } + /// Index into a flexbuffer. + pub fn index(&self, i: usize) -> Result, Error> { + if i >= self.length { + return Err(Error::IndexOutOfBounds); + } + let (fxb_type, bw) = self.get_elem_type(i)?; + let data_address = self.reader.address + self.reader.width.n_bytes() * i; + Reader::new( + self.reader.buffer.shallow_copy(), + data_address, + fxb_type, + bw, + self.reader.width, + ) + } + + pub fn iter(&self) -> ReaderIterator { + ReaderIterator::new(self.clone()) + } +} diff --git a/third_party/flatbuffers/rust/reflection/.gitignore b/third_party/flatbuffers/rust/reflection/.gitignore new file mode 100644 index 00000000000..96ef6c0b944 --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/third_party/flatbuffers/rust/reflection/Cargo.toml b/third_party/flatbuffers/rust/reflection/Cargo.toml new file mode 100644 index 00000000000..804fb68127a --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "flatbuffers-reflection" +version = "0.1.0" +edition = "2021" + +[dependencies] +flatbuffers = { path = "../flatbuffers"} +num-traits = "0.2.19" +anyhow = "1.0.75" +thiserror = "1.0" diff --git a/third_party/flatbuffers/rust/reflection/src/lib.rs b/third_party/flatbuffers/rust/reflection/src/lib.rs new file mode 100644 index 00000000000..f2ef413ae71 --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/src/lib.rs @@ -0,0 +1,1143 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +mod reflection_generated; +mod reflection_verifier; +mod safe_buffer; +mod r#struct; +pub use crate::r#struct::Struct; +pub use crate::reflection_generated::reflection; +pub use crate::safe_buffer::SafeBuffer; + +use flatbuffers::{ + emplace_scalar, read_scalar, EndianScalar, Follow, ForwardsUOffset, InvalidFlatbuffer, + SOffsetT, Table, UOffsetT, VOffsetT, Vector, SIZE_SOFFSET, SIZE_UOFFSET, +}; +use reflection_generated::reflection::{BaseType, Field, Object, Schema}; + +use core::mem::size_of; +use num_traits::float::Float; +use num_traits::int::PrimInt; +use num_traits::FromPrimitive; +use thiserror::Error; + +#[derive(Error, Debug, PartialEq)] +pub enum FlatbufferError { + #[error(transparent)] + VerificationError(#[from] flatbuffers::InvalidFlatbuffer), + #[error("Failed to convert between data type {0} and field type {1}")] + FieldTypeMismatch(String, String), + #[error("Set field value not supported for non-populated or non-scalar fields")] + SetValueNotSupported, + #[error(transparent)] + ParseFloatError(#[from] std::num::ParseFloatError), + #[error(transparent)] + TryFromIntError(#[from] std::num::TryFromIntError), + #[error("Couldn't set string because cache vector is polluted")] + SetStringPolluted, + #[error("Invalid schema: Polluted buffer or the schema doesn't match the buffer.")] + InvalidSchema, + #[error("Type not supported: {0}")] + TypeNotSupported(String), + #[error("No type or invalid type found in union enum")] + InvalidUnionEnum, + #[error("Table or Struct doesn't belong to the buffer")] + InvalidTableOrStruct, + #[error("Field not found in the table schema")] + FieldNotFound, +} + +pub type FlatbufferResult = core::result::Result; + +/// Gets the root table from a trusted Flatbuffer. +/// +/// # Safety +/// +/// Flatbuffers accessors do not perform validation checks before accessing. Users +/// must trust [data] contains a valid flatbuffer. Reading unchecked buffers may cause panics or even UB. +pub unsafe fn get_any_root(data: &[u8]) -> Table { + >::follow(data, 0) +} + +/// Gets an integer table field given its exact type. Returns default integer value if the field is not set. Returns [None] if no default value is found. Returns error if the type size doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type T +pub unsafe fn get_field_integer Follow<'a, Inner = T> + PrimInt + FromPrimitive>( + table: &Table, + field: &Field, +) -> FlatbufferResult> { + if size_of::() != get_type_size(field.type_().base_type()) { + return Err(FlatbufferError::FieldTypeMismatch( + std::any::type_name::().to_string(), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + let default = T::from_i64(field.default_integer()); + Ok(table.get::(field.offset(), default)) +} + +/// Gets a floating point table field given its exact type. Returns default float value if the field is not set. Returns [None] if no default value is found. Returns error if the type doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type T +pub unsafe fn get_field_float Follow<'a, Inner = T> + Float>( + table: &Table, + field: &Field, +) -> FlatbufferResult> { + if size_of::() != get_type_size(field.type_().base_type()) { + return Err(FlatbufferError::FieldTypeMismatch( + std::any::type_name::().to_string(), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + let default = T::from(field.default_real()); + Ok(table.get::(field.offset(), default)) +} + +/// Gets a String table field given its exact type. Returns empty string if the field is not set. Returns [None] if no default value is found. Returns error if the type size doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type String +pub unsafe fn get_field_string<'a>( + table: &Table<'a>, + field: &Field, +) -> FlatbufferResult> { + if field.type_().base_type() != BaseType::String { + return Err(FlatbufferError::FieldTypeMismatch( + String::from("String"), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + Ok(table.get::>(field.offset(), Some(""))) +} + +/// Gets a [Struct] table field given its exact type. Returns [None] if the field is not set. Returns error if the type doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type Struct +pub unsafe fn get_field_struct<'a>( + table: &Table<'a>, + field: &Field, +) -> FlatbufferResult>> { + // TODO inherited from C++: This does NOT check if the field is a table or struct, but we'd need + // access to the schema to check the is_struct flag. + if field.type_().base_type() != BaseType::Obj { + return Err(FlatbufferError::FieldTypeMismatch( + String::from("Obj"), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + Ok(table.get::(field.offset(), None)) +} + +/// Gets a Vector table field given its exact type. Returns empty vector if the field is not set. Returns error if the type doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type Vector +pub unsafe fn get_field_vector<'a, T: Follow<'a, Inner = T>>( + table: &Table<'a>, + field: &Field, +) -> FlatbufferResult>> { + if field.type_().base_type() != BaseType::Vector + || core::mem::size_of::() != get_type_size(field.type_().element()) + { + return Err(FlatbufferError::FieldTypeMismatch( + std::any::type_name::().to_string(), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + Ok(table.get::>>(field.offset(), Some(Vector::::default()))) +} + +/// Gets a Table table field given its exact type. Returns [None] if the field is not set. Returns error if the type doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type Table +pub unsafe fn get_field_table<'a>( + table: &Table<'a>, + field: &Field, +) -> FlatbufferResult>> { + if field.type_().base_type() != BaseType::Obj { + return Err(FlatbufferError::FieldTypeMismatch( + String::from("Obj"), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + Ok(table.get::>>(field.offset(), None)) +} + +/// Returns the value of any table field as a 64-bit int, regardless of what type it is. Returns default integer if the field is not set or error if the value cannot be parsed as integer. +/// [num_traits](https://docs.rs/num-traits/latest/num_traits/cast/trait.NumCast.html) is used for number casting. +/// +/// # Safety +/// +/// [table] must contain recursively valid offsets that match the [field]. +pub unsafe fn get_any_field_integer(table: &Table, field: &Field) -> FlatbufferResult { + if let Some(field_loc) = get_field_loc(table, field) { + get_any_value_integer(field.type_().base_type(), table.buf(), field_loc) + } else { + Ok(field.default_integer()) + } +} + +/// Returns the value of any table field as a 64-bit floating point, regardless of what type it is. Returns default float if the field is not set or error if the value cannot be parsed as float. +/// +/// # Safety +/// +/// [table] must contain recursively valid offsets that match the [field]. +pub unsafe fn get_any_field_float(table: &Table, field: &Field) -> FlatbufferResult { + if let Some(field_loc) = get_field_loc(table, field) { + get_any_value_float(field.type_().base_type(), table.buf(), field_loc) + } else { + Ok(field.default_real()) + } +} + +/// Returns the value of any table field as a string, regardless of what type it is. Returns empty string if the field is not set. +/// +/// # Safety +/// +/// [table] must contain recursively valid offsets that match the [field]. +pub unsafe fn get_any_field_string(table: &Table, field: &Field, schema: &Schema) -> String { + if let Some(field_loc) = get_field_loc(table, field) { + get_any_value_string( + field.type_().base_type(), + table.buf(), + field_loc, + schema, + field.type_().index() as usize, + ) + } else { + String::from("") + } +} + +/// Gets a [Struct] struct field given its exact type. Returns error if the type doesn't match. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type Struct. +pub unsafe fn get_field_struct_in_struct<'a>( + st: &Struct<'a>, + field: &Field, +) -> FlatbufferResult> { + // TODO inherited from C++: This does NOT check if the field is a table or struct, but we'd need + // access to the schema to check the is_struct flag. + if field.type_().base_type() != BaseType::Obj { + return Err(FlatbufferError::FieldTypeMismatch( + String::from("Obj"), + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + + Ok(st.get::(field.offset() as usize)) +} + +/// Returns the value of any struct field as a 64-bit int, regardless of what type it is. Returns error if the value cannot be parsed as integer. +/// +/// # Safety +/// +/// [st] must contain valid offsets that match the [field]. +pub unsafe fn get_any_field_integer_in_struct(st: &Struct, field: &Field) -> FlatbufferResult { + let field_loc = st.loc() + field.offset() as usize; + + get_any_value_integer(field.type_().base_type(), st.buf(), field_loc) +} + +/// Returns the value of any struct field as a 64-bit floating point, regardless of what type it is. Returns error if the value cannot be parsed as float. +/// +/// # Safety +/// +/// [st] must contain valid offsets that match the [field]. +pub unsafe fn get_any_field_float_in_struct(st: &Struct, field: &Field) -> FlatbufferResult { + let field_loc = st.loc() + field.offset() as usize; + + get_any_value_float(field.type_().base_type(), st.buf(), field_loc) +} + +/// Returns the value of any struct field as a string, regardless of what type it is. +/// +/// # Safety +/// +/// [st] must contain valid offsets that match the [field]. +pub unsafe fn get_any_field_string_in_struct( + st: &Struct, + field: &Field, + schema: &Schema, +) -> String { + let field_loc = st.loc() + field.offset() as usize; + + get_any_value_string( + field.type_().base_type(), + st.buf(), + field_loc, + schema, + field.type_().index() as usize, + ) +} + +/// Sets any table field with the value of a 64-bit integer. Returns error if the field is not originally set or is with non-scalar value or the provided value cannot be cast into the field type. +/// +/// # Safety +/// +/// [buf] must contain a valid root table and valid offset to it. +pub unsafe fn set_any_field_integer( + buf: &mut [u8], + table_loc: usize, + field: &Field, + v: i64, +) -> FlatbufferResult<()> { + let field_type = field.type_().base_type(); + let table = Table::follow(buf, table_loc); + + let Some(field_loc) = get_field_loc(&table, field) else { + return Err(FlatbufferError::SetValueNotSupported); + }; + + if !is_scalar(field_type) { + return Err(FlatbufferError::SetValueNotSupported); + } + + set_any_value_integer(field_type, buf, field_loc, v) +} + +/// Sets any table field with the value of a 64-bit floating point. Returns error if the field is not originally set or is with non-scalar value or the provided value cannot be cast into the field type. +/// +/// # Safety +/// +/// [buf] must contain a valid root table and valid offset to it. +pub unsafe fn set_any_field_float( + buf: &mut [u8], + table_loc: usize, + field: &Field, + v: f64, +) -> FlatbufferResult<()> { + let field_type = field.type_().base_type(); + let table = Table::follow(buf, table_loc); + + let Some(field_loc) = get_field_loc(&table, field) else { + return Err(FlatbufferError::SetValueNotSupported); + }; + + if !is_scalar(field_type) { + return Err(FlatbufferError::SetValueNotSupported); + } + + set_any_value_float(field_type, buf, field_loc, v) +} + +/// Sets any table field with the value of a string. Returns error if the field is not originally set or is with non-scalar value or the provided value cannot be parsed as the field type. +/// +/// # Safety +/// +/// [buf] must contain a valid root table and valid offset to it. +pub unsafe fn set_any_field_string( + buf: &mut [u8], + table_loc: usize, + field: &Field, + v: &str, +) -> FlatbufferResult<()> { + let field_type = field.type_().base_type(); + let table = Table::follow(buf, table_loc); + + let Some(field_loc) = get_field_loc(&table, field) else { + return Err(FlatbufferError::SetValueNotSupported); + }; + + if !is_scalar(field_type) { + return Err(FlatbufferError::SetValueNotSupported); + } + + set_any_value_float(field_type, buf, field_loc, v.parse::()?) +} + +/// Sets any scalar field given its exact type. Returns error if the field is not originally set or is with non-scalar value. +/// +/// # Safety +/// +/// [buf] must contain a valid root table and valid offset to it. +pub unsafe fn set_field( + buf: &mut [u8], + table_loc: usize, + field: &Field, + v: T, +) -> FlatbufferResult<()> { + let field_type = field.type_().base_type(); + let table = Table::follow(buf, table_loc); + + if !is_scalar(field_type) { + return Err(FlatbufferError::SetValueNotSupported); + } + + if core::mem::size_of::() != get_type_size(field_type) { + return Err(FlatbufferError::FieldTypeMismatch( + std::any::type_name::().to_string(), + field_type.variant_name().unwrap_or_default().to_string(), + )); + } + + let Some(field_loc) = get_field_loc(&table, field) else { + return Err(FlatbufferError::SetValueNotSupported); + }; + + if buf.len() < field_loc.saturating_add(get_type_size(field_type)) { + return Err(FlatbufferError::VerificationError( + InvalidFlatbuffer::RangeOutOfBounds { + range: core::ops::Range { + start: field_loc, + end: field_loc.saturating_add(get_type_size(field_type)), + }, + error_trace: Default::default(), + }, + )); + } + + // SAFETY: the buffer range was verified above. + unsafe { Ok(emplace_scalar::(&mut buf[field_loc..], v)) } +} + +/// Sets a string field to a new value. Returns error if the field is not originally set or is not of string type in which cases the [buf] stays intact. Returns error if the [buf] fails to be updated. +/// +/// # Safety +/// +/// [buf] must contain a valid root table and valid offset to it and conform to the [schema]. +pub unsafe fn set_string( + buf: &mut Vec, + table_loc: usize, + field: &Field, + v: &str, + schema: &Schema, +) -> FlatbufferResult<()> { + if v.is_empty() { + return Ok(()); + } + + let field_type = field.type_().base_type(); + if field_type != BaseType::String { + return Err(FlatbufferError::FieldTypeMismatch( + String::from("String"), + field_type.variant_name().unwrap_or_default().to_string(), + )); + } + + let table = Table::follow(buf, table_loc); + + let Some(field_loc) = get_field_loc(&table, field) else { + return Err(FlatbufferError::SetValueNotSupported); + }; + + if buf.len() < field_loc + get_type_size(field_type) { + return Err(FlatbufferError::VerificationError( + InvalidFlatbuffer::RangeOutOfBounds { + range: core::ops::Range { + start: field_loc, + end: field_loc.saturating_add(get_type_size(field_type)), + }, + error_trace: Default::default(), + }, + )); + } + + // SAFETY: the buffer range was verified above. + let string_loc = unsafe { deref_uoffset(buf, field_loc)? }; + if buf.len() < string_loc.saturating_add(SIZE_UOFFSET) { + return Err(FlatbufferError::VerificationError( + InvalidFlatbuffer::RangeOutOfBounds { + range: core::ops::Range { + start: string_loc, + end: string_loc.saturating_add(SIZE_UOFFSET), + }, + error_trace: Default::default(), + }, + )); + } + + // SAFETY: the buffer range was verified above. + let len_old = unsafe { read_uoffset(buf, string_loc) }; + if buf.len() + < string_loc + .saturating_add(SIZE_UOFFSET) + .saturating_add(len_old.try_into()?) + { + return Err(FlatbufferError::VerificationError( + InvalidFlatbuffer::RangeOutOfBounds { + range: core::ops::Range { + start: string_loc, + end: string_loc + .saturating_add(SIZE_UOFFSET) + .saturating_add(len_old.try_into()?), + }, + error_trace: Default::default(), + }, + )); + } + + let len_new = v.len(); + let delta = len_new as isize - len_old as isize; + let mut bytes_to_insert = v.as_bytes().to_vec(); + + if delta != 0 { + // Rounds the delta up to the nearest multiple of the maximum int size to keep the types after the insersion point aligned. + // stdint crate defines intmax_t as an alias for c_long; use it directly to avoid extra + // dependency. + let mask = (size_of::() - 1) as isize; + let offset = (delta + mask) & !mask; + let mut visited_vec = vec![false; buf.len()]; + + if offset != 0 { + update_offset( + buf, + table_loc, + &mut visited_vec, + &schema.root_table().unwrap(), + schema, + string_loc, + offset, + )?; + + // Sets the new length. + emplace_scalar::( + &mut buf[string_loc..string_loc + SIZE_UOFFSET], + len_new.try_into()?, + ); + } + + // Pads the bytes vector with 0 if `offset` doesn't equal `delta`. + bytes_to_insert.resize(bytes_to_insert.len() + (offset - delta) as usize, 0); + } + + // Replaces the data. + buf.splice( + string_loc + SIZE_SOFFSET..string_loc + SIZE_UOFFSET + usize::try_from(len_old)?, + bytes_to_insert, + ); + Ok(()) +} + +/// Returns the size of a scalar type in the `BaseType` enum. In the case of structs, returns the size of their offset (`UOffsetT`) in the buffer. +fn get_type_size(base_type: BaseType) -> usize { + match base_type { + BaseType::UType | BaseType::Bool | BaseType::Byte | BaseType::UByte => 1, + BaseType::Short | BaseType::UShort => 2, + BaseType::Int + | BaseType::UInt + | BaseType::Float + | BaseType::String + | BaseType::Vector + | BaseType::Obj + | BaseType::Union => 4, + BaseType::Long | BaseType::ULong | BaseType::Double | BaseType::Vector64 => 8, + _ => 0, + } +} + +/// Returns the absolute field location in the buffer and [None] if the field is not populated. +/// +/// # Safety +/// +/// [table] must contain a valid vtable. +unsafe fn get_field_loc(table: &Table, field: &Field) -> Option { + let field_offset = table.vtable().get(field.offset()) as usize; + if field_offset == 0 { + return None; + } + + Some(table.loc() + field_offset) +} + +/// Reads value as a 64-bit int from the provided byte slice at the specified location. Returns error if the value cannot be parsed as integer. +/// +/// # Safety +/// +/// Caller must ensure `buf.len() >= loc + size_of::()` at all the access layers. +unsafe fn get_any_value_integer( + base_type: BaseType, + buf: &[u8], + loc: usize, +) -> FlatbufferResult { + match base_type { + BaseType::UType | BaseType::UByte => i64::from_u8(u8::follow(buf, loc)), + BaseType::Bool => bool::follow(buf, loc).try_into().ok(), + BaseType::Byte => i64::from_i8(i8::follow(buf, loc)), + BaseType::Short => i64::from_i16(i16::follow(buf, loc)), + BaseType::UShort => i64::from_u16(u16::follow(buf, loc)), + BaseType::Int => i64::from_i32(i32::follow(buf, loc)), + BaseType::UInt => i64::from_u32(u32::follow(buf, loc)), + BaseType::Long => Some(i64::follow(buf, loc)), + BaseType::ULong => i64::from_u64(u64::follow(buf, loc)), + BaseType::Float => i64::from_f32(f32::follow(buf, loc)), + BaseType::Double => i64::from_f64(f64::follow(buf, loc)), + BaseType::String => ForwardsUOffset::<&str>::follow(buf, loc) + .parse::() + .ok(), + _ => None, // Tables & vectors do not make sense. + } + .ok_or(FlatbufferError::FieldTypeMismatch( + String::from("i64"), + base_type.variant_name().unwrap_or_default().to_string(), + )) +} + +/// Reads value as a 64-bit floating point from the provided byte slice at the specified location. Returns error if the value cannot be parsed as float. +/// +/// # Safety +/// +/// Caller must ensure `buf.len() >= loc + size_of::()` at all the access layers. +unsafe fn get_any_value_float( + base_type: BaseType, + buf: &[u8], + loc: usize, +) -> FlatbufferResult { + match base_type { + BaseType::UType | BaseType::UByte => f64::from_u8(u8::follow(buf, loc)), + BaseType::Bool => bool::follow(buf, loc).try_into().ok(), + BaseType::Byte => f64::from_i8(i8::follow(buf, loc)), + BaseType::Short => f64::from_i16(i16::follow(buf, loc)), + BaseType::UShort => f64::from_u16(u16::follow(buf, loc)), + BaseType::Int => f64::from_i32(i32::follow(buf, loc)), + BaseType::UInt => f64::from_u32(u32::follow(buf, loc)), + BaseType::Long => f64::from_i64(i64::follow(buf, loc)), + BaseType::ULong => f64::from_u64(u64::follow(buf, loc)), + BaseType::Float => f64::from_f32(f32::follow(buf, loc)), + BaseType::Double => Some(f64::follow(buf, loc)), + BaseType::String => ForwardsUOffset::<&str>::follow(buf, loc) + .parse::() + .ok(), + _ => None, + } + .ok_or(FlatbufferError::FieldTypeMismatch( + String::from("f64"), + base_type.variant_name().unwrap_or_default().to_string(), + )) +} + +/// Reads value as a string from the provided byte slice at the specified location. +/// +/// # Safety +/// +/// Caller must ensure `buf.len() >= loc + size_of::()` at all the access layers. +unsafe fn get_any_value_string( + base_type: BaseType, + buf: &[u8], + loc: usize, + schema: &Schema, + type_index: usize, +) -> String { + match base_type { + BaseType::Float | BaseType::Double => get_any_value_float(base_type, buf, loc) + .unwrap_or_default() + .to_string(), + BaseType::String => { + String::from_utf8_lossy(ForwardsUOffset::<&[u8]>::follow(buf, loc)).to_string() + } + BaseType::Obj => { + // Converts the table to a string. This is mostly for debugging purposes, + // and does NOT promise to be JSON compliant. + // Also prefixes the type. + let object: Object = schema.objects().get(type_index); + let mut s = object.name().to_string(); + s += " { "; + if object.is_struct() { + let st: Struct<'_> = Struct::follow(buf, loc); + for field in object.fields() { + let field_value = get_any_field_string_in_struct(&st, &field, schema); + s += field.name(); + s += ": "; + s += field_value.as_str(); + s += ", "; + } + } else { + let table = ForwardsUOffset::::follow(buf, loc); + for field in object.fields() { + if table.vtable().get(field.offset()) == 0 { + continue; + } + let mut field_value = get_any_field_string(&table, &field, schema); + if field.type_().base_type() == BaseType::String { + // Escape the string + field_value = format!("{:?}", field_value.as_str()); + } + s += field.name(); + s += ": "; + s += field_value.as_str(); + s += ", "; + } + } + s + "}" + } + BaseType::Vector => String::from("[(elements)]"), // TODO inherited from C++: implement this as well. + BaseType::Union => String::from("(union)"), // TODO inherited from C++: implement this as well. + _ => get_any_value_integer(base_type, buf, loc) + .unwrap_or_default() + .to_string(), + } +} + +/// Sets any scalar value with a 64-bit integer. Returns error if the value is not successfully replaced. +fn set_any_value_integer( + base_type: BaseType, + buf: &mut [u8], + field_loc: usize, + v: i64, +) -> FlatbufferResult<()> { + if buf.len() < get_type_size(base_type) { + return Err(FlatbufferError::VerificationError( + InvalidFlatbuffer::RangeOutOfBounds { + range: core::ops::Range { + start: field_loc, + end: field_loc.saturating_add(get_type_size(base_type)), + }, + error_trace: Default::default(), + }, + )); + } + let buf = &mut buf[field_loc..]; + let type_name = base_type.variant_name().unwrap_or_default().to_string(); + + macro_rules! try_emplace { + ($ty:ty, $value:expr) => { + if let Ok(v) = TryInto::<$ty>::try_into($value) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { Ok(emplace_scalar::<$ty>(buf, v)) } + } else { + Err(FlatbufferError::FieldTypeMismatch( + String::from("i64"), + type_name, + )) + } + }; + } + + match base_type { + BaseType::UType | BaseType::UByte => { + try_emplace!(u8, v) + } + BaseType::Bool => { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { Ok(emplace_scalar::(buf, v != 0)) } + } + BaseType::Byte => { + try_emplace!(i8, v) + } + BaseType::Short => { + try_emplace!(i16, v) + } + BaseType::UShort => { + try_emplace!(u16, v) + } + BaseType::Int => { + try_emplace!(i32, v) + } + BaseType::UInt => { + try_emplace!(u32, v) + } + BaseType::Long => { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { Ok(emplace_scalar::(buf, v)) } + } + BaseType::ULong => { + try_emplace!(u64, v) + } + BaseType::Float => { + if let Some(value) = f32::from_i64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { Ok(emplace_scalar::(buf, value)) } + } else { + Err(FlatbufferError::FieldTypeMismatch( + String::from("i64"), + type_name, + )) + } + } + BaseType::Double => { + if let Some(value) = f64::from_i64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { Ok(emplace_scalar::(buf, value)) } + } else { + Err(FlatbufferError::FieldTypeMismatch( + String::from("i64"), + type_name, + )) + } + } + _ => Err(FlatbufferError::SetValueNotSupported), + } +} + +/// Sets any scalar value with a 64-bit floating point. Returns error if the value is not successfully replaced. +fn set_any_value_float( + base_type: BaseType, + buf: &mut [u8], + field_loc: usize, + v: f64, +) -> FlatbufferResult<()> { + if buf.len() < get_type_size(base_type) { + return Err(FlatbufferError::VerificationError( + InvalidFlatbuffer::RangeOutOfBounds { + range: core::ops::Range { + start: field_loc, + end: field_loc.saturating_add(get_type_size(base_type)), + }, + error_trace: Default::default(), + }, + )); + } + let buf = &mut buf[field_loc..]; + let type_name = base_type.variant_name().unwrap_or_default().to_string(); + + match base_type { + BaseType::UType | BaseType::UByte => { + if let Some(value) = u8::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::Bool => { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, v != 0f64)); + } + } + BaseType::Byte => { + if let Some(value) = i8::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::Short => { + if let Some(value) = i16::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::UShort => { + if let Some(value) = u16::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::Int => { + if let Some(value) = i32::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::UInt => { + if let Some(value) = u32::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::Long => { + if let Some(value) = i64::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::ULong => { + if let Some(value) = u64::from_f64(v) { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + BaseType::Float => { + if let Some(value) = f32::from_f64(v) { + // Value converted to inf if overflow occurs + if value != f32::INFINITY { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, value)); + } + } + } + } + BaseType::Double => { + // SAFETY: buffer size is verified at the beginning of this function. + unsafe { + return Ok(emplace_scalar::(buf, v)); + } + } + _ => return Err(FlatbufferError::SetValueNotSupported), + } + return Err(FlatbufferError::FieldTypeMismatch( + String::from("f64"), + type_name, + )); +} + +fn is_scalar(base_type: BaseType) -> bool { + return base_type <= BaseType::Double; +} + +/// Iterates through the buffer and updates all the relative offsets affected by the insertion. +/// +/// # Safety +/// +/// Caller must ensure [buf] contains valid data that conforms to [schema]. +unsafe fn update_offset( + buf: &mut [u8], + table_loc: usize, + updated: &mut [bool], + object: &Object, + schema: &Schema, + insertion_loc: usize, + offset: isize, +) -> FlatbufferResult<()> { + if updated.len() != buf.len() { + return Err(FlatbufferError::SetStringPolluted); + } + + if updated[table_loc] { + return Ok(()); + } + + let slice = &mut buf[table_loc..table_loc + SIZE_SOFFSET]; + let vtable_offset = isize::try_from(read_scalar::(slice))?; + let vtable_loc = (isize::try_from(table_loc)? - vtable_offset).try_into()?; + + if insertion_loc <= table_loc { + // Checks if insertion point is between the table and a vtable that + // precedes it. + if (vtable_loc..table_loc).contains(&insertion_loc) { + emplace_scalar::(slice, (vtable_offset + offset).try_into()?); + updated[table_loc] = true; + } + + // Early out: since all fields inside the table must point forwards in + // memory, if the insertion point is before the table we can stop here. + return Ok(()); + } + + for field in object.fields() { + let field_type = field.type_().base_type(); + if is_scalar(field_type) { + continue; + } + + let field_offset = VOffsetT::follow(buf, vtable_loc.saturating_add(field.offset().into())); + if field_offset == 0 { + continue; + } + + let field_loc = table_loc + usize::from(field_offset); + if updated[field_loc] { + continue; + } + + if field_type == BaseType::Obj + && schema + .objects() + .get(field.type_().index().try_into()?) + .is_struct() + { + continue; + } + + // Updates the relative offset from table to actual data if needed + let slice = &mut buf[field_loc..field_loc + SIZE_UOFFSET]; + let field_value_offset = read_scalar::(slice); + let field_value_loc = field_loc.saturating_add(field_value_offset.try_into()?); + if (field_loc..field_value_loc).contains(&insertion_loc) { + emplace_scalar::( + slice, + (isize::try_from(field_value_offset)? + offset).try_into()?, + ); + updated[field_loc] = true; + } + + match field_type { + BaseType::Obj => { + let field_obj = schema.objects().get(field.type_().index().try_into()?); + update_offset( + buf, + field_value_loc, + updated, + &field_obj, + schema, + insertion_loc, + offset, + )?; + } + BaseType::Vector => { + let elem_type = field.type_().element(); + if elem_type != BaseType::Obj || elem_type != BaseType::String { + continue; + } + if elem_type == BaseType::Obj + && schema + .objects() + .get(field.type_().index().try_into()?) + .is_struct() + { + continue; + } + let vec_size = usize::try_from(read_uoffset(buf, field_value_loc))?; + for index in 0..vec_size { + let elem_loc = field_value_loc + SIZE_UOFFSET + index * SIZE_UOFFSET; + if updated[elem_loc] { + continue; + } + let slice = &mut buf[elem_loc..elem_loc + SIZE_UOFFSET]; + let elem_value_offset = read_scalar::(slice); + let elem_value_loc = elem_loc.saturating_add(elem_value_offset.try_into()?); + if (elem_loc..elem_value_loc).contains(&insertion_loc) { + emplace_scalar::( + slice, + (isize::try_from(elem_value_offset)? + offset).try_into()?, + ); + updated[elem_loc] = true; + } + + if elem_type == BaseType::Obj { + let elem_obj = schema.objects().get(field.type_().index().try_into()?); + update_offset( + buf, + elem_value_loc, + updated, + &elem_obj, + schema, + insertion_loc, + offset, + )?; + } + } + } + BaseType::Union => { + let union_enum = schema.enums().get(field.type_().index().try_into()?); + let union_type = object + .fields() + .lookup_by_key(field.name().to_string() + "_type", |field, key| { + field.key_compare_with_value(key) + }) + .unwrap(); + let union_type_loc = vtable_loc.saturating_add(union_type.offset().into()); + let union_type_offset = VOffsetT::follow(buf, union_type_loc); + let union_type_value = + u8::follow(buf, table_loc.saturating_add(union_type_offset.into())); + let union_enum_value = union_enum + .values() + .lookup_by_key(union_type_value.into(), |value, key| { + value.key_compare_with_value(*key) + }) + .unwrap(); + let union_object = schema + .objects() + .get(union_enum_value.union_type().unwrap().index().try_into()?); + update_offset( + buf, + field_value_loc, + updated, + &union_object, + schema, + insertion_loc, + offset, + )?; + } + _ => (), + } + } + + // Checks if the vtable offset points beyond the insertion point. + if (table_loc..vtable_loc).contains(&insertion_loc) { + let slice = &mut buf[table_loc..table_loc + SIZE_SOFFSET]; + emplace_scalar::(slice, (vtable_offset - offset).try_into()?); + updated[table_loc] = true; + } + Ok(()) +} + +/// Returns the absolute location of the data (e.g. string) in the buffer when the field contains relative offset (`UOffsetT`) to the data. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type `UOffsetT`. +unsafe fn deref_uoffset(buf: &[u8], field_loc: usize) -> FlatbufferResult { + Ok(field_loc.saturating_add(read_uoffset(buf, field_loc).try_into()?)) +} + +/// Reads the value of `UOffsetT` at the give location. +/// +/// # Safety +/// +/// The value of the corresponding slot must have type `UOffsetT`. +unsafe fn read_uoffset(buf: &[u8], loc: usize) -> UOffsetT { + let slice = &buf[loc..loc + SIZE_UOFFSET]; + read_scalar::(slice) +} diff --git a/third_party/flatbuffers/rust/reflection/src/reflection_generated.rs b/third_party/flatbuffers/rust/reflection/src/reflection_generated.rs new file mode 100644 index 00000000000..84581e82c57 --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/src/reflection_generated.rs @@ -0,0 +1,2285 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +// @generated + +use core::mem; +use core::cmp::Ordering; + +extern crate flatbuffers; +use self::flatbuffers::{EndianScalar, Follow}; + +#[allow(unused_imports, dead_code)] +pub mod reflection { + + use core::mem; + use core::cmp::Ordering; + + extern crate flatbuffers; + use self::flatbuffers::{EndianScalar, Follow}; + +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_BASE_TYPE: i8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_BASE_TYPE: i8 = 19; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_BASE_TYPE: [BaseType; 20] = [ + BaseType::None, + BaseType::UType, + BaseType::Bool, + BaseType::Byte, + BaseType::UByte, + BaseType::Short, + BaseType::UShort, + BaseType::Int, + BaseType::UInt, + BaseType::Long, + BaseType::ULong, + BaseType::Float, + BaseType::Double, + BaseType::String, + BaseType::Vector, + BaseType::Obj, + BaseType::Union, + BaseType::Array, + BaseType::Vector64, + BaseType::MaxBaseType, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct BaseType(pub i8); +#[allow(non_upper_case_globals)] +impl BaseType { + pub const None: Self = Self(0); + pub const UType: Self = Self(1); + pub const Bool: Self = Self(2); + pub const Byte: Self = Self(3); + pub const UByte: Self = Self(4); + pub const Short: Self = Self(5); + pub const UShort: Self = Self(6); + pub const Int: Self = Self(7); + pub const UInt: Self = Self(8); + pub const Long: Self = Self(9); + pub const ULong: Self = Self(10); + pub const Float: Self = Self(11); + pub const Double: Self = Self(12); + pub const String: Self = Self(13); + pub const Vector: Self = Self(14); + pub const Obj: Self = Self(15); + pub const Union: Self = Self(16); + pub const Array: Self = Self(17); + pub const Vector64: Self = Self(18); + pub const MaxBaseType: Self = Self(19); + + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 19; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::UType, + Self::Bool, + Self::Byte, + Self::UByte, + Self::Short, + Self::UShort, + Self::Int, + Self::UInt, + Self::Long, + Self::ULong, + Self::Float, + Self::Double, + Self::String, + Self::Vector, + Self::Obj, + Self::Union, + Self::Array, + Self::Vector64, + Self::MaxBaseType, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::UType => Some("UType"), + Self::Bool => Some("Bool"), + Self::Byte => Some("Byte"), + Self::UByte => Some("UByte"), + Self::Short => Some("Short"), + Self::UShort => Some("UShort"), + Self::Int => Some("Int"), + Self::UInt => Some("UInt"), + Self::Long => Some("Long"), + Self::ULong => Some("ULong"), + Self::Float => Some("Float"), + Self::Double => Some("Double"), + Self::String => Some("String"), + Self::Vector => Some("Vector"), + Self::Obj => Some("Obj"), + Self::Union => Some("Union"), + Self::Array => Some("Array"), + Self::Vector64 => Some("Vector64"), + Self::MaxBaseType => Some("MaxBaseType"), + _ => None, + } + } +} +impl core::fmt::Debug for BaseType { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for BaseType { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for BaseType { + type Output = BaseType; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for BaseType { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for BaseType { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for BaseType {} +#[allow(non_upper_case_globals)] +mod bitflags_advanced_features { + flatbuffers::bitflags::bitflags! { + /// New schema language features that are not supported by old code generators. + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct AdvancedFeatures: u64 { + const AdvancedArrayFeatures = 1; + const AdvancedUnionFeatures = 2; + const OptionalScalars = 4; + const DefaultVectorsAndStrings = 8; + } + } +} +pub use self::bitflags_advanced_features::AdvancedFeatures; + +impl<'a> flatbuffers::Follow<'a> for AdvancedFeatures { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self::from_bits_retain(b) + } +} + +impl flatbuffers::Push for AdvancedFeatures { + type Output = AdvancedFeatures; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.bits()); + } +} + +impl flatbuffers::EndianScalar for AdvancedFeatures { + type Scalar = u64; + #[inline] + fn to_little_endian(self) -> u64 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u64) -> Self { + let b = u64::from_le(v); + Self::from_bits_retain(b) + } +} + +impl<'a> flatbuffers::Verifiable for AdvancedFeatures { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for AdvancedFeatures {} +pub enum TypeOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Type<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Type<'a> { + type Inner = Type<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Type<'a> { + pub const VT_BASE_TYPE: flatbuffers::VOffsetT = 4; + pub const VT_ELEMENT: flatbuffers::VOffsetT = 6; + pub const VT_INDEX: flatbuffers::VOffsetT = 8; + pub const VT_FIXED_LENGTH: flatbuffers::VOffsetT = 10; + pub const VT_BASE_SIZE: flatbuffers::VOffsetT = 12; + pub const VT_ELEMENT_SIZE: flatbuffers::VOffsetT = 14; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Type { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TypeArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = TypeBuilder::new(_fbb); + builder.add_element_size(args.element_size); + builder.add_base_size(args.base_size); + builder.add_index(args.index); + builder.add_fixed_length(args.fixed_length); + builder.add_element(args.element); + builder.add_base_type(args.base_type); + builder.finish() + } + + + #[inline] + pub fn base_type(&self) -> BaseType { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Type::VT_BASE_TYPE, Some(BaseType::None)).unwrap()} + } + #[inline] + pub fn element(&self) -> BaseType { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Type::VT_ELEMENT, Some(BaseType::None)).unwrap()} + } + #[inline] + pub fn index(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Type::VT_INDEX, Some(-1)).unwrap()} + } + #[inline] + pub fn fixed_length(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Type::VT_FIXED_LENGTH, Some(0)).unwrap()} + } + /// The size (octets) of the `base_type` field. + #[inline] + pub fn base_size(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Type::VT_BASE_SIZE, Some(4)).unwrap()} + } + /// The size (octets) of the `element` field, if present. + #[inline] + pub fn element_size(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Type::VT_ELEMENT_SIZE, Some(0)).unwrap()} + } +} + +impl flatbuffers::Verifiable for Type<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("base_type", Self::VT_BASE_TYPE, false)? + .visit_field::("element", Self::VT_ELEMENT, false)? + .visit_field::("index", Self::VT_INDEX, false)? + .visit_field::("fixed_length", Self::VT_FIXED_LENGTH, false)? + .visit_field::("base_size", Self::VT_BASE_SIZE, false)? + .visit_field::("element_size", Self::VT_ELEMENT_SIZE, false)? + .finish(); + Ok(()) + } +} +pub struct TypeArgs { + pub base_type: BaseType, + pub element: BaseType, + pub index: i32, + pub fixed_length: u16, + pub base_size: u32, + pub element_size: u32, +} +impl<'a> Default for TypeArgs { + #[inline] + fn default() -> Self { + TypeArgs { + base_type: BaseType::None, + element: BaseType::None, + index: -1, + fixed_length: 0, + base_size: 4, + element_size: 0, + } + } +} + +pub struct TypeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TypeBuilder<'a, 'b, A> { + #[inline] + pub fn add_base_type(&mut self, base_type: BaseType) { + self.fbb_.push_slot::(Type::VT_BASE_TYPE, base_type, BaseType::None); + } + #[inline] + pub fn add_element(&mut self, element: BaseType) { + self.fbb_.push_slot::(Type::VT_ELEMENT, element, BaseType::None); + } + #[inline] + pub fn add_index(&mut self, index: i32) { + self.fbb_.push_slot::(Type::VT_INDEX, index, -1); + } + #[inline] + pub fn add_fixed_length(&mut self, fixed_length: u16) { + self.fbb_.push_slot::(Type::VT_FIXED_LENGTH, fixed_length, 0); + } + #[inline] + pub fn add_base_size(&mut self, base_size: u32) { + self.fbb_.push_slot::(Type::VT_BASE_SIZE, base_size, 4); + } + #[inline] + pub fn add_element_size(&mut self, element_size: u32) { + self.fbb_.push_slot::(Type::VT_ELEMENT_SIZE, element_size, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TypeBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TypeBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Type<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Type"); + ds.field("base_type", &self.base_type()); + ds.field("element", &self.element()); + ds.field("index", &self.index()); + ds.field("fixed_length", &self.fixed_length()); + ds.field("base_size", &self.base_size()); + ds.field("element_size", &self.element_size()); + ds.finish() + } +} +pub enum KeyValueOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct KeyValue<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for KeyValue<'a> { + type Inner = KeyValue<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> KeyValue<'a> { + pub const VT_KEY: flatbuffers::VOffsetT = 4; + pub const VT_VALUE: flatbuffers::VOffsetT = 6; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + KeyValue { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args KeyValueArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = KeyValueBuilder::new(_fbb); + if let Some(x) = args.value { builder.add_value(x); } + if let Some(x) = args.key { builder.add_key(x); } + builder.finish() + } + + + #[inline] + pub fn key(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(KeyValue::VT_KEY, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &KeyValue) -> bool { + self.key() < o.key() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.key(); + key.cmp(val) + } + #[inline] + pub fn value(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(KeyValue::VT_VALUE, None)} + } +} + +impl flatbuffers::Verifiable for KeyValue<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("key", Self::VT_KEY, true)? + .visit_field::>("value", Self::VT_VALUE, false)? + .finish(); + Ok(()) + } +} +pub struct KeyValueArgs<'a> { + pub key: Option>, + pub value: Option>, +} +impl<'a> Default for KeyValueArgs<'a> { + #[inline] + fn default() -> Self { + KeyValueArgs { + key: None, // required field + value: None, + } + } +} + +pub struct KeyValueBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> KeyValueBuilder<'a, 'b, A> { + #[inline] + pub fn add_key(&mut self, key: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(KeyValue::VT_KEY, key); + } + #[inline] + pub fn add_value(&mut self, value: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(KeyValue::VT_VALUE, value); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> KeyValueBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + KeyValueBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, KeyValue::VT_KEY,"key"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for KeyValue<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("KeyValue"); + ds.field("key", &self.key()); + ds.field("value", &self.value()); + ds.finish() + } +} +pub enum EnumValOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct EnumVal<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for EnumVal<'a> { + type Inner = EnumVal<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> EnumVal<'a> { + pub const VT_NAME: flatbuffers::VOffsetT = 4; + pub const VT_VALUE: flatbuffers::VOffsetT = 6; + pub const VT_UNION_TYPE: flatbuffers::VOffsetT = 10; + pub const VT_DOCUMENTATION: flatbuffers::VOffsetT = 12; + pub const VT_ATTRIBUTES: flatbuffers::VOffsetT = 14; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + EnumVal { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args EnumValArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = EnumValBuilder::new(_fbb); + builder.add_value(args.value); + if let Some(x) = args.attributes { builder.add_attributes(x); } + if let Some(x) = args.documentation { builder.add_documentation(x); } + if let Some(x) = args.union_type { builder.add_union_type(x); } + if let Some(x) = args.name { builder.add_name(x); } + builder.finish() + } + + + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(EnumVal::VT_NAME, None).unwrap()} + } + #[inline] + pub fn value(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(EnumVal::VT_VALUE, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &EnumVal) -> bool { + self.value() < o.value() + } + + #[inline] + pub fn key_compare_with_value(&self, val: i64) -> ::core::cmp::Ordering { + let key = self.value(); + key.cmp(&val) + } + #[inline] + pub fn union_type(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(EnumVal::VT_UNION_TYPE, None)} + } + #[inline] + pub fn documentation(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(EnumVal::VT_DOCUMENTATION, None)} + } + #[inline] + pub fn attributes(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(EnumVal::VT_ATTRIBUTES, None)} + } +} + +impl flatbuffers::Verifiable for EnumVal<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::("value", Self::VT_VALUE, false)? + .visit_field::>("union_type", Self::VT_UNION_TYPE, false)? + .visit_field::>>>("documentation", Self::VT_DOCUMENTATION, false)? + .visit_field::>>>("attributes", Self::VT_ATTRIBUTES, false)? + .finish(); + Ok(()) + } +} +pub struct EnumValArgs<'a> { + pub name: Option>, + pub value: i64, + pub union_type: Option>>, + pub documentation: Option>>>, + pub attributes: Option>>>>, +} +impl<'a> Default for EnumValArgs<'a> { + #[inline] + fn default() -> Self { + EnumValArgs { + name: None, // required field + value: 0, + union_type: None, + documentation: None, + attributes: None, + } + } +} + +pub struct EnumValBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> EnumValBuilder<'a, 'b, A> { + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(EnumVal::VT_NAME, name); + } + #[inline] + pub fn add_value(&mut self, value: i64) { + self.fbb_.push_slot::(EnumVal::VT_VALUE, value, 0); + } + #[inline] + pub fn add_union_type(&mut self, union_type: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(EnumVal::VT_UNION_TYPE, union_type); + } + #[inline] + pub fn add_documentation(&mut self, documentation: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(EnumVal::VT_DOCUMENTATION, documentation); + } + #[inline] + pub fn add_attributes(&mut self, attributes: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(EnumVal::VT_ATTRIBUTES, attributes); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> EnumValBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + EnumValBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, EnumVal::VT_NAME,"name"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for EnumVal<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("EnumVal"); + ds.field("name", &self.name()); + ds.field("value", &self.value()); + ds.field("union_type", &self.union_type()); + ds.field("documentation", &self.documentation()); + ds.field("attributes", &self.attributes()); + ds.finish() + } +} +pub enum EnumOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Enum<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Enum<'a> { + type Inner = Enum<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Enum<'a> { + pub const VT_NAME: flatbuffers::VOffsetT = 4; + pub const VT_VALUES: flatbuffers::VOffsetT = 6; + pub const VT_IS_UNION: flatbuffers::VOffsetT = 8; + pub const VT_UNDERLYING_TYPE: flatbuffers::VOffsetT = 10; + pub const VT_ATTRIBUTES: flatbuffers::VOffsetT = 12; + pub const VT_DOCUMENTATION: flatbuffers::VOffsetT = 14; + pub const VT_DECLARATION_FILE: flatbuffers::VOffsetT = 16; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Enum { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args EnumArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = EnumBuilder::new(_fbb); + if let Some(x) = args.declaration_file { builder.add_declaration_file(x); } + if let Some(x) = args.documentation { builder.add_documentation(x); } + if let Some(x) = args.attributes { builder.add_attributes(x); } + if let Some(x) = args.underlying_type { builder.add_underlying_type(x); } + if let Some(x) = args.values { builder.add_values(x); } + if let Some(x) = args.name { builder.add_name(x); } + builder.add_is_union(args.is_union); + builder.finish() + } + + + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Enum::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Enum) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn values(&self) -> flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Enum::VT_VALUES, None).unwrap()} + } + #[inline] + pub fn is_union(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Enum::VT_IS_UNION, Some(false)).unwrap()} + } + #[inline] + pub fn underlying_type(&self) -> Type<'a> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Enum::VT_UNDERLYING_TYPE, None).unwrap()} + } + #[inline] + pub fn attributes(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Enum::VT_ATTRIBUTES, None)} + } + #[inline] + pub fn documentation(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Enum::VT_DOCUMENTATION, None)} + } + /// File that this Enum is declared in. + #[inline] + pub fn declaration_file(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Enum::VT_DECLARATION_FILE, None)} + } +} + +impl flatbuffers::Verifiable for Enum<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>>>("values", Self::VT_VALUES, true)? + .visit_field::("is_union", Self::VT_IS_UNION, false)? + .visit_field::>("underlying_type", Self::VT_UNDERLYING_TYPE, true)? + .visit_field::>>>("attributes", Self::VT_ATTRIBUTES, false)? + .visit_field::>>>("documentation", Self::VT_DOCUMENTATION, false)? + .visit_field::>("declaration_file", Self::VT_DECLARATION_FILE, false)? + .finish(); + Ok(()) + } +} +pub struct EnumArgs<'a> { + pub name: Option>, + pub values: Option>>>>, + pub is_union: bool, + pub underlying_type: Option>>, + pub attributes: Option>>>>, + pub documentation: Option>>>, + pub declaration_file: Option>, +} +impl<'a> Default for EnumArgs<'a> { + #[inline] + fn default() -> Self { + EnumArgs { + name: None, // required field + values: None, // required field + is_union: false, + underlying_type: None, // required field + attributes: None, + documentation: None, + declaration_file: None, + } + } +} + +pub struct EnumBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> EnumBuilder<'a, 'b, A> { + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Enum::VT_NAME, name); + } + #[inline] + pub fn add_values(&mut self, values: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Enum::VT_VALUES, values); + } + #[inline] + pub fn add_is_union(&mut self, is_union: bool) { + self.fbb_.push_slot::(Enum::VT_IS_UNION, is_union, false); + } + #[inline] + pub fn add_underlying_type(&mut self, underlying_type: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Enum::VT_UNDERLYING_TYPE, underlying_type); + } + #[inline] + pub fn add_attributes(&mut self, attributes: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Enum::VT_ATTRIBUTES, attributes); + } + #[inline] + pub fn add_documentation(&mut self, documentation: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Enum::VT_DOCUMENTATION, documentation); + } + #[inline] + pub fn add_declaration_file(&mut self, declaration_file: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Enum::VT_DECLARATION_FILE, declaration_file); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> EnumBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + EnumBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Enum::VT_NAME,"name"); + self.fbb_.required(o, Enum::VT_VALUES,"values"); + self.fbb_.required(o, Enum::VT_UNDERLYING_TYPE,"underlying_type"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Enum<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Enum"); + ds.field("name", &self.name()); + ds.field("values", &self.values()); + ds.field("is_union", &self.is_union()); + ds.field("underlying_type", &self.underlying_type()); + ds.field("attributes", &self.attributes()); + ds.field("documentation", &self.documentation()); + ds.field("declaration_file", &self.declaration_file()); + ds.finish() + } +} +pub enum FieldOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Field<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Field<'a> { + type Inner = Field<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Field<'a> { + pub const VT_NAME: flatbuffers::VOffsetT = 4; + pub const VT_TYPE_: flatbuffers::VOffsetT = 6; + pub const VT_ID: flatbuffers::VOffsetT = 8; + pub const VT_OFFSET: flatbuffers::VOffsetT = 10; + pub const VT_DEFAULT_INTEGER: flatbuffers::VOffsetT = 12; + pub const VT_DEFAULT_REAL: flatbuffers::VOffsetT = 14; + pub const VT_DEPRECATED: flatbuffers::VOffsetT = 16; + pub const VT_REQUIRED: flatbuffers::VOffsetT = 18; + pub const VT_KEY: flatbuffers::VOffsetT = 20; + pub const VT_ATTRIBUTES: flatbuffers::VOffsetT = 22; + pub const VT_DOCUMENTATION: flatbuffers::VOffsetT = 24; + pub const VT_OPTIONAL: flatbuffers::VOffsetT = 26; + pub const VT_PADDING: flatbuffers::VOffsetT = 28; + pub const VT_OFFSET64: flatbuffers::VOffsetT = 30; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Field { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args FieldArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = FieldBuilder::new(_fbb); + builder.add_default_real(args.default_real); + builder.add_default_integer(args.default_integer); + if let Some(x) = args.documentation { builder.add_documentation(x); } + if let Some(x) = args.attributes { builder.add_attributes(x); } + if let Some(x) = args.type_ { builder.add_type_(x); } + if let Some(x) = args.name { builder.add_name(x); } + builder.add_padding(args.padding); + builder.add_offset(args.offset); + builder.add_id(args.id); + builder.add_offset64(args.offset64); + builder.add_optional(args.optional); + builder.add_key(args.key); + builder.add_required(args.required); + builder.add_deprecated(args.deprecated); + builder.finish() + } + + + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Field::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Field) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn type_(&self) -> Type<'a> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Field::VT_TYPE_, None).unwrap()} + } + #[inline] + pub fn id(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_ID, Some(0)).unwrap()} + } + #[inline] + pub fn offset(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_OFFSET, Some(0)).unwrap()} + } + #[inline] + pub fn default_integer(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_DEFAULT_INTEGER, Some(0)).unwrap()} + } + #[inline] + pub fn default_real(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_DEFAULT_REAL, Some(0.0)).unwrap()} + } + #[inline] + pub fn deprecated(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_DEPRECATED, Some(false)).unwrap()} + } + #[inline] + pub fn required(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_REQUIRED, Some(false)).unwrap()} + } + #[inline] + pub fn key(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_KEY, Some(false)).unwrap()} + } + #[inline] + pub fn attributes(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Field::VT_ATTRIBUTES, None)} + } + #[inline] + pub fn documentation(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Field::VT_DOCUMENTATION, None)} + } + #[inline] + pub fn optional(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_OPTIONAL, Some(false)).unwrap()} + } + /// Number of padding octets to always add after this field. Structs only. + #[inline] + pub fn padding(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_PADDING, Some(0)).unwrap()} + } + /// If the field uses 64-bit offsets. + #[inline] + pub fn offset64(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Field::VT_OFFSET64, Some(false)).unwrap()} + } +} + +impl flatbuffers::Verifiable for Field<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>("type_", Self::VT_TYPE_, true)? + .visit_field::("id", Self::VT_ID, false)? + .visit_field::("offset", Self::VT_OFFSET, false)? + .visit_field::("default_integer", Self::VT_DEFAULT_INTEGER, false)? + .visit_field::("default_real", Self::VT_DEFAULT_REAL, false)? + .visit_field::("deprecated", Self::VT_DEPRECATED, false)? + .visit_field::("required", Self::VT_REQUIRED, false)? + .visit_field::("key", Self::VT_KEY, false)? + .visit_field::>>>("attributes", Self::VT_ATTRIBUTES, false)? + .visit_field::>>>("documentation", Self::VT_DOCUMENTATION, false)? + .visit_field::("optional", Self::VT_OPTIONAL, false)? + .visit_field::("padding", Self::VT_PADDING, false)? + .visit_field::("offset64", Self::VT_OFFSET64, false)? + .finish(); + Ok(()) + } +} +pub struct FieldArgs<'a> { + pub name: Option>, + pub type_: Option>>, + pub id: u16, + pub offset: u16, + pub default_integer: i64, + pub default_real: f64, + pub deprecated: bool, + pub required: bool, + pub key: bool, + pub attributes: Option>>>>, + pub documentation: Option>>>, + pub optional: bool, + pub padding: u16, + pub offset64: bool, +} +impl<'a> Default for FieldArgs<'a> { + #[inline] + fn default() -> Self { + FieldArgs { + name: None, // required field + type_: None, // required field + id: 0, + offset: 0, + default_integer: 0, + default_real: 0.0, + deprecated: false, + required: false, + key: false, + attributes: None, + documentation: None, + optional: false, + padding: 0, + offset64: false, + } + } +} + +pub struct FieldBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> FieldBuilder<'a, 'b, A> { + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Field::VT_NAME, name); + } + #[inline] + pub fn add_type_(&mut self, type_: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Field::VT_TYPE_, type_); + } + #[inline] + pub fn add_id(&mut self, id: u16) { + self.fbb_.push_slot::(Field::VT_ID, id, 0); + } + #[inline] + pub fn add_offset(&mut self, offset: u16) { + self.fbb_.push_slot::(Field::VT_OFFSET, offset, 0); + } + #[inline] + pub fn add_default_integer(&mut self, default_integer: i64) { + self.fbb_.push_slot::(Field::VT_DEFAULT_INTEGER, default_integer, 0); + } + #[inline] + pub fn add_default_real(&mut self, default_real: f64) { + self.fbb_.push_slot::(Field::VT_DEFAULT_REAL, default_real, 0.0); + } + #[inline] + pub fn add_deprecated(&mut self, deprecated: bool) { + self.fbb_.push_slot::(Field::VT_DEPRECATED, deprecated, false); + } + #[inline] + pub fn add_required(&mut self, required: bool) { + self.fbb_.push_slot::(Field::VT_REQUIRED, required, false); + } + #[inline] + pub fn add_key(&mut self, key: bool) { + self.fbb_.push_slot::(Field::VT_KEY, key, false); + } + #[inline] + pub fn add_attributes(&mut self, attributes: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Field::VT_ATTRIBUTES, attributes); + } + #[inline] + pub fn add_documentation(&mut self, documentation: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Field::VT_DOCUMENTATION, documentation); + } + #[inline] + pub fn add_optional(&mut self, optional: bool) { + self.fbb_.push_slot::(Field::VT_OPTIONAL, optional, false); + } + #[inline] + pub fn add_padding(&mut self, padding: u16) { + self.fbb_.push_slot::(Field::VT_PADDING, padding, 0); + } + #[inline] + pub fn add_offset64(&mut self, offset64: bool) { + self.fbb_.push_slot::(Field::VT_OFFSET64, offset64, false); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> FieldBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + FieldBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Field::VT_NAME,"name"); + self.fbb_.required(o, Field::VT_TYPE_,"type_"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Field<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Field"); + ds.field("name", &self.name()); + ds.field("type_", &self.type_()); + ds.field("id", &self.id()); + ds.field("offset", &self.offset()); + ds.field("default_integer", &self.default_integer()); + ds.field("default_real", &self.default_real()); + ds.field("deprecated", &self.deprecated()); + ds.field("required", &self.required()); + ds.field("key", &self.key()); + ds.field("attributes", &self.attributes()); + ds.field("documentation", &self.documentation()); + ds.field("optional", &self.optional()); + ds.field("padding", &self.padding()); + ds.field("offset64", &self.offset64()); + ds.finish() + } +} +pub enum ObjectOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Object<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Object<'a> { + type Inner = Object<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Object<'a> { + pub const VT_NAME: flatbuffers::VOffsetT = 4; + pub const VT_FIELDS: flatbuffers::VOffsetT = 6; + pub const VT_IS_STRUCT: flatbuffers::VOffsetT = 8; + pub const VT_MINALIGN: flatbuffers::VOffsetT = 10; + pub const VT_BYTESIZE: flatbuffers::VOffsetT = 12; + pub const VT_ATTRIBUTES: flatbuffers::VOffsetT = 14; + pub const VT_DOCUMENTATION: flatbuffers::VOffsetT = 16; + pub const VT_DECLARATION_FILE: flatbuffers::VOffsetT = 18; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Object { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ObjectArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = ObjectBuilder::new(_fbb); + if let Some(x) = args.declaration_file { builder.add_declaration_file(x); } + if let Some(x) = args.documentation { builder.add_documentation(x); } + if let Some(x) = args.attributes { builder.add_attributes(x); } + builder.add_bytesize(args.bytesize); + builder.add_minalign(args.minalign); + if let Some(x) = args.fields { builder.add_fields(x); } + if let Some(x) = args.name { builder.add_name(x); } + builder.add_is_struct(args.is_struct); + builder.finish() + } + + + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Object::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Object) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn fields(&self) -> flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Object::VT_FIELDS, None).unwrap()} + } + #[inline] + pub fn is_struct(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Object::VT_IS_STRUCT, Some(false)).unwrap()} + } + #[inline] + pub fn minalign(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Object::VT_MINALIGN, Some(0)).unwrap()} + } + #[inline] + pub fn bytesize(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Object::VT_BYTESIZE, Some(0)).unwrap()} + } + #[inline] + pub fn attributes(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Object::VT_ATTRIBUTES, None)} + } + #[inline] + pub fn documentation(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Object::VT_DOCUMENTATION, None)} + } + /// File that this Object is declared in. + #[inline] + pub fn declaration_file(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Object::VT_DECLARATION_FILE, None)} + } +} + +impl flatbuffers::Verifiable for Object<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>>>("fields", Self::VT_FIELDS, true)? + .visit_field::("is_struct", Self::VT_IS_STRUCT, false)? + .visit_field::("minalign", Self::VT_MINALIGN, false)? + .visit_field::("bytesize", Self::VT_BYTESIZE, false)? + .visit_field::>>>("attributes", Self::VT_ATTRIBUTES, false)? + .visit_field::>>>("documentation", Self::VT_DOCUMENTATION, false)? + .visit_field::>("declaration_file", Self::VT_DECLARATION_FILE, false)? + .finish(); + Ok(()) + } +} +pub struct ObjectArgs<'a> { + pub name: Option>, + pub fields: Option>>>>, + pub is_struct: bool, + pub minalign: i32, + pub bytesize: i32, + pub attributes: Option>>>>, + pub documentation: Option>>>, + pub declaration_file: Option>, +} +impl<'a> Default for ObjectArgs<'a> { + #[inline] + fn default() -> Self { + ObjectArgs { + name: None, // required field + fields: None, // required field + is_struct: false, + minalign: 0, + bytesize: 0, + attributes: None, + documentation: None, + declaration_file: None, + } + } +} + +pub struct ObjectBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ObjectBuilder<'a, 'b, A> { + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Object::VT_NAME, name); + } + #[inline] + pub fn add_fields(&mut self, fields: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Object::VT_FIELDS, fields); + } + #[inline] + pub fn add_is_struct(&mut self, is_struct: bool) { + self.fbb_.push_slot::(Object::VT_IS_STRUCT, is_struct, false); + } + #[inline] + pub fn add_minalign(&mut self, minalign: i32) { + self.fbb_.push_slot::(Object::VT_MINALIGN, minalign, 0); + } + #[inline] + pub fn add_bytesize(&mut self, bytesize: i32) { + self.fbb_.push_slot::(Object::VT_BYTESIZE, bytesize, 0); + } + #[inline] + pub fn add_attributes(&mut self, attributes: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Object::VT_ATTRIBUTES, attributes); + } + #[inline] + pub fn add_documentation(&mut self, documentation: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Object::VT_DOCUMENTATION, documentation); + } + #[inline] + pub fn add_declaration_file(&mut self, declaration_file: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Object::VT_DECLARATION_FILE, declaration_file); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ObjectBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ObjectBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Object::VT_NAME,"name"); + self.fbb_.required(o, Object::VT_FIELDS,"fields"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Object<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Object"); + ds.field("name", &self.name()); + ds.field("fields", &self.fields()); + ds.field("is_struct", &self.is_struct()); + ds.field("minalign", &self.minalign()); + ds.field("bytesize", &self.bytesize()); + ds.field("attributes", &self.attributes()); + ds.field("documentation", &self.documentation()); + ds.field("declaration_file", &self.declaration_file()); + ds.finish() + } +} +pub enum RPCCallOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct RPCCall<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for RPCCall<'a> { + type Inner = RPCCall<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> RPCCall<'a> { + pub const VT_NAME: flatbuffers::VOffsetT = 4; + pub const VT_REQUEST: flatbuffers::VOffsetT = 6; + pub const VT_RESPONSE: flatbuffers::VOffsetT = 8; + pub const VT_ATTRIBUTES: flatbuffers::VOffsetT = 10; + pub const VT_DOCUMENTATION: flatbuffers::VOffsetT = 12; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + RPCCall { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args RPCCallArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = RPCCallBuilder::new(_fbb); + if let Some(x) = args.documentation { builder.add_documentation(x); } + if let Some(x) = args.attributes { builder.add_attributes(x); } + if let Some(x) = args.response { builder.add_response(x); } + if let Some(x) = args.request { builder.add_request(x); } + if let Some(x) = args.name { builder.add_name(x); } + builder.finish() + } + + + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(RPCCall::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &RPCCall) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn request(&self) -> Object<'a> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(RPCCall::VT_REQUEST, None).unwrap()} + } + #[inline] + pub fn response(&self) -> Object<'a> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(RPCCall::VT_RESPONSE, None).unwrap()} + } + #[inline] + pub fn attributes(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(RPCCall::VT_ATTRIBUTES, None)} + } + #[inline] + pub fn documentation(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(RPCCall::VT_DOCUMENTATION, None)} + } +} + +impl flatbuffers::Verifiable for RPCCall<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>("request", Self::VT_REQUEST, true)? + .visit_field::>("response", Self::VT_RESPONSE, true)? + .visit_field::>>>("attributes", Self::VT_ATTRIBUTES, false)? + .visit_field::>>>("documentation", Self::VT_DOCUMENTATION, false)? + .finish(); + Ok(()) + } +} +pub struct RPCCallArgs<'a> { + pub name: Option>, + pub request: Option>>, + pub response: Option>>, + pub attributes: Option>>>>, + pub documentation: Option>>>, +} +impl<'a> Default for RPCCallArgs<'a> { + #[inline] + fn default() -> Self { + RPCCallArgs { + name: None, // required field + request: None, // required field + response: None, // required field + attributes: None, + documentation: None, + } + } +} + +pub struct RPCCallBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> RPCCallBuilder<'a, 'b, A> { + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(RPCCall::VT_NAME, name); + } + #[inline] + pub fn add_request(&mut self, request: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(RPCCall::VT_REQUEST, request); + } + #[inline] + pub fn add_response(&mut self, response: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(RPCCall::VT_RESPONSE, response); + } + #[inline] + pub fn add_attributes(&mut self, attributes: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(RPCCall::VT_ATTRIBUTES, attributes); + } + #[inline] + pub fn add_documentation(&mut self, documentation: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(RPCCall::VT_DOCUMENTATION, documentation); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> RPCCallBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + RPCCallBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, RPCCall::VT_NAME,"name"); + self.fbb_.required(o, RPCCall::VT_REQUEST,"request"); + self.fbb_.required(o, RPCCall::VT_RESPONSE,"response"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for RPCCall<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("RPCCall"); + ds.field("name", &self.name()); + ds.field("request", &self.request()); + ds.field("response", &self.response()); + ds.field("attributes", &self.attributes()); + ds.field("documentation", &self.documentation()); + ds.finish() + } +} +pub enum ServiceOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Service<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Service<'a> { + type Inner = Service<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Service<'a> { + pub const VT_NAME: flatbuffers::VOffsetT = 4; + pub const VT_CALLS: flatbuffers::VOffsetT = 6; + pub const VT_ATTRIBUTES: flatbuffers::VOffsetT = 8; + pub const VT_DOCUMENTATION: flatbuffers::VOffsetT = 10; + pub const VT_DECLARATION_FILE: flatbuffers::VOffsetT = 12; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Service { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ServiceArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = ServiceBuilder::new(_fbb); + if let Some(x) = args.declaration_file { builder.add_declaration_file(x); } + if let Some(x) = args.documentation { builder.add_documentation(x); } + if let Some(x) = args.attributes { builder.add_attributes(x); } + if let Some(x) = args.calls { builder.add_calls(x); } + if let Some(x) = args.name { builder.add_name(x); } + builder.finish() + } + + + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Service::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Service) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn calls(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Service::VT_CALLS, None)} + } + #[inline] + pub fn attributes(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Service::VT_ATTRIBUTES, None)} + } + #[inline] + pub fn documentation(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Service::VT_DOCUMENTATION, None)} + } + /// File that this Service is declared in. + #[inline] + pub fn declaration_file(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Service::VT_DECLARATION_FILE, None)} + } +} + +impl flatbuffers::Verifiable for Service<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>>>("calls", Self::VT_CALLS, false)? + .visit_field::>>>("attributes", Self::VT_ATTRIBUTES, false)? + .visit_field::>>>("documentation", Self::VT_DOCUMENTATION, false)? + .visit_field::>("declaration_file", Self::VT_DECLARATION_FILE, false)? + .finish(); + Ok(()) + } +} +pub struct ServiceArgs<'a> { + pub name: Option>, + pub calls: Option>>>>, + pub attributes: Option>>>>, + pub documentation: Option>>>, + pub declaration_file: Option>, +} +impl<'a> Default for ServiceArgs<'a> { + #[inline] + fn default() -> Self { + ServiceArgs { + name: None, // required field + calls: None, + attributes: None, + documentation: None, + declaration_file: None, + } + } +} + +pub struct ServiceBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ServiceBuilder<'a, 'b, A> { + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Service::VT_NAME, name); + } + #[inline] + pub fn add_calls(&mut self, calls: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Service::VT_CALLS, calls); + } + #[inline] + pub fn add_attributes(&mut self, attributes: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Service::VT_ATTRIBUTES, attributes); + } + #[inline] + pub fn add_documentation(&mut self, documentation: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Service::VT_DOCUMENTATION, documentation); + } + #[inline] + pub fn add_declaration_file(&mut self, declaration_file: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Service::VT_DECLARATION_FILE, declaration_file); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ServiceBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ServiceBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Service::VT_NAME,"name"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Service<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Service"); + ds.field("name", &self.name()); + ds.field("calls", &self.calls()); + ds.field("attributes", &self.attributes()); + ds.field("documentation", &self.documentation()); + ds.field("declaration_file", &self.declaration_file()); + ds.finish() + } +} +pub enum SchemaFileOffset {} +#[derive(Copy, Clone, PartialEq)] + +/// File specific information. +/// Symbols declared within a file may be recovered by iterating over all +/// symbols and examining the `declaration_file` field. +pub struct SchemaFile<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for SchemaFile<'a> { + type Inner = SchemaFile<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> SchemaFile<'a> { + pub const VT_FILENAME: flatbuffers::VOffsetT = 4; + pub const VT_INCLUDED_FILENAMES: flatbuffers::VOffsetT = 6; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + SchemaFile { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args SchemaFileArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = SchemaFileBuilder::new(_fbb); + if let Some(x) = args.included_filenames { builder.add_included_filenames(x); } + if let Some(x) = args.filename { builder.add_filename(x); } + builder.finish() + } + + + /// Filename, relative to project root. + #[inline] + pub fn filename(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(SchemaFile::VT_FILENAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &SchemaFile) -> bool { + self.filename() < o.filename() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.filename(); + key.cmp(val) + } + /// Names of included files, relative to project root. + #[inline] + pub fn included_filenames(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(SchemaFile::VT_INCLUDED_FILENAMES, None)} + } +} + +impl flatbuffers::Verifiable for SchemaFile<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("filename", Self::VT_FILENAME, true)? + .visit_field::>>>("included_filenames", Self::VT_INCLUDED_FILENAMES, false)? + .finish(); + Ok(()) + } +} +pub struct SchemaFileArgs<'a> { + pub filename: Option>, + pub included_filenames: Option>>>, +} +impl<'a> Default for SchemaFileArgs<'a> { + #[inline] + fn default() -> Self { + SchemaFileArgs { + filename: None, // required field + included_filenames: None, + } + } +} + +pub struct SchemaFileBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> SchemaFileBuilder<'a, 'b, A> { + #[inline] + pub fn add_filename(&mut self, filename: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(SchemaFile::VT_FILENAME, filename); + } + #[inline] + pub fn add_included_filenames(&mut self, included_filenames: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(SchemaFile::VT_INCLUDED_FILENAMES, included_filenames); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> SchemaFileBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + SchemaFileBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, SchemaFile::VT_FILENAME,"filename"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for SchemaFile<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("SchemaFile"); + ds.field("filename", &self.filename()); + ds.field("included_filenames", &self.included_filenames()); + ds.finish() + } +} +pub enum SchemaOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Schema<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Schema<'a> { + type Inner = Schema<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Schema<'a> { + pub const VT_OBJECTS: flatbuffers::VOffsetT = 4; + pub const VT_ENUMS: flatbuffers::VOffsetT = 6; + pub const VT_FILE_IDENT: flatbuffers::VOffsetT = 8; + pub const VT_FILE_EXT: flatbuffers::VOffsetT = 10; + pub const VT_ROOT_TABLE: flatbuffers::VOffsetT = 12; + pub const VT_SERVICES: flatbuffers::VOffsetT = 14; + pub const VT_ADVANCED_FEATURES: flatbuffers::VOffsetT = 16; + pub const VT_FBS_FILES: flatbuffers::VOffsetT = 18; + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Schema { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args SchemaArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = SchemaBuilder::new(_fbb); + builder.add_advanced_features(args.advanced_features); + if let Some(x) = args.fbs_files { builder.add_fbs_files(x); } + if let Some(x) = args.services { builder.add_services(x); } + if let Some(x) = args.root_table { builder.add_root_table(x); } + if let Some(x) = args.file_ext { builder.add_file_ext(x); } + if let Some(x) = args.file_ident { builder.add_file_ident(x); } + if let Some(x) = args.enums { builder.add_enums(x); } + if let Some(x) = args.objects { builder.add_objects(x); } + builder.finish() + } + + + #[inline] + pub fn objects(&self) -> flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Schema::VT_OBJECTS, None).unwrap()} + } + #[inline] + pub fn enums(&self) -> flatbuffers::Vector<'a, flatbuffers::ForwardsUOffset>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Schema::VT_ENUMS, None).unwrap()} + } + #[inline] + pub fn file_ident(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Schema::VT_FILE_IDENT, None)} + } + #[inline] + pub fn file_ext(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Schema::VT_FILE_EXT, None)} + } + #[inline] + pub fn root_table(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Schema::VT_ROOT_TABLE, None)} + } + #[inline] + pub fn services(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Schema::VT_SERVICES, None)} + } + #[inline] + pub fn advanced_features(&self) -> AdvancedFeatures { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Schema::VT_ADVANCED_FEATURES, Some(Default::default())).unwrap()} + } + /// All the files used in this compilation. Files are relative to where + /// flatc was invoked. + #[inline] + pub fn fbs_files(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Schema::VT_FBS_FILES, None)} + } +} + +impl flatbuffers::Verifiable for Schema<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>>>("objects", Self::VT_OBJECTS, true)? + .visit_field::>>>("enums", Self::VT_ENUMS, true)? + .visit_field::>("file_ident", Self::VT_FILE_IDENT, false)? + .visit_field::>("file_ext", Self::VT_FILE_EXT, false)? + .visit_field::>("root_table", Self::VT_ROOT_TABLE, false)? + .visit_field::>>>("services", Self::VT_SERVICES, false)? + .visit_field::("advanced_features", Self::VT_ADVANCED_FEATURES, false)? + .visit_field::>>>("fbs_files", Self::VT_FBS_FILES, false)? + .finish(); + Ok(()) + } +} +pub struct SchemaArgs<'a> { + pub objects: Option>>>>, + pub enums: Option>>>>, + pub file_ident: Option>, + pub file_ext: Option>, + pub root_table: Option>>, + pub services: Option>>>>, + pub advanced_features: AdvancedFeatures, + pub fbs_files: Option>>>>, +} +impl<'a> Default for SchemaArgs<'a> { + #[inline] + fn default() -> Self { + SchemaArgs { + objects: None, // required field + enums: None, // required field + file_ident: None, + file_ext: None, + root_table: None, + services: None, + advanced_features: Default::default(), + fbs_files: None, + } + } +} + +pub struct SchemaBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> SchemaBuilder<'a, 'b, A> { + #[inline] + pub fn add_objects(&mut self, objects: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Schema::VT_OBJECTS, objects); + } + #[inline] + pub fn add_enums(&mut self, enums: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Schema::VT_ENUMS, enums); + } + #[inline] + pub fn add_file_ident(&mut self, file_ident: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Schema::VT_FILE_IDENT, file_ident); + } + #[inline] + pub fn add_file_ext(&mut self, file_ext: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Schema::VT_FILE_EXT, file_ext); + } + #[inline] + pub fn add_root_table(&mut self, root_table: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Schema::VT_ROOT_TABLE, root_table); + } + #[inline] + pub fn add_services(&mut self, services: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Schema::VT_SERVICES, services); + } + #[inline] + pub fn add_advanced_features(&mut self, advanced_features: AdvancedFeatures) { + self.fbb_.push_slot::(Schema::VT_ADVANCED_FEATURES, advanced_features, Default::default()); + } + #[inline] + pub fn add_fbs_files(&mut self, fbs_files: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Schema::VT_FBS_FILES, fbs_files); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> SchemaBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + SchemaBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Schema::VT_OBJECTS,"objects"); + self.fbb_.required(o, Schema::VT_ENUMS,"enums"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Schema<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Schema"); + ds.field("objects", &self.objects()); + ds.field("enums", &self.enums()); + ds.field("file_ident", &self.file_ident()); + ds.field("file_ext", &self.file_ext()); + ds.field("root_table", &self.root_table()); + ds.field("services", &self.services()); + ds.field("advanced_features", &self.advanced_features()); + ds.field("fbs_files", &self.fbs_files()); + ds.finish() + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `Schema` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_schema_unchecked`. +pub fn root_as_schema(buf: &[u8]) -> Result { + flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `Schema` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_schema_unchecked`. +pub fn size_prefixed_root_as_schema(buf: &[u8]) -> Result { + flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `Schema` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_schema_unchecked`. +pub fn root_as_schema_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `Schema` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_schema_unchecked`. +pub fn size_prefixed_root_as_schema_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a Schema and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `Schema`. +pub unsafe fn root_as_schema_unchecked(buf: &[u8]) -> Schema { + flatbuffers::root_unchecked::(buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed Schema and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `Schema`. +pub unsafe fn size_prefixed_root_as_schema_unchecked(buf: &[u8]) -> Schema { + flatbuffers::size_prefixed_root_unchecked::(buf) +} +pub const SCHEMA_IDENTIFIER: &str = "BFBS"; + +#[inline] +pub fn schema_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, SCHEMA_IDENTIFIER, false) +} + +#[inline] +pub fn schema_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, SCHEMA_IDENTIFIER, true) +} + +pub const SCHEMA_EXTENSION: &str = "bfbs"; + +#[inline] +pub fn finish_schema_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( + fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + root: flatbuffers::WIPOffset>) { + fbb.finish(root, Some(SCHEMA_IDENTIFIER)); +} + +#[inline] +pub fn finish_size_prefixed_schema_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(SCHEMA_IDENTIFIER)); +} +} // pub mod reflection + diff --git a/third_party/flatbuffers/rust/reflection/src/reflection_verifier.rs b/third_party/flatbuffers/rust/reflection/src/reflection_verifier.rs new file mode 100644 index 00000000000..43739147783 --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/src/reflection_verifier.rs @@ -0,0 +1,421 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use crate::reflection_generated::reflection::{BaseType, Field, Object, Schema}; +use crate::{FlatbufferError, FlatbufferResult}; +use flatbuffers::{ + ForwardsUOffset, InvalidFlatbuffer, TableVerifier, UOffsetT, Vector, Verifiable, Verifier, + VerifierOptions, SIZE_UOFFSET, SIZE_VOFFSET, +}; +use std::collections::HashMap; + +/// Verifies a buffer against its schema with custom verification options. +pub fn verify_with_options( + buffer: &[u8], + schema: &Schema, + opts: &VerifierOptions, + buf_loc_to_obj_idx: &mut HashMap, +) -> FlatbufferResult<()> { + let mut verifier = Verifier::new(opts, buffer); + if let Some(table_object) = schema.root_table() { + if let core::result::Result::Ok(table_pos) = verifier.get_uoffset(0) { + // Inserts -1 as object index for root table + buf_loc_to_obj_idx.insert(table_pos.try_into()?, -1); + let mut verified = vec![false; buffer.len()]; + return verify_table( + &mut verifier, + &table_object, + table_pos.try_into()?, + schema, + &mut verified, + buf_loc_to_obj_idx, + ); + } + } + Err(FlatbufferError::InvalidSchema) +} + +fn verify_table( + verifier: &mut Verifier, + table_object: &Object, + table_pos: usize, + schema: &Schema, + verified: &mut [bool], + buf_loc_to_obj_idx: &mut HashMap, +) -> FlatbufferResult<()> { + if table_pos < verified.len() && verified[table_pos] { + return Ok(()); + } + + let mut table_verifier = verifier.visit_table(table_pos)?; + + for field in &table_object.fields() { + let field_name = field.name().to_owned(); + table_verifier = match field.type_().base_type() { + BaseType::UType | BaseType::UByte => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Bool => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Byte => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Short => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::UShort => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Int => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::UInt => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Long => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::ULong => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Float => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::Double => { + table_verifier.visit_field::(field_name, field.offset(), field.required())? + } + BaseType::String => table_verifier.visit_field::>( + field_name, + field.offset(), + field.required(), + )?, + BaseType::Vector => { + verify_vector(table_verifier, &field, schema, verified, buf_loc_to_obj_idx)? + } + BaseType::Obj => { + if let Some(field_pos) = table_verifier.deref(field.offset())? { + let object_index = field.type_().index(); + let child_obj = schema.objects().get(object_index.try_into()?); + if child_obj.is_struct() { + buf_loc_to_obj_idx.insert(field_pos, object_index); + verify_struct( + table_verifier.verifier(), + &child_obj, + field_pos, + schema, + buf_loc_to_obj_idx, + )? + } else { + let field_value = table_verifier.verifier().get_uoffset(field_pos)?; + let table_pos = field_pos.saturating_add(field_value.try_into()?); + buf_loc_to_obj_idx.insert(table_pos, object_index); + verify_table( + table_verifier.verifier(), + &child_obj, + table_pos, + schema, + verified, + buf_loc_to_obj_idx, + )?; + } + } else if field.required() { + return InvalidFlatbuffer::new_missing_required(field.name().to_string())?; + } + table_verifier + } + BaseType::Union => { + if let Some(field_pos) = table_verifier.deref(field.offset())? { + let field_value = table_verifier.verifier().get_uoffset(field_pos)?; + verify_union( + table_verifier, + &field, + field_pos.saturating_add(field_value.try_into()?), + schema, + verified, + buf_loc_to_obj_idx, + )? + } else if field.required() { + return InvalidFlatbuffer::new_missing_required(field.name().to_string())?; + } else { + table_verifier + } + } + _ => { + return Err(FlatbufferError::TypeNotSupported( + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )); + } + }; + } + + table_verifier.finish(); + verified[table_pos] = true; + Ok(()) +} + +fn verify_struct( + verifier: &mut Verifier, + struct_object: &Object, + struct_pos: usize, + schema: &Schema, + buf_loc_to_obj_idx: &mut HashMap, +) -> FlatbufferResult<()> { + verifier.range_in_buffer(struct_pos, struct_object.bytesize().try_into()?)?; + for field in &struct_object.fields() { + if field.type_().base_type() == BaseType::Obj { + let obj_idx = field.type_().index(); + let child_obj = schema.objects().get(obj_idx.try_into()?); + if child_obj.is_struct() { + let field_pos = struct_pos.saturating_add(field.offset().into()); + buf_loc_to_obj_idx.insert(field_pos, obj_idx); + verify_struct(verifier, &child_obj, field_pos, schema, buf_loc_to_obj_idx)?; + } + } + } + Ok(()) +} + +fn verify_vector<'a, 'b, 'c>( + mut table_verifier: TableVerifier<'a, 'b, 'c>, + field: &Field, + schema: &Schema, + verified: &mut [bool], + buf_loc_to_obj_idx: &mut HashMap, +) -> FlatbufferResult> { + let field_name = field.name().to_owned(); + match field.type_().element() { + BaseType::UType | BaseType::UByte => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Bool => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Byte => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Short => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::UShort => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Int => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::UInt => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Long => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::ULong => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Float => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Double => table_verifier + .visit_field::>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::String => table_verifier + .visit_field::>>>( + field_name, + field.offset(), + field.required(), + ) + .map_err(FlatbufferError::VerificationError), + BaseType::Obj => { + if let Some(field_pos) = table_verifier.deref(field.offset())? { + let verifier = table_verifier.verifier(); + let vector_offset = verifier.get_uoffset(field_pos)?; + let vector_pos = field_pos.saturating_add(vector_offset.try_into()?); + let vector_len = verifier.get_uoffset(vector_pos)?; + let vector_start = vector_pos.saturating_add(SIZE_UOFFSET); + let child_obj_idx = field.type_().index(); + let child_obj = schema.objects().get(child_obj_idx.try_into()?); + if child_obj.is_struct() { + let vector_size = vector_len.saturating_mul(child_obj.bytesize().try_into()?); + verifier.range_in_buffer(vector_start, vector_size.try_into()?)?; + let vector_range = core::ops::Range { + start: vector_start, + end: vector_start.saturating_add(vector_size.try_into()?), + }; + for struct_pos in vector_range.step_by(child_obj.bytesize().try_into()?) { + buf_loc_to_obj_idx.insert(struct_pos, child_obj_idx); + verify_struct( + verifier, + &child_obj, + struct_pos, + schema, + buf_loc_to_obj_idx, + )?; + } + } else { + verifier.is_aligned::(vector_start)?; + let vector_size = vector_len.saturating_mul(SIZE_UOFFSET.try_into()?); + verifier.range_in_buffer(vector_start, vector_size.try_into()?)?; + let vector_range = core::ops::Range { + start: vector_start, + end: vector_start.saturating_add(vector_size.try_into()?), + }; + for element_pos in vector_range.step_by(SIZE_UOFFSET) { + let table_pos = element_pos + .saturating_add(verifier.get_uoffset(element_pos)?.try_into()?); + buf_loc_to_obj_idx.insert(table_pos, child_obj_idx); + verify_table( + verifier, + &child_obj, + table_pos, + schema, + verified, + buf_loc_to_obj_idx, + )?; + } + } + } else if field.required() { + return InvalidFlatbuffer::new_missing_required(field.name().to_string())?; + } + Ok(table_verifier) + } + _ => { + return Err(FlatbufferError::TypeNotSupported( + field + .type_() + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )) + } + } +} + +fn verify_union<'a, 'b, 'c>( + mut table_verifier: TableVerifier<'a, 'b, 'c>, + field: &Field, + union_pos: usize, + schema: &Schema, + verified: &mut [bool], + buf_loc_to_obj_idx: &mut HashMap, +) -> FlatbufferResult> { + let union_enum = schema.enums().get(field.type_().index().try_into()?); + if union_enum.values().is_empty() { + return Err(FlatbufferError::InvalidUnionEnum); + } + + let enum_offset = field.offset() - u16::try_from(SIZE_VOFFSET)?; + if let Some(enum_pos) = table_verifier.deref(enum_offset)? { + let enum_value = table_verifier.verifier().get_u8(enum_pos)?; + let enum_type = union_enum + .values() + .get(enum_value.into()) + .union_type() + .ok_or(FlatbufferError::InvalidUnionEnum)?; + + match enum_type.base_type() { + BaseType::String => <&str>::run_verifier(table_verifier.verifier(), union_pos)?, + BaseType::Obj => { + let child_obj = schema.objects().get(enum_type.index().try_into()?); + buf_loc_to_obj_idx.insert(union_pos, enum_type.index()); + if child_obj.is_struct() { + verify_struct( + table_verifier.verifier(), + &child_obj, + union_pos, + schema, + buf_loc_to_obj_idx, + )? + } else { + verify_table( + table_verifier.verifier(), + &child_obj, + union_pos, + schema, + verified, + buf_loc_to_obj_idx, + )?; + } + } + _ => { + return Err(FlatbufferError::TypeNotSupported( + enum_type + .base_type() + .variant_name() + .unwrap_or_default() + .to_string(), + )) + } + } + } else { + return InvalidFlatbuffer::new_inconsistent_union( + format!("{}_type", field.name()), + field.name().to_string(), + )?; + } + + verified[union_pos] = true; + Ok(table_verifier) +} diff --git a/third_party/flatbuffers/rust/reflection/src/safe_buffer.rs b/third_party/flatbuffers/rust/reflection/src/safe_buffer.rs new file mode 100644 index 00000000000..ba61e87301f --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/src/safe_buffer.rs @@ -0,0 +1,319 @@ +/* + * Copyright 2025 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use crate::r#struct::Struct; +use crate::reflection_generated::reflection::{Field, Schema}; +use crate::reflection_verifier::verify_with_options; +use crate::{ + get_any_field_float, get_any_field_float_in_struct, get_any_field_integer, + get_any_field_integer_in_struct, get_any_field_string, get_any_field_string_in_struct, + get_any_root, get_field_float, get_field_integer, get_field_string, get_field_struct, + get_field_struct_in_struct, get_field_table, get_field_vector, FlatbufferError, + FlatbufferResult, ForwardsUOffset, +}; +use flatbuffers::{Follow, Table, Vector, VerifierOptions}; +use num_traits::float::Float; +use num_traits::int::PrimInt; +use num_traits::FromPrimitive; +use std::collections::HashMap; + +#[derive(Debug)] +pub struct SafeBuffer<'a> { + buf: &'a [u8], + schema: &'a Schema<'a>, + buf_loc_to_obj_idx: HashMap, +} + +impl<'a> SafeBuffer<'a> { + pub fn new(buf: &'a [u8], schema: &'a Schema) -> FlatbufferResult { + Self::new_with_options(buf, schema, &VerifierOptions::default()) + } + + pub fn new_with_options( + buf: &'a [u8], + schema: &'a Schema, + opts: &VerifierOptions, + ) -> FlatbufferResult { + let mut buf_loc_to_obj_idx = HashMap::new(); + verify_with_options(&buf, schema, opts, &mut buf_loc_to_obj_idx)?; + Ok(SafeBuffer { + buf, + schema, + buf_loc_to_obj_idx, + }) + } + + /// Gets the root table in the buffer. + pub fn get_root(&self) -> SafeTable { + // SAFETY: the buffer was verified during construction. + let table = unsafe { get_any_root(self.buf) }; + + SafeTable { + safe_buf: self, + loc: table.loc(), + } + } + + fn find_field_by_name( + &self, + buf_loc: usize, + field_name: &str, + ) -> FlatbufferResult> { + Ok(self + .get_all_fields(buf_loc)? + .lookup_by_key(field_name, |field: &Field<'_>, key| { + field.key_compare_with_value(key) + })) + } + + fn get_all_fields(&self, buf_loc: usize) -> FlatbufferResult>> { + if let Some(&obj_idx) = self.buf_loc_to_obj_idx.get(&buf_loc) { + let obj = if obj_idx == -1 { + self.schema.root_table().unwrap() + } else { + self.schema.objects().get(obj_idx.try_into()?) + }; + Ok(obj.fields()) + } else { + Err(FlatbufferError::InvalidTableOrStruct) + } + } +} + +#[derive(Debug)] +pub struct SafeTable<'a> { + safe_buf: &'a SafeBuffer<'a>, + loc: usize, +} + +impl<'a> SafeTable<'a> { + /// Gets an integer table field given its exact type. Returns default integer value if the field is not set. Returns [None] if no default value is found. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table or + /// the field type doesn't match. + pub fn get_field_integer Follow<'b, Inner = T> + PrimInt + FromPrimitive>( + &self, + field_name: &str, + ) -> FlatbufferResult> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { get_field_integer::(&Table::new(&self.safe_buf.buf, self.loc), &field) } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Gets a floating point table field given its exact type. Returns default float value if the field is not set. Returns [None] if no default value is found. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table or + /// the field type doesn't match. + pub fn get_field_float Follow<'b, Inner = T> + Float>( + &self, + field_name: &str, + ) -> FlatbufferResult> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { get_field_float::(&Table::new(&self.safe_buf.buf, self.loc), &field) } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Gets a String table field given its exact type. Returns empty string if the field is not set. Returns [None] if no default value is found. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table or + /// the field type doesn't match. + pub fn get_field_string(&self, field_name: &str) -> FlatbufferResult> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { get_field_string(&Table::new(&self.safe_buf.buf, self.loc), &field) } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Gets a [SafeStruct] table field given its exact type. Returns [None] if the field is not set. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table or + /// the field type doesn't match. + pub fn get_field_struct(&self, field_name: &str) -> FlatbufferResult>> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + let optional_st = + unsafe { get_field_struct(&Table::new(&self.safe_buf.buf, self.loc), &field)? }; + Ok(optional_st.map(|st| SafeStruct { + safe_buf: self.safe_buf, + loc: st.loc(), + })) + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Gets a Vector table field given its exact type. Returns empty vector if the field is not set. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table or + /// the field type doesn't match. + pub fn get_field_vector>( + &self, + field_name: &str, + ) -> FlatbufferResult>> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { get_field_vector(&Table::new(&self.safe_buf.buf, self.loc), &field) } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Gets a [SafeTable] table field given its exact type. Returns [None] if the field is not set. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table or + /// the field type doesn't match. + pub fn get_field_table(&self, field_name: &str) -> FlatbufferResult>> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + let optional_table = + unsafe { get_field_table(&Table::new(&self.safe_buf.buf, self.loc), &field)? }; + Ok(optional_table.map(|t| SafeTable { + safe_buf: self.safe_buf, + loc: t.loc(), + })) + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Returns the value of any table field as a 64-bit int, regardless of what type it is. Returns default integer if the field is not set or error if + /// the value cannot be parsed as integer or + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table. + /// [num_traits](https://docs.rs/num-traits/latest/num_traits/cast/trait.NumCast.html) is used for number casting. + pub fn get_any_field_integer(&self, field_name: &str) -> FlatbufferResult { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { get_any_field_integer(&Table::new(&self.safe_buf.buf, self.loc), &field) } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Returns the value of any table field as a 64-bit floating point, regardless of what type it is. Returns default float if the field is not set or error if + /// the value cannot be parsed as float or + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table. + pub fn get_any_field_float(&self, field_name: &str) -> FlatbufferResult { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { get_any_field_float(&Table::new(&self.safe_buf.buf, self.loc), &field) } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Returns the string representation of any table field value (e.g. integer 123 is returned as "123"), regardless of what type it is. Returns empty string if the field is not set. Returns error if + /// the table doesn't match the buffer or + /// the [field_name] doesn't match the table. + pub fn get_any_field_string(&self, field_name: &str) -> FlatbufferResult { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { + Ok(get_any_field_string( + &Table::new(&self.safe_buf.buf, self.loc), + &field, + self.safe_buf.schema, + )) + } + } else { + Err(FlatbufferError::FieldNotFound) + } + } +} + +#[derive(Debug)] +pub struct SafeStruct<'a> { + safe_buf: &'a SafeBuffer<'a>, + loc: usize, +} + +impl<'a> SafeStruct<'a> { + /// Gets a [SafeStruct] struct field given its exact type. Returns error if + /// the struct doesn't match the buffer or + /// the [field_name] doesn't match the struct or + /// the field type doesn't match. + pub fn get_field_struct(&self, field_name: &str) -> FlatbufferResult> { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + let st = unsafe { + get_field_struct_in_struct(&Struct::new(&self.safe_buf.buf, self.loc), &field)? + }; + Ok(SafeStruct { + safe_buf: self.safe_buf, + loc: st.loc(), + }) + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Returns the value of any struct field as a 64-bit int, regardless of what type it is. Returns error if + /// the struct doesn't match the buffer or + /// the [field_name] doesn't match the struct or + /// the value cannot be parsed as integer. + pub fn get_any_field_integer(&self, field_name: &str) -> FlatbufferResult { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { + get_any_field_integer_in_struct(&Struct::new(&self.safe_buf.buf, self.loc), &field) + } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Returns the value of any struct field as a 64-bit floating point, regardless of what type it is. Returns error if + /// the struct doesn't match the buffer or + /// the [field_name] doesn't match the struct or + /// the value cannot be parsed as float. + pub fn get_any_field_float(&self, field_name: &str) -> FlatbufferResult { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { + get_any_field_float_in_struct(&Struct::new(&self.safe_buf.buf, self.loc), &field) + } + } else { + Err(FlatbufferError::FieldNotFound) + } + } + + /// Returns the string representation of any struct field value (e.g. integer 123 is returned as "123"), regardless of what type it is. Returns error if + /// the struct doesn't match the buffer or + /// the [field_name] doesn't match the struct. + pub fn get_any_field_string(&self, field_name: &str) -> FlatbufferResult { + if let Some(field) = self.safe_buf.find_field_by_name(self.loc, field_name)? { + // SAFETY: the buffer was verified during construction. + unsafe { + Ok(get_any_field_string_in_struct( + &Struct::new(&self.safe_buf.buf, self.loc), + &field, + self.safe_buf.schema, + )) + } + } else { + Err(FlatbufferError::FieldNotFound) + } + } +} diff --git a/third_party/flatbuffers/rust/reflection/src/struct.rs b/third_party/flatbuffers/rust/reflection/src/struct.rs new file mode 100644 index 00000000000..0952fafd4fa --- /dev/null +++ b/third_party/flatbuffers/rust/reflection/src/struct.rs @@ -0,0 +1,61 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use flatbuffers::Follow; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Struct<'a> { + buf: &'a [u8], + loc: usize, +} + +impl<'a> Struct<'a> { + #[inline] + pub fn buf(&self) -> &'a [u8] { + self.buf + } + + #[inline] + pub fn loc(&self) -> usize { + self.loc + } + + /// # Safety + /// + /// [buf] must contain a valid struct at [loc] + #[inline] + pub unsafe fn new(buf: &'a [u8], loc: usize) -> Self { + Struct { buf, loc } + } + + /// Retrieves the value at the provided [byte_loc]. No field in [Struct] is optional. + /// + /// # Safety + /// + /// The value of the corresponding slot must have type T + #[inline] + pub unsafe fn get + 'a>(&self, byte_loc: usize) -> T::Inner { + ::follow(self.buf, self.loc + byte_loc) + } +} + +impl<'a> Follow<'a> for Struct<'a> { + type Inner = Struct<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Struct { buf, loc } + } +} diff --git a/third_party/flatbuffers/samples/monster_generated.h b/third_party/flatbuffers/samples/monster_generated.h index 96795af5282..10141753c12 100644 --- a/third_party/flatbuffers/samples/monster_generated.h +++ b/third_party/flatbuffers/samples/monster_generated.h @@ -8,9 +8,9 @@ // Ensure the included flatbuffers.h is the same version as when this file was // generated, otherwise it may not be compatible. -static_assert(FLATBUFFERS_VERSION_MAJOR == 24 && - FLATBUFFERS_VERSION_MINOR == 3 && - FLATBUFFERS_VERSION_REVISION == 25, +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, "Non-compatible flatbuffers version included"); namespace MyGame { @@ -607,7 +607,7 @@ inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_functi { auto _e = name(); if (_e) _o->name = _e->str(); } { auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } } { auto _e = color(); _o->color = _e; } - { auto _e = weapons(); if (_e) { _o->weapons.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->weapons[_i]) { _e->Get(_i)->UnPackTo(_o->weapons[_i].get(), _resolver); } else { _o->weapons[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); }; } } else { _o->weapons.resize(0); } } + { auto _e = weapons(); if (_e) { _o->weapons.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->weapons[_i]) { _e->Get(_i)->UnPackTo(_o->weapons[_i].get(), _resolver); } else { _o->weapons[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->weapons.resize(0); } } { auto _e = equipped_type(); _o->equipped.type = _e; } { auto _e = equipped(); if (_e) _o->equipped.value = MyGame::Sample::EquipmentUnion::UnPack(_e, equipped_type(), _resolver); } { auto _e = path(); if (_e) { _o->path.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->path[_i] = *_e->Get(_i); } } else { _o->path.resize(0); } } diff --git a/third_party/flatbuffers/samples/monster_generated.swift b/third_party/flatbuffers/samples/monster_generated.swift index b536d1f4f5e..527560ae2ff 100644 --- a/third_party/flatbuffers/samples/monster_generated.swift +++ b/third_party/flatbuffers/samples/monster_generated.swift @@ -36,7 +36,7 @@ public enum MyGame_Sample_Equipment: UInt8, UnionEnum { public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable { - static func validateVersion() { FlatBuffersVersion_24_3_25() } + static func validateVersion() { FlatBuffersVersion_25_2_10() } private var _x: Float32 private var _y: Float32 @@ -72,7 +72,7 @@ public struct MyGame_Sample_Vec3: NativeStruct, Verifiable, FlatbuffersInitializ public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject { - static func validateVersion() { FlatBuffersVersion_24_3_25() } + static func validateVersion() { FlatBuffersVersion_25_2_10() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Struct @@ -88,7 +88,7 @@ public struct MyGame_Sample_Vec3_Mutable: FlatBufferObject { public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_24_3_25() } + static func validateVersion() { FlatBuffersVersion_25_2_10() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table @@ -111,7 +111,7 @@ public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable { } public var pos: MyGame_Sample_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Sample_Vec3.self, at: o) } - public var mutablePos: MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: o + _accessor.postion) } + public var mutablePos: MyGame_Sample_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Sample_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.mana.v); return _accessor.mutate(mana, index: o) } public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } @@ -200,7 +200,7 @@ public struct MyGame_Sample_Monster: FlatBufferObject, Verifiable { public struct MyGame_Sample_Weapon: FlatBufferObject, Verifiable { - static func validateVersion() { FlatBuffersVersion_24_3_25() } + static func validateVersion() { FlatBuffersVersion_25_2_10() } public var __buffer: ByteBuffer! { return _accessor.bb } private var _accessor: Table diff --git a/third_party/flatbuffers/samples/rust_generated/my_game/sample/vec_3_generated.rs b/third_party/flatbuffers/samples/rust_generated/my_game/sample/vec_3_generated.rs index 185677f8946..bc5e52a6751 100644 --- a/third_party/flatbuffers/samples/rust_generated/my_game/sample/vec_3_generated.rs +++ b/third_party/flatbuffers/samples/rust_generated/my_game/sample/vec_3_generated.rs @@ -47,9 +47,13 @@ impl<'b> flatbuffers::Push for Vec3 { type Output = Vec3; #[inline] unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { - let src = ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, Self::size()); + let src = ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, ::size()); dst.copy_from_slice(src); } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } } impl<'a> flatbuffers::Verifiable for Vec3 { diff --git a/third_party/flatbuffers/samples/sample_binary.swift b/third_party/flatbuffers/samples/sample_binary.swift index 4df546fca23..08fb9a825a0 100644 --- a/third_party/flatbuffers/samples/sample_binary.swift +++ b/third_party/flatbuffers/samples/sample_binary.swift @@ -1,5 +1,5 @@ /* - * Copyright 2023 Google Inc. All rights reserved. + * Copyright 2024 Google Inc. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/third_party/flatbuffers/scripts/release.sh b/third_party/flatbuffers/scripts/release.sh index 4a426f68703..c1315aa6ad7 100755 --- a/third_party/flatbuffers/scripts/release.sh +++ b/third_party/flatbuffers/scripts/release.sh @@ -1,5 +1,34 @@ #!/usr/bin/bash +# Steps to do a release: +# +# 1. Make sure the repo builds and ./flatttests passes first, so that any +# version changes are localized. +# 2. Run this script which should update all the version strings in the +# appropriate places. +# 3. `make clean` +# 4. `make -j flatc` +# 5. Make sure the version is part of flatc: `./flatc --version` +# 6. `scripts/generated_code.py` +# 7. `goldens/generated_code.py` +# 8. `make -j` +# 9. Make sure the tests pass: `./flattests` +# 10. Do a search for the old version string in the code base. It should only +# appear in the changelog. +# 11. Update the CHANGELOG.md +# 12. Make the git commit with the message: "FlatBuffers Version X.X.X" +# 13. Tag the commit with `git -tag -a -m "FlatBuffers Version X.X.X` vX.X.X +# 14. Push the tag `git push origin vX.X.X` +# 15. Make a release from the tag at https://github.com/google/flatbuffers/tags + +# Requires the xmlstarlet command. +# Install via: apt install xmlstarlet +if ! command -v xmlstarlet 2>&1 >/dev/null +then + echo "xmlstarlet could not be found" + exit 1 +fi + # Read the date as in the Pacific TZ, with no leading padding read year month day <<<$(date --date="TZ=\"US/Pacific\"" +'%-y %-m %-d') @@ -31,7 +60,9 @@ sed -i \ -e "s/\(FLATBUFFERS_VERSION_REVISION == \)[0-9]*\(.*\)/\1$day\2/" \ include/flatbuffers/reflection_generated.h \ tests/evolution_test/evolution_v1_generated.h \ - tests/evolution_test/evolution_v2_generated.h + tests/evolution_test/evolution_v2_generated.h \ + tests/*_generated.h \ + tests/**/*_generated.h echo "Updating java/pom.xml..." xmlstarlet edit --inplace -N s=http://maven.apache.org/POM/4.0.0 \ @@ -68,6 +99,11 @@ sed -i \ "s/^version = \".*\"$/version = \"$version\"/g" \ rust/flatbuffers/Cargo.toml +echo "Updating rust/flexbuffers/Cargo.toml..." +sed -i \ + "s/^version = \".*\"$/version = \"$version\"/g" \ + rust/flexbuffers/Cargo.toml + echo "Updating FlatBuffers.podspec..." sed -i \ -e "s/\(s.version\s*= \).*/\1'$version'/" \ @@ -84,3 +120,8 @@ grep -rl 'FLATBUFFERS_\d*' * --exclude=release.sh | xargs -i@ \ sed -i \ -e "s/\(FLATBUFFERS_\)[0-9]\{2\}.*()/\1$version_underscore()/g" \ @ + +echo "Updating MODULES.bazel..." +sed -i \ + "3s/version = \".*\"/version = \"$version\"/" \ + MODULE.bazel diff --git a/third_party/flatbuffers/src/BUILD.bazel b/third_party/flatbuffers/src/BUILD.bazel index 679b10f787d..4b9fb7a8156 100644 --- a/third_party/flatbuffers/src/BUILD.bazel +++ b/third_party/flatbuffers/src/BUILD.bazel @@ -89,6 +89,7 @@ cc_library( visibility = ["//:__pkg__"], deps = [ ":flatbuffers", + "//include/codegen:namer", ], ) @@ -155,5 +156,7 @@ cc_library( "//grpc/src/compiler:python_generator", "//grpc/src/compiler:swift_generator", "//grpc/src/compiler:ts_generator", + "//include/codegen:namer", + "//include/codegen:python", ], ) diff --git a/third_party/flatbuffers/src/annotated_binary_text_gen.cpp b/third_party/flatbuffers/src/annotated_binary_text_gen.cpp index 3967066b168..87ab231ee28 100644 --- a/third_party/flatbuffers/src/annotated_binary_text_gen.cpp +++ b/third_party/flatbuffers/src/annotated_binary_text_gen.cpp @@ -402,7 +402,8 @@ static void GenerateSection(std::ostream &os, const BinarySection §ion, } // namespace bool AnnotatedBinaryTextGenerator::Generate( - const std::string &filename, const std::string &schema_filename) { + const std::string &filename, const std::string &schema_filename, + const std::string &output_filename) { OutputConfig output_config; output_config.max_bytes_per_line = options_.max_bytes_per_line; output_config.include_vector_contents = options_.include_vector_contents; @@ -435,18 +436,23 @@ bool AnnotatedBinaryTextGenerator::Generate( } } - // Modify the output filename. - std::string output_filename = StripExtension(filename); - output_filename += options_.output_postfix; - output_filename += - "." + (options_.output_extension.empty() ? GetExtension(filename) - : options_.output_extension); + std::string out = output_filename; + if (out.empty()) { + // Modify the output filename. + out = StripExtension(filename); + out += options_.output_postfix; + out += + "." + (options_.output_extension.empty() ? GetExtension(filename) + : options_.output_extension); + } - std::ofstream ofs(output_filename.c_str()); + std::ofstream ofs(out.c_str()); ofs << "// Annotated Flatbuffer Binary" << std::endl; ofs << "//" << std::endl; - ofs << "// Schema file: " << schema_filename << std::endl; + if (!schema_filename.empty()) { + ofs << "// Schema file: " << schema_filename << std::endl; + } ofs << "// Binary file: " << filename << std::endl; // Generate each of the binary sections diff --git a/third_party/flatbuffers/src/annotated_binary_text_gen.h b/third_party/flatbuffers/src/annotated_binary_text_gen.h index a0806d88a06..97acd292669 100644 --- a/third_party/flatbuffers/src/annotated_binary_text_gen.h +++ b/third_party/flatbuffers/src/annotated_binary_text_gen.h @@ -56,8 +56,8 @@ class AnnotatedBinaryTextGenerator { // Generate the annotated binary for the given `filename`. Returns true if the // annotated binary was successfully saved. - bool Generate(const std::string &filename, - const std::string &schema_filename); + bool Generate(const std::string &filename, const std::string &schema_filename, + const std::string &output_filename = ""); private: const std::map annotations_; diff --git a/third_party/flatbuffers/src/binary_annotator.cpp b/third_party/flatbuffers/src/binary_annotator.cpp index 498a7bfc6a3..16fd82a1895 100644 --- a/third_party/flatbuffers/src/binary_annotator.cpp +++ b/third_party/flatbuffers/src/binary_annotator.cpp @@ -120,12 +120,13 @@ static BinarySection GenerateMissingSection(const uint64_t offset, } // namespace std::map BinaryAnnotator::Annotate() { - flatbuffers::Verifier verifier(bfbs_, static_cast(bfbs_length_)); - - if ((is_size_prefixed_ && - !reflection::VerifySizePrefixedSchemaBuffer(verifier)) || - !reflection::VerifySchemaBuffer(verifier)) { - return {}; + if (bfbs_ != nullptr && bfbs_length_ != 0) { + flatbuffers::Verifier verifier(bfbs_, static_cast(bfbs_length_)); + if ((is_size_prefixed_ && + !reflection::VerifySizePrefixedSchemaBuffer(verifier)) || + !reflection::VerifySchemaBuffer(verifier)) { + return {}; + } } // The binary is too short to read as a flatbuffers. @@ -141,8 +142,7 @@ std::map BinaryAnnotator::Annotate() { if (IsValidOffset(root_table_offset)) { // Build the root table, and all else will be referenced from it. - BuildTable(root_table_offset, BinarySectionType::RootTable, - schema_->root_table()); + BuildTable(root_table_offset, BinarySectionType::RootTable, RootTable()); } // Now that all the sections are built, make sure the binary sections are @@ -203,7 +203,7 @@ uint64_t BinaryAnnotator::BuildHeader(const uint64_t header_offset) { BinaryRegionComment root_offset_comment; root_offset_comment.type = BinaryRegionCommentType::RootTableOffset; - root_offset_comment.name = schema_->root_table()->name()->str(); + root_offset_comment.name = RootTable()->name()->str(); if (!IsValidOffset(root_table_loc)) { SetError(root_offset_comment, @@ -1516,4 +1516,11 @@ bool BinaryAnnotator::ContainsSection(const uint64_t offset) { it->second.regions.back().length; } +const reflection::Object *BinaryAnnotator::RootTable() const { + if (!root_table_.empty()) { + return schema_->objects()->LookupByKey(root_table_); + } + return schema_->root_table(); +} + } // namespace flatbuffers diff --git a/third_party/flatbuffers/src/binary_annotator.h b/third_party/flatbuffers/src/binary_annotator.h index df8a17bed4f..4c84141e79e 100644 --- a/third_party/flatbuffers/src/binary_annotator.h +++ b/third_party/flatbuffers/src/binary_annotator.h @@ -17,15 +17,21 @@ #ifndef FLATBUFFERS_BINARY_ANNOTATOR_H_ #define FLATBUFFERS_BINARY_ANNOTATOR_H_ +#include +#include +#include +#include #include #include +#include #include +#include #include #include "flatbuffers/base.h" #include "flatbuffers/reflection.h" +#include "flatbuffers/reflection_generated.h" #include "flatbuffers/stl_emulation.h" -#include "flatbuffers/util.h" namespace flatbuffers { @@ -227,7 +233,7 @@ inline static std::string ToString(const BinaryRegionType type) { case BinaryRegionType::Uint8: return "uint8_t"; case BinaryRegionType::Uint16: return "uint16_t"; case BinaryRegionType::Uint32: return "uint32_t"; - case BinaryRegionType::Uint64: return "uint64_t"; ; + case BinaryRegionType::Uint64: return "uint64_t"; case BinaryRegionType::Int8: return "int8_t"; case BinaryRegionType::Int16: return "int16_t"; case BinaryRegionType::Int32: return "int32_t"; @@ -250,6 +256,18 @@ class BinaryAnnotator { : bfbs_(bfbs), bfbs_length_(bfbs_length), schema_(reflection::GetSchema(bfbs)), + root_table_(""), + binary_(binary), + binary_length_(binary_length), + is_size_prefixed_(is_size_prefixed) {} + + BinaryAnnotator(const reflection::Schema *schema, + const std::string &root_table, const uint8_t *binary, + uint64_t binary_length, bool is_size_prefixed) + : bfbs_(nullptr), + bfbs_length_(0), + schema_(schema), + root_table_(root_table), binary_(binary), binary_length_(binary_length), is_size_prefixed_(is_size_prefixed) {} @@ -329,7 +347,7 @@ class BinaryAnnotator { } // Adds the provided `section` keyed by the `offset` it occurs at. If a - // section is already added at that offset, it doesn't replace the exisiting + // section is already added at that offset, it doesn't replace the existing // one. void AddSection(const uint64_t offset, const BinarySection §ion) { sections_.insert(std::make_pair(offset, section)); @@ -384,10 +402,13 @@ class BinaryAnnotator { bool ContainsSection(const uint64_t offset); + const reflection::Object *RootTable() const; + // The schema for the binary file const uint8_t *bfbs_; const uint64_t bfbs_length_; const reflection::Schema *schema_; + const std::string root_table_; // The binary data itself. const uint8_t *binary_; diff --git a/third_party/flatbuffers/src/flatc.cpp b/third_party/flatbuffers/src/flatc.cpp index f29d1092646..d06e858a11d 100644 --- a/third_party/flatbuffers/src/flatc.cpp +++ b/third_party/flatbuffers/src/flatc.cpp @@ -21,6 +21,7 @@ #include #include #include +#include #include "annotated_binary_text_gen.h" #include "binary_annotator.h" @@ -87,7 +88,7 @@ const static FlatCOption flatc_options[] = { "Output fields whose value is the default when writing JSON" }, { "", "unknown-json", "", "Allow fields in JSON that are not defined in the schema. These fields " - "will be discared when generating binaries." }, + "will be discarded when generating binaries." }, { "", "no-prefix", "", "Don't prefix enum values with the enum type in C++." }, { "", "scoped-enums", "", @@ -254,10 +255,21 @@ const static FlatCOption flatc_options[] = { { "", "python-no-type-prefix-suffix", "", "Skip emission of Python functions that are prefixed with typenames" }, { "", "python-typing", "", "Generate Python type annotations" }, + { "", "python-version", "", "Generate code for the given Python version." }, + { "", "python-gen-numpy", "", "Whether to generate numpy helpers." }, { "", "ts-omit-entrypoint", "", "Omit emission of namespace entrypoint file" }, { "", "file-names-only", "", "Print out generated file names without writing to the files" }, + { "", "grpc-filename-suffix", "SUFFIX", + "The suffix for the generated file names (Default is '.fb')." }, + { "", "grpc-additional-header", "", + "Additional headers to prepend to the generated files." }, + { "", "grpc-use-system-headers", "", + "Use <> for headers included from the generated code." }, + { "", "grpc-search-path", "PATH", "Prefix to any gRPC includes." }, + { "", "grpc-python-typed-handlers", "", + "The handlers will use the generated classes rather than raw bytes." }, }; auto cmp = [](FlatCOption a, FlatCOption b) { return a.long_opt < b.long_opt; }; @@ -664,6 +676,18 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc, opts.python_no_type_prefix_suffix = true; } else if (arg == "--python-typing") { opts.python_typing = true; + } else if (arg.rfind("--python-version=", 0) == 0) { + opts.python_version = + arg.substr(std::string("--python-version=").size()); + } else if (arg == "--python-version") { + if (++argi >= argc) Error("missing value following: " + arg, true); + opts.python_version = argv[argi]; + } else if (arg == "--python-gen-numpy" || + arg == "--python-gen-numpy=true") { + opts.python_gen_numpy = true; + } else if (arg == "--no-python-gen-numpy" || + arg == "--python-gen-numpy=false") { + opts.python_gen_numpy = false; } else if (arg == "--ts-omit-entrypoint") { opts.ts_omit_entrypoint = true; } else if (arg == "--annotate-sparse-vectors") { @@ -674,6 +698,36 @@ FlatCOptions FlatCompiler::ParseFromCommandLineArguments(int argc, } else if (arg == "--file-names-only") { // TODO (khhn): Provide 2 implementation options.file_names_only = true; + } else if (arg == "--grpc-filename-suffix") { + if (++argi >= argc) Error("missing gRPC filename suffix: " + arg, true); + opts.grpc_filename_suffix = argv[argi]; + } else if (arg.rfind("--grpc-filename-suffix=", 0) == 0) { + opts.grpc_filename_suffix = + arg.substr(std::string("--grpc-filename-suffix=").size()); + } else if (arg == "--grpc-additional-header") { + if (++argi >= argc) Error("missing include following: " + arg, true); + opts.grpc_additional_headers.push_back(argv[argi]); + } else if (arg.rfind("--grpc-additional-header=", 0) == 0) { + opts.grpc_additional_headers.push_back( + arg.substr(std::string("--grpc-additional-header=").size())); + } else if (arg == "--grpc-search-path") { + if (++argi >= argc) Error("missing gRPC search path: " + arg, true); + opts.grpc_search_path = argv[argi]; + } else if (arg.rfind("--grpc-search-path=", 0) == 0) { + opts.grpc_search_path = + arg.substr(std::string("--grpc-search-path=").size()); + } else if (arg == "--grpc-use-system-headers" || + arg == "--grpc-use-system-headers=true") { + opts.grpc_use_system_headers = true; + } else if (arg == "--no-grpc-use-system-headers" || + arg == "--grpc-use-system-headers=false") { + opts.grpc_use_system_headers = false; + } else if (arg == "--grpc-python-typed-handlers" || + arg == "--grpc-python-typed-handlers=true") { + opts.grpc_python_typed_handlers = true; + } else if (arg == "--no-grpc-python-typed-handlers" || + arg == "--grpc-python-typed-handlers=false") { + opts.grpc_python_typed_handlers = false; } else { if (arg == "--proto") { opts.proto_mode = true; } diff --git a/third_party/flatbuffers/src/idl_gen_cpp.cpp b/third_party/flatbuffers/src/idl_gen_cpp.cpp index 301c08d2c56..37fbccc5920 100644 --- a/third_party/flatbuffers/src/idl_gen_cpp.cpp +++ b/third_party/flatbuffers/src/idl_gen_cpp.cpp @@ -467,6 +467,24 @@ class CppGenerator : public BaseGenerator { } if (opts_.generate_object_based_api) { auto nativeName = NativeName(Name(*struct_def), struct_def, opts_); + + // Check that nativeName doesn't collide the name of another struct. + for (const auto &other_struct_def : parser_.structs_.vec) { + if (other_struct_def == struct_def || + other_struct_def->defined_namespace != + struct_def->defined_namespace) { + continue; + } + + auto other_name = Name(*other_struct_def); + if (nativeName == other_name) { + LogCompilerError("Generated Object API type for " + + Name(*struct_def) + " collides with " + + other_name); + FLATBUFFERS_ASSERT(true); + } + } + if (!struct_def->fixed) { code_ += "struct " + nativeName + ";"; } } code_ += ""; @@ -2635,7 +2653,7 @@ class CppGenerator : public BaseGenerator { code_ += "if constexpr (Index == {{FIELD_INDEX}}) \\"; code_ += "return {{FIELD_NAME}}();"; } - code_ += " else static_assert(Index != Index, \"Invalid Field Index\");"; + code_ += " else static_assert(Index != -1, \"Invalid Field Index\");"; code_ += " }"; } @@ -3291,7 +3309,7 @@ class CppGenerator : public BaseGenerator { "static_cast<::flatbuffers::hash_value_t>(" + indexing + "));"; if (PtrType(&field) == "naked") { code += " else "; - code += "_o->" + name + "[_i]" + access + " = nullptr"; + code += "_o->" + name + "[_i]" + access + " = nullptr; "; } else { // code += " else "; // code += "_o->" + name + "[_i]" + access + " = " + @@ -3309,9 +3327,10 @@ class CppGenerator : public BaseGenerator { code += "_o->" + name + "[_i]" + access + " = "; code += GenUnpackVal(field.value.type.VectorType(), indexing, true, field); - if (is_pointer) { code += "; }"; } + code += "; "; + if (is_pointer) { code += "} "; } } - code += "; } } else { " + vector_field + ".resize(0); }"; + code += "} } else { " + vector_field + ".resize(0); }"; } break; } diff --git a/third_party/flatbuffers/src/idl_gen_csharp.cpp b/third_party/flatbuffers/src/idl_gen_csharp.cpp index 9a4936ca20d..9988523f32f 100644 --- a/third_party/flatbuffers/src/idl_gen_csharp.cpp +++ b/third_party/flatbuffers/src/idl_gen_csharp.cpp @@ -850,7 +850,7 @@ class CSharpGenerator : public BaseGenerator { // Force compile time error if not using the same version runtime. code += " public static void ValidateVersion() {"; code += " FlatBufferConstants."; - code += "FLATBUFFERS_24_3_25(); "; + code += "FLATBUFFERS_25_2_10(); "; code += "}\n"; // Generate a special accessor for the table that when used as the root diff --git a/third_party/flatbuffers/src/idl_gen_dart.cpp b/third_party/flatbuffers/src/idl_gen_dart.cpp index a4df1f4dfcb..f0df15da0f8 100644 --- a/third_party/flatbuffers/src/idl_gen_dart.cpp +++ b/third_party/flatbuffers/src/idl_gen_dart.cpp @@ -135,7 +135,7 @@ class DartGenerator : public BaseGenerator { code = code + "// " + FlatBuffersGeneratedWarning() + "\n"; code = code + "// ignore_for_file: unused_import, unused_field, unused_element, " - "unused_local_variable\n\n"; + "unused_local_variable, constant_identifier_names\n\n"; if (!kv->first.empty()) { code += "library " + kv->first + ";\n\n"; } @@ -215,36 +215,45 @@ class DartGenerator : public BaseGenerator { namer_.Type(enum_def) + (enum_def.is_union ? "TypeId" : ""); const bool is_bit_flags = enum_def.attributes.Lookup("bit_flags") != nullptr; + // The flatbuffer schema language allows bit flag enums to potentially have // a default value of zero, even if it's not a valid enum value... - const bool permit_zero = is_bit_flags; + const bool auto_default = is_bit_flags && !enum_def.FindByValue("0"); + + code += "enum " + enum_type + " {\n"; + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { + auto &ev = **it; + const auto enum_var = namer_.Variant(ev); + if (it != enum_def.Vals().begin()) code += ",\n"; + code += " " + enum_var + "(" + enum_def.ToString(ev) + ")"; + } + if (auto_default) { code += ",\n _default(0)"; } + code += ";\n\n"; - code += "class " + enum_type + " {\n"; code += " final int value;\n"; - code += " const " + enum_type + "._(this.value);\n\n"; + code += " const " + enum_type + "(this.value);\n\n"; code += " factory " + enum_type + ".fromValue(int value) {\n"; - code += " final result = values[value];\n"; - code += " if (result == null) {\n"; - if (permit_zero) { - code += " if (value == 0) {\n"; - code += " return " + enum_type + "._(0);\n"; - code += " } else {\n"; + code += " switch (value) {\n"; + for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { + auto &ev = **it; + const auto enum_var = namer_.Variant(ev); + code += " case " + enum_def.ToString(ev) + ":"; + code += " return " + enum_type + "." + enum_var + ";\n"; } - code += " throw StateError('Invalid value $value for bit flag enum "; - code += enum_type + "');\n"; - if (permit_zero) { code += " }\n"; } + if (auto_default) { + code += " case 0: return " + enum_type + "._default;\n"; + } + code += " default: throw StateError("; + code += "'Invalid value $value for bit flag enum');\n"; code += " }\n"; - - code += " return result;\n"; code += " }\n\n"; - code += " static " + enum_type + "? _createOrNull(int? value) => \n"; + code += " static " + enum_type + "? _createOrNull(int? value) =>\n"; code += " value == null ? null : " + enum_type + ".fromValue(value);\n\n"; - // this is meaningless for bit_flags - // however, note that unlike "regular" dart enums this enum can still have - // holes. + // This is meaningless for bit_flags, however, note that unlike "regular" + // dart enums this enum can still have holes. if (!is_bit_flags) { code += " static const int minValue = " + enum_def.ToString(*enum_def.MinValue()) + ";\n"; @@ -252,37 +261,8 @@ class DartGenerator : public BaseGenerator { enum_def.ToString(*enum_def.MaxValue()) + ";\n"; } - code += - " static bool containsValue(int value) =>" - " values.containsKey(value);\n\n"; - - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { - auto &ev = **it; - const auto enum_var = namer_.Variant(ev); - - if (!ev.doc_comment.empty()) { - if (it != enum_def.Vals().begin()) { code += '\n'; } - GenDocComment(ev.doc_comment, " ", code); - } - code += " static const " + enum_type + " " + enum_var + " = " + - enum_type + "._(" + enum_def.ToString(ev) + ");\n"; - } - - code += " static const Map values = {\n"; - for (auto it = enum_def.Vals().begin(); it != enum_def.Vals().end(); ++it) { - auto &ev = **it; - const auto enum_var = namer_.Variant(ev); - if (it != enum_def.Vals().begin()) code += ",\n"; - code += " " + enum_def.ToString(ev) + ": " + enum_var; - } - code += "};\n\n"; - code += " static const " + _kFb + ".Reader<" + enum_type + "> reader = _" + - enum_type + "Reader();\n\n"; - code += " @override\n"; - code += " String toString() {\n"; - code += " return '" + enum_type + "{value: $value}';\n"; - code += " }\n"; + enum_type + "Reader();\n"; code += "}\n\n"; GenEnumReader(enum_def, enum_type, code); @@ -552,8 +532,7 @@ class DartGenerator : public BaseGenerator { if (auto val = enum_def.FindByValue(defaultValue)) { constructor_args += " = " + namer_.EnumVariant(enum_def, *val); } else { - constructor_args += " = const " + namer_.Type(enum_def) + "._(" + - defaultValue + ")"; + constructor_args += " = " + namer_.Type(enum_def) + "._default"; } } else { constructor_args += " = " + defaultValue; diff --git a/third_party/flatbuffers/src/idl_gen_grpc.cpp b/third_party/flatbuffers/src/idl_gen_grpc.cpp index 2be24e71a27..4764e25a450 100644 --- a/third_party/flatbuffers/src/idl_gen_grpc.cpp +++ b/third_party/flatbuffers/src/idl_gen_grpc.cpp @@ -16,6 +16,8 @@ // independent from idl_parser, since this code is not needed for most clients +#include + #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" @@ -253,6 +255,15 @@ class FlatBufFile : public grpc_generator::File { std::string additional_headers() const { switch (language_) { case kLanguageCpp: { + if (!parser_.opts.grpc_additional_headers.empty()) { + std::string result = ""; + for (const std::string &header : + parser_.opts.grpc_additional_headers) { + if (!result.empty()) result += "\n"; + result += "#include \"" + header + "\""; + } + return result; + } return "#include \"flatbuffers/grpc.h\"\n"; } case kLanguageGo: { @@ -356,10 +367,16 @@ bool GenerateCppGRPC(const Parser &parser, const std::string &path, grpc_cpp_generator::Parameters generator_parameters; // TODO(wvo): make the other parameters in this struct configurable. - generator_parameters.use_system_headers = true; + generator_parameters.use_system_headers = opts.grpc_use_system_headers; generator_parameters.message_header_extension = suffix; - - FlatBufFile fbfile(parser, file_name, FlatBufFile::kLanguageCpp); + generator_parameters.service_header_extension = + ".grpc" + opts.grpc_filename_suffix + ".h"; + generator_parameters.grpc_search_path = opts.grpc_search_path; + std::string filename = flatbuffers::StripExtension(parser.file_being_parsed_); + if (!opts.keep_prefix) { + filename = flatbuffers::StripPath(filename); + } + FlatBufFile fbfile(parser, filename, FlatBufFile::kLanguageCpp); std::string header_code = grpc_cpp_generator::GetHeaderPrologue(&fbfile, generator_parameters) + @@ -373,10 +390,14 @@ bool GenerateCppGRPC(const Parser &parser, const std::string &path, grpc_cpp_generator::GetSourceServices(&fbfile, generator_parameters) + grpc_cpp_generator::GetSourceEpilogue(&fbfile, generator_parameters); - return flatbuffers::SaveFile((path + file_name + ".grpc.fb.h").c_str(), - header_code, false) && - flatbuffers::SaveFile((path + file_name + ".grpc.fb.cc").c_str(), - source_code, false); + return flatbuffers::SaveFile( + (path + file_name + ".grpc" + opts.grpc_filename_suffix + ".h") + .c_str(), + header_code, false) && + flatbuffers::SaveFile( + (path + file_name + ".grpc" + opts.grpc_filename_suffix + ".cc") + .c_str(), + source_code, false); } class JavaGRPCGenerator : public flatbuffers::BaseGenerator { @@ -414,47 +435,8 @@ bool GenerateJavaGRPC(const Parser &parser, const std::string &path, return JavaGRPCGenerator(parser, path, file_name).generate(); } -class PythonGRPCGenerator : public flatbuffers::BaseGenerator { - private: - CodeWriter code_; - - public: - PythonGRPCGenerator(const Parser &parser, const std::string &filename) - : BaseGenerator(parser, "", filename, "", "" /*Unused*/, "swift") {} - - bool generate() { - code_.Clear(); - code_ += - "# Generated by the gRPC Python protocol compiler plugin. " - "DO NOT EDIT!\n"; - code_ += "import grpc\n"; - - FlatBufFile file(parser_, file_name_, FlatBufFile::kLanguagePython); - - for (int i = 0; i < file.service_count(); i++) { - auto service = file.service(i); - code_ += grpc_python_generator::Generate(&file, service.get()); - } - const auto final_code = code_.ToString(); - const auto filename = GenerateFileName(); - return SaveFile(filename.c_str(), final_code, false); - } - - std::string GenerateFileName() { - std::string namespace_dir; - auto &namespaces = parser_.namespaces_.back()->components; - for (auto it = namespaces.begin(); it != namespaces.end(); ++it) { - if (it != namespaces.begin()) namespace_dir += kPathSeparator; - namespace_dir += *it; - } - std::string grpc_py_filename = namespace_dir; - if (!namespace_dir.empty()) grpc_py_filename += kPathSeparator; - return grpc_py_filename + file_name_ + "_grpc_fb.py"; - } -}; - -bool GeneratePythonGRPC(const Parser &parser, const std::string & /*path*/, - const std::string &file_name) { +bool GeneratePythonGRPC(const Parser &parser, const std::string &path, + const std::string & /*file_name*/) { int nservices = 0; for (auto it = parser.services_.vec.begin(); it != parser.services_.vec.end(); ++it) { @@ -462,7 +444,16 @@ bool GeneratePythonGRPC(const Parser &parser, const std::string & /*path*/, } if (!nservices) return true; - return PythonGRPCGenerator(parser, file_name).generate(); + flatbuffers::python::Version version{parser.opts.python_version}; + if (!version.IsValid()) return false; + + if (!flatbuffers::python::grpc::Generate(parser, path, version)) { + return false; + } + if (parser.opts.python_typing) { + return flatbuffers::python::grpc::GenerateStub(parser, path, version); + } + return true; } class SwiftGRPCGenerator : public flatbuffers::BaseGenerator { diff --git a/third_party/flatbuffers/src/idl_gen_java.cpp b/third_party/flatbuffers/src/idl_gen_java.cpp index c1ec1d6c262..51c388d4d9e 100644 --- a/third_party/flatbuffers/src/idl_gen_java.cpp +++ b/third_party/flatbuffers/src/idl_gen_java.cpp @@ -701,7 +701,7 @@ class JavaGenerator : public BaseGenerator { // Force compile time error if not using the same version runtime. code += " public static void ValidateVersion() {"; code += " Constants."; - code += "FLATBUFFERS_24_3_25(); "; + code += "FLATBUFFERS_25_2_10(); "; code += "}\n"; // Generate a special accessor for the table that when used as the root diff --git a/third_party/flatbuffers/src/idl_gen_kotlin.cpp b/third_party/flatbuffers/src/idl_gen_kotlin.cpp index 675a15c36a4..7b95f967a32 100644 --- a/third_party/flatbuffers/src/idl_gen_kotlin.cpp +++ b/third_party/flatbuffers/src/idl_gen_kotlin.cpp @@ -524,7 +524,7 @@ class KotlinGenerator : public BaseGenerator { // runtime. GenerateFunOneLine( writer, "validateVersion", "", "", - [&]() { writer += "Constants.FLATBUFFERS_24_3_25()"; }, + [&]() { writer += "Constants.FLATBUFFERS_25_2_10()"; }, options.gen_jvmstatic); GenerateGetRootAsAccessors(namer_.Type(struct_def), writer, options); diff --git a/third_party/flatbuffers/src/idl_gen_python.cpp b/third_party/flatbuffers/src/idl_gen_python.cpp index 9e1627592e4..1c814cd53cf 100644 --- a/third_party/flatbuffers/src/idl_gen_python.cpp +++ b/third_party/flatbuffers/src/idl_gen_python.cpp @@ -18,17 +18,23 @@ #include "idl_gen_python.h" -#include +#include +#include +#include +#include +#include #include +#include #include -#include +#include #include +#include "codegen/idl_namer.h" +#include "codegen/python.h" #include "flatbuffers/code_generators.h" #include "flatbuffers/flatbuffers.h" #include "flatbuffers/idl.h" #include "flatbuffers/util.h" -#include "idl_namer.h" namespace flatbuffers { namespace python { @@ -38,53 +44,580 @@ namespace { typedef std::pair ImportMapEntry; typedef std::set ImportMap; -static std::set PythonKeywords() { - return { "False", "None", "True", "and", "as", "assert", - "break", "class", "continue", "def", "del", "elif", - "else", "except", "finally", "for", "from", "global", - "if", "import", "in", "is", "lambda", "nonlocal", - "not", "or", "pass", "raise", "return", "try", - "while", "with", "yield" }; -} - -static Namer::Config PythonDefaultConfig() { - return { /*types=*/Case::kKeep, - /*constants=*/Case::kScreamingSnake, - /*methods=*/Case::kUpperCamel, - /*functions=*/Case::kUpperCamel, - /*fields=*/Case::kLowerCamel, - /*variable=*/Case::kLowerCamel, - /*variants=*/Case::kKeep, - /*enum_variant_seperator=*/".", - /*escape_keywords=*/Namer::Config::Escape::BeforeConvertingCase, - /*namespaces=*/Case::kKeep, // Packages in python. - /*namespace_seperator=*/".", - /*object_prefix=*/"", - /*object_suffix=*/"T", - /*keyword_prefix=*/"", - /*keyword_suffix=*/"_", - /*filenames=*/Case::kKeep, - /*directories=*/Case::kKeep, - /*output_path=*/"", - /*filename_suffix=*/"", - /*filename_extension=*/".py" }; -} - // Hardcode spaces per indentation. static const CommentConfig def_comment = { nullptr, "#", nullptr }; static const std::string Indent = " "; -} // namespace +class PythonStubGenerator { + public: + PythonStubGenerator(const Parser &parser, const std::string &path, + const Version &version) + : parser_{parser}, + namer_{WithFlagOptions(kStubConfig, parser.opts, path), + Keywords(version)}, + version_(version) {} + + bool Generate() { + if (parser_.opts.one_file) { + Imports imports; + std::stringstream stub; + + DeclareUOffset(stub, &imports); + for (const EnumDef *def : parser_.enums_.vec) { + if (def->generated) continue; + GenerateEnumStub(stub, def, &imports); + } + for (const StructDef *def : parser_.structs_.vec) { + if (def->generated) continue; + GenerateStructStub(stub, def, &imports); + } + + std::string filename = + namer_.config_.output_path + + StripPath(StripExtension(parser_.file_being_parsed_)) + + namer_.config_.filename_suffix + namer_.config_.filename_extension; + + return SaveFile(filename, imports, stub); + } + + for (const EnumDef *def : parser_.enums_.vec) { + if (def->generated) continue; + + Imports imports; + std::stringstream stub; + + DeclareUOffset(stub, &imports); + GenerateEnumStub(stub, def, &imports); + + std::string filename = namer_.Directories(*def->defined_namespace) + + namer_.File(*def, SkipFile::Suffix); + if (!SaveFile(filename, imports, stub)) return false; + } + + for (const StructDef *def : parser_.structs_.vec) { + if (def->generated) continue; + + Imports imports; + std::stringstream stub; + + DeclareUOffset(stub, &imports); + GenerateStructStub(stub, def, &imports); + + std::string filename = namer_.Directories(*def->defined_namespace) + + namer_.File(*def, SkipFile::Suffix); + if (!SaveFile(filename, imports, stub)) return false; + } + + return true; + } + + private: + bool SaveFile(const std::string &filename, const Imports &imports, + const std::stringstream &content) { + std::stringstream ss; + GenerateImports(ss, imports); + ss << '\n'; + ss << content.str() << '\n'; + + EnsureDirExists(StripFileName(filename)); + return flatbuffers::SaveFile(filename.c_str(), ss.str(), false); + } + + static void DeclareUOffset(std::stringstream &stub, Imports *imports) { + imports->Import("flatbuffers"); + imports->Import("typing"); + stub << "uoffset: typing.TypeAlias = " + "flatbuffers.number_types.UOffsetTFlags.py_type\n" + << '\n'; + } + + std::string ModuleForFile(const std::string &file) const { + if (parser_.file_being_parsed_ == file) return "."; + + std::string module = parser_.opts.include_prefix + StripExtension(file) + + parser_.opts.filename_suffix; + std::replace(module.begin(), module.end(), '/', '.'); + return module; + } + + template + std::string ModuleFor(const T *def) const { + if (parser_.opts.one_file) return ModuleForFile(def->file); + return namer_.NamespacedType(*def); + } + + const StructDef *GetNestedStruct(const FieldDef *field) const { + const Value *nested = field->attributes.Lookup("nested_flatbuffer"); + if (nested == nullptr) return nullptr; + + StructDef *nested_def = parser_.LookupStruct(nested->constant); + if (nested_def != nullptr) return nested_def; + + return parser_.LookupStruct(namer_.NamespacedType( + parser_.current_namespace_->components, nested->constant)); + } + + static std::string ScalarType(BaseType type) { + if (IsBool(type)) return "bool"; + if (IsInteger(type)) return "int"; + if (IsFloat(type)) return "float"; + FLATBUFFERS_ASSERT(false); + return "None"; + } + + template + std::string UnionType(const EnumDef &enum_def, Imports *imports, + F type) const { + imports->Import("typing"); + + std::string result = ""; + for (const EnumVal *val : enum_def.Vals()) { + if (!result.empty()) result += ", "; + + switch (val->union_type.base_type) { + case BASE_TYPE_STRUCT: { + Import import = imports->Import(ModuleFor(val->union_type.struct_def), + type(*val->union_type.struct_def)); + result += import.name; + break; + } + case BASE_TYPE_STRING: + result += "str"; + break; + case BASE_TYPE_NONE: + result += "None"; + break; + default: + break; + } + } + return "typing.Union[" + result + "]"; + } + + std::string UnionObjectType(const EnumDef &enum_def, Imports *imports) const { + return UnionType(enum_def, imports, [this](const StructDef &struct_def) { + return namer_.ObjectType(struct_def); + }); + } + + std::string UnionType(const EnumDef &enum_def, Imports *imports) const { + return UnionType(enum_def, imports, [this](const StructDef &struct_def) { + return namer_.Type(struct_def); + }); + } + + std::string EnumType(const EnumDef &enum_def, Imports *imports) const { + imports->Import("typing"); + const Import &import = + imports->Import(ModuleFor(&enum_def), namer_.Type(enum_def)); + + std::string result = ""; + for (const EnumVal *val : enum_def.Vals()) { + if (!result.empty()) result += ", "; + result += import.name + "." + namer_.Variant(*val); + } + return "typing.Literal[" + result + "]"; + } + + std::string TypeOf(const Type &type, Imports *imports) const { + if (type.enum_def != nullptr) return EnumType(*type.enum_def, imports); + if (IsScalar(type.base_type)) return ScalarType(type.base_type); + + switch (type.base_type) { + case BASE_TYPE_STRUCT: { + const Import &import = imports->Import(ModuleFor(type.struct_def), + namer_.Type(*type.struct_def)); + return import.name; + } + case BASE_TYPE_STRING: + return "str"; + case BASE_TYPE_ARRAY: + case BASE_TYPE_VECTOR: { + imports->Import("typing"); + return "typing.List[" + TypeOf(type.VectorType(), imports) + "]"; + } + case BASE_TYPE_UNION: + return UnionType(*type.enum_def, imports); + default: + FLATBUFFERS_ASSERT(0); + return ""; + } + } + + std::string GenerateObjectFieldStub(const FieldDef *field, + Imports *imports) const { + std::string field_name = namer_.Field(*field); + + const Type &field_type = field->value.type; + if (IsScalar(field_type.base_type)) { + std::string result = field_name + ": " + TypeOf(field_type, imports); + if (field->IsOptional()) result += " | None"; + return result; + } + + switch (field_type.base_type) { + case BASE_TYPE_STRUCT: { + Import import = + imports->Import(ModuleFor(field_type.struct_def), + namer_.ObjectType(*field_type.struct_def)); + return field_name + ": " + import.name + " | None"; + } + case BASE_TYPE_STRING: + return field_name + ": str | None"; + case BASE_TYPE_ARRAY: + case BASE_TYPE_VECTOR: { + imports->Import("typing"); + if (field_type.element == BASE_TYPE_STRUCT) { + Import import = + imports->Import(ModuleFor(field_type.struct_def), + namer_.ObjectType(*field_type.struct_def)); + return field_name + ": typing.List[" + import.name + "]"; + } + if (field_type.element == BASE_TYPE_STRING) { + return field_name + ": typing.List[str]"; + } + return field_name + ": typing.List[" + + TypeOf(field_type.VectorType(), imports) + "]"; + } + case BASE_TYPE_UNION: + return field_name + ": " + + UnionObjectType(*field->value.type.enum_def, imports); + default: + return field_name; + } + } + + void GenerateObjectStub(std::stringstream &stub, const StructDef *struct_def, + Imports *imports) const { + std::string name = namer_.ObjectType(*struct_def); + + stub << "class " << name; + if (version_.major != 3) stub << "(object)"; + stub << ":\n"; + for (const FieldDef *field : struct_def->fields.vec) { + if (field->deprecated) continue; + stub << " " << GenerateObjectFieldStub(field, imports) << "\n"; + } + + stub << " @classmethod\n"; + stub << " def InitFromBuf(cls, buf: bytes, pos: int) -> " << name + << ": ...\n"; + + stub << " @classmethod\n"; + stub << " def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> " << name + << ": ...\n"; + + const Import &import = + imports->Import(ModuleFor(struct_def), namer_.Type(*struct_def)); + + stub << " @classmethod\n"; + stub << " def InitFromObj(cls, " << namer_.Variable(*struct_def) + << ": " + import.name + ") -> " << name << ": ...\n"; + + stub << " def _UnPack(self, " << namer_.Variable(*struct_def) << ": " + << import.name << ") -> None: ...\n"; + + stub << " def Pack(self, builder: flatbuffers.Builder) -> None: ...\n"; + + if (parser_.opts.gen_compare) { + stub << " def __eq__(self, other: " << name + ") -> bool: ...\n"; + } + } + + void GenerateStructStub(std::stringstream &stub, const StructDef *struct_def, + Imports *imports) const { + std::string type = namer_.Type(*struct_def); + + stub << "class " << type; + if (version_.major != 3) stub << "(object)"; + stub << ":\n"; + if (struct_def->fixed) { + stub << " @classmethod\n"; + stub << " def SizeOf(cls) -> int: ...\n\n"; + } else { + stub << " @classmethod\n"; + stub << " def GetRootAs(cls, buf: bytes, offset: int) -> " << type + << ": ...\n"; + + if (!parser_.opts.python_no_type_prefix_suffix) { + stub << " @classmethod\n"; + stub << " def GetRootAs" << type + << "(cls, buf: bytes, offset: int) -> " << type << ": ...\n"; + } + if (parser_.file_identifier_.length()) { + stub << " @classmethod\n"; + stub << " def " << type + << "BufferHasIdentifier(cls, buf: bytes, offset: int, " + "size_prefixed: bool) -> bool: ...\n"; + } + } + + stub << " def Init(self, buf: bytes, pos: int) -> None: ...\n"; + + for (const FieldDef *field : struct_def->fields.vec) { + if (field->deprecated) continue; + + std::string name = namer_.Method(*field); + + const Type &field_type = field->value.type; + if (IsScalar(field_type.base_type)) { + stub << " def " << name << "(self) -> " << TypeOf(field_type, imports); + if (field->IsOptional()) stub << " | None"; + stub << ": ...\n"; + } else { + switch (field_type.base_type) { + case BASE_TYPE_STRUCT: { + const Import &import = + imports->Import(ModuleFor(field_type.struct_def), + namer_.Type(*field_type.struct_def)); + if (struct_def->fixed) { + stub << " def " << name << "(self, obj: " << import.name + << ") -> " << import.name << ": ...\n"; + } else { + stub << " def " << name + "(self) -> " << import.name + << " | None: ...\n"; + } + break; + } + case BASE_TYPE_STRING: + stub << " def " << name << "(self) -> str | None: ...\n"; + break; + case BASE_TYPE_ARRAY: + case BASE_TYPE_VECTOR: { + switch (field_type.element) { + case BASE_TYPE_STRUCT: { + const Import &import = + imports->Import(ModuleFor(field_type.struct_def), + namer_.Type(*field_type.struct_def)); + stub << " def " << name << "(self, i: int) -> " << import.name + << " | None: ...\n"; + break; + } + case BASE_TYPE_STRING: + stub << " def " << name << "(self, i: int) -> str: ...\n"; + break; + default: // scalars + stub << " def " << name << "(self, i: int) -> " + << TypeOf(field_type, imports) << ": ...\n"; + + if (parser_.opts.python_gen_numpy) { + stub << " def " << name + << "AsNumpy(self) -> np.ndarray: ...\n"; + } + + const StructDef *nested_def = GetNestedStruct(field); + if (nested_def != nullptr) { + const Import &import = imports->Import( + ModuleFor(nested_def), namer_.Type(*nested_def)); + + stub << " def " << name + "NestedRoot(self) -> " + << import.name << " | None: ...\n"; + } + break; + } + stub << " def " << name << "Length(self) -> int: ...\n"; + stub << " def " << name << "IsNone(self) -> bool: ...\n"; + break; + } + case BASE_TYPE_UNION: { + imports->Import("flatbuffers", "table"); + stub << " def " << name << "(self) -> table.Table | None: ...\n"; + break; + } + default: + break; + } + } + } + + if (parser_.opts.generate_object_based_api) { + GenerateObjectStub(stub, struct_def, imports); + } + + if (struct_def->fixed) { + GenerateStructBuilderStub(stub, struct_def, imports); + } else { + GenerateTableBuilderStub(stub, struct_def, imports); + } + } + + void StructBuilderArgs(const StructDef &struct_def, const std::string prefix, + Imports *imports, + std::vector *args) const { + for (const FieldDef *field : struct_def.fields.vec) { + const Type type = IsArray(field->value.type) + ? field->value.type.VectorType() + : field->value.type; + if (type.base_type == BASE_TYPE_STRUCT) { + StructBuilderArgs(*field->value.type.struct_def, + prefix + namer_.Field(*field) + "_", imports, args); + } else { + args->push_back(prefix + namer_.Field(*field) + ": " + + TypeOf(type, imports)); + } + } + } + + void GenerateStructBuilderStub(std::stringstream &stub, + const StructDef *struct_def, + Imports *imports) const { + imports->Import("flatbuffers"); + + std::vector args; + StructBuilderArgs(*struct_def, "", imports, &args); + + stub << '\n'; + stub << "def Create" + namer_.Type(*struct_def) + << "(builder: flatbuffers.Builder"; + for (const std::string &arg : args) { + stub << ", " << arg; + } + stub << ") -> uoffset: ...\n"; + } + + void GenerateTableBuilderStub(std::stringstream &stub, + const StructDef *struct_def, + Imports *imports) const { + std::string type = namer_.Type(*struct_def); + + /**************************** def TableStart ****************************/ + stub << "def "; + if (!parser_.opts.python_no_type_prefix_suffix) stub << type; + stub << "Start(builder: flatbuffers.Builder) -> None: ...\n"; + if (!parser_.opts.one_file && !parser_.opts.python_no_type_prefix_suffix) { + stub << "def Start(builder: flatbuffers.Builder) -> None: ...\n"; + } + + /************************** def TableAddField ***************************/ + for (const FieldDef *field : struct_def->fields.vec) { + if (field->deprecated) continue; + + stub << "def "; + if (!parser_.opts.python_no_type_prefix_suffix) stub << type; + stub << "Add" << namer_.Method(*field) + << "(builder: flatbuffers.Builder, " + << namer_.Variable(*field) + ": "; + if (IsScalar(field->value.type.base_type)) { + stub << TypeOf(field->value.type, imports); + } else if (IsArray(field->value.type)) { + stub << TypeOf(field->value.type.VectorType(), imports); + } else { + stub << "uoffset"; + } + stub << ") -> None: ...\n"; + + if (IsVector(field->value.type)) { + stub << "def "; + if (!parser_.opts.python_no_type_prefix_suffix) stub << type; + stub << "Start" << namer_.Method(*field) + << "Vector(builder: flatbuffers.Builder, num_elems: int) -> " + "uoffset: ...\n"; + + if (!parser_.opts.one_file && + !parser_.opts.python_no_type_prefix_suffix) { + stub << "def Start" << namer_.Method(*field) + << "Vector(builder: flatbuffers.Builder, num_elems: int) -> " + "uoffset: ...\n"; + } + + if (GetNestedStruct(field) != nullptr) { + stub << "def " << type << "Make" << namer_.Method(*field) + << "VectorFromBytes(builder: flatbuffers.Builder, buf: " + "bytes) -> uoffset: ...\n"; + if (!parser_.opts.one_file) { + stub << "def Make" << namer_.Method(*field) + << "VectorFromBytes(builder: flatbuffers.Builder, buf: " + "bytes) -> uoffset: ...\n"; + } + } + } + } + + /***************************** def TableEnd *****************************/ + stub << "def "; + if (!parser_.opts.python_no_type_prefix_suffix) stub << type; + stub << "End(builder: flatbuffers.Builder) -> uoffset: ...\n"; + if (!parser_.opts.one_file && !parser_.opts.python_no_type_prefix_suffix) { + stub << "def End(builder: flatbuffers.Builder) -> uoffset: ...\n"; + } + } + + void GenerateEnumStub(std::stringstream &stub, const EnumDef *enum_def, + Imports *imports) const { + stub << "class " << namer_.Type(*enum_def); + + if (version_.major == 3){ + imports->Import("enum", "IntEnum"); + stub << "(IntEnum)"; + } + else { + stub << "(object)"; + } + + stub << ":\n"; + for (const EnumVal *val : enum_def->Vals()) { + stub << " " << namer_.Variant(*val) << ": " + << ScalarType(enum_def->underlying_type.base_type) << "\n"; + } + + if (parser_.opts.generate_object_based_api & enum_def->is_union) { + imports->Import("flatbuffers", "table"); + stub << "def " << namer_.Function(*enum_def) + << "Creator(union_type: " << EnumType(*enum_def, imports) + << ", table: table.Table) -> " << UnionType(*enum_def, imports) + << ": ...\n"; + } + } + + void GenerateImports(std::stringstream &ss, const Imports &imports) { + ss << "from __future__ import annotations\n"; + ss << '\n'; + ss << "import flatbuffers\n"; + if (parser_.opts.python_gen_numpy) { + ss << "import numpy as np\n"; + } + ss << '\n'; + + std::set modules; + std::map> names_by_module; + for (const Import &import : imports.imports) { + if (import.IsLocal()) continue; // skip all local imports + if (import.name == "") { + modules.insert(import.module); + } else { + names_by_module[import.module].insert(import.name); + } + } + + for (const std::string &module : modules) { + ss << "import " << module << '\n'; + } + for (const auto &import : names_by_module) { + ss << "from " << import.first << " import "; + size_t i = 0; + for (const std::string &name : import.second) { + if (i > 0) ss << ", "; + ss << name; + ++i; + } + ss << '\n'; + } + } + + const Parser &parser_; + const IdlNamer namer_; + const Version version_; +};} // namespace class PythonGenerator : public BaseGenerator { public: PythonGenerator(const Parser &parser, const std::string &path, - const std::string &file_name) + const std::string &file_name, const Version &version) : BaseGenerator(parser, path, file_name, "" /* not used */, "" /* not used */, "py"), float_const_gen_("float('nan')", "float('inf')", "float('-inf')"), - namer_(WithFlagOptions(PythonDefaultConfig(), parser.opts, path), - PythonKeywords()) {} + namer_(WithFlagOptions(kConfig, parser.opts, path), + Keywords(version)) {} // Most field accessors need to retrieve and test the field offset first, // this is the prefix code for that. @@ -424,16 +957,29 @@ class PythonGenerator : public BaseGenerator { code += Indent + Indent + "return None\n\n"; } + template + std::string ModuleFor(const T *def) const { + if (!parser_.opts.one_file) { + return namer_.NamespacedType(*def); + } + + std::string filename = + StripExtension(def->file) + parser_.opts.filename_suffix; + if (parser_.file_being_parsed_ == def->file) { + return "." + StripPath(filename); // make it a "local" import + } + + std::string module = parser_.opts.include_prefix + filename; + std::replace(module.begin(), module.end(), '/', '.'); + return module; + } + // Generate the package reference when importing a struct or enum from its // module. std::string GenPackageReference(const Type &type) const { - if (type.struct_def) { - return namer_.NamespacedType(*type.struct_def); - } else if (type.enum_def) { - return namer_.NamespacedType(*type.enum_def); - } else { - return "." + GenTypeGet(type); - } + if (type.struct_def) return ModuleFor(type.struct_def); + if (type.enum_def) return ModuleFor(type.enum_def); + return "." + GenTypeGet(type); } // Get the value of a vector's struct member. @@ -925,7 +1471,9 @@ class PythonGenerator : public BaseGenerator { GetMemberOfVectorOfStruct(struct_def, field, code_ptr, imports); } else { GetMemberOfVectorOfNonStruct(struct_def, field, code_ptr); - GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr); + if (parser_.opts.python_gen_numpy) { + GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr); + } GetVectorAsNestedFlatbuffer(struct_def, field, code_ptr, imports); } break; @@ -936,7 +1484,9 @@ class PythonGenerator : public BaseGenerator { GetArrayOfStruct(struct_def, field, code_ptr, imports); } else { GetArrayOfNonStruct(struct_def, field, code_ptr); - GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr); + if (parser_.opts.python_gen_numpy) { + GetVectorOfNonStructAsNumpy(struct_def, field, code_ptr); + } GetVectorAsNestedFlatbuffer(struct_def, field, code_ptr, imports); } break; @@ -1465,13 +2015,17 @@ class PythonGenerator : public BaseGenerator { return; } - code += GenIndents(3) + "if np is None:"; - GenUnpackforScalarVectorHelper(struct_def, field, code_ptr, 4); + if (parser_.opts.python_gen_numpy) { + code += GenIndents(3) + "if np is None:"; + GenUnpackforScalarVectorHelper(struct_def, field, code_ptr, 4); - // If numpy exists, use the AsNumpy method to optimize the unpack speed. - code += GenIndents(3) + "else:"; - code += GenIndents(4) + "self." + field_field + " = " + struct_var + "." + - field_method + "AsNumpy()"; + // If numpy exists, use the AsNumpy method to optimize the unpack speed. + code += GenIndents(3) + "else:"; + code += GenIndents(4) + "self." + field_field + " = " + struct_var + "." + + field_method + "AsNumpy()"; + } else { + GenUnpackforScalarVectorHelper(struct_def, field, code_ptr, 3); + } } void GenUnPackForScalar(const StructDef &struct_def, const FieldDef &field, @@ -1670,14 +2224,20 @@ class PythonGenerator : public BaseGenerator { return; } - code_prefix += GenIndents(3) + "if np is not None and type(self." + - field_field + ") is np.ndarray:"; - code_prefix += GenIndents(4) + field_field + - " = builder.CreateNumpyVector(self." + field_field + ")"; - code_prefix += GenIndents(3) + "else:"; - GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4); - code_prefix += "(self." + field_field + "[i])"; - code_prefix += GenIndents(4) + field_field + " = builder.EndVector()"; + if (parser_.opts.python_gen_numpy) { + code_prefix += GenIndents(3) + "if np is not None and type(self." + + field_field + ") is np.ndarray:"; + code_prefix += GenIndents(4) + field_field + + " = builder.CreateNumpyVector(self." + field_field + ")"; + code_prefix += GenIndents(3) + "else:"; + GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 4); + code_prefix += "(self." + field_field + "[i])"; + code_prefix += GenIndents(4) + field_field + " = builder.EndVector()"; + } else { + GenPackForScalarVectorFieldHelper(struct_def, field, code_prefix_ptr, 3); + code_prefix += "(self." + field_field + "[i])"; + code_prefix += GenIndents(4) + field_field + " = builder.EndVector()"; + } } void GenPackForStructField(const StructDef &struct_def, const FieldDef &field, @@ -1835,7 +2395,7 @@ class PythonGenerator : public BaseGenerator { auto field_type = namer_.ObjectType(*ev.union_type.struct_def); code += - GenIndents(1) + "if unionType == " + union_type + "()." + variant + ":"; + GenIndents(1) + "if unionType == " + union_type + "." + variant + ":"; if (parser_.opts.include_dependence_headers) { auto package_reference = GenPackageReference(ev.union_type); code += GenIndents(2) + "import " + package_reference; @@ -2021,7 +2581,7 @@ class PythonGenerator : public BaseGenerator { if (!generateStructs(&one_file_code, one_file_imports)) return false; if (parser_.opts.one_file) { - const std::string mod = file_name_ + "_generated"; + const std::string mod = file_name_ + parser_.opts.filename_suffix; // Legacy file format uses keep casing. return SaveType(mod + ".py", *parser_.current_namespace_, one_file_code, @@ -2098,7 +2658,9 @@ class PythonGenerator : public BaseGenerator { const std::string local_import = "." + mod; code += "import flatbuffers\n"; - code += "from flatbuffers.compat import import_numpy\n"; + if (parser_.opts.python_gen_numpy) { + code += "from flatbuffers.compat import import_numpy\n"; + } if (parser_.opts.python_typing) { code += "from typing import Any\n"; @@ -2114,7 +2676,9 @@ class PythonGenerator : public BaseGenerator { } } } - code += "np = import_numpy()\n\n"; + if (parser_.opts.python_gen_numpy) { + code += "np = import_numpy()\n\n"; + } } } @@ -2122,11 +2686,14 @@ class PythonGenerator : public BaseGenerator { bool SaveType(const std::string &defname, const Namespace &ns, const std::string &classcode, const ImportMap &imports, const std::string &mod, bool needs_imports) const { - if (!classcode.length()) return true; - std::string code = ""; - BeginFile(LastNamespacePart(ns), needs_imports, &code, mod, imports); - code += classcode; + if (classcode.empty()) { + BeginFile(LastNamespacePart(ns), false, &code, "", {}); + code += "# NOTE " + defname + " does not declare any structs or enums\n"; + } else { + BeginFile(LastNamespacePart(ns), needs_imports, &code, mod, imports); + code += classcode; + } const std::string directories = parser_.opts.one_file ? path_ : namer_.Directories(ns.components); @@ -2152,8 +2719,17 @@ class PythonGenerator : public BaseGenerator { static bool GeneratePython(const Parser &parser, const std::string &path, const std::string &file_name) { - python::PythonGenerator generator(parser, path, file_name); - return generator.generate(); + python::Version version{parser.opts.python_version}; + if (!version.IsValid()) return false; + + python::PythonGenerator generator(parser, path, file_name, version); + if (!generator.generate()) return false; + + if (parser.opts.python_typing) { + python::PythonStubGenerator stub_generator(parser, path, version); + if (!stub_generator.Generate()) return false; + } + return true; } namespace { diff --git a/third_party/flatbuffers/src/idl_gen_rust.cpp b/third_party/flatbuffers/src/idl_gen_rust.cpp index a85a7812dc6..b8811c6f3ff 100644 --- a/third_party/flatbuffers/src/idl_gen_rust.cpp +++ b/third_party/flatbuffers/src/idl_gen_rust.cpp @@ -131,8 +131,6 @@ static std::set RustKeywords() { // Terms that we use ourselves "follow", "push", - "size", - "alignment", "to_little_endian", "from_little_endian", "ENUM_MAX", @@ -729,7 +727,7 @@ class RustGenerator : public BaseGenerator { code_ += "mod bitflags_{{ENUM_NAMESPACE}} {"; code_ += " flatbuffers::bitflags::bitflags! {"; GenComment(enum_def.doc_comment, " "); - code_ += " #[derive(Default)]"; + code_ += " #[derive(Default, Debug, Clone, Copy, PartialEq)]"; code_ += " {{ACCESS_TYPE}} struct {{ENUM_TY}}: {{BASE_TYPE}} {"; ForAllEnumValues1(enum_def, [&](const EnumVal &ev) { this->GenComment(ev.doc_comment, " "); @@ -845,20 +843,7 @@ class RustGenerator : public BaseGenerator { code_ += " let b = flatbuffers::read_scalar_at::<{{BASE_TYPE}}>(buf, loc);"; if (IsBitFlagsEnum(enum_def)) { - // Safety: - // This is safe because we know bitflags is implemented with a repr - // transparent uint of the correct size. from_bits_unchecked will be - // replaced by an equivalent but safe from_bits_retain in bitflags 2.0 - // https://github.com/bitflags/bitflags/issues/262 - code_ += " // Safety:"; - code_ += - " // This is safe because we know bitflags is implemented with a " - "repr transparent uint of the correct size."; - code_ += - " // from_bits_unchecked will be replaced by an equivalent but " - "safe from_bits_retain in bitflags 2.0"; - code_ += " // https://github.com/bitflags/bitflags/issues/262"; - code_ += " Self::from_bits_unchecked(b)"; + code_ += " Self::from_bits_retain(b)"; } else { code_ += " Self(b)"; } @@ -886,20 +871,7 @@ class RustGenerator : public BaseGenerator { code_ += " fn from_little_endian(v: {{BASE_TYPE}}) -> Self {"; code_ += " let b = {{BASE_TYPE}}::from_le(v);"; if (IsBitFlagsEnum(enum_def)) { - // Safety: - // This is safe because we know bitflags is implemented with a repr - // transparent uint of the correct size. from_bits_unchecked will be - // replaced by an equivalent but safe from_bits_retain in bitflags 2.0 - // https://github.com/bitflags/bitflags/issues/262 - code_ += " // Safety:"; - code_ += - " // This is safe because we know bitflags is implemented with a " - "repr transparent uint of the correct size."; - code_ += - " // from_bits_unchecked will be replaced by an equivalent but " - "safe from_bits_retain in bitflags 2.0"; - code_ += " // https://github.com/bitflags/bitflags/issues/262"; - code_ += " unsafe { Self::from_bits_unchecked(b) }"; + code_ += " Self::from_bits_retain(b)"; } else { code_ += " Self(b)"; } @@ -2700,9 +2672,13 @@ class RustGenerator : public BaseGenerator { code_ += " unsafe fn push(&self, dst: &mut [u8], _written_len: usize) {"; code_ += " let src = ::core::slice::from_raw_parts(self as *const " - "{{STRUCT_TY}} as *const u8, Self::size());"; + "{{STRUCT_TY}} as *const u8, ::size());"; code_ += " dst.copy_from_slice(src);"; code_ += " }"; + code_ += " #[inline]"; + code_ += " fn alignment() -> flatbuffers::PushAlignment {"; + code_ += " flatbuffers::PushAlignment::new({{ALIGN}})"; + code_ += " }"; code_ += "}"; code_ += ""; diff --git a/third_party/flatbuffers/src/idl_gen_swift.cpp b/third_party/flatbuffers/src/idl_gen_swift.cpp index 6ac487c5573..e3318c968e8 100644 --- a/third_party/flatbuffers/src/idl_gen_swift.cpp +++ b/third_party/flatbuffers/src/idl_gen_swift.cpp @@ -328,7 +328,7 @@ class SwiftGenerator : public BaseGenerator { } else { code_ += "_{{FIELDVAR}} = {{VALUETYPE}}({{ACCESS}}.bb, o: " - "{{ACCESS}}.postion + {{OFFSET}})"; + "{{ACCESS}}.position + {{OFFSET}})"; } } Outdent(); @@ -361,7 +361,7 @@ class SwiftGenerator : public BaseGenerator { } else if (IsStruct(field.value.type)) { code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable()); code_ += GenReaderMainBody() + "return " + - GenConstructor("{{ACCESS}}.postion + {{OFFSET}}"); + GenConstructor("{{ACCESS}}.position + {{OFFSET}}"); } if (parser_.opts.mutable_buffer && !IsStruct(field.value.type)) code_ += GenMutate("{{OFFSET}}", "", IsEnum(field.value.type)); @@ -754,7 +754,7 @@ class SwiftGenerator : public BaseGenerator { code_.SetValue("VALUETYPE", GenType(field.value.type) + Mutable()); code_.SetValue("CONSTANT", "nil"); code_ += GenReaderMainBody(is_required) + GenOffset() + required_reader + - GenConstructor("o + {{ACCESS}}.postion"); + GenConstructor("o + {{ACCESS}}.position"); return; } switch (field.value.type.base_type) { @@ -763,7 +763,7 @@ class SwiftGenerator : public BaseGenerator { code_.SetValue("CONSTANT", "nil"); code_ += GenReaderMainBody(is_required) + GenOffset() + required_reader + - GenConstructor(GenIndirect("o + {{ACCESS}}.postion")); + GenConstructor(GenIndirect("o + {{ACCESS}}.position")); break; case BASE_TYPE_STRING: { @@ -1845,7 +1845,7 @@ class SwiftGenerator : public BaseGenerator { } std::string ValidateFunc() { - return "static func validateVersion() { FlatBuffersVersion_24_3_25() }"; + return "static func validateVersion() { FlatBuffersVersion_25_2_10() }"; } std::string GenType(const Type &type, diff --git a/third_party/flatbuffers/src/idl_gen_ts.cpp b/third_party/flatbuffers/src/idl_gen_ts.cpp index 41c05e3b887..e170514fdae 100644 --- a/third_party/flatbuffers/src/idl_gen_ts.cpp +++ b/third_party/flatbuffers/src/idl_gen_ts.cpp @@ -901,11 +901,15 @@ class TsGenerator : public BaseGenerator { std::string bare_file_path; std::string rel_file_path; - const auto &dep_comps = dependent.defined_namespace->components; - for (size_t i = 0; i < dep_comps.size(); i++) { - rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string("..")); + if (dependent.defined_namespace) { + const auto &dep_comps = dependent.defined_namespace->components; + for (size_t i = 0; i < dep_comps.size(); i++) { + rel_file_path += i == 0 ? ".." : (kPathSeparator + std::string("..")); + } + if (dep_comps.size() == 0) { rel_file_path += "."; } + } else { + rel_file_path += ".."; } - if (dep_comps.size() == 0) { rel_file_path += "."; } bare_file_path += kPathSeparator + diff --git a/third_party/flatbuffers/src/idl_namer.h b/third_party/flatbuffers/src/idl_namer.h index 9a7fdb8e368..dc829e78642 100644 --- a/third_party/flatbuffers/src/idl_namer.h +++ b/third_party/flatbuffers/src/idl_namer.h @@ -1,179 +1,6 @@ -#ifndef FLATBUFFERS_IDL_NAMER -#define FLATBUFFERS_IDL_NAMER +#ifndef FLATBUFFERS_IDL_NAMER_H_ +#define FLATBUFFERS_IDL_NAMER_H_ -#include "flatbuffers/idl.h" -#include "namer.h" +#include "codegen/idl_namer.h" -namespace flatbuffers { - -// Provides Namer capabilities to types defined in the flatbuffers IDL. -class IdlNamer : public Namer { - public: - explicit IdlNamer(Config config, std::set keywords) - : Namer(config, std::move(keywords)) {} - - using Namer::Constant; - using Namer::Directories; - using Namer::Field; - using Namer::File; - using Namer::Function; - using Namer::Method; - using Namer::Namespace; - using Namer::NamespacedType; - using Namer::ObjectType; - using Namer::Type; - using Namer::Variable; - using Namer::Variant; - - std::string Constant(const FieldDef &d) const { return Constant(d.name); } - - // Types are always structs or enums so we can only expose these two - // overloads. - std::string Type(const StructDef &d) const { return Type(d.name); } - std::string Type(const EnumDef &d) const { return Type(d.name); } - - std::string Function(const Definition &s) const { return Function(s.name); } - std::string Function(const std::string& prefix, const Definition &s) const { - return Function(prefix + s.name); - } - - std::string Field(const FieldDef &s) const { return Field(s.name); } - std::string Field(const FieldDef &d, const std::string &s) const { - return Field(d.name + "_" + s); - } - - std::string Variable(const FieldDef &s) const { return Variable(s.name); } - - std::string Variable(const StructDef &s) const { return Variable(s.name); } - - std::string Variant(const EnumVal &s) const { return Variant(s.name); } - - std::string EnumVariant(const EnumDef &e, const EnumVal &v) const { - return Type(e) + config_.enum_variant_seperator + Variant(v); - } - - std::string ObjectType(const StructDef &d) const { - return ObjectType(d.name); - } - std::string ObjectType(const EnumDef &d) const { return ObjectType(d.name); } - - std::string Method(const FieldDef &d, const std::string &suffix) const { - return Method(d.name, suffix); - } - std::string Method(const std::string &prefix, const StructDef &d) const { - return Method(prefix, d.name); - } - std::string Method(const std::string &prefix, const FieldDef &d) const { - return Method(prefix, d.name); - } - std::string Method(const std::string &prefix, const FieldDef &d, - const std::string &suffix) const { - return Method(prefix, d.name, suffix); - } - - std::string Namespace(const struct Namespace &ns) const { - return Namespace(ns.components); - } - - std::string NamespacedEnumVariant(const EnumDef &e, const EnumVal &v) const { - return NamespacedString(e.defined_namespace, EnumVariant(e, v)); - } - - std::string NamespacedType(const Definition &def) const { - return NamespacedString(def.defined_namespace, Type(def.name)); - } - - std::string NamespacedObjectType(const Definition &def) const { - return NamespacedString(def.defined_namespace, ObjectType(def.name)); - } - - std::string Directories(const struct Namespace &ns, - SkipDir skips = SkipDir::None, - Case input_case = Case::kUpperCamel) const { - return Directories(ns.components, skips, input_case); - } - - // Legacy fields do not really follow the usual config and should be - // considered for deprecation. - - std::string LegacyRustNativeVariant(const EnumVal &v) const { - return ConvertCase(EscapeKeyword(v.name), Case::kUpperCamel); - } - - std::string LegacyRustFieldOffsetName(const FieldDef &field) const { - return "VT_" + ConvertCase(EscapeKeyword(field.name), Case::kAllUpper); - } - std::string LegacyRustUnionTypeOffsetName(const FieldDef &field) const { - return "VT_" + ConvertCase(EscapeKeyword(field.name + "_type"), Case::kAllUpper); - } - - - std::string LegacySwiftVariant(const EnumVal &ev) const { - auto name = ev.name; - if (isupper(name.front())) { - std::transform(name.begin(), name.end(), name.begin(), CharToLower); - } - return EscapeKeyword(ConvertCase(name, Case::kLowerCamel)); - } - - // Also used by Kotlin, lol. - std::string LegacyJavaMethod2(const std::string &prefix, const StructDef &sd, - const std::string &suffix) const { - return prefix + sd.name + suffix; - } - - std::string LegacyKotlinVariant(EnumVal &ev) const { - // Namer assumes the input case is snake case which is wrong... - return ConvertCase(EscapeKeyword(ev.name), Case::kLowerCamel); - } - // Kotlin methods escapes keywords after case conversion but before - // prefixing and suffixing. - std::string LegacyKotlinMethod(const std::string &prefix, const FieldDef &d, - const std::string &suffix) const { - return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) + - suffix; - } - std::string LegacyKotlinMethod(const std::string &prefix, const StructDef &d, - const std::string &suffix) const { - return prefix + ConvertCase(EscapeKeyword(d.name), Case::kUpperCamel) + - suffix; - } - - // This is a mix of snake case and keep casing, when Ts should be using - // lower camel case. - std::string LegacyTsMutateMethod(const FieldDef& d) { - return "mutate_" + d.name; - } - - std::string LegacyRustUnionTypeMethod(const FieldDef &d) { - // assert d is a union - // d should convert case but not escape keywords due to historical reasons - return ConvertCase(d.name, config_.fields, Case::kLowerCamel) + "_type"; - } - - private: - std::string NamespacedString(const struct Namespace *ns, - const std::string &str) const { - std::string ret; - if (ns != nullptr) { ret += Namespace(ns->components); } - if (!ret.empty()) ret += config_.namespace_seperator; - return ret + str; - } -}; - -// This is a temporary helper function for code generators to call until all -// flag-overriding logic into flatc.cpp -inline Namer::Config WithFlagOptions(const Namer::Config &input, - const IDLOptions &opts, - const std::string &path) { - Namer::Config result = input; - result.object_prefix = opts.object_prefix; - result.object_suffix = opts.object_suffix; - result.output_path = path; - result.filename_suffix = opts.filename_suffix; - return result; -} - -} // namespace flatbuffers - -#endif // FLATBUFFERS_IDL_NAMER +#endif // FLATBUFFERS_IDL_NAMER_H_ diff --git a/third_party/flatbuffers/src/namer.h b/third_party/flatbuffers/src/namer.h index 097d4490bcd..1bb3a087f89 100644 --- a/third_party/flatbuffers/src/namer.h +++ b/third_party/flatbuffers/src/namer.h @@ -1,270 +1,6 @@ -#ifndef FLATBUFFERS_NAMER -#define FLATBUFFERS_NAMER +#ifndef FLATBUFFERS_NAMER_H_ +#define FLATBUFFERS_NAMER_H_ -#include "flatbuffers/util.h" +#include "codegen/namer.h" -namespace flatbuffers { - -// Options for Namer::File. -enum class SkipFile { - None = 0, - Suffix = 1, - Extension = 2, - SuffixAndExtension = 3, -}; -inline SkipFile operator&(SkipFile a, SkipFile b) { - return static_cast(static_cast(a) & static_cast(b)); -} -// Options for Namer::Directories -enum class SkipDir { - None = 0, - // Skip prefixing the -o $output_path. - OutputPath = 1, - // Skip trailing path seperator. - TrailingPathSeperator = 2, - OutputPathAndTrailingPathSeparator = 3, -}; -inline SkipDir operator&(SkipDir a, SkipDir b) { - return static_cast(static_cast(a) & static_cast(b)); -} - -// `Namer` applies style configuration to symbols in generated code. It manages -// casing, escapes keywords, and object API naming. -// TODO: Refactor all code generators to use this. -class Namer { - public: - struct Config { - // Symbols in code. - - // Case style for flatbuffers-defined types. - // e.g. `class TableA {}` - Case types; - // Case style for flatbuffers-defined constants. - // e.g. `uint64_t ENUM_A_MAX`; - Case constants; - // Case style for flatbuffers-defined methods. - // e.g. `class TableA { int field_a(); }` - Case methods; - // Case style for flatbuffers-defined functions. - // e.g. `TableA* get_table_a_root()`; - Case functions; - // Case style for flatbuffers-defined fields. - // e.g. `struct Struct { int my_field; }` - Case fields; - // Case style for flatbuffers-defined variables. - // e.g. `int my_variable = 2` - Case variables; - // Case style for flatbuffers-defined variants. - // e.g. `enum class Enum { MyVariant, }` - Case variants; - // Seperator for qualified enum names. - // e.g. `Enum::MyVariant` uses `::`. - std::string enum_variant_seperator; - - // Configures, when formatting code, whether symbols are checked against - // keywords and escaped before or after case conversion. It does not make - // sense to do so before, but its legacy behavior. :shrug: - // TODO(caspern): Deprecate. - enum class Escape { - BeforeConvertingCase, - AfterConvertingCase, - }; - Escape escape_keywords; - - // Namespaces - - // e.g. `namespace my_namespace {}` - Case namespaces; - // The seperator between namespaces in a namespace path. - std::string namespace_seperator; - - // Object API. - // Native versions flatbuffers types have this prefix. - // e.g. "" (it's usually empty string) - std::string object_prefix; - // Native versions flatbuffers types have this suffix. - // e.g. "T" - std::string object_suffix; - - // Keywords. - // Prefix used to escape keywords. It is usually empty string. - std::string keyword_prefix; - // Suffix used to escape keywords. It is usually "_". - std::string keyword_suffix; - - // Files. - - // Case style for filenames. e.g. `foo_bar_generated.rs` - Case filenames; - // Case style for directories, e.g. `output_files/foo_bar/baz/` - Case directories; - // The directory within which we will generate files. - std::string output_path; - // Suffix for generated file names, e.g. "_generated". - std::string filename_suffix; - // Extension for generated files, e.g. ".cpp" or ".rs". - std::string filename_extension; - }; - Namer(Config config, std::set keywords) - : config_(config), keywords_(std::move(keywords)) {} - - virtual ~Namer() {} - - template std::string Method(const T &s) const { - return Method(s.name); - } - - virtual std::string Method(const std::string &pre, - const std::string &mid, - const std::string &suf) const { - return Format(pre + "_" + mid + "_" + suf, config_.methods); - } - virtual std::string Method(const std::string &pre, - const std::string &suf) const { - return Format(pre + "_" + suf, config_.methods); - } - virtual std::string Method(const std::string &s) const { - return Format(s, config_.methods); - } - - virtual std::string Constant(const std::string &s) const { - return Format(s, config_.constants); - } - - virtual std::string Function(const std::string &s) const { - return Format(s, config_.functions); - } - - virtual std::string Variable(const std::string &s) const { - return Format(s, config_.variables); - } - - template - std::string Variable(const std::string &p, const T &s) const { - return Format(p + "_" + s.name, config_.variables); - } - virtual std::string Variable(const std::string &p, - const std::string &s) const { - return Format(p + "_" + s, config_.variables); - } - - virtual std::string Namespace(const std::string &s) const { - return Format(s, config_.namespaces); - } - - virtual std::string Namespace(const std::vector &ns) const { - std::string result; - for (auto it = ns.begin(); it != ns.end(); it++) { - if (it != ns.begin()) result += config_.namespace_seperator; - result += Namespace(*it); - } - return result; - } - - virtual std::string NamespacedType(const std::vector &ns, - const std::string &s) const { - return (ns.empty() ? "" : (Namespace(ns) + config_.namespace_seperator)) + - Type(s); - } - - // Returns `filename` with the right casing, suffix, and extension. - virtual std::string File(const std::string &filename, - SkipFile skips = SkipFile::None) const { - const bool skip_suffix = (skips & SkipFile::Suffix) != SkipFile::None; - const bool skip_ext = (skips & SkipFile::Extension) != SkipFile::None; - return ConvertCase(filename, config_.filenames, Case::kUpperCamel) + - (skip_suffix ? "" : config_.filename_suffix) + - (skip_ext ? "" : config_.filename_extension); - } - template - std::string File(const T &f, SkipFile skips = SkipFile::None) const { - return File(f.name, skips); - } - - // Formats `directories` prefixed with the output_path and joined with the - // right seperator. Output path prefixing and the trailing separator may be - // skiped using `skips`. - // Callers may want to use `EnsureDirExists` with the result. - // input_case is used to tell how to modify namespace. e.g. kUpperCamel will - // add a underscode between case changes, so MyGame turns into My_Game - // (depending also on the output_case). - virtual std::string Directories(const std::vector &directories, - SkipDir skips = SkipDir::None, - Case input_case = Case::kUpperCamel) const { - const bool skip_output_path = - (skips & SkipDir::OutputPath) != SkipDir::None; - const bool skip_trailing_seperator = - (skips & SkipDir::TrailingPathSeperator) != SkipDir::None; - std::string result = skip_output_path ? "" : config_.output_path; - for (auto d = directories.begin(); d != directories.end(); d++) { - result += ConvertCase(*d, config_.directories, input_case); - result.push_back(kPathSeparator); - } - if (skip_trailing_seperator && !result.empty()) result.pop_back(); - return result; - } - - virtual std::string EscapeKeyword(const std::string &name) const { - if (keywords_.find(name) == keywords_.end()) { - return name; - } else { - return config_.keyword_prefix + name + config_.keyword_suffix; - } - } - - virtual std::string Type(const std::string &s) const { - return Format(s, config_.types); - } - virtual std::string Type(const std::string &t, const std::string &s) const { - return Format(t + "_" + s, config_.types); - } - - virtual std::string ObjectType(const std::string &s) const { - return config_.object_prefix + Type(s) + config_.object_suffix; - } - - virtual std::string Field(const std::string &s) const { - return Format(s, config_.fields); - } - - virtual std::string Variant(const std::string &s) const { - return Format(s, config_.variants); - } - - virtual std::string Format(const std::string &s, Case casing) const { - if (config_.escape_keywords == Config::Escape::BeforeConvertingCase) { - return ConvertCase(EscapeKeyword(s), casing, Case::kLowerCamel); - } else { - return EscapeKeyword(ConvertCase(s, casing, Case::kLowerCamel)); - } - } - - // Denamespaces a string (e.g. The.Quick.Brown.Fox) by returning the last part - // after the `delimiter` (Fox) and placing the rest in `namespace_prefix` - // (The.Quick.Brown). - virtual std::string Denamespace(const std::string &s, - std::string &namespace_prefix, - const char delimiter = '.') const { - const size_t pos = s.find_last_of(delimiter); - if (pos == std::string::npos) { - namespace_prefix = ""; - return s; - } - namespace_prefix = s.substr(0, pos); - return s.substr(pos + 1); - } - - // Same as above, but disregards the prefix. - virtual std::string Denamespace(const std::string &s, - const char delimiter = '.') const { - std::string prefix; - return Denamespace(s, prefix, delimiter); - } - - const Config config_; - const std::set keywords_; -}; - -} // namespace flatbuffers - -#endif // FLATBUFFERS_NAMER +#endif // FLATBUFFERS_NAMER_H_ diff --git a/third_party/flatbuffers/swift.swiftformat b/third_party/flatbuffers/swift.swiftformat index 80e475a51f3..f8b2a6b028d 100644 --- a/third_party/flatbuffers/swift.swiftformat +++ b/third_party/flatbuffers/swift.swiftformat @@ -6,7 +6,7 @@ # options --self remove # redundantSelf ---importgrouping testable-bottom # sortedImports +--importgrouping testable-bottom # sortImports --trimwhitespace always --indentcase false --ifdef no-indent #indent @@ -17,7 +17,7 @@ --typeattributes prev-line # wrapAttributes # rules ---rules wrap,todos,anyObjectProtocol,redundantParens,redundantReturn,redundantSelf,sortedImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader +--rules wrap,todos,anyObjectProtocol,redundantParens,redundantReturn,redundantSelf,sortImports,strongifiedSelf,trailingCommas,trailingSpace,wrapArguments,wrapMultilineStatementBraces,indent,wrapAttributes,void,fileHeader --disable trailingclosures --exclude **/*_generated.swift diff --git a/third_party/flatbuffers/swift/BUILD.bazel b/third_party/flatbuffers/swift/BUILD.bazel new file mode 100644 index 00000000000..7bbf2988719 --- /dev/null +++ b/third_party/flatbuffers/swift/BUILD.bazel @@ -0,0 +1,8 @@ +load("@build_bazel_rules_swift//swift:swift.bzl", "swift_library") + +swift_library( + name = "swift", + srcs = glob(["Sources/FlatBuffers/*.swift"]), + module_name = "FlatBuffers", + visibility = ["//visibility:public"], +) diff --git a/third_party/flatbuffers/swift/LICENSE b/third_party/flatbuffers/swift/LICENSE new file mode 100644 index 00000000000..d6456956733 --- /dev/null +++ b/third_party/flatbuffers/swift/LICENSE @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/third_party/flatbuffers/swift/README.md b/third_party/flatbuffers/swift/README.md new file mode 100644 index 00000000000..cbacbf4f9c9 --- /dev/null +++ b/third_party/flatbuffers/swift/README.md @@ -0,0 +1,11 @@ +FlatBuffers swift can be found in both SPM + +`.package(url: "https://github.com/google/flatbuffers.git", from: "X.Y.Z"),` + +and Cocoapods + +`pod 'FlatBuffers'` + +### Contribute + +1- Always run `swift test --generate-linuxmain` whenever new test functions are added or removed \ No newline at end of file diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/ByteBuffer.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/ByteBuffer.swift new file mode 100644 index 00000000000..9442c855a6c --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/ByteBuffer.swift @@ -0,0 +1,542 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// `ByteBuffer` is the interface that stores the data for a `Flatbuffers` object +/// it allows users to write and read data directly from memory thus the use of its +/// functions should be used +@frozen +public struct ByteBuffer { + + /// Storage is a container that would hold the memory pointer to solve the issue of + /// deallocating the memory that was held by (memory: UnsafeMutableRawPointer) + @usableFromInline + final class Storage { + // This storage doesn't own the memory, therefore, we won't deallocate on deinit. + private let unowned: Bool + /// pointer to the start of the buffer object in memory + var memory: UnsafeMutableRawPointer + /// Capacity of UInt8 the buffer can hold + var capacity: Int + + @usableFromInline + init(count: Int, alignment: Int) { + memory = UnsafeMutableRawPointer.allocate( + byteCount: count, + alignment: alignment) + capacity = count + unowned = false + } + + @usableFromInline + init(memory: UnsafeMutableRawPointer, capacity: Int, unowned: Bool) { + self.memory = memory + self.capacity = capacity + self.unowned = unowned + } + + deinit { + if !unowned { + memory.deallocate() + } + } + + @usableFromInline + func copy(from ptr: UnsafeRawPointer, count: Int) { + assert( + !unowned, + "copy should NOT be called on a buffer that is built by assumingMemoryBound") + memory.copyMemory(from: ptr, byteCount: count) + } + + @usableFromInline + func initialize(for size: Int) { + assert( + !unowned, + "initalize should NOT be called on a buffer that is built by assumingMemoryBound") + memset(memory, 0, size) + } + + /// Reallocates the buffer incase the object to be written doesnt fit in the current buffer + /// - Parameter size: Size of the current object + @usableFromInline + func reallocate(_ size: Int, writerSize: Int, alignment: Int) { + let currentWritingIndex = capacity &- writerSize + while capacity <= writerSize &+ size { + capacity = capacity << 1 + } + + /// solution take from Apple-NIO + capacity = capacity.convertToPowerofTwo + + let newData = UnsafeMutableRawPointer.allocate( + byteCount: capacity, + alignment: alignment) + memset(newData, 0, capacity &- writerSize) + memcpy( + newData.advanced(by: capacity &- writerSize), + memory.advanced(by: currentWritingIndex), + writerSize) + memory.deallocate() + memory = newData + } + } + + @usableFromInline var _storage: Storage + + /// The size of the elements written to the buffer + their paddings + private var _writerSize: Int = 0 + /// Alignment of the current memory being written to the buffer + var alignment = 1 + /// Current Index which is being used to write to the buffer, it is written from the end to the start of the buffer + var writerIndex: Int { _storage.capacity &- _writerSize } + + /// Reader is the position of the current Writer Index (capacity - size) + public var reader: Int { writerIndex } + /// Current size of the buffer + public var size: UOffset { UOffset(_writerSize) } + /// Public Pointer to the buffer object in memory. This should NOT be modified for any reason + public var memory: UnsafeMutableRawPointer { _storage.memory } + /// Current capacity for the buffer + public var capacity: Int { _storage.capacity } + /// Crash if the trying to read an unaligned buffer instead of allowing users to read them. + public let allowReadingUnalignedBuffers: Bool + + /// Constructor that creates a Flatbuffer object from a UInt8 + /// - Parameter + /// - bytes: Array of UInt8 + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + public init( + bytes: [UInt8], + allowReadingUnalignedBuffers allowUnalignedBuffers: Bool = false) + { + var b = bytes + _storage = Storage(count: bytes.count, alignment: alignment) + _writerSize = _storage.capacity + allowReadingUnalignedBuffers = allowUnalignedBuffers + b.withUnsafeMutableBytes { bufferPointer in + _storage.copy(from: bufferPointer.baseAddress!, count: bytes.count) + } + } + + #if !os(WASI) + /// Constructor that creates a Flatbuffer from the Swift Data type object + /// - Parameter + /// - data: Swift data Object + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + public init( + data: Data, + allowReadingUnalignedBuffers allowUnalignedBuffers: Bool = false) + { + var b = data + _storage = Storage(count: data.count, alignment: alignment) + _writerSize = _storage.capacity + allowReadingUnalignedBuffers = allowUnalignedBuffers + b.withUnsafeMutableBytes { bufferPointer in + _storage.copy(from: bufferPointer.baseAddress!, count: data.count) + } + } + #endif + + /// Constructor that creates a Flatbuffer instance with a size + /// - Parameter: + /// - size: Length of the buffer + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + init(initialSize size: Int) { + let size = size.convertToPowerofTwo + _storage = Storage(count: size, alignment: alignment) + _storage.initialize(for: size) + allowReadingUnalignedBuffers = false + } + + #if swift(>=5.0) && !os(WASI) + /// Constructor that creates a Flatbuffer object from a ContiguousBytes + /// - Parameters: + /// - contiguousBytes: Binary stripe to use as the buffer + /// - count: amount of readable bytes + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + public init( + contiguousBytes: Bytes, + count: Int, + allowReadingUnalignedBuffers allowUnalignedBuffers: Bool = false) + { + _storage = Storage(count: count, alignment: alignment) + _writerSize = _storage.capacity + allowReadingUnalignedBuffers = allowUnalignedBuffers + contiguousBytes.withUnsafeBytes { buf in + _storage.copy(from: buf.baseAddress!, count: buf.count) + } + } + #endif + + /// Constructor that creates a Flatbuffer from unsafe memory region without copying + /// - Parameter: + /// - assumingMemoryBound: The unsafe memory region + /// - capacity: The size of the given memory region + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + public init( + assumingMemoryBound memory: UnsafeMutableRawPointer, + capacity: Int, + allowReadingUnalignedBuffers allowUnalignedBuffers: Bool = false) + { + _storage = Storage(memory: memory, capacity: capacity, unowned: true) + _writerSize = capacity + allowReadingUnalignedBuffers = allowUnalignedBuffers + } + + /// Creates a copy of the buffer that's being built by calling sizedBuffer + /// - Parameters: + /// - memory: Current memory of the buffer + /// - count: count of bytes + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + init( + memory: UnsafeMutableRawPointer, + count: Int, + allowReadingUnalignedBuffers allowUnalignedBuffers: Bool = false) + { + _storage = Storage(count: count, alignment: alignment) + _storage.copy(from: memory, count: count) + _writerSize = _storage.capacity + allowReadingUnalignedBuffers = allowUnalignedBuffers + } + + /// Creates a copy of the existing flatbuffer, by copying it to a different memory. + /// - Parameters: + /// - memory: Current memory of the buffer + /// - count: count of bytes + /// - removeBytes: Removes a number of bytes from the current size + /// - allowReadingUnalignedBuffers: allow reading from unaligned buffer + init( + memory: UnsafeMutableRawPointer, + count: Int, + removing removeBytes: Int, + allowReadingUnalignedBuffers allowUnalignedBuffers: Bool = false) + { + _storage = Storage(count: count, alignment: alignment) + _storage.copy(from: memory, count: count) + _writerSize = removeBytes + allowReadingUnalignedBuffers = allowUnalignedBuffers + } + + /// Fills the buffer with padding by adding to the writersize + /// - Parameter padding: Amount of padding between two to be serialized objects + @inline(__always) + @usableFromInline + mutating func fill(padding: Int) { + assert(padding >= 0, "Fill should be larger than or equal to zero") + ensureSpace(size: padding) + _writerSize = _writerSize &+ (MemoryLayout.size &* padding) + } + + /// Adds an array of type Scalar to the buffer memory + /// - Parameter elements: An array of Scalars + @inline(__always) + @usableFromInline + mutating func push(elements: [T]) { + elements.withUnsafeBytes { ptr in + ensureSpace(size: ptr.count) + memcpy( + _storage.memory.advanced(by: writerIndex &- ptr.count), + ptr.baseAddress!, + ptr.count) + _writerSize = _writerSize &+ ptr.count + } + } + + /// Adds an array of type Scalar to the buffer memory + /// - Parameter elements: An array of Scalars + @inline(__always) + @usableFromInline + mutating func push(elements: [T]) { + elements.withUnsafeBytes { ptr in + ensureSpace(size: ptr.count) + memcpy( + _storage.memory.advanced(by: writerIndex &- ptr.count), + ptr.baseAddress!, + ptr.count) + _writerSize = _writerSize &+ ptr.count + } + } + + /// Adds a `ContiguousBytes` to buffer memory + /// - Parameter value: bytes to copy + #if swift(>=5.0) && !os(WASI) + @inline(__always) + @usableFromInline + mutating func push(bytes: ContiguousBytes) { + bytes.withUnsafeBytes { ptr in + ensureSpace(size: ptr.count) + memcpy( + _storage.memory.advanced(by: writerIndex &- ptr.count), + ptr.baseAddress!, + ptr.count) + _writerSize = _writerSize &+ ptr.count + } + } + #endif + + /// Adds an object of type NativeStruct into the buffer + /// - Parameters: + /// - value: Object that will be written to the buffer + /// - size: size to subtract from the WriterIndex + @usableFromInline + @inline(__always) + mutating func push(struct value: T, size: Int) { + ensureSpace(size: size) + withUnsafePointer(to: value) { + memcpy( + _storage.memory.advanced(by: writerIndex &- size), + $0, + size) + _writerSize = _writerSize &+ size + } + } + + /// Adds an object of type Scalar into the buffer + /// - Parameters: + /// - value: Object that will be written to the buffer + /// - len: Offset to subtract from the WriterIndex + @inline(__always) + @usableFromInline + mutating func push(value: T, len: Int) { + ensureSpace(size: len) + withUnsafePointer(to: value) { + memcpy( + _storage.memory.advanced(by: writerIndex &- len), + $0, + len) + _writerSize = _writerSize &+ len + } + } + + /// Adds a string to the buffer using swift.utf8 object + /// - Parameter str: String that will be added to the buffer + /// - Parameter len: length of the string + @inline(__always) + @usableFromInline + mutating func push(string str: String, len: Int) { + ensureSpace(size: len) + if str.utf8 + .withContiguousStorageIfAvailable({ self.push(bytes: $0, len: len) }) != + nil + { + } else { + let utf8View = str.utf8 + for c in utf8View.reversed() { + push(value: c, len: 1) + } + } + } + + /// Writes a string to Bytebuffer using UTF8View + /// - Parameters: + /// - bytes: Pointer to the view + /// - len: Size of string + @usableFromInline + @inline(__always) + mutating func push( + bytes: UnsafeBufferPointer, + len: Int) -> Bool + { + memcpy( + _storage.memory.advanced(by: writerIndex &- len), + bytes.baseAddress!, + len) + _writerSize = _writerSize &+ len + return true + } + + /// Write stores an object into the buffer directly or indirectly. + /// + /// Direct: ignores the capacity of buffer which would mean we are referring to the direct point in memory + /// indirect: takes into respect the current capacity of the buffer (capacity - index), writing to the buffer from the end + /// - Parameters: + /// - value: Value that needs to be written to the buffer + /// - index: index to write to + /// - direct: Should take into consideration the capacity of the buffer + @inline(__always) + func write(value: T, index: Int, direct: Bool = false) { + var index = index + if !direct { + index = _storage.capacity &- index + } + assert(index < _storage.capacity, "Write index is out of writing bound") + assert(index >= 0, "Writer index should be above zero") + withUnsafePointer(to: value) { + memcpy( + _storage.memory.advanced(by: index), + $0, + MemoryLayout.size) + } + } + + /// Makes sure that buffer has enouch space for each of the objects that will be written into it + /// - Parameter size: size of object + @discardableResult + @usableFromInline + @inline(__always) + mutating func ensureSpace(size: Int) -> Int { + if size &+ _writerSize > _storage.capacity { + _storage.reallocate(size, writerSize: _writerSize, alignment: alignment) + } + assert(size < FlatBufferMaxSize, "Buffer can't grow beyond 2 Gigabytes") + return size + } + + /// pops the written VTable if it's already written into the buffer + /// - Parameter size: size of the `VTable` + @usableFromInline + @inline(__always) + mutating func pop(_ size: Int) { + assert( + (_writerSize &- size) > 0, + "New size should NOT be a negative number") + memset(_storage.memory.advanced(by: writerIndex), 0, _writerSize &- size) + _writerSize = size + } + + /// Clears the current size of the buffer + @inline(__always) + mutating public func clearSize() { + _writerSize = 0 + } + + /// Clears the current instance of the buffer, replacing it with new memory + @inline(__always) + mutating public func clear() { + _writerSize = 0 + alignment = 1 + _storage.initialize(for: _storage.capacity) + } + + /// Reads an object from the buffer + /// - Parameters: + /// - def: Type of the object + /// - position: the index of the object in the buffer + @inline(__always) + public func read(def: T.Type, position: Int) -> T { + if allowReadingUnalignedBuffers { + return _storage.memory.advanced(by: position).loadUnaligned(as: T.self) + } + return _storage.memory.advanced(by: position).load(as: T.self) + } + + /// Reads a slice from the memory assuming a type of T + /// - Parameters: + /// - index: index of the object to be read from the buffer + /// - count: count of bytes in memory + @inline(__always) + public func readSlice( + index: Int, + count: Int) -> [T] + { + assert( + index + count <= _storage.capacity, + "Reading out of bounds is illegal") + let start = _storage.memory.advanced(by: index) + .assumingMemoryBound(to: T.self) + let array = UnsafeBufferPointer(start: start, count: count) + return Array(array) + } + + #if !os(WASI) + /// Reads a string from the buffer and encodes it to a swift string + /// - Parameters: + /// - index: index of the string in the buffer + /// - count: length of the string + /// - type: Encoding of the string + @inline(__always) + public func readString( + at index: Int, + count: Int, + type: String.Encoding = .utf8) -> String? + { + assert( + index + count <= _storage.capacity, + "Reading out of bounds is illegal") + let start = _storage.memory.advanced(by: index) + .assumingMemoryBound(to: UInt8.self) + let bufprt = UnsafeBufferPointer(start: start, count: count) + return String(bytes: Array(bufprt), encoding: type) + } + #else + /// Reads a string from the buffer and encodes it to a swift string + /// - Parameters: + /// - index: index of the string in the buffer + /// - count: length of the string + @inline(__always) + public func readString( + at index: Int, + count: Int) -> String? + { + assert( + index + count <= _storage.capacity, + "Reading out of bounds is illegal") + let start = _storage.memory.advanced(by: index) + .assumingMemoryBound(to: UInt8.self) + let bufprt = UnsafeBufferPointer(start: start, count: count) + return String(cString: bufprt.baseAddress!) + } + #endif + + /// Creates a new Flatbuffer object that's duplicated from the current one + /// - Parameter removeBytes: the amount of bytes to remove from the current Size + @inline(__always) + public func duplicate(removing removeBytes: Int = 0) -> ByteBuffer { + assert(removeBytes > 0, "Can NOT remove negative bytes") + assert( + removeBytes < _storage.capacity, + "Can NOT remove more bytes than the ones allocated") + return ByteBuffer( + memory: _storage.memory, + count: _storage.capacity, + removing: _writerSize &- removeBytes) + } + + /// Returns the written bytes into the ``ByteBuffer`` + public var underlyingBytes: [UInt8] { + let cp = capacity &- writerIndex + let start = memory.advanced(by: writerIndex) + .bindMemory(to: UInt8.self, capacity: cp) + + let ptr = UnsafeBufferPointer(start: start, count: cp) + return Array(ptr) + } + + /// SkipPrefix Skips the first 4 bytes in case one of the following + /// functions are called `getPrefixedSizeCheckedRoot` & `getPrefixedSizeRoot` + /// which allows us to skip the first 4 bytes instead of recreating the buffer + @discardableResult + @usableFromInline + @inline(__always) + mutating func skipPrefix() -> Int32 { + _writerSize = _writerSize &- MemoryLayout.size + return read(def: Int32.self, position: 0) + } + +} + +extension ByteBuffer: CustomDebugStringConvertible { + + public var debugDescription: String { + """ + buffer located at: \(_storage.memory), with capacity of \(_storage.capacity) + { writerSize: \(_writerSize), readerSize: \(reader), writerIndex: \( + writerIndex) } + """ + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Constants.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Constants.swift new file mode 100644 index 00000000000..e24fc05b1f3 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Constants.swift @@ -0,0 +1,114 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// A boolean to see if the system is littleEndian +let isLitteEndian: Bool = { + let number: UInt32 = 0x12345678 + return number == number.littleEndian +}() +/// Constant for the file id length +let FileIdLength = 4 +/// Type aliases +public typealias Byte = UInt8 +public typealias UOffset = UInt32 +public typealias SOffset = Int32 +public typealias VOffset = UInt16 +/// Maximum size for a buffer +public let FlatBufferMaxSize = UInt32 + .max << ((MemoryLayout.size * 8 - 1) - 1) + +/// Protocol that All Scalars should conform to +/// +/// Scalar is used to conform all the numbers that can be represented in a FlatBuffer. It's used to write/read from the buffer. +public protocol Scalar: Equatable { + associatedtype NumericValue + var convertedEndian: NumericValue { get } +} + +extension Scalar where Self: Verifiable {} + +extension Scalar where Self: FixedWidthInteger { + /// Converts the value from BigEndian to LittleEndian + /// + /// Converts values to little endian on machines that work with BigEndian, however this is NOT TESTED yet. + public var convertedEndian: NumericValue { + self as! Self.NumericValue + } +} + +extension Double: Scalar, Verifiable { + public typealias NumericValue = UInt64 + + public var convertedEndian: UInt64 { + bitPattern.littleEndian + } +} + +extension Float32: Scalar, Verifiable { + public typealias NumericValue = UInt32 + + public var convertedEndian: UInt32 { + bitPattern.littleEndian + } +} + +extension Bool: Scalar, Verifiable { + public var convertedEndian: UInt8 { + self == true ? 1 : 0 + } + + public typealias NumericValue = UInt8 +} + +extension Int: Scalar, Verifiable { + public typealias NumericValue = Int +} + +extension Int8: Scalar, Verifiable { + public typealias NumericValue = Int8 +} + +extension Int16: Scalar, Verifiable { + public typealias NumericValue = Int16 +} + +extension Int32: Scalar, Verifiable { + public typealias NumericValue = Int32 +} + +extension Int64: Scalar, Verifiable { + public typealias NumericValue = Int64 +} + +extension UInt8: Scalar, Verifiable { + public typealias NumericValue = UInt8 +} + +extension UInt16: Scalar, Verifiable { + public typealias NumericValue = UInt16 +} + +extension UInt32: Scalar, Verifiable { + public typealias NumericValue = UInt32 +} + +extension UInt64: Scalar, Verifiable { + public typealias NumericValue = UInt64 +} + +public func FlatBuffersVersion_25_2_10() {} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Documentation.md b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Documentation.md new file mode 100644 index 00000000000..a1510808ebf --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Documentation.md @@ -0,0 +1,22 @@ +# ``FlatBuffers`` + +FlatBuffers: Memory Efficient Serialization Library + +## Overview + +- Access to serialized data without parsing/unpacking - What sets FlatBuffers apart is that it represents hierarchical data in a flat binary buffer in such a way that it can still be accessed directly without parsing/unpacking, while also still supporting data structure evolution (forwards/backwards compatibility). +- Memory efficiency and speed - The only memory needed to access your data is that of the buffer. It requires 0 additional allocations (in C++, other languages may vary). FlatBuffers is also very suitable for use with mmap (or streaming), requiring only part of the buffer to be in memory. Access is close to the speed of raw struct access with only one extra indirection (a kind of vtable) to allow for format evolution and optional fields. It is aimed at projects where spending time and space (many memory allocations) to be able to access or construct serialized data is undesirable, such as in games or any other performance sensitive applications. See the benchmarks for details. +- Flexible - Optional fields means not only do you get great forwards and backwards compatibility (increasingly important for long-lived games: don't have to update all data with each new version!). It also means you have a lot of choice in what data you write and what data you don't, and how you design data structures. +- Tiny code footprint - Small amounts of generated code, and just a single small header as the minimum dependency, which is very easy to integrate. Again, see the benchmark section for details. +- Strongly typed - Errors happen at compile time rather than manually having to write repetitive and error prone run-time checks. Useful code can be generated for you. + +## Topics + +### Read this first + +- + +### Where to start + +- ``FlatBufferBuilder`` +- ``ByteBuffer`` diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_1.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_1.fbs new file mode 100644 index 00000000000..8b137891791 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_1.fbs @@ -0,0 +1 @@ + diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_2.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_2.fbs new file mode 100644 index 00000000000..a43897845ef --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_2.fbs @@ -0,0 +1 @@ +enum Color:byte { red, green, blue } diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_3.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_3.fbs new file mode 100644 index 00000000000..d31a29cd029 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_3.fbs @@ -0,0 +1,6 @@ +enum Color:byte { red, green, blue } + +struct Vec3 { + x:float; + y:float; +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_4.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_4.fbs new file mode 100644 index 00000000000..51f7bb1aa60 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_4.fbs @@ -0,0 +1,12 @@ +enum Color:byte { red, green, blue } + +struct Vec3 { + x:float; + y:float; +} + +table Monster { + pos:Vec3; + color:Color = Blue; +} + diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_5.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_5.fbs new file mode 100644 index 00000000000..8d0b72956b0 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_5.fbs @@ -0,0 +1,18 @@ +enum Color:byte { red, green, blue } + +struct Vec3 { + x:float; + y:float; +} + +table Monster { + pos:Vec3; + color:Color = Blue; + + mana:short = 150; + hp:short = 100; + name:string; + equipped:Equipment; + weapons:[Weapon]; + path:[Vec3]; +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_6.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_6.fbs new file mode 100644 index 00000000000..10c3eaf67d8 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_6.fbs @@ -0,0 +1,25 @@ +enum Color:byte { red, green, blue } + +union Equipment { Weapon } // Optionally add more tables. + +struct Vec3 { + x:float; + y:float; +} + +table Monster { + pos:Vec3; + color:Color = Blue; + + mana:short = 150; + hp:short = 100; + name:string; + equipped:Equipment; + weapons:[Weapon]; + path:[Vec3]; +} + +table Weapon { + name:string; + damage:short; +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_7.fbs b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_7.fbs new file mode 100644 index 00000000000..b4dde6ced60 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/fbs/monster_step_7.fbs @@ -0,0 +1,27 @@ +enum Color:byte { red, green, blue } + +union Equipment { Weapon } // Optionally add more tables. + +struct Vec3 { + x:float; + y:float; +} + +table Monster { + pos:Vec3; + color:Color = Blue; + + mana:short = 150; + hp:short = 100; + name:string; + equipped:Equipment; + weapons:[Weapon]; + path:[Vec3]; +} + +table Weapon { + name:string; + damage:short; +} + +root_type Monster; // flatc --swift monster.fbs diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_1.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_1.swift new file mode 100644 index 00000000000..fecc4ab4499 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_1.swift @@ -0,0 +1 @@ +import Foundation diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift new file mode 100644 index 00000000000..51d4fbfcdb6 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_10.swift @@ -0,0 +1,71 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) + + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) + + // Name of the Monster. + let name = builder.create(string: "Orc") + + let pathOffset = fbb.createVector(ofStructs: [ + Vec3(x: 0, y: 0), + Vec3(x: 5, y: 5), + ]) + + // startVector(len, elementSize: MemoryLayout.size) + // for o in offsets.reversed() { + // push(element: o) + // } + // endVector(len: len) + + let orc = Monster.createMonster( + &builder, + pos: Vec3(x: 1, y: 2), + hp: 300, + nameOffset: name, + color: .red, + weaponsVectorOffset: weaponsOffset, + equippedType: .weapon, + equippedOffset: axe, + pathOffset: pathOffset) + + // let start = Monster.startMonster(&builder) + // Monster.add(pos: Vec3(x: 1, y: 2), &builder) + // Monster.add(hp: 300, &builder) + // Monster.add(name: name, &builder) + // Monster.add(color: .red, &builder) + // Monster.addVectorOf(weapons: weaponsOffset, &builder) + // Monster.add(equippedType: .weapon, &builder) + // Monster.addVectorOf(paths: weaponsOffset, &builder) + // Monster.add(equipped: axe, &builder) + // var orc = Monster.endMonster(&builder, start: start) + + // Call `finish(offset:)` to instruct the builder that this monster is complete. + builder.finish(offset: orc) + // This must be called after `finish()`. + // `sizedByteArray` returns the finished buf of type [UInt8]. + let buf = builder.sizedByteArray + + // or you can use to get an object of type Data + let bufData = ByteBuffer(data: builder.sizedBuffer) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_11.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_11.swift new file mode 100644 index 00000000000..07d2d8d2b01 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_11.swift @@ -0,0 +1,11 @@ +import FlatBuffers +import Foundation + +func run() { + // create a ByteBuffer(:) from an [UInt8] or Data() + let buf = [] // Get your data + var byteBuffer = ByteBuffer(bytes: buf) + // Get an accessor to the root object inside the buffer. + let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) + // let monster: Monster = getRoot(byteBuffer: &byteBuffer) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_12.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_12.swift new file mode 100644 index 00000000000..0d9ff694329 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_12.swift @@ -0,0 +1,19 @@ +import FlatBuffers +import Foundation + +func run() { + // create a ByteBuffer(:) from an [UInt8] or Data() + let buf = [] // Get your data + var byteBuffer = ByteBuffer(bytes: buf) + // Get an accessor to the root object inside the buffer. + let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) + // let monster: Monster = getRoot(byteBuffer: &byteBuffer) + + let hp = monster.hp + let mana = monster.mana + let name = monster.name // returns an optional string + + let pos = monster.pos + let x = pos.x + let y = pos.y +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift new file mode 100644 index 00000000000..1372d6fc086 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_13.swift @@ -0,0 +1,26 @@ +import FlatBuffers +import Foundation + +func run() { + // create a ByteBuffer(:) from an [UInt8] or Data() + let buf = [] // Get your data + var byteBuffer = ByteBuffer(bytes: buf) + // Get an accessor to the root object inside the buffer. + let monster: Monster = try! getCheckedRoot(byteBuffer: &byteBuffer) + // let monster: Monster = getRoot(byteBuffer: &byteBuffer) + + let hp = monster.hp + let mana = monster.mana + let name = monster.name // returns an optional string + + let pos = monster.pos + let x = pos.x + let y = pos.y + + // Get and check if the monster has an equipped item + if monster.equippedType == .weapon { + let _weapon = monster.equipped(type: Weapon.self) + let name = _weapon.name // should return "Axe" + let dmg = _weapon.damage // should return 5 + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_2.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_2.swift new file mode 100644 index 00000000000..ddd066e7a82 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_2.swift @@ -0,0 +1,2 @@ +import FlatBuffers +import Foundation diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_3.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_3.swift new file mode 100644 index 00000000000..bacdaa55133 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_3.swift @@ -0,0 +1,7 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_4.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_4.swift new file mode 100644 index 00000000000..87546993bf5 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_4.swift @@ -0,0 +1,10 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_5.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_5.swift new file mode 100644 index 00000000000..12e0d4ca660 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_5.swift @@ -0,0 +1,22 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift new file mode 100644 index 00000000000..bfb4f7e5157 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_6.swift @@ -0,0 +1,26 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) + + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_7.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_7.swift new file mode 100644 index 00000000000..97264b018da --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_7.swift @@ -0,0 +1,29 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) + + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) + + // Name of the Monster. + let name = builder.create(string: "Orc") +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_8.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_8.swift new file mode 100644 index 00000000000..a0c2819809f --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_8.swift @@ -0,0 +1,40 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) + + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) + + // Name of the Monster. + let name = builder.create(string: "Orc") + + let pathOffset = fbb.createVector(ofStructs: [ + Vec3(x: 0, y: 0), + Vec3(x: 5, y: 5), + ]) + + // startVector(len, elementSize: MemoryLayout.size) + // for o in offsets.reversed() { + // push(element: o) + // } + // endVector(len: len) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_9.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_9.swift new file mode 100644 index 00000000000..51ce8fd2c2b --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/code/swift/swift_code_9.swift @@ -0,0 +1,62 @@ +import FlatBuffers +import Foundation + +func run() { + // create a `FlatBufferBuilder`, which will be used to serialize objects + let builder = FlatBufferBuilder(initialSize: 1024) + + let weapon1Name = builder.create(string: "Sword") + let weapon2Name = builder.create(string: "Axe") + + // start creating the weapon by calling startWeapon + let weapon1Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon1Name, &builder) + Weapon.add(damage: 3, &builder) + // end the object by passing the start point for the weapon 1 + let sword = Weapon.endWeapon(&builder, start: weapon1Start) + + let weapon2Start = Weapon.startWeapon(&builder) + Weapon.add(name: weapon2Name, &builder) + Weapon.add(damage: 5, &builder) + let axe = Weapon.endWeapon(&builder, start: weapon2Start) + + // Create a FlatBuffer `vector` that contains offsets to the sword and axe + // we created above. + let weaponsOffset = builder.createVector(ofOffsets: [sword, axe]) + + // Name of the Monster. + let name = builder.create(string: "Orc") + + let pathOffset = fbb.createVector(ofStructs: [ + Vec3(x: 0, y: 0), + Vec3(x: 5, y: 5), + ]) + + // startVector(len, elementSize: MemoryLayout.size) + // for o in offsets.reversed() { + // push(element: o) + // } + // endVector(len: len) + + let orc = Monster.createMonster( + &builder, + pos: Vec3(x: 1, y: 2), + hp: 300, + nameOffset: name, + color: .red, + weaponsVectorOffset: weaponsOffset, + equippedType: .weapon, + equippedOffset: axe, + pathOffset: pathOffset) + + // let start = Monster.startMonster(&builder) + // Monster.add(pos: Vec3(x: 1, y: 2), &builder) + // Monster.add(hp: 300, &builder) + // Monster.add(name: name, &builder) + // Monster.add(color: .red, &builder) + // Monster.addVectorOf(weapons: weaponsOffset, &builder) + // Monster.add(equippedType: .weapon, &builder) + // Monster.addVectorOf(paths: weaponsOffset, &builder) + // Monster.add(equipped: axe, &builder) + // var orc = Monster.endMonster(&builder, start: start) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/images/tutorial_cover_image_1.png b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/images/tutorial_cover_image_1.png new file mode 100644 index 00000000000..0e64fe60148 Binary files /dev/null and b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Resources/images/tutorial_cover_image_1.png differ diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/Tutorial_Table_of_Contents.tutorial b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/Tutorial_Table_of_Contents.tutorial new file mode 100644 index 00000000000..009116fc4c8 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/Tutorial_Table_of_Contents.tutorial @@ -0,0 +1,14 @@ +@Tutorials(name: "Starting with FlatBuffers") { + @Intro(title: "Starting with FlatBuffers") { + FlatBuffers is an efficient cross platform serialization library for C++, + C#, C, Go, Java, Kotlin, JavaScript, Lobster, Lua, TypeScript, PHP, Python, Rust and Swift. + It was originally created at Google for game development and other performance-critical applications. + } + @Chapter(name: "Generating your code") { + Start by generating your first FlatBuffers objects. + @Image(source: tutorial_cover_image_1.png, alt: "A code structure for a base struct in flatbuffers") + @TutorialReference(tutorial: "doc:creating_flatbuffer_schema") + @TutorialReference(tutorial: "doc:create_your_first_buffer") + @TutorialReference(tutorial: "doc:reading_bytebuffer") + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/create_your_first_buffer.tutorial b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/create_your_first_buffer.tutorial new file mode 100644 index 00000000000..2f8089f7d3d --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/create_your_first_buffer.tutorial @@ -0,0 +1,72 @@ +@Tutorial(time: 5) { + @Intro(title: "After having our code generated") { + After generating the code from the previous section, we will know start creating our monster object. + We will create a monster object called orc. + } + + @Section(title: "Building your first buffer") { + @ContentAndMedia {} + @Steps { + @Step { + Starting with a new file, we will create our very first Flatbuffer. + @Code(name: "ViewController.swift", file: "swift_code_1.swift") + } + @Step { + First, we need to import ``FlatBuffers`` + @Code(name: "ViewController.swift", file: "swift_code_2.swift") + } + @Step { + We need to create an instance of the `FlatBufferBuilder`, which will contain the buffer as it grows. + You can pass an initial size of the buffer (here 1024 bytes), which will grow automatically if needed. + @Code(name: "ViewController.swift", file: "swift_code_3.swift") + } + @Step { + After creating the builder, we can start serializing our data. Before we make our orc Monster, + let's create some Weapons: a Sword and an Axe. However we will start by naming our weapons as `Sword` and `Axe` + @Code(name: "ViewController.swift", file: "swift_code_4.swift") + } + @Step { + After naming the weapons, we will create two weapon objects with the damage that the weapon is going to deal. + That's done by calling the `start` Method on each table you will be creating, in this case its called `startWeapon` + and finished by calling `end`. + @Code(name: "ViewController.swift", file: "swift_code_5.swift") + } + @Step { + We will take our (Sword and Axe) serialized data and serialize their offsets as a vector of tables into our `ByteBuffer`. + So we can reference them later on from our Monster Object + @Code(name: "ViewController.swift", file: "swift_code_6.swift") + } + @Step { + We will add our Monster name as a string value just like we did with the weapons. + @Code(name: "ViewController.swift", file: "swift_code_7.swift") + } + + @Step { + We will create a path that our monster should be using while roaming in its den. To create a vector of paths we would us + `createVector(ofStructs: [])` which will take a Native `Swift` struct that has been padded to fit the `FlatBuffers` standards. + + There are usually two ways of creating vectors in `FlatBuffers` which you can see in commented out code. + And thus there are multiple convenience methods that will cover all the bases + when trying to create a vector so that you dont have to create it with `start` and `end` + @Code(name: "ViewController.swift", file: "swift_code_8.swift") + } + + @Step { + Now to serialize our data into our `Monster` object. Which again there are two ways of doing, by calling the `create` method or + by serializing the objects yourself. What we added to our Monster were the `Equipped Type` and the `Equipped` union itself, which + allows the Monster to have the `Axe` as his equipped weapon. + + Important: Unlike structs, you should not nest tables or other objects, + which is why we created all the `strings/vectors/tables` that this monster refers to before start. + If you try to create any of them between start and end, you will get an `assert`. + @Code(name: "ViewController.swift", file: "swift_code_9.swift") + } + + @Step { + Finally you can just finalize the buffer by calling `builder.finish` and get the Byte array from the buffer. + @Code(name: "ViewController.swift", file: "swift_code_10.swift") + } + + } + } + } diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/creating_flatbuffer_schema.tutorial b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/creating_flatbuffer_schema.tutorial new file mode 100644 index 00000000000..0fcd362ef9e --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/creating_flatbuffer_schema.tutorial @@ -0,0 +1,47 @@ +@Tutorial(time: 2) { + @Intro(title: "Creating a schema") { + You will need to have the FlatBuffer compiler to be installed on your device + } + + @Section(title: "Creating a schema") { + @ContentAndMedia {} + @Steps { + @Step { + Start by creating a new empty folder called `monster.fbs`. We want to create a Monster table, that contains + position, color, and basic information about the monster. + @Code(name: "monster.fbs", file: "monster_step_1.fbs") + } + @Step { + We will start by adding our Color object. We will be using an enumerate, to represent this object + @Code(name: "monster.fbs", file: "monster_step_2.fbs") + } + @Step { + We will add a position object and will use a struct to represent that type of data. Where we will need the monsters + x and y positions. + @Code(name: "monster.fbs", file: "monster_step_3.fbs") + } + @Step { + Then we will be creating our Monster object of type table. This will contain the current position of our + monster and its color + @Code(name: "monster.fbs", file: "monster_step_4.fbs") + } + @Step { + Our Monster is missing a name, mana, hp, name, equipped Weapon, weapons, and path. We will be adding these + fields to our table with a proper data type for each. Example; weapons, and path would be a vector of data. + @Code(name: "monster.fbs", file: "monster_step_5.fbs") + } + @Step { + Now we are missing two data types here, `Weapon` and `Equipment`. And since Equipment can be a weapon, we will be using + a `Union` enumerate that can contain all the equipment that you would want your monster to have. And the weapon can simply + have a name and amount of damage + @Code(name: "monster.fbs", file: "monster_step_6.fbs") + } + @Step { + And to finalize our monster table, we can add a root type of type Monster. + Then run the command `flatc --swift monster.fbs` + Note: Make sure to import the file to your xcode project. + @Code(name: "monster.fbs", file: "monster_step_7.fbs") + } + } + } + } diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/reading_bytebuffer.tutorial b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/reading_bytebuffer.tutorial new file mode 100644 index 00000000000..2c4609f7e3c --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Documentation.docc/Tutorials/reading_bytebuffer.tutorial @@ -0,0 +1,27 @@ +@Tutorial(time: 2) { + @Intro(title: "Reading ByteBuffers") { + After getting our ByteBuffer created, we can now read it. + } + + @Section(title: "Reading your first buffer") { + @ContentAndMedia {} + @Steps { + @Step { + After fetching the data from disk or network you need to access that data, and that can be done. + By simply calling `getCheckedRoot`, which checks if the data is valid before enabling you to read from a corrupt buffer. + however, if you are sure that the data is 100% correct you can simply call `getRoot` + @Code(name: "ViewController.swift", file: "swift_code_11.swift") + } + @Step { + Now since we have a Monster object, all the fields can be accessed by simply fetching the data. Note, Deprecated fields will not + show up + @Code(name: "ViewController.swift", file: "swift_code_12.swift") + } + @Step { + And you can access union types as easy as this + @Code(name: "ViewController.swift", file: "swift_code_13.swift") + } + } + } + } + diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Enum.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Enum.swift new file mode 100644 index 00000000000..29b382247a6 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Enum.swift @@ -0,0 +1,55 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Enum is a protocol that all flatbuffers enums should conform to +/// Since it allows us to get the actual `ByteSize` and `Value` from +/// a swift enum. +public protocol Enum { + /// associatedtype that the type of the enum should conform to + associatedtype T: Scalar & Verifiable + /// Size of the current associatedtype in the enum + static var byteSize: Int { get } + /// The current value the enum hosts + var value: T { get } +} + +extension Enum where Self: Verifiable { + + /// Verifies that the current value is which the bounds of the buffer, and if + /// the current `Value` is aligned properly + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Errors coming from `inBuffer` function + public static func verify( + _ verifier: inout Verifier, + at position: Int, + of type: T.Type) throws where T: Verifiable + { + try verifier.inBuffer(position: position, of: type.self) + } + +} + +/// UnionEnum is a Protocol that allows us to create Union type of enums +/// and their value initializers. Since an `init` was required by +/// the verifier +public protocol UnionEnum: Enum { + init?(value: T) throws +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBufferBuilder.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBufferBuilder.swift new file mode 100644 index 00000000000..26ae6349154 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBufferBuilder.swift @@ -0,0 +1,925 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// ``FlatBufferBuilder`` builds a `FlatBuffer` through manipulating its internal state. +/// +/// This is done by creating a ``ByteBuffer`` that hosts the incoming data and +/// has a hardcoded growth limit of `2GiB` which is set by the Flatbuffers standards. +/// +/// ```swift +/// var builder = FlatBufferBuilder() +/// ``` +/// The builder should be always created as a variable, since it would be passed into the writers +/// +@frozen +public struct FlatBufferBuilder { + + /// Storage for the Vtables used in the buffer are stored in here, so they would be written later in EndTable + @usableFromInline internal var _vtableStorage = VTableStorage() + /// Flatbuffer data will be written into + @usableFromInline internal var _bb: ByteBuffer + + /// Reference Vtables that were already written to the buffer + private var _vtables: [UOffset] = [] + /// A check if the buffer is being written into by a different table + private var isNested = false + /// Dictonary that stores a map of all the strings that were written to the buffer + private var stringOffsetMap: [String: Offset] = [:] + /// A check to see if finish(::) was ever called to retreive data object + private var finished = false + /// A check to see if the buffer should serialize Default values + private var serializeDefaults: Bool + + /// Current alignment for the buffer + var _minAlignment: Int = 0 { + didSet { + _bb.alignment = _minAlignment + } + } + + /// Gives a read access to the buffer's size + public var size: UOffset { _bb.size } + + #if !os(WASI) + /// Data representation of the buffer + /// + /// Should only be used after ``finish(offset:addPrefix:)`` is called + public var data: Data { + assert(finished, "Data shouldn't be called before finish()") + return Data( + bytes: _bb.memory.advanced(by: _bb.writerIndex), + count: _bb.capacity &- _bb.writerIndex) + } + #endif + + /// Returns the underlying bytes in the ``ByteBuffer`` + /// + /// Note: This should be used with caution. + public var fullSizedByteArray: [UInt8] { + let ptr = UnsafeBufferPointer( + start: _bb.memory.assumingMemoryBound(to: UInt8.self), + count: _bb.capacity) + return Array(ptr) + } + + /// Returns the written bytes into the ``ByteBuffer`` + /// + /// Should only be used after ``finish(offset:addPrefix:)`` is called + public var sizedByteArray: [UInt8] { + assert(finished, "Data shouldn't be called before finish()") + return _bb.underlyingBytes + } + + /// Returns the original ``ByteBuffer`` + /// + /// Returns the current buffer that was just created + /// with the offsets, and data written to it. + public var buffer: ByteBuffer { _bb } + + /// Returns a newly created sized ``ByteBuffer`` + /// + /// returns a new buffer that is sized to the data written + /// to the main buffer + public var sizedBuffer: ByteBuffer { + assert(finished, "Data shouldn't be called before finish()") + return ByteBuffer( + memory: _bb.memory.advanced(by: _bb.reader), + count: Int(_bb.size)) + } + + // MARK: - Init + + /// Initialize the buffer with a size + /// - Parameters: + /// - initialSize: Initial size for the buffer + /// - force: Allows default to be serialized into the buffer + /// + /// This initializes a new builder with an initialSize that would initialize + /// a new ``ByteBuffer``. ``FlatBufferBuilder`` by default doesnt serialize defaults + /// however the builder can be force by passing true for `serializeDefaults` + public init( + initialSize: Int32 = 1024, + serializeDefaults force: Bool = false) + { + assert(initialSize > 0, "Size should be greater than zero!") + guard isLitteEndian else { + fatalError( + "Reading/Writing a buffer in big endian machine is not supported on swift") + } + serializeDefaults = force + _bb = ByteBuffer(initialSize: Int(initialSize)) + } + + /// Clears the builder and the buffer from the written data. + mutating public func clear() { + _minAlignment = 0 + isNested = false + stringOffsetMap.removeAll(keepingCapacity: true) + _vtables.removeAll(keepingCapacity: true) + _vtableStorage.clear() + _bb.clear() + } + + // MARK: - Create Tables + + /// Checks if the required fields were serialized into the buffer + /// - Parameters: + /// - table: offset for the table + /// - fields: Array of all the important fields to be serialized + /// + /// *NOTE: Never call this function, this is only supposed to be called + /// by the generated code* + @inline(__always) + mutating public func require(table: Offset, fields: [Int32]) { + for index in stride(from: 0, to: fields.count, by: 1) { + let start = _bb.capacity &- Int(table.o) + let startTable = start &- Int(_bb.read(def: Int32.self, position: start)) + let isOkay = _bb.read( + def: VOffset.self, + position: startTable &+ Int(fields[index])) != 0 + assert(isOkay, "Flatbuffers requires the following field") + } + } + + /// Finished the buffer by adding the file id and then calling finish + /// - Parameters: + /// - offset: Offset of the table + /// - fileId: Takes the fileId + /// - prefix: if false it wont add the size of the buffer + /// + /// ``finish(offset:fileId:addPrefix:)`` should be called at the end of creating + /// a table + /// ```swift + /// var root = SomeObject + /// .createObject(&builder, + /// name: nameOffset) + /// builder.finish( + /// offset: root, + /// fileId: "ax1a", + /// addPrefix: true) + /// ``` + /// File id would append a file id name at the end of the written bytes before, + /// finishing the buffer. + /// + /// Whereas, if `addPrefix` is true, the written bytes would + /// include the size of the current buffer. + mutating public func finish( + offset: Offset, + fileId: String, + addPrefix prefix: Bool = false) + { + let size = MemoryLayout.size + preAlign( + len: size &+ (prefix ? size : 0) &+ FileIdLength, + alignment: _minAlignment) + assert(fileId.count == FileIdLength, "Flatbuffers requires file id to be 4") + _bb.push(string: fileId, len: 4) + finish(offset: offset, addPrefix: prefix) + } + + /// Finished the buffer by adding the file id, offset, and prefix to it. + /// - Parameters: + /// - offset: Offset of the table + /// - prefix: if false it wont add the size of the buffer + /// + /// ``finish(offset:addPrefix:)`` should be called at the end of creating + /// a table + /// ```swift + /// var root = SomeObject + /// .createObject(&builder, + /// name: nameOffset) + /// builder.finish( + /// offset: root, + /// addPrefix: true) + /// ``` + /// If `addPrefix` is true, the written bytes would + /// include the size of the current buffer. + mutating public func finish( + offset: Offset, + addPrefix prefix: Bool = false) + { + notNested() + let size = MemoryLayout.size + preAlign(len: size &+ (prefix ? size : 0), alignment: _minAlignment) + push(element: refer(to: offset.o)) + if prefix { push(element: _bb.size) } + _vtableStorage.clear() + finished = true + } + + /// ``startTable(with:)`` will let the builder know, that a new object is being serialized. + /// + /// The function will fatalerror if called while there is another object being serialized. + /// ```swift + /// let start = Monster + /// .startMonster(&fbb) + /// ``` + /// - Parameter numOfFields: Number of elements to be written to the buffer + /// - Returns: Offset of the newly started table + @inline(__always) + mutating public func startTable(with numOfFields: Int) -> UOffset { + notNested() + isNested = true + _vtableStorage.start(count: numOfFields) + return _bb.size + } + + /// ``endTable(at:)`` will let the ``FlatBufferBuilder`` know that the + /// object that's written to it is completed + /// + /// This would be called after all the elements are serialized, + /// it will add the current vtable into the ``ByteBuffer``. + /// The functions will `fatalError` in case the object is called + /// without ``startTable(with:)``, or the object has exceeded the limit of 2GB. + /// + /// - Parameter startOffset:Start point of the object written + /// - returns: The root of the table + mutating public func endTable(at startOffset: UOffset) -> UOffset { + assert(isNested, "Calling endtable without calling starttable") + let sizeofVoffset = MemoryLayout.size + let vTableOffset = push(element: SOffset(0)) + + let tableObjectSize = vTableOffset &- startOffset + assert(tableObjectSize < 0x10000, "Buffer can't grow beyond 2 Gigabytes") + let _max = Int(_vtableStorage.maxOffset) &+ sizeofVoffset + + _bb.fill(padding: _max) + _bb.write( + value: VOffset(tableObjectSize), + index: _bb.writerIndex &+ sizeofVoffset, + direct: true) + _bb.write(value: VOffset(_max), index: _bb.writerIndex, direct: true) + + var itr = 0 + while itr < _vtableStorage.writtenIndex { + let loaded = _vtableStorage.load(at: itr) + itr = itr &+ _vtableStorage.size + guard loaded.offset != 0 else { continue } + let _index = (_bb.writerIndex &+ Int(loaded.position)) + _bb.write( + value: VOffset(vTableOffset &- loaded.offset), + index: _index, + direct: true) + } + + _vtableStorage.clear() + let vt_use = _bb.size + + var isAlreadyAdded: Int? + + let vt2 = _bb.memory.advanced(by: _bb.writerIndex) + let len2 = vt2.load(fromByteOffset: 0, as: Int16.self) + + for index in stride(from: 0, to: _vtables.count, by: 1) { + let position = _bb.capacity &- Int(_vtables[index]) + let vt1 = _bb.memory.advanced(by: position) + let len1 = _bb.read(def: Int16.self, position: position) + if len2 != len1 || 0 != memcmp(vt1, vt2, Int(len2)) { continue } + + isAlreadyAdded = Int(_vtables[index]) + break + } + + if let offset = isAlreadyAdded { + let vTableOff = Int(vTableOffset) + let space = _bb.capacity &- vTableOff + _bb.write(value: Int32(offset &- vTableOff), index: space, direct: true) + _bb.pop(_bb.capacity &- space) + } else { + _bb.write(value: Int32(vt_use &- vTableOffset), index: Int(vTableOffset)) + _vtables.append(_bb.size) + } + isNested = false + return vTableOffset + } + + // MARK: - Builds Buffer + + /// Asserts to see if the object is not nested + @inline(__always) + @usableFromInline + mutating internal func notNested() { + assert(!isNested, "Object serialization must not be nested") + } + + /// Changes the minimuim alignment of the buffer + /// - Parameter size: size of the current alignment + @inline(__always) + @usableFromInline + mutating internal func minAlignment(size: Int) { + if size > _minAlignment { + _minAlignment = size + } + } + + /// Gets the padding for the current element + /// - Parameters: + /// - bufSize: Current size of the buffer + the offset of the object to be written + /// - elementSize: Element size + @inline(__always) + @usableFromInline + mutating internal func padding( + bufSize: UInt32, + elementSize: UInt32) -> UInt32 + { + ((~bufSize) &+ 1) & (elementSize - 1) + } + + /// Prealigns the buffer before writting a new object into the buffer + /// - Parameters: + /// - len:Length of the object + /// - alignment: Alignment type + @inline(__always) + @usableFromInline + mutating internal func preAlign(len: Int, alignment: Int) { + minAlignment(size: alignment) + _bb.fill(padding: Int(padding( + bufSize: _bb.size &+ UOffset(len), + elementSize: UOffset(alignment)))) + } + + /// Prealigns the buffer before writting a new object into the buffer + /// - Parameters: + /// - len: Length of the object + /// - type: Type of the object to be written + @inline(__always) + @usableFromInline + mutating internal func preAlign(len: Int, type: T.Type) { + preAlign(len: len, alignment: MemoryLayout.size) + } + + /// Refers to an object that's written in the buffer + /// - Parameter off: the objects index value + @inline(__always) + @usableFromInline + mutating internal func refer(to off: UOffset) -> UOffset { + let size = MemoryLayout.size + preAlign(len: size, alignment: size) + return _bb.size &- off &+ UInt32(size) + } + + /// Tracks the elements written into the buffer + /// - Parameters: + /// - offset: The offset of the element witten + /// - position: The position of the element + @inline(__always) + @usableFromInline + mutating internal func track(offset: UOffset, at position: VOffset) { + _vtableStorage.add(loc: (offset: offset, position: position)) + } + + // MARK: - Inserting Vectors + + /// ``startVector(_:elementSize:)`` creates a new vector within buffer + /// + /// The function checks if there is a current object being written, if + /// the check passes it creates a buffer alignment of `length * elementSize` + /// ```swift + /// builder.startVector( + /// int32Values.count, elementSize: 4) + /// ``` + /// + /// - Parameters: + /// - len: Length of vector to be created + /// - elementSize: Size of object type to be written + @inline(__always) + mutating public func startVector(_ len: Int, elementSize: Int) { + notNested() + isNested = true + preAlign(len: len &* elementSize, type: UOffset.self) + preAlign(len: len &* elementSize, alignment: elementSize) + } + + /// ``endVector(len:)`` ends the currently created vector + /// + /// Calling ``endVector(len:)`` requires the length, of the current + /// vector. The length would be pushed to indicate the count of numbers + /// within the vector. If ``endVector(len:)`` is called without + /// ``startVector(_:elementSize:)`` it asserts. + /// + /// ```swift + /// let vectorOffset = builder. + /// endVector(len: int32Values.count) + /// ``` + /// + /// - Parameter len: Length of the buffer + /// - Returns: Returns the current ``Offset`` in the ``ByteBuffer`` + @inline(__always) + mutating public func endVector(len: Int) -> Offset { + assert(isNested, "Calling endVector without calling startVector") + isNested = false + return Offset(offset: push(element: Int32(len))) + } + + /// Creates a vector of type ``Scalar`` into the ``ByteBuffer`` + /// + /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into + /// ``ByteBuffer``. This is a convenient method instead of calling, + /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` + /// ```swift + /// let vectorOffset = builder. + /// createVector([1, 2, 3, 4]) + /// ``` + /// + /// The underlying implementation simply calls ``createVector(_:size:)-4lhrv`` + /// + /// - Parameter elements: elements to be written into the buffer + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector(_ elements: [T]) -> Offset { + createVector(elements, size: elements.count) + } + + /// Creates a vector of type Scalar in the buffer + /// + /// ``createVector(_:)-4swl0`` writes a vector of type Scalars into + /// ``ByteBuffer``. This is a convenient method instead of calling, + /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` + /// ```swift + /// let vectorOffset = builder. + /// createVector([1, 2, 3, 4], size: 4) + /// ``` + /// + /// - Parameter elements: Elements to be written into the buffer + /// - Parameter size: Count of elements + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector( + _ elements: [T], + size: Int) -> Offset + { + let size = size + startVector(size, elementSize: MemoryLayout.size) + _bb.push(elements: elements) + return endVector(len: size) + } + + #if swift(>=5.0) && !os(WASI) + @inline(__always) + /// Creates a vector of bytes in the buffer. + /// + /// Allows creating a vector from `Data` without copying to a `[UInt8]` + /// + /// - Parameter bytes: bytes to be written into the buffer + /// - Returns: ``Offset`` of the vector + mutating public func createVector(bytes: ContiguousBytes) -> Offset { + let size = bytes.withUnsafeBytes { ptr in ptr.count } + startVector(size, elementSize: MemoryLayout.size) + _bb.push(bytes: bytes) + return endVector(len: size) + } + #endif + + /// Creates a vector of type ``Enum`` into the ``ByteBuffer`` + /// + /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into + /// ``ByteBuffer``. This is a convenient method instead of calling, + /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` + /// ```swift + /// let vectorOffset = builder. + /// createVector([.swift, .cpp]) + /// ``` + /// + /// The underlying implementation simply calls ``createVector(_:size:)-7cx6z`` + /// + /// - Parameter elements: elements to be written into the buffer + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector(_ elements: [T]) -> Offset { + createVector(elements, size: elements.count) + } + + /// Creates a vector of type ``Enum`` into the ``ByteBuffer`` + /// + /// ``createVector(_:)-9h189`` writes a vector of type ``Enum`` into + /// ``ByteBuffer``. This is a convenient method instead of calling, + /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` + /// ```swift + /// let vectorOffset = builder. + /// createVector([.swift, .cpp]) + /// ``` + /// + /// - Parameter elements: Elements to be written into the buffer + /// - Parameter size: Count of elements + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector( + _ elements: [T], + size: Int) -> Offset + { + let size = size + startVector(size, elementSize: T.byteSize) + for index in stride(from: elements.count, to: 0, by: -1) { + _bb.push(value: elements[index &- 1].value, len: T.byteSize) + } + return endVector(len: size) + } + + /// Creates a vector of already written offsets + /// + /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into + /// ``ByteBuffer``. This is a convenient method instead of calling, + /// ``startVector(_:elementSize:)`` and then ``endVector(len:)``. + /// + /// The underlying implementation simply calls ``createVector(ofOffsets:len:)`` + /// + /// ```swift + /// let namesOffsets = builder. + /// createVector(ofOffsets: [name1, name2]) + /// ``` + /// - Parameter offsets: Array of offsets of type ``Offset`` + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector(ofOffsets offsets: [Offset]) -> Offset { + createVector(ofOffsets: offsets, len: offsets.count) + } + + /// Creates a vector of already written offsets + /// + /// ``createVector(ofOffsets:)`` creates a vector of ``Offset`` into + /// ``ByteBuffer``. This is a convenient method instead of calling, + /// ``startVector(_:elementSize:)`` and then ``endVector(len:)`` + /// + /// ```swift + /// let namesOffsets = builder. + /// createVector(ofOffsets: [name1, name2]) + /// ``` + /// + /// - Parameter offsets: Array of offsets of type ``Offset`` + /// - Parameter size: Count of elements + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector( + ofOffsets offsets: [Offset], + len: Int) -> Offset + { + startVector(len, elementSize: MemoryLayout.size) + for index in stride(from: offsets.count, to: 0, by: -1) { + push(element: offsets[index &- 1]) + } + return endVector(len: len) + } + + /// Creates a vector of strings + /// + /// ``createVector(ofStrings:)`` creates a vector of `String` into + /// ``ByteBuffer``. This is a convenient method instead of manually + /// creating the string offsets, you simply pass it to this function + /// and it would write the strings into the ``ByteBuffer``. + /// After that it calls ``createVector(ofOffsets:)`` + /// + /// ```swift + /// let namesOffsets = builder. + /// createVector(ofStrings: ["Name", "surname"]) + /// ``` + /// + /// - Parameter str: Array of string + /// - returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector(ofStrings str: [String]) -> Offset { + var offsets: [Offset] = [] + for index in stride(from: 0, to: str.count, by: 1) { + offsets.append(create(string: str[index])) + } + return createVector(ofOffsets: offsets) + } + + /// Creates a vector of type ``NativeStruct``. + /// + /// Any swift struct in the generated code, should confirm to + /// ``NativeStruct``. Since the generated swift structs are padded + /// to the `FlatBuffers` standards. + /// + /// ```swift + /// let offsets = builder. + /// createVector(ofStructs: [NativeStr(num: 1), NativeStr(num: 2)]) + /// ``` + /// + /// - Parameter structs: A vector of ``NativeStruct`` + /// - Returns: ``Offset`` of the vector + @inline(__always) + mutating public func createVector(ofStructs structs: [T]) + -> Offset + { + startVector( + structs.count * MemoryLayout.size, + elementSize: MemoryLayout.alignment) + _bb.push(elements: structs) + return endVector(len: structs.count) + } + + // MARK: - Inserting Structs + + /// Writes a ``NativeStruct`` into the ``ByteBuffer`` + /// + /// Adds a native struct that's build and padded according + /// to `FlatBuffers` standards. with a predefined position. + /// + /// ```swift + /// let offset = builder.create( + /// struct: NativeStr(num: 1), + /// position: 10) + /// ``` + /// + /// - Parameters: + /// - s: ``NativeStruct`` to be inserted into the ``ByteBuffer`` + /// - position: The predefined position of the object + /// - Returns: ``Offset`` of written struct + @inline(__always) + @discardableResult + mutating public func create( + struct s: T, position: VOffset) -> Offset + { + let offset = create(struct: s) + _vtableStorage.add( + loc: (offset: _bb.size, position: VOffset(position))) + return offset + } + + /// Writes a ``NativeStruct`` into the ``ByteBuffer`` + /// + /// Adds a native struct that's build and padded according + /// to `FlatBuffers` standards, directly into the buffer without + /// a predefined position. + /// + /// ```swift + /// let offset = builder.create( + /// struct: NativeStr(num: 1)) + /// ``` + /// + /// - Parameters: + /// - s: ``NativeStruct`` to be inserted into the ``ByteBuffer`` + /// - Returns: ``Offset`` of written struct + @inline(__always) + @discardableResult + mutating public func create( + struct s: T) -> Offset + { + let size = MemoryLayout.size + preAlign(len: size, alignment: MemoryLayout.alignment) + _bb.push(struct: s, size: size) + return Offset(offset: _bb.size) + } + + // MARK: - Inserting Strings + + /// Insets a string into the buffer of type `UTF8` + /// + /// Adds a swift string into ``ByteBuffer`` by encoding it + /// using `UTF8` + /// + /// ```swift + /// let nameOffset = builder + /// .create(string: "welcome") + /// ``` + /// + /// - Parameter str: String to be serialized + /// - returns: ``Offset`` of inserted string + @inline(__always) + mutating public func create(string str: String?) -> Offset { + guard let str = str else { return Offset() } + let len = str.utf8.count + notNested() + preAlign(len: len &+ 1, type: UOffset.self) + _bb.fill(padding: 1) + _bb.push(string: str, len: len) + push(element: UOffset(len)) + return Offset(offset: _bb.size) + } + + /// Insets a shared string into the buffer of type `UTF8` + /// + /// Adds a swift string into ``ByteBuffer`` by encoding it + /// using `UTF8`. The function will check if the string, + /// is already written to the ``ByteBuffer`` + /// + /// ```swift + /// let nameOffset = builder + /// .createShared(string: "welcome") + /// + /// + /// let secondOffset = builder + /// .createShared(string: "welcome") + /// + /// assert(nameOffset.o == secondOffset.o) + /// ``` + /// + /// - Parameter str: String to be serialized + /// - returns: ``Offset`` of inserted string + @inline(__always) + mutating public func createShared(string str: String?) -> Offset { + guard let str = str else { return Offset() } + if let offset = stringOffsetMap[str] { + return offset + } + let offset = create(string: str) + stringOffsetMap[str] = offset + return offset + } + + // MARK: - Inseting offsets + + /// Writes the ``Offset`` of an already written table + /// + /// Writes the ``Offset`` of a table if not empty into the + /// ``ByteBuffer`` + /// + /// - Parameters: + /// - offset: ``Offset`` of another object to be written + /// - position: The predefined position of the object + @inline(__always) + mutating public func add(offset: Offset, at position: VOffset) { + if offset.isEmpty { return } + add(element: refer(to: offset.o), def: 0, at: position) + } + + /// Pushes a value of type ``Offset`` into the ``ByteBuffer`` + /// - Parameter o: ``Offset`` + /// - returns: Current position of the ``Offset`` + @inline(__always) + @discardableResult + mutating public func push(element o: Offset) -> UOffset { + push(element: refer(to: o.o)) + } + + // MARK: - Inserting Scalars to Buffer + + /// Writes a ``Scalar`` value into ``ByteBuffer`` + /// + /// ``add(element:def:at:)`` takes in a default value, and current value + /// and the position within the `VTable`. The default value would not + /// be serialized if the value is the same as the current value or + /// `serializeDefaults` is equal to false. + /// + /// If serializing defaults is important ``init(initialSize:serializeDefaults:)``, + /// passing true for `serializeDefaults` would do the job. + /// + /// ```swift + /// // Adds 10 to the buffer + /// builder.add(element: Int(10), def: 1, position 12) + /// ``` + /// + /// *NOTE: Never call this manually* + /// + /// - Parameters: + /// - element: Element to insert + /// - def: Default value for that element + /// - position: The predefined position of the element + @inline(__always) + mutating public func add( + element: T, + def: T, + at position: VOffset) + { + if element == def && !serializeDefaults { return } + track(offset: push(element: element), at: position) + } + + /// Writes a optional ``Scalar`` value into ``ByteBuffer`` + /// + /// Takes an optional value to be written into the ``ByteBuffer`` + /// + /// *NOTE: Never call this manually* + /// + /// - Parameters: + /// - element: Optional element of type scalar + /// - position: The predefined position of the element + @inline(__always) + mutating public func add(element: T?, at position: VOffset) { + guard let element = element else { return } + track(offset: push(element: element), at: position) + } + + /// Pushes a values of type ``Scalar`` into the ``ByteBuffer`` + /// + /// *NOTE: Never call this manually* + /// + /// - Parameter element: Element to insert + /// - returns: position of the Element + @inline(__always) + @discardableResult + mutating public func push(element: T) -> UOffset { + let size = MemoryLayout.size + preAlign( + len: size, + alignment: size) + _bb.push(value: element, len: size) + return _bb.size + } + +} + +extension FlatBufferBuilder: CustomDebugStringConvertible { + + public var debugDescription: String { + """ + buffer debug: + \(_bb) + builder debug: + { finished: \(finished), serializeDefaults: \( + serializeDefaults), isNested: \(isNested) } + """ + } + + typealias FieldLoc = (offset: UOffset, position: VOffset) + + /// VTableStorage is a class to contain the VTable buffer that would be serialized into buffer + @usableFromInline + internal class VTableStorage { + /// Memory check since deallocating each time we want to clear would be expensive + /// and memory leaks would happen if we dont deallocate the first allocated memory. + /// memory is promised to be available before adding `FieldLoc` + private var memoryInUse = false + /// Size of FieldLoc in memory + let size = MemoryLayout.stride + /// Memeory buffer + var memory: UnsafeMutableRawBufferPointer! + /// Capacity of the current buffer + var capacity: Int = 0 + /// Maximuim offset written to the class + var maxOffset: VOffset = 0 + /// number of fields written into the buffer + var numOfFields: Int = 0 + /// Last written Index + var writtenIndex: Int = 0 + + /// Creates the memory to store the buffer in + @usableFromInline + @inline(__always) + init() { + memory = UnsafeMutableRawBufferPointer.allocate( + byteCount: 0, + alignment: 0) + } + + @inline(__always) + deinit { + memory.deallocate() + } + + /// Builds a buffer with byte count of fieldloc.size * count of field numbers + /// - Parameter count: number of fields to be written + @inline(__always) + func start(count: Int) { + assert(count >= 0, "number of fields should NOT be negative") + let capacity = count &* size + ensure(space: capacity) + } + + /// Adds a FieldLoc into the buffer, which would track how many have been written, + /// and max offset + /// - Parameter loc: Location of encoded element + @inline(__always) + func add(loc: FieldLoc) { + memory.baseAddress?.advanced(by: writtenIndex).storeBytes( + of: loc, + as: FieldLoc.self) + writtenIndex = writtenIndex &+ size + numOfFields = numOfFields &+ 1 + maxOffset = max(loc.position, maxOffset) + } + + /// Clears the data stored related to the encoded buffer + @inline(__always) + func clear() { + maxOffset = 0 + numOfFields = 0 + writtenIndex = 0 + } + + /// Ensure that the buffer has enough space instead of recreating the buffer each time. + /// - Parameter space: space required for the new vtable + @inline(__always) + func ensure(space: Int) { + guard space &+ writtenIndex > capacity else { return } + memory.deallocate() + memory = UnsafeMutableRawBufferPointer.allocate( + byteCount: space, + alignment: size) + capacity = space + } + + /// Loads an object of type `FieldLoc` from buffer memory + /// - Parameter index: index of element + /// - Returns: a FieldLoc at index + @inline(__always) + func load(at index: Int) -> FieldLoc { + memory.load(fromByteOffset: index, as: FieldLoc.self) + } + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBufferObject.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBufferObject.swift new file mode 100644 index 00000000000..e836e6120c7 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBufferObject.swift @@ -0,0 +1,64 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// NativeStruct is a protocol that indicates if the struct is a native `swift` struct +/// since now we will be serializing native structs into the buffer. +public protocol NativeStruct {} + +/// FlatbuffersInitializable is a protocol that allows any object to be +/// Initialized from a ByteBuffer +public protocol FlatbuffersInitializable { + /// Any flatbuffers object that confirms to this protocol is going to be + /// initializable through this initializer + init(_ bb: ByteBuffer, o: Int32) +} + +/// FlatbufferObject structures all the Flatbuffers objects +public protocol FlatBufferObject: FlatbuffersInitializable { + var __buffer: ByteBuffer! { get } +} + +/// ``ObjectAPIPacker`` is a protocol that allows object to pack and unpack from a +/// ``NativeObject`` to a flatbuffers Object and vice versa. +public protocol ObjectAPIPacker { + /// associatedtype to the object that should be unpacked. + associatedtype T + + /// ``pack(_:obj:)-3ptws`` tries to pacs the variables of a native Object into the `ByteBuffer` by using + /// a FlatBufferBuilder + /// - Parameters: + /// - builder: FlatBufferBuilder that will host incoming data + /// - obj: Object of associatedtype to the current implementer + /// + /// ``pack(_:obj:)-3ptws`` can be called by passing through an already initialized ``FlatBufferBuilder`` + /// or it can be called by using the public API that will create a new ``FlatBufferBuilder`` + static func pack(_ builder: inout FlatBufferBuilder, obj: inout T?) -> Offset + + /// ``pack(_:obj:)-20ipk`` packs the variables of a native Object into the `ByteBuffer` by using + /// the FlatBufferBuilder + /// - Parameters: + /// - builder: FlatBufferBuilder that will host incoming data + /// - obj: Object of associatedtype to the current implementer + /// + /// ``pack(_:obj:)-20ipk`` can be called by passing through an already initialized ``FlatBufferBuilder`` + /// or it can be called by using the public API that will create a new ``FlatBufferBuilder`` + static func pack(_ builder: inout FlatBufferBuilder, obj: inout T) -> Offset + + /// ``unpack()`` unpacks a ``FlatBuffers`` object into a Native swift object. + mutating func unpack() -> T +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBuffersUtils.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBuffersUtils.swift new file mode 100644 index 00000000000..18c130f5a2f --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatBuffersUtils.swift @@ -0,0 +1,37 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// FlatBuffersUtils hosts some utility functions that might be useful +public enum FlatBuffersUtils { + + /// Gets the size of the prefix + /// - Parameter bb: Flatbuffer object + public static func getSizePrefix(bb: ByteBuffer) -> Int32 { + bb.read(def: Int32.self, position: bb.reader) + } + + /// Removes the prefix by duplicating the Flatbuffer this call is expensive since its + /// creates a new buffer use `readPrefixedSizeCheckedRoot` instead + /// unless a completely new buffer is required + /// - Parameter bb: Flatbuffer object + /// + /// + public static func removeSizePrefix(bb: ByteBuffer) -> ByteBuffer { + bb.duplicate(removing: MemoryLayout.size) + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatbuffersErrors.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatbuffersErrors.swift new file mode 100644 index 00000000000..13207b53a99 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/FlatbuffersErrors.swift @@ -0,0 +1,75 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Collection of thrown from the Flatbuffer verifier +public enum FlatbuffersErrors: Error, Equatable { + + /// Thrown when trying to verify a buffer that doesnt have the length of an ID + case bufferDoesntContainID + /// Thrown when verifying a file id that doesnt match buffer id + case bufferIdDidntMatchPassedId + /// Prefixed size doesnt match the current (readable) buffer size + case prefixedSizeNotEqualToBufferSize + /// Thrown when buffer is bigger than the allowed 2GiB + case exceedsMaxSizeAllowed + /// Thrown when there is an missaligned pointer at position + /// of type + case missAlignedPointer(position: Int, type: String) + /// Thrown when trying to read a value that goes out of the + /// current buffer bounds + case outOfBounds(position: UInt, end: Int) + /// Thrown when the signed offset is out of the bounds of the + /// current buffer + case signedOffsetOutOfBounds(offset: Int, position: Int) + /// Thrown when a required field doesnt exist within the buffer + case requiredFieldDoesntExist(position: VOffset, name: String) + /// Thrown when a string is missing its NULL Terminator `\0`, + /// this can be disabled in the `VerifierOptions` + case missingNullTerminator(position: Int, str: String?) + /// Thrown when the verifier has reached the maximum tables allowed, + /// this can be disabled in the `VerifierOptions` + case maximumTables + /// Thrown when the verifier has reached the maximum depth allowed, + /// this can be disabled in the `VerifierOptions` + case maximumDepth + /// Thrown when the verifier is presented with an unknown union case + case unknownUnionCase + /// thrown when a value for a union is not found within the buffer + case valueNotFound(key: Int?, keyName: String, field: Int?, fieldName: String) + /// thrown when the size of the keys vector doesnt match fields vector + case unionVectorSize( + keyVectorSize: Int, + fieldVectorSize: Int, + unionKeyName: String, + fieldName: String) + case apparentSizeTooLarge + +} + +#if !os(WASI) + +extension FlatbuffersErrors { + public static func == ( + lhs: FlatbuffersErrors, + rhs: FlatbuffersErrors) -> Bool + { + lhs.localizedDescription == rhs.localizedDescription + } +} + +#endif diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Int+extension.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Int+extension.swift new file mode 100644 index 00000000000..62b5cd5cd1a --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Int+extension.swift @@ -0,0 +1,47 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +extension Int { + + /// Moves the current int into the nearest power of two + /// + /// This is used since the UnsafeMutableRawPointer will face issues when writing/reading + /// if the buffer alignment exceeds that actual size of the buffer + var convertToPowerofTwo: Int { + guard self > 0 else { return 1 } + var n = UOffset(self) + + #if arch(arm) || arch(i386) + let max = UInt32(Int.max) + #else + let max = UInt32.max + #endif + + n -= 1 + n |= n >> 1 + n |= n >> 2 + n |= n >> 4 + n |= n >> 8 + n |= n >> 16 + if n != max { + n += 1 + } + + return Int(n) + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Message.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Message.swift new file mode 100644 index 00000000000..8ccfca41866 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Message.swift @@ -0,0 +1,65 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// FlatBufferGRPCMessage protocol that should allow us to invoke +/// initializers directly from the GRPC generated code +public protocol FlatBufferGRPCMessage { + + /// Raw pointer which would be pointing to the beginning of the readable bytes + var rawPointer: UnsafeMutableRawPointer { get } + + /// Size of readable bytes in the buffer + var size: Int { get } + + init(byteBuffer: ByteBuffer) +} + +/// Message is a wrapper around Buffers to to able to send Flatbuffers `Buffers` through the +/// GRPC library +public struct Message: FlatBufferGRPCMessage { + internal var buffer: ByteBuffer + + /// Returns the an object of type T that would be read from the buffer + public var object: T { + T.init( + buffer, + o: Int32(buffer.read(def: UOffset.self, position: buffer.reader)) + + Int32(buffer.reader)) + } + + public var rawPointer: UnsafeMutableRawPointer { + buffer.memory.advanced(by: buffer.reader) } + + public var size: Int { Int(buffer.size) } + + /// Initializes the message with the type Flatbuffer.Bytebuffer that is transmitted over + /// GRPC + /// - Parameter byteBuffer: Flatbuffer ByteBuffer object + public init(byteBuffer: ByteBuffer) { + buffer = byteBuffer + } + + /// Initializes the message by copying the buffer to the message to be sent. + /// from the builder + /// - Parameter builder: FlatbufferBuilder that has the bytes created in + /// - Note: Use `builder.finish(offset)` before passing the builder without prefixing anything to it + public init(builder: inout FlatBufferBuilder) { + buffer = builder.sizedBuffer + builder.clear() + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Mutable.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Mutable.swift new file mode 100644 index 00000000000..307e9a927c3 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Mutable.swift @@ -0,0 +1,84 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Mutable is a protocol that allows us to mutate Scalar values within a ``ByteBuffer`` +public protocol Mutable { + /// makes Flatbuffer accessed within the Protocol + var bb: ByteBuffer { get } + /// makes position of the ``Table``/``Struct`` accessed within the Protocol + var position: Int32 { get } +} + +extension Mutable { + + /// Mutates the memory in the buffer, this is only called from the access function of ``Table`` and ``struct`` + /// - Parameters: + /// - value: New value to be inserted to the buffer + /// - index: index of the Element + func mutate(value: T, o: Int32) -> Bool { + guard o != 0 else { return false } + bb.write(value: value, index: Int(o), direct: true) + return true + } +} + +extension Mutable where Self == Table { + + /// Mutates a value by calling mutate with respect to the position in a ``Table`` + /// - Parameters: + /// - value: New value to be inserted to the buffer + /// - index: index of the Element + public func mutate(_ value: T, index: Int32) -> Bool { + guard index != 0 else { return false } + return mutate(value: value, o: index + position) + } + + /// Directly mutates the element by calling mutate + /// + /// Mutates the Element at index ignoring the current position by calling mutate + /// - Parameters: + /// - value: New value to be inserted to the buffer + /// - index: index of the Element + public func directMutate(_ value: T, index: Int32) -> Bool { + mutate(value: value, o: index) + } +} + +extension Mutable where Self == Struct { + + /// Mutates a value by calling mutate with respect to the position in the struct + /// - Parameters: + /// - value: New value to be inserted to the buffer + /// - index: index of the Element + public func mutate(_ value: T, index: Int32) -> Bool { + mutate(value: value, o: index + position) + } + + /// Directly mutates the element by calling mutate + /// + /// Mutates the Element at index ignoring the current position by calling mutate + /// - Parameters: + /// - value: New value to be inserted to the buffer + /// - index: index of the Element + public func directMutate(_ value: T, index: Int32) -> Bool { + mutate(value: value, o: index) + } +} + +extension Struct: Mutable {} +extension Table: Mutable {} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/NativeObject.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/NativeObject.swift new file mode 100644 index 00000000000..2ed83970fff --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/NativeObject.swift @@ -0,0 +1,53 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// NativeObject is a protocol that all of the `Object-API` generated code should be +/// conforming to since it allows developers the ease of use to pack and unpack their +/// Flatbuffers objects +public protocol NativeObject {} + +extension NativeObject { + + /// Serialize is a helper function that serializes the data from the Object API to a bytebuffer directly th + /// - Parameter type: Type of the Flatbuffer object + /// - Returns: returns the encoded sized ByteBuffer + public func serialize(type: T.Type) -> ByteBuffer + where T.T == Self + { + var builder = FlatBufferBuilder(initialSize: 1024) + return serialize(builder: &builder, type: type.self) + } + + /// Serialize is a helper function that serializes the data from the Object API to a bytebuffer directly. + /// + /// - Parameters: + /// - builder: A FlatBufferBuilder + /// - type: Type of the Flatbuffer object + /// - Returns: returns the encoded sized ByteBuffer + /// - Note: The `serialize(builder:type)` can be considered as a function that allows you to create smaller builder instead of the default `1024`. + /// It can be considered less expensive in terms of memory allocation + public func serialize( + builder: inout FlatBufferBuilder, + type: T.Type) -> ByteBuffer where T.T == Self + { + var s = self + let root = type.pack(&builder, obj: &s) + builder.finish(offset: root) + return builder.sizedBuffer + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Offset.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Offset.swift new file mode 100644 index 00000000000..95ef9df993f --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Offset.swift @@ -0,0 +1,28 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Offset object for all the Objects that are written into the buffer +public struct Offset { + /// Offset of the object in the buffer + public var o: UOffset + /// Returns false if the offset is equal to zero + public var isEmpty: Bool { o == 0 } + + public init(offset: UOffset) { o = offset } + public init() { o = 0 } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Root.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Root.swift new file mode 100644 index 00000000000..8e606e6ccf4 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Root.swift @@ -0,0 +1,116 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Takes in a prefixed sized buffer, where the prefixed size would be skipped. +/// And would verify that the buffer passed is a valid `Flatbuffers` Object. +/// - Parameters: +/// - byteBuffer: Buffer that needs to be checked and read +/// - options: Verifier options +/// - Throws: FlatbuffersErrors +/// - Returns: Returns a valid, checked Flatbuffers object +/// +/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in +/// the ``ByteBuffer`` and verifies the buffer by calling ``getCheckedRoot(byteBuffer:options:)`` +public func getPrefixedSizeCheckedRoot( + byteBuffer: inout ByteBuffer, + fileId: String? = nil, + options: VerifierOptions = .init()) throws -> T +{ + byteBuffer.skipPrefix() + return try getCheckedRoot( + byteBuffer: &byteBuffer, + fileId: fileId, + options: options) +} + +/// Takes in a prefixed sized buffer, where we check if the sized buffer is equal to prefix size. +/// And would verify that the buffer passed is a valid `Flatbuffers` Object. +/// - Parameters: +/// - byteBuffer: Buffer that needs to be checked and read +/// - options: Verifier options +/// - Throws: FlatbuffersErrors +/// - Returns: Returns a valid, checked Flatbuffers object +/// +/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in +/// the ``ByteBuffer`` and verifies the buffer by calling ``getCheckedRoot(byteBuffer:options:)`` +public func getCheckedPrefixedSizeRoot( + byteBuffer: inout ByteBuffer, + fileId: String? = nil, + options: VerifierOptions = .init()) throws -> T +{ + let prefix = byteBuffer.skipPrefix() + if prefix != byteBuffer.size { + throw FlatbuffersErrors.prefixedSizeNotEqualToBufferSize + } + return try getCheckedRoot( + byteBuffer: &byteBuffer, + fileId: fileId, + options: options) +} + +/// Takes in a prefixed sized buffer, where the prefixed size would be skipped. +/// Returns a `NON-Checked` flatbuffers object +/// - Parameter byteBuffer: Buffer that contains data +/// - Returns: Returns a Flatbuffers object +/// +/// ``getPrefixedSizeCheckedRoot(byteBuffer:options:)`` would skip the first Bytes in +/// the ``ByteBuffer`` and then calls ``getRoot(byteBuffer:)`` +public func getPrefixedSizeRoot( + byteBuffer: inout ByteBuffer) + -> T +{ + byteBuffer.skipPrefix() + return getRoot(byteBuffer: &byteBuffer) + +} + +/// Verifies that the buffer passed is a valid `Flatbuffers` Object. +/// - Parameters: +/// - byteBuffer: Buffer that needs to be checked and read +/// - options: Verifier options +/// - Throws: FlatbuffersErrors +/// - Returns: Returns a valid, checked Flatbuffers object +/// +/// ``getCheckedRoot(byteBuffer:options:)`` Takes in a ``ByteBuffer`` and verifies +/// that by creating a ``Verifier`` and checkes if all the `Bytes` and correctly aligned +/// and within the ``ByteBuffer`` range. +public func getCheckedRoot( + byteBuffer: inout ByteBuffer, + fileId: String? = nil, + options: VerifierOptions = .init()) throws -> T +{ + var verifier = try Verifier(buffer: &byteBuffer, options: options) + if let fileId = fileId { + try verifier.verify(id: fileId) + } + try ForwardOffset.verify(&verifier, at: 0, of: T.self) + return T.init( + byteBuffer, + o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) + + Int32(byteBuffer.reader)) +} + +/// Returns a `NON-Checked` flatbuffers object +/// - Parameter byteBuffer: Buffer that contains data +/// - Returns: Returns a Flatbuffers object +public func getRoot(byteBuffer: inout ByteBuffer) -> T { + T.init( + byteBuffer, + o: Int32(byteBuffer.read(def: UOffset.self, position: byteBuffer.reader)) + + Int32(byteBuffer.reader)) +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/String+extension.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/String+extension.swift new file mode 100644 index 00000000000..de4f5f91f0f --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/String+extension.swift @@ -0,0 +1,109 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +extension String: Verifiable { + + /// Verifies that the current value is which the bounds of the buffer, and if + /// the current `Value` is aligned properly + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Errors coming from `inBuffer`, `missingNullTerminator` and `outOfBounds` + public static func verify( + _ verifier: inout Verifier, + at position: Int, + of type: T.Type) throws where T: Verifiable + { + + let range = try String.verifyRange(&verifier, at: position, of: UInt8.self) + /// Safe &+ since we already check for overflow in verify range + let stringLen = range.start &+ range.count + + if stringLen >= verifier.capacity { + throw FlatbuffersErrors.outOfBounds( + position: UInt(clamping: stringLen.magnitude), + end: verifier.capacity) + } + + let isNullTerminated = verifier._buffer.read( + def: UInt8.self, + position: stringLen) == 0 + + if !verifier._options._ignoreMissingNullTerminators && !isNullTerminated { + let str = verifier._buffer.readString(at: range.start, count: range.count) + throw FlatbuffersErrors.missingNullTerminator( + position: position, + str: str) + } + } +} + +extension String: FlatbuffersInitializable { + + /// Initailizes a string from a Flatbuffers ByteBuffer + /// - Parameters: + /// - bb: ByteBuffer containing the readable string + /// - o: Current position + public init(_ bb: ByteBuffer, o: Int32) { + let v = Int(o) + let count = bb.read(def: Int32.self, position: v) + self = bb.readString( + at: MemoryLayout.size + v, + count: Int(count)) ?? "" + } +} + +extension String: ObjectAPIPacker { + + public static func pack( + _ builder: inout FlatBufferBuilder, + obj: inout String?) -> Offset + { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack( + _ builder: inout FlatBufferBuilder, + obj: inout String) -> Offset + { + builder.create(string: obj) + } + + public mutating func unpack() -> String { + self + } + +} + +extension String: NativeObject { + + public func serialize(type: T.Type) -> ByteBuffer + where T.T == Self + { + fatalError("serialize should never be called from string directly") + } + + public func serialize( + builder: inout FlatBufferBuilder, + type: T.Type) -> ByteBuffer where T.T == Self + { + fatalError("serialize should never be called from string directly") + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Struct.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Struct.swift new file mode 100644 index 00000000000..bbce8f978c7 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Struct.swift @@ -0,0 +1,47 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Struct is a representation of a mutable `Flatbuffers` struct +/// since native structs are value types and cant be mutated +@frozen +public struct Struct { + + /// Hosting Bytebuffer + public private(set) var bb: ByteBuffer + /// Current position of the struct + public private(set) var position: Int32 + + /// Initializer for a mutable flatbuffers struct + /// - Parameters: + /// - bb: Current hosting Bytebuffer + /// - position: Current position for the struct in the ByteBuffer + public init(bb: ByteBuffer, position: Int32 = 0) { + self.bb = bb + self.position = position + } + + /// Reads data from the buffer directly at offset O + /// - Parameters: + /// - type: Type of data to be read + /// - o: Current offset of the data + /// - Returns: Data of Type T that conforms to type Scalar + public func readBuffer(of type: T.Type, at o: Int32) -> T { + let r = bb.read(def: T.self, position: Int(o + position)) + return r + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Table.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Table.swift new file mode 100644 index 00000000000..02a2e6f2cdd --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Table.swift @@ -0,0 +1,236 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// `Table` is a Flatbuffers object that can read, +/// mutate scalar fields within a valid flatbuffers buffer +@frozen +public struct Table { + + /// Hosting Bytebuffer + public private(set) var bb: ByteBuffer + /// Current position of the table within the buffer + public private(set) var position: Int32 + + /// Initializer for the table interface to allow generated code to read + /// data from memory + /// - Parameters: + /// - bb: ByteBuffer that stores data + /// - position: Current table position + /// - Note: This will `CRASH` if read on a big endian machine + public init(bb: ByteBuffer, position: Int32 = 0) { + guard isLitteEndian else { + fatalError( + "Reading/Writing a buffer in big endian machine is not supported on swift") + } + self.bb = bb + self.position = position + } + + /// Gets the offset of the current field within the buffer by reading + /// the vtable + /// - Parameter o: current offset + /// - Returns: offset of field within buffer + public func offset(_ o: Int32) -> Int32 { + let vtable = position - bb.read(def: Int32.self, position: Int(position)) + return o < bb + .read(def: VOffset.self, position: Int(vtable)) ? Int32(bb.read( + def: Int16.self, + position: Int(vtable + o))) : 0 + } + + /// Gets the indirect offset of the current stored object + /// (applicable only for object arrays) + /// - Parameter o: current offset + /// - Returns: offset of field within buffer + public func indirect(_ o: Int32) -> Int32 { + o + bb.read(def: Int32.self, position: Int(o)) + } + + /// String reads from the buffer with respect to position of the current table. + /// - Parameter offset: Offset of the string + public func string(at offset: Int32) -> String? { + directString(at: offset + position) + } + + /// Direct string reads from the buffer disregarding the position of the table. + /// It would be preferable to use string unless the current position of the table + /// is not needed + /// - Parameter offset: Offset of the string + public func directString(at offset: Int32) -> String? { + var offset = offset + offset += bb.read(def: Int32.self, position: Int(offset)) + let count = bb.read(def: Int32.self, position: Int(offset)) + let position = Int(offset) + MemoryLayout.size + return bb.readString(at: position, count: Int(count)) + } + + /// Reads from the buffer with respect to the position in the table. + /// - Parameters: + /// - type: Type of Element that needs to be read from the buffer + /// - o: Offset of the Element + public func readBuffer(of type: T.Type, at o: Int32) -> T { + directRead(of: T.self, offset: o + position) + } + + /// Reads from the buffer disregarding the position of the table. + /// It would be used when reading from an + /// ``` + /// let offset = __t.offset(10) + /// //Only used when the we already know what is the + /// // position in the table since __t.vector(at:) + /// // returns the index with respect to the position + /// __t.directRead(of: Byte.self, + /// offset: __t.vector(at: offset) + index * 1) + /// ``` + /// - Parameters: + /// - type: Type of Element that needs to be read from the buffer + /// - o: Offset of the Element + public func directRead(of type: T.Type, offset o: Int32) -> T { + let r = bb.read(def: T.self, position: Int(o)) + return r + } + + /// Returns that current `Union` object at a specific offset + /// by adding offset to the current position of table + /// - Parameter o: offset + /// - Returns: A flatbuffers object + public func union(_ o: Int32) -> T { + let o = o + position + return directUnion(o) + } + + /// Returns a direct `Union` object at a specific offset + /// - Parameter o: offset + /// - Returns: A flatbuffers object + public func directUnion(_ o: Int32) -> T { + T.init(bb, o: o + bb.read(def: Int32.self, position: Int(o))) + } + + /// Returns a vector of type T at a specific offset + /// This should only be used by `Scalars` + /// - Parameter off: Readable offset + /// - Returns: Returns a vector of type [T] + public func getVector(at off: Int32) -> [T]? { + let o = offset(off) + guard o != 0 else { return nil } + return bb.readSlice(index: Int(vector(at: o)), count: Int(vector(count: o))) + } + + /// Vector count gets the count of Elements within the array + /// - Parameter o: start offset of the vector + /// - returns: Count of elements + public func vector(count o: Int32) -> Int32 { + var o = o + o += position + o += bb.read(def: Int32.self, position: Int(o)) + return bb.read(def: Int32.self, position: Int(o)) + } + + /// Vector start index in the buffer + /// - Parameter o:start offset of the vector + /// - returns: the start index of the vector + public func vector(at o: Int32) -> Int32 { + var o = o + o += position + return o + bb.read(def: Int32.self, position: Int(o)) + 4 + } + + /// Reading an indirect offset of a table. + /// - Parameters: + /// - o: position within the buffer + /// - fbb: ByteBuffer + /// - Returns: table offset + static public func indirect(_ o: Int32, _ fbb: ByteBuffer) -> Int32 { + o + fbb.read(def: Int32.self, position: Int(o)) + } + + /// Gets a vtable value according to an table Offset and a field offset + /// - Parameters: + /// - o: offset relative to entire buffer + /// - vOffset: Field offset within a vtable + /// - fbb: ByteBuffer + /// - Returns: an position of a field + static public func offset( + _ o: Int32, + vOffset: Int32, + fbb: ByteBuffer) -> Int32 + { + let vTable = Int32(fbb.capacity) - o + return vTable + Int32(fbb.read( + def: Int16.self, + position: Int(vTable + vOffset - fbb.read( + def: Int32.self, + position: Int(vTable))))) + } + + /// Compares two objects at offset A and offset B within a ByteBuffer + /// - Parameters: + /// - off1: first offset to compare + /// - off2: second offset to compare + /// - fbb: Bytebuffer + /// - Returns: returns the difference between + static public func compare( + _ off1: Int32, + _ off2: Int32, + fbb: ByteBuffer) -> Int32 + { + let memorySize = Int32(MemoryLayout.size) + let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) + let _off2 = off2 + fbb.read(def: Int32.self, position: Int(off2)) + let len1 = fbb.read(def: Int32.self, position: Int(_off1)) + let len2 = fbb.read(def: Int32.self, position: Int(_off2)) + let startPos1 = _off1 + memorySize + let startPos2 = _off2 + memorySize + let minValue = min(len1, len2) + for i in 0...minValue { + let b1 = fbb.read(def: Int8.self, position: Int(i + startPos1)) + let b2 = fbb.read(def: Int8.self, position: Int(i + startPos2)) + if b1 != b2 { + return Int32(b2 - b1) + } + } + return len1 - len2 + } + + /// Compares two objects at offset A and array of `Bytes` within a ByteBuffer + /// - Parameters: + /// - off1: Offset to compare to + /// - key: bytes array to compare to + /// - fbb: Bytebuffer + /// - Returns: returns the difference between + static public func compare( + _ off1: Int32, + _ key: [Byte], + fbb: ByteBuffer) -> Int32 + { + let memorySize = Int32(MemoryLayout.size) + let _off1 = off1 + fbb.read(def: Int32.self, position: Int(off1)) + let len1 = fbb.read(def: Int32.self, position: Int(_off1)) + let len2 = Int32(key.count) + let startPos1 = _off1 + memorySize + let minValue = min(len1, len2) + for i in 0.. Int? { + if field >= _vtableLength { + return nil + } + + /// Reading the offset for the field needs to be read. + let offset: VOffset = try _verifier.getValue( + at: Int(clamping: _vtable &+ Int(field))) + + if offset > 0 { + return Int(clamping: _position &+ Int(offset)) + } + return nil + } + + /// Visits all the fields within the table to validate the integrity + /// of the data + /// - Parameters: + /// - field: voffset of the current field to be read + /// - fieldName: fieldname to report data Errors. + /// - required: If the field has to be available in the buffer + /// - type: Type of field to be read + /// - Throws: A `FlatbuffersErrors` where the field is corrupt + public mutating func visit( + field: VOffset, + fieldName: String, + required: Bool, + type: T.Type) throws where T: Verifiable + { + let derefValue = try dereference(field) + + if let value = derefValue { + try T.verify(&_verifier, at: value, of: T.self) + return + } + if required { + throw FlatbuffersErrors.requiredFieldDoesntExist( + position: field, + name: fieldName) + } + } + + /// Visits all the fields for a union object within the table to + /// validate the integrity of the data + /// - Parameters: + /// - key: Current Key Voffset + /// - field: Current field Voffset + /// - unionKeyName: Union key name + /// - fieldName: Field key name + /// - required: indicates if an object is required to be present + /// - completion: Completion is a handler that WILL be called in the generated + /// - Throws: A `FlatbuffersErrors` where the field is corrupt + public mutating func visit( + unionKey key: VOffset, + unionField field: VOffset, + unionKeyName: String, + fieldName: String, + required: Bool, + completion: @escaping (inout Verifier, T, Int) throws -> Void) throws + where T: UnionEnum + { + let keyPos = try dereference(key) + let valPos = try dereference(field) + + if keyPos == nil && valPos == nil { + if required { + throw FlatbuffersErrors.requiredFieldDoesntExist( + position: key, + name: unionKeyName) + } + return + } + + if let _key = keyPos, + let _val = valPos + { + /// verifiying that the key is within the buffer + try T.T.verify(&_verifier, at: _key, of: T.T.self) + guard let _enum = try T.init(value: _verifier._buffer.read( + def: T.T.self, + position: _key)) else + { + throw FlatbuffersErrors.unknownUnionCase + } + /// we are assuming that Unions will always be of type Uint8 + try completion( + &_verifier, + _enum, + _val) + return + } + throw FlatbuffersErrors.valueNotFound( + key: keyPos, + keyName: unionKeyName, + field: valPos, + fieldName: fieldName) + } + + /// Visits and validates all the objects within a union vector + /// - Parameters: + /// - key: Current Key Voffset + /// - field: Current field Voffset + /// - unionKeyName: Union key name + /// - fieldName: Field key name + /// - required: indicates if an object is required to be present + /// - completion: Completion is a handler that WILL be called in the generated + /// - Throws: A `FlatbuffersErrors` where the field is corrupt + public mutating func visitUnionVector( + unionKey key: VOffset, + unionField field: VOffset, + unionKeyName: String, + fieldName: String, + required: Bool, + completion: @escaping (inout Verifier, T, Int) throws -> Void) throws + where T: UnionEnum + { + let keyVectorPosition = try dereference(key) + let offsetVectorPosition = try dereference(field) + + if let keyPos = keyVectorPosition, + let valPos = offsetVectorPosition + { + try UnionVector.verify( + &_verifier, + keyPosition: keyPos, + fieldPosition: valPos, + unionKeyName: unionKeyName, + fieldName: fieldName, + completion: completion) + return + } + if required { + throw FlatbuffersErrors.requiredFieldDoesntExist( + position: field, + name: fieldName) + } + } + + /// Finishs the current Table verifier, and subtracts the current + /// table from the incremented depth. + public mutating func finish() { + _verifier.finish() + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/VeriferOptions.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/VeriferOptions.swift new file mode 100644 index 00000000000..a7f11e243d1 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/VeriferOptions.swift @@ -0,0 +1,52 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// `VerifierOptions` is a set of options to verify a flatbuffer +public struct VerifierOptions { + + /// Maximum `Apparent` size if the buffer can be expanded into a DAG tree + internal var _maxApparentSize: UOffset + + /// Maximum table count allowed in a buffer + internal var _maxTableCount: UOffset + + /// Maximum depth allowed in a buffer + internal var _maxDepth: UOffset + + /// Ignoring missing null terminals in strings + internal var _ignoreMissingNullTerminators: Bool + + /// initializes the set of options for the verifier + /// - Parameters: + /// - maxDepth: Maximum depth allowed in a buffer + /// - maxTableCount: Maximum table count allowed in a buffer + /// - maxApparentSize: Maximum `Apparent` size if the buffer can be expanded into a DAG tree + /// - ignoreMissingNullTerminators: Ignoring missing null terminals in strings *Currently not supported in swift* + public init( + maxDepth: UOffset = 64, + maxTableCount: UOffset = 1000000, + maxApparentSize: UOffset = 1 << 31, + ignoreMissingNullTerminators: Bool = false) + { + _maxDepth = maxDepth + _maxTableCount = maxTableCount + _maxApparentSize = maxApparentSize + _ignoreMissingNullTerminators = ignoreMissingNullTerminators + } + +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Verifiable.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Verifiable.swift new file mode 100644 index 00000000000..3d3e08f0f83 --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Verifiable.swift @@ -0,0 +1,213 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Verifiable is a protocol all swift flatbuffers object should conform to, +/// since swift is similar to `cpp` and `rust` where the data is read directly +/// from `unsafeMemory` thus the need to verify if the buffer received is a valid one +public protocol Verifiable { + + /// Verifies that the current value is which the bounds of the buffer, and if + /// the current `Value` is aligned properly + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Errors coming from `inBuffer` function + static func verify( + _ verifier: inout Verifier, + at position: Int, + of type: T.Type) throws where T: Verifiable +} + +extension Verifiable { + + /// Verifies if the current range to be read is within the bounds of the buffer, + /// and if the range is properly aligned + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Erros thrown from `isAligned` & `rangeInBuffer` + /// - Returns: a tuple of the start position and the count of objects within the range + @discardableResult + public static func verifyRange( + _ verifier: inout Verifier, + at position: Int, of type: T.Type) throws -> (start: Int, count: Int) + { + let len: UOffset = try verifier.getValue(at: position) + let intLen = Int(len) + let start = Int(clamping: (position &+ MemoryLayout.size).magnitude) + try verifier.isAligned(position: start, type: type.self) + try verifier.rangeInBuffer(position: start, size: intLen) + return (start, intLen) + } +} + +extension Verifiable where Self: Scalar { + + /// Verifies that the current value is which the bounds of the buffer, and if + /// the current `Value` is aligned properly + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Errors coming from `inBuffer` function + public static func verify( + _ verifier: inout Verifier, + at position: Int, + of type: T.Type) throws where T: Verifiable + { + try verifier.inBuffer(position: position, of: type.self) + } +} + +// MARK: - ForwardOffset + +/// ForwardOffset is a container to wrap around the Generic type to be verified +/// from the flatbuffers object. +public enum ForwardOffset: Verifiable where U: Verifiable { + + /// Verifies that the current value is which the bounds of the buffer, and if + /// the current `Value` is aligned properly + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Errors coming from `inBuffer` function + public static func verify( + _ verifier: inout Verifier, + at position: Int, + of type: T.Type) throws where T: Verifiable + { + let offset: UOffset = try verifier.getValue(at: position) + let nextOffset = Int(clamping: (Int(offset) &+ position).magnitude) + try U.verify(&verifier, at: nextOffset, of: U.self) + } +} + +// MARK: - Vector + +/// Vector is a container to wrap around the Generic type to be verified +/// from the flatbuffers object. +public enum Vector: Verifiable where U: Verifiable, S: Verifiable { + + /// Verifies that the current value is which the bounds of the buffer, and if + /// the current `Value` is aligned properly + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - position: Current position within the buffer + /// - type: The type of the object to be verified + /// - Throws: Errors coming from `inBuffer` function + public static func verify( + _ verifier: inout Verifier, + at position: Int, + of type: T.Type) throws where T: Verifiable + { + /// checks if the next verification type S is equal to U of type forwardOffset + /// This had to be done since I couldnt find a solution for duplicate call functions + /// A fix will be appreciated + if U.self is ForwardOffset.Type { + let range = try verifyRange(&verifier, at: position, of: UOffset.self) + for index in stride( + from: range.start, + to: Int( + clamping: range + .start &+ (range.count &* MemoryLayout.size)), + by: MemoryLayout.size) + { + try U.verify(&verifier, at: index, of: U.self) + } + } else { + try S.verifyRange(&verifier, at: position, of: S.self) + } + } +} + +// MARK: - UnionVector + +/// UnionVector is a container to wrap around the Generic type to be verified +/// from the flatbuffers object. +public enum UnionVector where S: UnionEnum { + + /// Completion handler for the function Verify, that passes the verifier + /// enum type and position of union field + public typealias Completion = (inout Verifier, S, Int) throws -> Void + + /// Verifies if the current range to be read is within the bounds of the buffer, + /// and if the range is properly aligned. It also verifies if the union type is a + /// *valid/supported* union type. + /// - Parameters: + /// - verifier: Verifier that hosts the buffer + /// - keyPosition: Current union key position within the buffer + /// - fieldPosition: Current union field position within the buffer + /// - unionKeyName: Name of key to written if error is presented + /// - fieldName: Name of field to written if error is presented + /// - completion: Completion is a handler that WILL be called in the generated + /// code to verify the actual objects + /// - Throws: FlatbuffersErrors + public static func verify( + _ verifier: inout Verifier, + keyPosition: Int, + fieldPosition: Int, + unionKeyName: String, + fieldName: String, + completion: @escaping Completion) throws + { + /// Get offset for union key vectors and offset vectors + let keyOffset: UOffset = try verifier.getValue(at: keyPosition) + let fieldOffset: UOffset = try verifier.getValue(at: fieldPosition) + + /// Check if values are within the buffer, returns the start position of vectors, and vector counts + /// Using &+ is safe since we already verified that the value is within the buffer, where the max is + /// going to be 2Gib and swift supports Int64 by default + let keysRange = try S.T.verifyRange( + &verifier, + at: Int(keyOffset) &+ keyPosition, + of: S.T.self) + let offsetsRange = try UOffset.verifyRange( + &verifier, + at: Int(fieldOffset) &+ fieldPosition, + of: UOffset.self) + + guard keysRange.count == offsetsRange.count else { + throw FlatbuffersErrors.unionVectorSize( + keyVectorSize: keysRange.count, + fieldVectorSize: offsetsRange.count, + unionKeyName: unionKeyName, + fieldName: fieldName) + } + + var count = 0 + /// Iterate over the vector of keys and offsets. + while count < keysRange.count { + + /// index of readable enum value in array + let keysIndex = MemoryLayout.size * count + guard let _enum = try S.init(value: verifier._buffer.read( + def: S.T.self, + position: keysRange.start + keysIndex)) else + { + throw FlatbuffersErrors.unknownUnionCase + } + /// index of readable offset value in array + let fieldIndex = MemoryLayout.size * count + try completion(&verifier, _enum, offsetsRange.start + fieldIndex) + count += 1 + } + } +} diff --git a/third_party/flatbuffers/swift/Sources/FlatBuffers/Verifier.swift b/third_party/flatbuffers/swift/Sources/FlatBuffers/Verifier.swift new file mode 100644 index 00000000000..0d52ccd8a8d --- /dev/null +++ b/third_party/flatbuffers/swift/Sources/FlatBuffers/Verifier.swift @@ -0,0 +1,238 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation + +/// Verifier that check if the buffer passed into it is a valid, +/// safe, aligned Flatbuffers object since swift read from `unsafeMemory` +public struct Verifier { + + /// Flag to check for alignment if true + fileprivate let _checkAlignment: Bool + /// Storage for all changing values within the verifier + private let storage: Storage + /// Current verifiable ByteBuffer + internal var _buffer: ByteBuffer + /// Options for verification + internal let _options: VerifierOptions + + /// Current stored capacity within the verifier + var capacity: Int { + storage.capacity + } + + /// Current depth of verifier + var depth: Int { + storage.depth + } + + /// Current table count + var tableCount: Int { + storage.tableCount + } + + + /// Initializer for the verifier + /// - Parameters: + /// - buffer: Bytebuffer that is required to be verified + /// - options: `VerifierOptions` that set the rule for some of the verification done + /// - checkAlignment: If alignment check is required to be preformed + /// - Throws: `exceedsMaxSizeAllowed` if capacity of the buffer is more than 2GiB + public init( + buffer: inout ByteBuffer, + options: VerifierOptions = .init(), + checkAlignment: Bool = true) throws + { + guard buffer.capacity < FlatBufferMaxSize else { + throw FlatbuffersErrors.exceedsMaxSizeAllowed + } + + _buffer = buffer + _checkAlignment = checkAlignment + _options = options + storage = Storage(capacity: buffer.capacity) + } + + /// Resets the verifier to initial state + public func reset() { + storage.depth = 0 + storage.tableCount = 0 + } + + /// Checks if the value of type `T` is aligned properly in the buffer + /// - Parameters: + /// - position: Current position + /// - type: Type of value to check + /// - Throws: `missAlignedPointer` if the pointer is not aligned properly + public func isAligned(position: Int, type: T.Type) throws { + + /// If check alignment is false this mutating function doesnt continue + if !_checkAlignment { return } + + /// advance pointer to position X + let ptr = _buffer._storage.memory.advanced(by: position) + /// Check if the pointer is aligned + if Int(bitPattern: ptr) & (MemoryLayout.alignment &- 1) == 0 { + return + } + + throw FlatbuffersErrors.missAlignedPointer( + position: position, + type: String(describing: T.self)) + } + + /// Checks if the value of Size "X" is within the range of the buffer + /// - Parameters: + /// - position: Current position to be read + /// - size: `Byte` Size of readable object within the buffer + /// - Throws: `outOfBounds` if the value is out of the bounds of the buffer + /// and `apparentSizeTooLarge` if the apparent size is bigger than the one specified + /// in `VerifierOptions` + public func rangeInBuffer(position: Int, size: Int) throws { + let end = UInt(clamping: (position &+ size).magnitude) + if end > _buffer.capacity { + throw FlatbuffersErrors.outOfBounds(position: end, end: storage.capacity) + } + storage.apparentSize = storage.apparentSize &+ UInt32(size) + if storage.apparentSize > _options._maxApparentSize { + throw FlatbuffersErrors.apparentSizeTooLarge + } + } + + /// Validates if a value of type `T` is aligned and within the bounds of + /// the buffer + /// - Parameters: + /// - position: Current readable position + /// - type: Type of value to check + /// - Throws: FlatbuffersErrors + public func inBuffer(position: Int, of type: T.Type) throws { + try isAligned(position: position, type: type) + try rangeInBuffer(position: position, size: MemoryLayout.size) + } + + /// Visits a table at the current position and validates if the table meets + /// the rules specified in the `VerifierOptions` + /// - Parameter position: Current position to be read + /// - Throws: FlatbuffersErrors + /// - Returns: A `TableVerifier` at the current readable table + public mutating func visitTable(at position: Int) throws -> TableVerifier { + let vtablePosition = try derefOffset(position: position) + let vtableLength: VOffset = try getValue(at: vtablePosition) + + let length = Int(vtableLength) + try isAligned( + position: Int(clamping: (vtablePosition + length).magnitude), + type: VOffset.self) + try rangeInBuffer(position: vtablePosition, size: length) + + storage.tableCount += 1 + + if storage.tableCount > _options._maxTableCount { + throw FlatbuffersErrors.maximumTables + } + + storage.depth += 1 + + if storage.depth > _options._maxDepth { + throw FlatbuffersErrors.maximumDepth + } + + return TableVerifier( + position: position, + vtable: vtablePosition, + vtableLength: length, + verifier: &self) + } + + /// Validates if a value of type `T` is within the buffer and returns it + /// - Parameter position: Current position to be read + /// - Throws: `inBuffer` errors + /// - Returns: a value of type `T` usually a `VTable` or a table offset + internal func getValue(at position: Int) throws -> T { + try inBuffer(position: position, of: T.self) + return _buffer.read(def: T.self, position: position) + } + + /// derefrences an offset within a vtable to get the position of the field + /// in the bytebuffer + /// - Parameter position: Current readable position + /// - Throws: `inBuffer` errors & `signedOffsetOutOfBounds` + /// - Returns: Current readable position for a field + @inline(__always) + internal func derefOffset(position: Int) throws -> Int { + try inBuffer(position: position, of: Int32.self) + + let offset = _buffer.read(def: Int32.self, position: position) + // switching to int32 since swift's default Int is int64 + // this should be safe since we already checked if its within + // the buffer + let _int32Position = UInt32(position) + + let reportedOverflow: (partialValue: UInt32, overflow: Bool) + if offset > 0 { + reportedOverflow = _int32Position + .subtractingReportingOverflow(offset.magnitude) + } else { + reportedOverflow = _int32Position + .addingReportingOverflow(offset.magnitude) + } + + /// since `subtractingReportingOverflow` & `addingReportingOverflow` returns true, + /// if there is overflow we return failure + if reportedOverflow.overflow || reportedOverflow.partialValue > _buffer + .capacity + { + throw FlatbuffersErrors.signedOffsetOutOfBounds( + offset: Int(offset), + position: position) + } + + return Int(reportedOverflow.partialValue) + } + + /// finishes the current iteration of verification on an object + internal func finish() { + storage.depth -= 1 + } + + @inline(__always) + func verify(id: String) throws { + let size = MemoryLayout.size + guard storage.capacity >= (size * 2) else { + throw FlatbuffersErrors.bufferDoesntContainID + } + let str = _buffer.readString(at: size, count: size) + if id == str { + return + } + throw FlatbuffersErrors.bufferIdDidntMatchPassedId + } + + final private class Storage { + /// Current ApparentSize + fileprivate var apparentSize: UOffset = 0 + /// Amount of tables present within a buffer + fileprivate var tableCount = 0 + /// Capacity of the current buffer + fileprivate let capacity: Int + /// Current reached depth within the buffer + fileprivate var depth = 0 + + init(capacity: Int) { + self.capacity = capacity + } + } +} diff --git a/third_party/flatbuffers/tests/.gitignore b/third_party/flatbuffers/tests/.gitignore new file mode 100644 index 00000000000..25d3361959e --- /dev/null +++ b/third_party/flatbuffers/tests/.gitignore @@ -0,0 +1,2 @@ +# Generated files shouldn't be checked in for tests. +**_generated.h \ No newline at end of file diff --git a/third_party/flatbuffers/tests/64bit/evolution/v1.fbs b/third_party/flatbuffers/tests/64bit/evolution/v1.fbs new file mode 100644 index 00000000000..dcdc0badc9b --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/evolution/v1.fbs @@ -0,0 +1,8 @@ +namespace v1; + +table RootTable { + a:float; + b:[uint8]; +} + +root_type RootTable; diff --git a/third_party/flatbuffers/tests/64bit/evolution/v1_generated.h b/third_party/flatbuffers/tests/64bit/evolution/v1_generated.h new file mode 100644 index 00000000000..f14545dda17 --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/evolution/v1_generated.h @@ -0,0 +1,219 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_V1_V1_H_ +#define FLATBUFFERS_GENERATED_V1_V1_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace v1 { + +struct RootTable; +struct RootTableBuilder; +struct RootTableT; + +bool operator==(const RootTableT &lhs, const RootTableT &rhs); +bool operator!=(const RootTableT &lhs, const RootTableT &rhs); + +inline const ::flatbuffers::TypeTable *RootTableTypeTable(); + +struct RootTableT : public ::flatbuffers::NativeTable { + typedef RootTable TableType; + float a = 0.0f; + std::vector b{}; +}; + +struct RootTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RootTableT NativeTableType; + typedef RootTableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RootTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6 + }; + float a() const { + return GetField(VT_A, 0.0f); + } + bool mutate_a(float _a = 0.0f) { + return SetField(VT_A, _a, 0.0f); + } + const ::flatbuffers::Vector *b() const { + return GetPointer *>(VT_B); + } + ::flatbuffers::Vector *mutable_b() { + return GetPointer<::flatbuffers::Vector *>(VT_B); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + VerifyOffset(verifier, VT_B) && + verifier.VerifyVector(b()) && + verifier.EndTable(); + } + RootTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(RootTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const RootTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct RootTableBuilder { + typedef RootTable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(float a) { + fbb_.AddElement(RootTable::VT_A, a, 0.0f); + } + void add_b(::flatbuffers::Offset<::flatbuffers::Vector> b) { + fbb_.AddOffset(RootTable::VT_B, b); + } + explicit RootTableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRootTable( + ::flatbuffers::FlatBufferBuilder &_fbb, + float a = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector> b = 0) { + RootTableBuilder builder_(_fbb); + builder_.add_b(b); + builder_.add_a(a); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateRootTableDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + float a = 0.0f, + const std::vector *b = nullptr) { + auto b__ = b ? _fbb.CreateVector(*b) : 0; + return v1::CreateRootTable( + _fbb, + a, + b__); +} + +::flatbuffers::Offset CreateRootTable(::flatbuffers::FlatBufferBuilder &_fbb, const RootTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const RootTableT &lhs, const RootTableT &rhs) { + return + (lhs.a == rhs.a) && + (lhs.b == rhs.b); +} + +inline bool operator!=(const RootTableT &lhs, const RootTableT &rhs) { + return !(lhs == rhs); +} + + +inline RootTableT *RootTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new RootTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void RootTable::UnPackTo(RootTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = a(); _o->a = _e; } + { auto _e = b(); if (_e) { _o->b.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->b.begin()); } } +} + +inline ::flatbuffers::Offset RootTable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const RootTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateRootTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateRootTable(::flatbuffers::FlatBufferBuilder &_fbb, const RootTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const RootTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _a = _o->a; + auto _b = _o->b.size() ? _fbb.CreateVector(_o->b) : 0; + return v1::CreateRootTable( + _fbb, + _a, + _b); +} + +inline const ::flatbuffers::TypeTable *RootTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 } + }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 2, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const v1::RootTable *GetRootTable(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const v1::RootTable *GetSizePrefixedRootTable(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline RootTable *GetMutableRootTable(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline v1::RootTable *GetMutableSizePrefixedRootTable(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline bool VerifyRootTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedRootTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishRootTableBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedRootTableBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +inline std::unique_ptr UnPackRootTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetRootTable(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedRootTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedRootTable(buf)->UnPack(res)); +} + +} // namespace v1 + +#endif // FLATBUFFERS_GENERATED_V1_V1_H_ diff --git a/third_party/flatbuffers/tests/64bit/evolution/v2.fbs b/third_party/flatbuffers/tests/64bit/evolution/v2.fbs new file mode 100644 index 00000000000..f83e510994d --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/evolution/v2.fbs @@ -0,0 +1,9 @@ +namespace v2; + +table RootTable { + a:float; + b:[uint8]; + big_vector:[uint8] (vector64); +} + +root_type RootTable; diff --git a/third_party/flatbuffers/tests/64bit/evolution/v2_generated.h b/third_party/flatbuffers/tests/64bit/evolution/v2_generated.h new file mode 100644 index 00000000000..d07d560fed8 --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/evolution/v2_generated.h @@ -0,0 +1,243 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_V2_V2_H_ +#define FLATBUFFERS_GENERATED_V2_V2_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace v2 { + +struct RootTable; +struct RootTableBuilder; +struct RootTableT; + +bool operator==(const RootTableT &lhs, const RootTableT &rhs); +bool operator!=(const RootTableT &lhs, const RootTableT &rhs); + +inline const ::flatbuffers::TypeTable *RootTableTypeTable(); + +struct RootTableT : public ::flatbuffers::NativeTable { + typedef RootTable TableType; + float a = 0.0f; + std::vector b{}; + std::vector big_vector{}; +}; + +struct RootTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RootTableT NativeTableType; + typedef RootTableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RootTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6, + VT_BIG_VECTOR = 8 + }; + float a() const { + return GetField(VT_A, 0.0f); + } + bool mutate_a(float _a = 0.0f) { + return SetField(VT_A, _a, 0.0f); + } + const ::flatbuffers::Vector *b() const { + return GetPointer *>(VT_B); + } + ::flatbuffers::Vector *mutable_b() { + return GetPointer<::flatbuffers::Vector *>(VT_B); + } + const ::flatbuffers::Vector64 *big_vector() const { + return GetPointer64 *>(VT_BIG_VECTOR); + } + ::flatbuffers::Vector64 *mutable_big_vector() { + return GetPointer64<::flatbuffers::Vector64 *>(VT_BIG_VECTOR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + VerifyOffset(verifier, VT_B) && + verifier.VerifyVector(b()) && + VerifyOffset64(verifier, VT_BIG_VECTOR) && + verifier.VerifyVector(big_vector()) && + verifier.EndTable(); + } + RootTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(RootTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct RootTableBuilder { + typedef RootTable Table; + ::flatbuffers::FlatBufferBuilder64 &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(float a) { + fbb_.AddElement(RootTable::VT_A, a, 0.0f); + } + void add_b(::flatbuffers::Offset<::flatbuffers::Vector> b) { + fbb_.AddOffset(RootTable::VT_B, b); + } + void add_big_vector(::flatbuffers::Offset64<::flatbuffers::Vector64> big_vector) { + fbb_.AddOffset(RootTable::VT_BIG_VECTOR, big_vector); + } + explicit RootTableBuilder(::flatbuffers::FlatBufferBuilder64 &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRootTable( + ::flatbuffers::FlatBufferBuilder64 &_fbb, + float a = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector> b = 0, + ::flatbuffers::Offset64<::flatbuffers::Vector64> big_vector = 0) { + RootTableBuilder builder_(_fbb); + builder_.add_big_vector(big_vector); + builder_.add_b(b); + builder_.add_a(a); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateRootTableDirect( + ::flatbuffers::FlatBufferBuilder64 &_fbb, + float a = 0.0f, + const std::vector *b = nullptr, + const std::vector *big_vector = nullptr) { + auto big_vector__ = big_vector ? _fbb.CreateVector64(*big_vector) : 0; + auto b__ = b ? _fbb.CreateVector(*b) : 0; + return v2::CreateRootTable( + _fbb, + a, + b__, + big_vector__); +} + +::flatbuffers::Offset CreateRootTable(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const RootTableT &lhs, const RootTableT &rhs) { + return + (lhs.a == rhs.a) && + (lhs.b == rhs.b) && + (lhs.big_vector == rhs.big_vector); +} + +inline bool operator!=(const RootTableT &lhs, const RootTableT &rhs) { + return !(lhs == rhs); +} + + +inline RootTableT *RootTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new RootTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void RootTable::UnPackTo(RootTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = a(); _o->a = _e; } + { auto _e = b(); if (_e) { _o->b.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->b.begin()); } } + { auto _e = big_vector(); if (_e) { _o->big_vector.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->big_vector.begin()); } } +} + +inline ::flatbuffers::Offset RootTable::Pack(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateRootTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateRootTable(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder64 *__fbb; const RootTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _a = _o->a; + auto _b = _o->b.size() ? _fbb.CreateVector(_o->b) : 0; + auto _big_vector = _o->big_vector.size() ? _fbb.CreateVector64(_o->big_vector) : 0; + return v2::CreateRootTable( + _fbb, + _a, + _b, + _big_vector); +} + +inline const ::flatbuffers::TypeTable *RootTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 } + }; + static const char * const names[] = { + "a", + "b", + "big_vector" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const v2::RootTable *GetRootTable(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const v2::RootTable *GetSizePrefixedRootTable(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline RootTable *GetMutableRootTable(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline v2::RootTable *GetMutableSizePrefixedRootTable(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline bool VerifyRootTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedRootTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishRootTableBuffer( + ::flatbuffers::FlatBufferBuilder64 &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedRootTableBuffer( + ::flatbuffers::FlatBufferBuilder64 &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +inline std::unique_ptr UnPackRootTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetRootTable(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedRootTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedRootTable(buf)->UnPack(res)); +} + +} // namespace v2 + +#endif // FLATBUFFERS_GENERATED_V2_V2_H_ diff --git a/third_party/flatbuffers/tests/64bit/offset64_test.cpp b/third_party/flatbuffers/tests/64bit/offset64_test.cpp new file mode 100644 index 00000000000..ce9e022eeba --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/offset64_test.cpp @@ -0,0 +1,458 @@ +#include "offset64_test.h" + +#include + +#include +#include +#include +#include + +#include "flatbuffers/base.h" +#include "flatbuffers/buffer.h" +#include "flatbuffers/flatbuffer_builder.h" +#include "flatbuffers/flatbuffers.h" +#include "tests/64bit/evolution/v1_generated.h" +#include "tests/64bit/evolution/v2_generated.h" +#include "tests/64bit/test_64bit_generated.h" +#include "tests/test_assert.h" + +namespace flatbuffers { +namespace tests { + +void Offset64Test() { + FlatBufferBuilder64 builder; + + const size_t far_vector_size = 1LL << 2; + // Make a large number if wanting to test a real large buffer. + const size_t big_vector_size = 1LL << 2; + + { + // First create the vectors that will be copied to the buffer. + std::vector far_data; + far_data.resize(far_vector_size); + far_data[0] = 4; + far_data[far_vector_size - 1] = 2; + + std::vector big_data; + big_data.resize(big_vector_size); + big_data[0] = 8; + big_data[big_vector_size - 1] = 3; + + // Then serialize all the fields that have 64-bit offsets, as these must be + // serialized before any 32-bit fields are added to the buffer. + const Offset64> far_vector_offset = + builder.CreateVector64(far_data); + + const Offset64 far_string_offset = + builder.CreateString("some far string"); + + const Offset64> big_vector_offset = + builder.CreateVector64(big_data); + + // Now that we are done with the 64-bit fields, we can create and add the + // normal fields. + const Offset near_string_offset = + builder.CreateString("some near string"); + + // Finish by building the root table by passing in all the offsets. + const Offset root_table_offset = + CreateRootTable(builder, far_vector_offset, 0, far_string_offset, + big_vector_offset, near_string_offset); + + // Finish the buffer. + builder.Finish(root_table_offset); + + Verifier::Options options; + // Allow the verifier to verify 64-bit buffers. + options.max_size = FLATBUFFERS_MAX_64_BUFFER_SIZE; + options.assert = true; + + Verifier verifier(builder.GetBufferPointer(), builder.GetSize(), options); + + TEST_EQ(VerifyRootTableBuffer(verifier), true); + } + + { + const RootTable *root_table = GetRootTable(builder.GetBufferPointer()); + + // Expect the far vector to be properly sized. + TEST_EQ(root_table->far_vector()->size(), far_vector_size); + TEST_EQ(root_table->far_vector()->Get(0), 4); + TEST_EQ(root_table->far_vector()->Get(far_vector_size - 1), 2); + + TEST_EQ_STR(root_table->far_string()->c_str(), "some far string"); + + // Expect the big vector to be properly sized. + TEST_EQ(root_table->big_vector()->size(), big_vector_size); + TEST_EQ(root_table->big_vector()->Get(0), 8); + TEST_EQ(root_table->big_vector()->Get(big_vector_size - 1), 3); + + TEST_EQ_STR(root_table->near_string()->c_str(), "some near string"); + } +} + +void Offset64SerializedFirst() { + FlatBufferBuilder64 fbb; + + // First create the vectors that will be copied to the buffer. + std::vector data; + data.resize(64); + + // Then serialize all the fields that have 64-bit offsets, as these must be + // serialized before any 32-bit fields are added to the buffer. + fbb.CreateVector64(data); + + // TODO(derekbailey): figure out how to test assertions. + // Uncommenting this line should fail the test with an assertion. + // fbb.CreateString("some near string"); + + fbb.CreateVector64(data); +} + +void Offset64NestedFlatBuffer() { + FlatBufferBuilder64 fbb; + + // First serialize a nested buffer. + const Offset near_string_offset = + fbb.CreateString("nested: some near string"); + + // Finish by building the root table by passing in all the offsets. + const Offset root_table_offset = + CreateRootTable(fbb, 0, 0, 0, 0, near_string_offset, 0); + + // Finish the buffer. + fbb.Finish(root_table_offset); + + // Ensure the buffer is valid. + const RootTable *root_table = GetRootTable(fbb.GetBufferPointer()); + TEST_EQ_STR(root_table->near_string()->c_str(), "nested: some near string"); + + // Copy the data out of the builder. + std::vector nested_data{ fbb.GetBufferPointer(), + fbb.GetBufferPointer() + fbb.GetSize() }; + + { + // Clear so we can reuse the builder. + fbb.Clear(); + + const Offset64> nested_flatbuffer_offset = + fbb.CreateVector64(nested_data); + + // Now that we are done with the 64-bit fields, we can create and add the + // normal fields. + const Offset near_string_offset = + fbb.CreateString("some near string"); + + // Finish by building the root table by passing in all the offsets. + const Offset root_table_offset = CreateRootTable( + fbb, 0, 0, 0, 0, near_string_offset, nested_flatbuffer_offset); + + // Finish the buffer. + fbb.Finish(root_table_offset); + + Verifier::Options options; + // Allow the verifier to verify 64-bit buffers. + options.max_size = FLATBUFFERS_MAX_64_BUFFER_SIZE; + options.assert = true; + + Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize(), options); + + TEST_EQ(VerifyRootTableBuffer(verifier), true); + } + + { + const RootTable *root_table = GetRootTable(fbb.GetBufferPointer()); + + // Test that the parent buffer field is ok. + TEST_EQ_STR(root_table->near_string()->c_str(), "some near string"); + + // Expect nested buffer to be properly sized. + TEST_EQ(root_table->nested_root()->size(), nested_data.size()); + + // Expect the direct accessors to the nested buffer work. + TEST_EQ_STR(root_table->nested_root_nested_root()->near_string()->c_str(), + "nested: some near string"); + } +} + +void Offset64CreateDirect() { + FlatBufferBuilder64 fbb; + + // Create a vector of some data + std::vector data{ 0, 1, 2 }; + + // Call the "Direct" creation method to ensure that things are added to the + // buffer in the correct order, Offset64 first followed by any Offsets. + const Offset root_table_offset = CreateRootTableDirect( + fbb, &data, 0, "some far string", &data, "some near string"); + + // Finish the buffer. + fbb.Finish(root_table_offset); + + Verifier::Options options; + // Allow the verifier to verify 64-bit buffers. + options.max_size = FLATBUFFERS_MAX_64_BUFFER_SIZE; + options.assert = true; + + Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize(), options); + + TEST_EQ(VerifyRootTableBuffer(verifier), true); + + // Verify the data. + const RootTable *root_table = GetRootTable(fbb.GetBufferPointer()); + TEST_EQ(root_table->far_vector()->size(), data.size()); + TEST_EQ(root_table->big_vector()->size(), data.size()); + TEST_EQ_STR(root_table->far_string()->c_str(), "some far string"); + TEST_EQ_STR(root_table->near_string()->c_str(), "some near string"); +} + +void Offset64Evolution() { + // Some common data for the tests. + const std::vector data = { 1, 2, 3, 4 }; + const std::vector big_data = { 6, 7, 8, 9, 10 }; + + // Built V1 read V2 + { + // Use the 32-bit builder since V1 doesn't have any 64-bit offsets. + FlatBufferBuilder builder; + + builder.Finish(v1::CreateRootTableDirect(builder, 1234, &data)); + + // Use each version to get a view at the root table. + auto v1_root = v1::GetRootTable(builder.GetBufferPointer()); + auto v2_root = v2::GetRootTable(builder.GetBufferPointer()); + + // Test field equivalents for fields common to V1 and V2. + TEST_EQ(v1_root->a(), v2_root->a()); + + TEST_EQ(v1_root->b(), v2_root->b()); + TEST_EQ(v1_root->b()->Get(2), 3); + TEST_EQ(v2_root->b()->Get(2), 3); + + // This field is added in V2, so it should be null since V1 couldn't have + // written it. + TEST_ASSERT(v2_root->big_vector() == nullptr); + } + + // Built V2 read V1 + { + // Use the 64-bit builder since V2 has 64-bit offsets. + FlatBufferBuilder64 builder; + + builder.Finish(v2::CreateRootTableDirect(builder, 1234, &data, &big_data)); + + // Use each version to get a view at the root table. + auto v1_root = v1::GetRootTable(builder.GetBufferPointer()); + auto v2_root = v2::GetRootTable(builder.GetBufferPointer()); + + // Test field equivalents for fields common to V1 and V2. + TEST_EQ(v1_root->a(), v2_root->a()); + + TEST_EQ(v1_root->b(), v2_root->b()); + TEST_EQ(v1_root->b()->Get(2), 3); + TEST_EQ(v2_root->b()->Get(2), 3); + + // Test that V2 can read the big vector, which V1 doesn't even have + // accessors for (i.e. v1_root->big_vector() doesn't exist). + TEST_ASSERT(v2_root->big_vector() != nullptr); + TEST_EQ(v2_root->big_vector()->size(), big_data.size()); + TEST_EQ(v2_root->big_vector()->Get(2), 8); + } + + // Built V2 read V1, bigger than max 32-bit buffer sized. + // This checks that even a large buffer can still be read by V1. + { + // Use the 64-bit builder since V2 has 64-bit offsets. + FlatBufferBuilder64 builder; + + std::vector giant_data; + giant_data.resize(1LL << 3); + giant_data[2] = 42; + + builder.Finish( + v2::CreateRootTableDirect(builder, 1234, &data, &giant_data)); + + // Use each version to get a view at the root table. + auto v1_root = v1::GetRootTable(builder.GetBufferPointer()); + auto v2_root = v2::GetRootTable(builder.GetBufferPointer()); + + // Test field equivalents for fields common to V1 and V2. + TEST_EQ(v1_root->a(), v2_root->a()); + + TEST_EQ(v1_root->b(), v2_root->b()); + TEST_EQ(v1_root->b()->Get(2), 3); + TEST_EQ(v2_root->b()->Get(2), 3); + + // Test that V2 can read the big vector, which V1 doesn't even have + // accessors for (i.e. v1_root->big_vector() doesn't exist). + TEST_ASSERT(v2_root->big_vector() != nullptr); + TEST_EQ(v2_root->big_vector()->size(), giant_data.size()); + TEST_EQ(v2_root->big_vector()->Get(2), 42); + } +} + +void Offset64VectorOfStructs() { + FlatBufferBuilder64 builder; + + std::vector far_leaves; + far_leaves.emplace_back(LeafStruct{ 123, 4.567 }); + far_leaves.emplace_back(LeafStruct{ 987, 6.543 }); + + std::vector big_leaves; + big_leaves.emplace_back(LeafStruct{ 72, 72.8 }); + big_leaves.emplace_back(LeafStruct{ 82, 82.8 }); + big_leaves.emplace_back(LeafStruct{ 92, 92.8 }); + + // Add the two vectors of leaf structs. + const Offset root_table_offset = + CreateRootTableDirect(builder, nullptr, 0, nullptr, nullptr, nullptr, + nullptr, &far_leaves, &big_leaves); + + // Finish the buffer. + builder.Finish(root_table_offset); + + Verifier::Options options; + // Allow the verifier to verify 64-bit buffers. + options.max_size = FLATBUFFERS_MAX_64_BUFFER_SIZE; + options.assert = true; + + Verifier verifier(builder.GetBufferPointer(), builder.GetSize(), options); + + TEST_EQ(VerifyRootTableBuffer(verifier), true); + + // Verify the data. + const RootTable *root_table = GetRootTable(builder.GetBufferPointer()); + TEST_EQ(root_table->far_struct_vector()->size(), far_leaves.size()); + TEST_EQ(root_table->far_struct_vector()->Get(0)->a(), 123); + TEST_EQ(root_table->far_struct_vector()->Get(0)->b(), 4.567); + TEST_EQ(root_table->far_struct_vector()->Get(1)->a(), 987); + TEST_EQ(root_table->far_struct_vector()->Get(1)->b(), 6.543); + + TEST_EQ(root_table->big_struct_vector()->size(), big_leaves.size()); + TEST_EQ(root_table->big_struct_vector()->Get(0)->a(), 72); + TEST_EQ(root_table->big_struct_vector()->Get(0)->b(), 72.8); + TEST_EQ(root_table->big_struct_vector()->Get(1)->a(), 82); + TEST_EQ(root_table->big_struct_vector()->Get(1)->b(), 82.8); + TEST_EQ(root_table->big_struct_vector()->Get(2)->a(), 92); + TEST_EQ(root_table->big_struct_vector()->Get(2)->b(), 92.8); +} + +void Offset64SizePrefix() { + FlatBufferBuilder64 builder; + + // First serialize a nested buffer. + const Offset near_string_offset = + builder.CreateString("some near string"); + + // Finish by building the root table by passing in all the offsets. + const Offset root_table_offset = + CreateRootTable(builder, 0, 0, 0, 0, near_string_offset, 0); + + // Finish the buffer. + FinishSizePrefixedRootTableBuffer(builder, root_table_offset); + + TEST_EQ(GetPrefixedSize(builder.GetBufferPointer()), + builder.GetSize() - sizeof(uoffset64_t)); + + Verifier::Options options; + // Allow the verifier to verify 64-bit buffers. + options.max_size = FLATBUFFERS_MAX_64_BUFFER_SIZE; + options.assert = true; + + Verifier verifier(builder.GetBufferPointer(), builder.GetSize(), options); + + TEST_EQ(VerifySizePrefixedRootTableBuffer(verifier), true); + + const RootTable *root_table = + GetSizePrefixedRootTable(builder.GetBufferPointer()); + + // Verify the fields. + TEST_EQ_STR(root_table->near_string()->c_str(), "some near string"); +} + +void Offset64ManyVectors() { + FlatBufferBuilder64 builder; + + // Setup some data to serialize. + std::vector data; + data.resize(20); + data.front() = 42; + data.back() = 18; + + const size_t kNumVectors = 20; + + // First serialize all the 64-bit address vectors. We need to store all the + // offsets to later add to a wrapper table. We cannot serialize one vector and + // then add it to a table immediately, as it would violate the strict ordering + // of putting all 64-bit things at the tail of the buffer. + std::array>, kNumVectors> offsets_64bit; + for (size_t i = 0; i < kNumVectors; ++i) { + offsets_64bit[i] = builder.CreateVector64(data); + } + + // Create some unrelated, 64-bit offset value for later testing. + const Offset64 far_string_offset = + builder.CreateString("some far string"); + + // Now place all the offsets into their own wrapper tables. Again, we have to + // store the offsets before we can add them to the root table vector. + std::array, kNumVectors> offsets_wrapper; + for (size_t i = 0; i < kNumVectors; ++i) { + offsets_wrapper[i] = CreateWrapperTable(builder, offsets_64bit[i]); + } + + // Now create the 32-bit vector that is stored in the root table. + // TODO(derekbailey): the array type wasn't auto deduced, see if that could be + // fixed. + const Offset>> many_vectors_offset = + builder.CreateVector>(offsets_wrapper); + + // Finish by building using the root table builder, to exercise a different + // code path than the other tests. + RootTableBuilder root_table_builder(builder); + root_table_builder.add_many_vectors(many_vectors_offset); + root_table_builder.add_far_string(far_string_offset); + const Offset root_table_offset = root_table_builder.Finish(); + + // Finish the buffer. + FinishRootTableBuffer(builder, root_table_offset); + + Verifier::Options options; + // Allow the verifier to verify 64-bit buffers. + options.max_size = FLATBUFFERS_MAX_64_BUFFER_SIZE; + options.assert = true; + + Verifier verifier(builder.GetBufferPointer(), builder.GetSize(), options); + + TEST_EQ(VerifyRootTableBuffer(verifier), true); + + const RootTable *root_table = GetRootTable(builder.GetBufferPointer()); + + // Verify the fields. + TEST_EQ_STR(root_table->far_string()->c_str(), "some far string"); + TEST_EQ(root_table->many_vectors()->size(), kNumVectors); + + // Spot check one of the vectors. + TEST_EQ(root_table->many_vectors()->Get(12)->vector()->size(), 20); + TEST_EQ(root_table->many_vectors()->Get(12)->vector()->Get(0), 42); + TEST_EQ(root_table->many_vectors()->Get(12)->vector()->Get(19), 18); +} + +void Offset64ForceAlign() { + FlatBufferBuilder64 builder; + + // Setup some data to serialize that is less than the force_align size of 32 + // bytes. + std::vector data{ 1, 2, 3 }; + + // Use the CreateDirect which calls the ForceVectorAlign + const auto root_table_offset = + CreateRootTableDirect(builder, nullptr, 0, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, nullptr, &data); + + // Finish the buffer. + FinishRootTableBuffer(builder, root_table_offset); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/64bit/offset64_test.h b/third_party/flatbuffers/tests/64bit/offset64_test.h new file mode 100644 index 00000000000..b30985ffb48 --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/offset64_test.h @@ -0,0 +1,20 @@ +#ifndef TESTS_64BIT_OFFSET64_TEST_H +#define TESTS_64BIT_OFFSET64_TEST_H + +namespace flatbuffers { +namespace tests { + +void Offset64Test(); +void Offset64SerializedFirst(); +void Offset64NestedFlatBuffer(); +void Offset64CreateDirect(); +void Offset64Evolution(); +void Offset64VectorOfStructs(); +void Offset64SizePrefix(); +void Offset64ManyVectors(); +void Offset64ForceAlign(); + +} // namespace tests +} // namespace flatbuffers + +#endif // TESTS_64BIT_OFFSET64_TEST_H diff --git a/third_party/flatbuffers/tests/64bit/test_64bit.afb b/third_party/flatbuffers/tests/64bit/test_64bit.afb new file mode 100644 index 00000000000..f6cef00e1c4 --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/test_64bit.afb @@ -0,0 +1,74 @@ +// Annotated Flatbuffer Binary +// +// Schema file: tests/64bit/test_64bit.fbs +// Binary file: tests/64bit/test_64bit.bin + +header: + +0x00 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x1C | offset to root table `RootTable` + +padding: + +0x04 | 00 00 00 00 | uint8_t[4] | .... | padding + +vtable (RootTable): + +0x08 | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x0A | 34 00 | uint16_t | 0x0034 (52) | size of referring table + +0x0C | 04 00 | VOffset16 | 0x0004 (4) | offset to field `far_vector` (id: 0) + +0x0E | 10 00 | VOffset16 | 0x0010 (16) | offset to field `a` (id: 1) + +0x10 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `far_string` (id: 2) + +0x12 | 24 00 | VOffset16 | 0x0024 (36) | offset to field `big_vector` (id: 3) + +0x14 | 20 00 | VOffset16 | 0x0020 (32) | offset to field `near_string` (id: 4) + +0x16 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `nested_root` (id: 5) (Vector64) + +0x18 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `far_struct_vector` (id: 6) (Vector) + +0x1A | 2C 00 | VOffset16 | 0x002C (44) | offset to field `big_struct_vector` (id: 7) + +root_table (RootTable): + +0x1C | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x08 | offset to vtable + +0x20 | D0 00 00 00 00 00 00 00 | UOffset64 | 0x00000000000000D0 (208) Loc: 0xF0 | offset to field `far_vector` (vector) + +0x28 | 00 00 00 00 | uint8_t[4] | .... | padding + +0x2C | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `a` (Int) + +0x30 | 8C 00 00 00 00 00 00 00 | UOffset64 | 0x000000000000008C (140) Loc: 0xBC | offset to field `far_string` (string) + +0x38 | 00 00 00 00 | uint8_t[4] | .... | padding + +0x3C | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x7C | offset to field `near_string` (string) + +0x40 | 70 00 00 00 00 00 00 00 | UOffset64 | 0x0000000000000070 (112) Loc: 0xB0 | offset to field `big_vector` (vector64) + +0x48 | 08 00 00 00 00 00 00 00 | UOffset64 | 0x0000000000000008 (8) Loc: 0x50 | offset to field `big_struct_vector` (vector64) + +vector64 (RootTable.big_struct_vector): + +0x50 | 02 00 00 00 00 00 00 00 | uint64_t | 0x0000000000000002 (2) | length of vector (# items) + +0x58 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `[0].a` of 'LeafStruct' (Int) + <4 regions omitted> + +0x70 | 33 33 33 33 33 33 22 40 | double | 0x4022333333333333 (9.1) | struct field `[1].b` of 'LeafStruct' (Double) + +padding: + +0x78 | 00 00 00 00 | uint8_t[4] | .... | padding + +string (RootTable.near_string): + +0x7C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x80 | 74 68 69 73 20 69 73 20 | char[47] | this is | string literal + +0x88 | 61 20 6E 65 61 72 20 73 | | a near s + +0x90 | 74 72 69 6E 67 20 77 68 | | tring wh + +0x98 | 69 63 68 20 68 61 73 20 | | ich has + +0xA0 | 61 20 33 32 2D 62 69 74 | | a 32-bit + +0xA8 | 20 6F 66 66 73 65 74 | | offset + +0xAF | 00 | char | 0x00 (0) | string terminator + +vector64 (RootTable.big_vector): + +0xB0 | 04 00 00 00 00 00 00 00 | uint64_t | 0x0000000000000004 (4) | length of vector (# items) + +0xB8 | 05 | uint8_t | 0x05 (5) | value[0] + <2 regions omitted> + +0xBB | 08 | uint8_t | 0x08 (8) | value[3] + +string (RootTable.far_string): + +0xBC | 2E 00 00 00 | uint32_t | 0x0000002E (46) | length of string + +0xC0 | 74 68 69 73 20 69 73 20 | char[46] | this is | string literal + +0xC8 | 61 20 66 61 72 20 73 74 | | a far st + +0xD0 | 72 69 6E 67 20 77 68 69 | | ring whi + +0xD8 | 63 68 20 68 61 73 20 61 | | ch has a + +0xE0 | 20 36 34 2D 62 69 74 20 | | 64-bit + +0xE8 | 6F 66 66 73 65 74 | | offset + +0xEE | 00 | char | 0x00 (0) | string terminator + +vector (RootTable.far_vector): + +0xF0 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0xF4 | 01 | uint8_t | 0x01 (1) | value[0] + +0xF5 | 02 | uint8_t | 0x02 (2) | value[1] + +0xF6 | 03 | uint8_t | 0x03 (3) | value[2] diff --git a/third_party/flatbuffers/tests/64bit/test_64bit.bfbs b/third_party/flatbuffers/tests/64bit/test_64bit.bfbs new file mode 100644 index 00000000000..29360deb094 Binary files /dev/null and b/third_party/flatbuffers/tests/64bit/test_64bit.bfbs differ diff --git a/third_party/flatbuffers/tests/64bit/test_64bit.bin b/third_party/flatbuffers/tests/64bit/test_64bit.bin new file mode 100644 index 00000000000..a8d2d2e15a5 Binary files /dev/null and b/third_party/flatbuffers/tests/64bit/test_64bit.bin differ diff --git a/third_party/flatbuffers/tests/64bit/test_64bit.fbs b/third_party/flatbuffers/tests/64bit/test_64bit.fbs new file mode 100644 index 00000000000..19b4a81d2aa --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/test_64bit.fbs @@ -0,0 +1,53 @@ +struct LeafStruct { + a:int; + b:double; +} + +table WrapperTable { + // A normal 32-bit sized vector that could be very far away (64-bit address). + vector:[int8] (offset64); +} + +table RootTable { + // A normal 32-bit sized vector, that could be very far away (64-bit address). + far_vector:[ubyte] (offset64); + + // An inplace value just to check that vtable offsets are correct. + a:int; + + // A normal 32-bit sized string, that could be very far away (64-bit address). + far_string:string (offset64); + + // A big 64-bit sized vector, that could be very far away (64-bit address). + big_vector:[ubyte] (vector64); + + // A normal 32-bit sized string that is no far away (32-bit address). + near_string:string; + + // A big 64-bit sized vector that is a nested flatbuffers (64-bit address). + nested_root:[ubyte] (vector64, nested_flatbuffer: "RootTable"); + + // A normal 32-bit size vector of structs, that could be very far away + // (64-bit address) + far_struct_vector:[LeafStruct] (offset64); + + // A big 64-bit size vector of structs that could be very far away + // (64-bit address) + big_struct_vector:[LeafStruct] (vector64); + + // A normal 32-bit size vector of tables. Currently 64-bit vectors don't + // support tables as it would require serializing a table (32-bit) before the + // vector (64-bit), which is not allowed. + // + // This demonstrates how you could have many vectors in the buffer, by + // effectively having a vector of 64-bit vectors. The IDL doesn't support + // nested vecotrs (e.g.: [[type]] ), so going through a wrapper table allows + // this. + many_vectors:[WrapperTable]; + + // A vector that has force_align to test that the 32/64 bit region of the + // builder is respected. + forced_aligned_vector:[ubyte] (vector64, force_align:32); +} + +root_type RootTable; diff --git a/third_party/flatbuffers/tests/64bit/test_64bit.json b/third_party/flatbuffers/tests/64bit/test_64bit.json new file mode 100644 index 00000000000..4b24f4e773c --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/test_64bit.json @@ -0,0 +1,17 @@ +{ + "far_vector": [1, 2, 3], + "a": 1234, + "far_string": "this is a far string which has a 64-bit offset", + "big_vector": [5, 6, 7, 8], + "near_string": "this is a near string which has a 32-bit offset", + "big_struct_vector": [ + { + "a": 12, + "b": 3.456 + }, + { + "a": 78, + "b": 9.10 + } + ] +} diff --git a/third_party/flatbuffers/tests/64bit/test_64bit_bfbs_generated.h b/third_party/flatbuffers/tests/64bit/test_64bit_bfbs_generated.h new file mode 100644 index 00000000000..2f2815d3dfc --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/test_64bit_bfbs_generated.h @@ -0,0 +1,90 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_TEST64BIT_BFBS_H_ +#define FLATBUFFERS_GENERATED_TEST64BIT_BFBS_H_ + +#include +#include +struct RootTableBinarySchema { + static const uint8_t *data() { + // Buffer containing the binary schema. + static const uint8_t bfbsData[1248] = { + 0x1C,0x00,0x00,0x00,0x42,0x46,0x42,0x53,0x14,0x00,0x20,0x00,0x04,0x00,0x08,0x00,0x0C,0x00,0x10,0x00, + 0x14,0x00,0x18,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x2C,0x00,0x00,0x00, + 0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x54,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x2C,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0xA4,0x03,0x00,0x00,0x28,0x00,0x00,0x00,0x00,0x03,0x00,0x00, + 0x01,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x08,0x00,0x08,0x00,0x00,0x00, + 0xA0,0x03,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x38,0xFD,0xFF,0xFF,0x3C,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x84,0x03,0x00,0x00,0x0A,0x00,0x00,0x00,0x60,0x02,0x00,0x00, + 0xAC,0x00,0x00,0x00,0xC4,0x01,0x00,0x00,0x24,0x02,0x00,0x00,0xF0,0x00,0x00,0x00,0x70,0x02,0x00,0x00, + 0x20,0x00,0x00,0x00,0x5C,0x00,0x00,0x00,0x7C,0x01,0x00,0x00,0x28,0x01,0x00,0x00,0x09,0x00,0x00,0x00, + 0x52,0x6F,0x6F,0x74,0x54,0x61,0x62,0x6C,0x65,0x00,0x00,0x00,0x28,0xFE,0xFF,0xFF,0x00,0x00,0x01,0x01, + 0x09,0x00,0x16,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x6C,0xFE,0xFF,0xFF,0x00,0x00,0x12,0x04, + 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x15,0x00,0x00,0x00,0x66,0x6F,0x72,0x63,0x65,0x64,0x5F,0x61, + 0x6C,0x69,0x67,0x6E,0x65,0x64,0x5F,0x76,0x65,0x63,0x74,0x6F,0x72,0x00,0x00,0x00,0xF8,0xFE,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x08,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x78,0xFF,0xFF,0xFF, + 0x00,0x00,0x0E,0x0F,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x6D,0x61,0x6E,0x79, + 0x5F,0x76,0x65,0x63,0x74,0x6F,0x72,0x73,0x00,0x00,0x00,0x00,0xA0,0xFE,0xFF,0xFF,0x00,0x00,0x01,0x01, + 0x07,0x00,0x12,0x00,0x2C,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x06,0x00,0x07,0x00, + 0x08,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x12,0x0F,0x00,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x62,0x69,0x67,0x5F,0x73,0x74,0x72,0x75, + 0x63,0x74,0x5F,0x76,0x65,0x63,0x74,0x6F,0x72,0x00,0x00,0x00,0xF0,0xFE,0xFF,0xFF,0x00,0x00,0x01,0x01, + 0x06,0x00,0x10,0x00,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x10,0x00,0x06,0x00,0x07,0x00, + 0x08,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x0E,0x0F,0x00,0x00,0x00,0x00, + 0x10,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x66,0x61,0x72,0x5F,0x73,0x74,0x72,0x75,0x63,0x74,0x5F,0x76, + 0x65,0x63,0x74,0x6F,0x72,0x00,0x00,0x00,0x3C,0xFF,0xFF,0xFF,0x00,0x00,0x01,0x01,0x05,0x00,0x0E,0x00, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0xFF,0xFF,0xFF,0x00,0x00,0x12,0x04,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x6E,0x65,0x73,0x74,0x65,0x64,0x5F,0x72,0x6F,0x6F,0x74,0x00, + 0x1C,0x00,0x14,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x0C,0x00, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x90,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x0D,0x01,0x00,0x00,0x00, + 0x0B,0x00,0x00,0x00,0x6E,0x65,0x61,0x72,0x5F,0x73,0x74,0x72,0x69,0x6E,0x67,0x00,0xBC,0xFF,0xFF,0xFF, + 0x00,0x00,0x01,0x01,0x03,0x00,0x0A,0x00,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x10,0x00, + 0x06,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x12,0x04, + 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x62,0x69,0x67,0x5F,0x76,0x65,0x63,0x74, + 0x6F,0x72,0x00,0x00,0x20,0x00,0x14,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x07,0x00,0x20,0x00,0x00,0x00, + 0x00,0x00,0x01,0x01,0x02,0x00,0x08,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x24,0xFE,0xFF,0xFF, + 0x00,0x00,0x00,0x0D,0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x66,0x61,0x72,0x5F,0x73,0x74,0x72,0x69, + 0x6E,0x67,0x00,0x00,0xB0,0xFE,0xFF,0xFF,0x01,0x00,0x06,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x50,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00, + 0x90,0xFF,0xFF,0xFF,0x01,0x01,0x04,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x70,0xFF,0xFF,0xFF, + 0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x66,0x61,0x72,0x5F,0x76,0x65,0x63,0x74, + 0x6F,0x72,0x00,0x00,0x14,0x00,0x14,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x10,0x00,0x14,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0xA8,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x57,0x72,0x61,0x70, + 0x70,0x65,0x72,0x54,0x61,0x62,0x6C,0x65,0x00,0x00,0x00,0x00,0x20,0x00,0x10,0x00,0x08,0x00,0x0C,0x00, + 0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x04,0x00, + 0x00,0x00,0x05,0x00,0x20,0x00,0x00,0x00,0x01,0x01,0x04,0x00,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x10,0x00,0x0C,0x00,0x06,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00, + 0x00,0x00,0x0E,0x03,0x01,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x00,0x00, + 0x14,0x00,0x1C,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x18,0x00, + 0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x38,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x2F,0x2F,0x74,0x65,0x73,0x74,0x5F,0x36, + 0x34,0x62,0x69,0x74,0x2E,0x66,0x62,0x73,0x00,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x78,0x00,0x00,0x00, + 0x20,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x4C,0x65,0x61,0x66,0x53,0x74,0x72,0x75,0x63,0x74,0x00,0x00, + 0x0C,0x00,0x10,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x08,0x00, + 0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x10,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x08,0x00,0x0C,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x0C,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x62,0x00,0x1E,0x00,0x10,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x00,0x1E,0x00,0x00,0x00, + 0x00,0x00,0x04,0x00,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x0C,0x00,0x07,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00 + }; + return bfbsData; + } + static size_t size() { + return 1248; + } + const uint8_t *begin() { + return data(); + } + const uint8_t *end() { + return data() + size(); + } +}; + +#endif // FLATBUFFERS_GENERATED_TEST64BIT_BFBS_H_ diff --git a/third_party/flatbuffers/tests/64bit/test_64bit_generated.h b/third_party/flatbuffers/tests/64bit/test_64bit_generated.h new file mode 100644 index 00000000000..4233f843015 --- /dev/null +++ b/third_party/flatbuffers/tests/64bit/test_64bit_generated.h @@ -0,0 +1,653 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_TEST64BIT_H_ +#define FLATBUFFERS_GENERATED_TEST64BIT_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +// For access to the binary schema that produced this file. +#include "test_64bit_bfbs_generated.h" + +struct LeafStruct; + +struct WrapperTable; +struct WrapperTableBuilder; +struct WrapperTableT; + +struct RootTable; +struct RootTableBuilder; +struct RootTableT; + +bool operator==(const LeafStruct &lhs, const LeafStruct &rhs); +bool operator!=(const LeafStruct &lhs, const LeafStruct &rhs); +bool operator==(const WrapperTableT &lhs, const WrapperTableT &rhs); +bool operator!=(const WrapperTableT &lhs, const WrapperTableT &rhs); +bool operator==(const RootTableT &lhs, const RootTableT &rhs); +bool operator!=(const RootTableT &lhs, const RootTableT &rhs); + +inline const ::flatbuffers::TypeTable *LeafStructTypeTable(); + +inline const ::flatbuffers::TypeTable *WrapperTableTypeTable(); + +inline const ::flatbuffers::TypeTable *RootTableTypeTable(); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) LeafStruct FLATBUFFERS_FINAL_CLASS { + private: + int32_t a_; + int32_t padding0__; + double b_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return LeafStructTypeTable(); + } + LeafStruct() + : a_(0), + padding0__(0), + b_(0) { + (void)padding0__; + } + LeafStruct(int32_t _a, double _b) + : a_(::flatbuffers::EndianScalar(_a)), + padding0__(0), + b_(::flatbuffers::EndianScalar(_b)) { + (void)padding0__; + } + int32_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int32_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + double b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(double _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(LeafStruct, 16); + +inline bool operator==(const LeafStruct &lhs, const LeafStruct &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const LeafStruct &lhs, const LeafStruct &rhs) { + return !(lhs == rhs); +} + + +struct WrapperTableT : public ::flatbuffers::NativeTable { + typedef WrapperTable TableType; + std::vector vector{}; +}; + +struct WrapperTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef WrapperTableT NativeTableType; + typedef WrapperTableBuilder Builder; + typedef RootTableBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return WrapperTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_VECTOR = 4 + }; + const ::flatbuffers::Vector *vector() const { + return GetPointer64 *>(VT_VECTOR); + } + ::flatbuffers::Vector *mutable_vector() { + return GetPointer64<::flatbuffers::Vector *>(VT_VECTOR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset64(verifier, VT_VECTOR) && + verifier.VerifyVector(vector()) && + verifier.EndTable(); + } + WrapperTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(WrapperTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder64 &_fbb, const WrapperTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct WrapperTableBuilder { + typedef WrapperTable Table; + ::flatbuffers::FlatBufferBuilder64 &fbb_; + ::flatbuffers::uoffset_t start_; + void add_vector(::flatbuffers::Offset64<::flatbuffers::Vector> vector) { + fbb_.AddOffset(WrapperTable::VT_VECTOR, vector); + } + explicit WrapperTableBuilder(::flatbuffers::FlatBufferBuilder64 &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateWrapperTable( + ::flatbuffers::FlatBufferBuilder64 &_fbb, + ::flatbuffers::Offset64<::flatbuffers::Vector> vector = 0) { + WrapperTableBuilder builder_(_fbb); + builder_.add_vector(vector); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateWrapperTableDirect( + ::flatbuffers::FlatBufferBuilder64 &_fbb, + const std::vector *vector = nullptr) { + auto vector__ = vector ? _fbb.CreateVector64<::flatbuffers::Vector>(*vector) : 0; + return CreateWrapperTable( + _fbb, + vector__); +} + +::flatbuffers::Offset CreateWrapperTable(::flatbuffers::FlatBufferBuilder64 &_fbb, const WrapperTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct RootTableT : public ::flatbuffers::NativeTable { + typedef RootTable TableType; + std::vector far_vector{}; + int32_t a = 0; + std::string far_string{}; + std::vector big_vector{}; + std::string near_string{}; + std::vector nested_root{}; + std::vector far_struct_vector{}; + std::vector big_struct_vector{}; + std::vector> many_vectors{}; + std::vector forced_aligned_vector{}; + RootTableT() = default; + RootTableT(const RootTableT &o); + RootTableT(RootTableT&&) FLATBUFFERS_NOEXCEPT = default; + RootTableT &operator=(RootTableT o) FLATBUFFERS_NOEXCEPT; +}; + +struct RootTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RootTableT NativeTableType; + typedef RootTableBuilder Builder; + typedef RootTableBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RootTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_FAR_VECTOR = 4, + VT_A = 6, + VT_FAR_STRING = 8, + VT_BIG_VECTOR = 10, + VT_NEAR_STRING = 12, + VT_NESTED_ROOT = 14, + VT_FAR_STRUCT_VECTOR = 16, + VT_BIG_STRUCT_VECTOR = 18, + VT_MANY_VECTORS = 20, + VT_FORCED_ALIGNED_VECTOR = 22 + }; + const ::flatbuffers::Vector *far_vector() const { + return GetPointer64 *>(VT_FAR_VECTOR); + } + ::flatbuffers::Vector *mutable_far_vector() { + return GetPointer64<::flatbuffers::Vector *>(VT_FAR_VECTOR); + } + int32_t a() const { + return GetField(VT_A, 0); + } + bool mutate_a(int32_t _a = 0) { + return SetField(VT_A, _a, 0); + } + const ::flatbuffers::String *far_string() const { + return GetPointer64(VT_FAR_STRING); + } + ::flatbuffers::String *mutable_far_string() { + return GetPointer64<::flatbuffers::String *>(VT_FAR_STRING); + } + const ::flatbuffers::Vector64 *big_vector() const { + return GetPointer64 *>(VT_BIG_VECTOR); + } + ::flatbuffers::Vector64 *mutable_big_vector() { + return GetPointer64<::flatbuffers::Vector64 *>(VT_BIG_VECTOR); + } + const ::flatbuffers::String *near_string() const { + return GetPointer(VT_NEAR_STRING); + } + ::flatbuffers::String *mutable_near_string() { + return GetPointer<::flatbuffers::String *>(VT_NEAR_STRING); + } + const ::flatbuffers::Vector64 *nested_root() const { + return GetPointer64 *>(VT_NESTED_ROOT); + } + ::flatbuffers::Vector64 *mutable_nested_root() { + return GetPointer64<::flatbuffers::Vector64 *>(VT_NESTED_ROOT); + } + const RootTable *nested_root_nested_root() const { + const auto _f = nested_root(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const ::flatbuffers::Vector *far_struct_vector() const { + return GetPointer64 *>(VT_FAR_STRUCT_VECTOR); + } + ::flatbuffers::Vector *mutable_far_struct_vector() { + return GetPointer64<::flatbuffers::Vector *>(VT_FAR_STRUCT_VECTOR); + } + const ::flatbuffers::Vector64 *big_struct_vector() const { + return GetPointer64 *>(VT_BIG_STRUCT_VECTOR); + } + ::flatbuffers::Vector64 *mutable_big_struct_vector() { + return GetPointer64<::flatbuffers::Vector64 *>(VT_BIG_STRUCT_VECTOR); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *many_vectors() const { + return GetPointer> *>(VT_MANY_VECTORS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_many_vectors() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_MANY_VECTORS); + } + const ::flatbuffers::Vector64 *forced_aligned_vector() const { + return GetPointer64 *>(VT_FORCED_ALIGNED_VECTOR); + } + ::flatbuffers::Vector64 *mutable_forced_aligned_vector() { + return GetPointer64<::flatbuffers::Vector64 *>(VT_FORCED_ALIGNED_VECTOR); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset64(verifier, VT_FAR_VECTOR) && + verifier.VerifyVector(far_vector()) && + VerifyField(verifier, VT_A, 4) && + VerifyOffset64(verifier, VT_FAR_STRING) && + verifier.VerifyString(far_string()) && + VerifyOffset64(verifier, VT_BIG_VECTOR) && + verifier.VerifyVector(big_vector()) && + VerifyOffset(verifier, VT_NEAR_STRING) && + verifier.VerifyString(near_string()) && + VerifyOffset64(verifier, VT_NESTED_ROOT) && + verifier.VerifyVector(nested_root()) && + verifier.VerifyNestedFlatBuffer(nested_root(), nullptr) && + VerifyOffset64(verifier, VT_FAR_STRUCT_VECTOR) && + verifier.VerifyVector(far_struct_vector()) && + VerifyOffset64(verifier, VT_BIG_STRUCT_VECTOR) && + verifier.VerifyVector(big_struct_vector()) && + VerifyOffset(verifier, VT_MANY_VECTORS) && + verifier.VerifyVector(many_vectors()) && + verifier.VerifyVectorOfTables(many_vectors()) && + VerifyOffset64(verifier, VT_FORCED_ALIGNED_VECTOR) && + verifier.VerifyVector(forced_aligned_vector()) && + verifier.EndTable(); + } + RootTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(RootTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct RootTableBuilder { + typedef RootTable Table; + ::flatbuffers::FlatBufferBuilder64 &fbb_; + ::flatbuffers::uoffset_t start_; + void add_far_vector(::flatbuffers::Offset64<::flatbuffers::Vector> far_vector) { + fbb_.AddOffset(RootTable::VT_FAR_VECTOR, far_vector); + } + void add_a(int32_t a) { + fbb_.AddElement(RootTable::VT_A, a, 0); + } + void add_far_string(::flatbuffers::Offset64<::flatbuffers::String> far_string) { + fbb_.AddOffset(RootTable::VT_FAR_STRING, far_string); + } + void add_big_vector(::flatbuffers::Offset64<::flatbuffers::Vector64> big_vector) { + fbb_.AddOffset(RootTable::VT_BIG_VECTOR, big_vector); + } + void add_near_string(::flatbuffers::Offset<::flatbuffers::String> near_string) { + fbb_.AddOffset(RootTable::VT_NEAR_STRING, near_string); + } + void add_nested_root(::flatbuffers::Offset64<::flatbuffers::Vector64> nested_root) { + fbb_.AddOffset(RootTable::VT_NESTED_ROOT, nested_root); + } + void add_far_struct_vector(::flatbuffers::Offset64<::flatbuffers::Vector> far_struct_vector) { + fbb_.AddOffset(RootTable::VT_FAR_STRUCT_VECTOR, far_struct_vector); + } + void add_big_struct_vector(::flatbuffers::Offset64<::flatbuffers::Vector64> big_struct_vector) { + fbb_.AddOffset(RootTable::VT_BIG_STRUCT_VECTOR, big_struct_vector); + } + void add_many_vectors(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> many_vectors) { + fbb_.AddOffset(RootTable::VT_MANY_VECTORS, many_vectors); + } + void add_forced_aligned_vector(::flatbuffers::Offset64<::flatbuffers::Vector64> forced_aligned_vector) { + fbb_.AddOffset(RootTable::VT_FORCED_ALIGNED_VECTOR, forced_aligned_vector); + } + explicit RootTableBuilder(::flatbuffers::FlatBufferBuilder64 &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRootTable( + ::flatbuffers::FlatBufferBuilder64 &_fbb, + ::flatbuffers::Offset64<::flatbuffers::Vector> far_vector = 0, + int32_t a = 0, + ::flatbuffers::Offset64<::flatbuffers::String> far_string = 0, + ::flatbuffers::Offset64<::flatbuffers::Vector64> big_vector = 0, + ::flatbuffers::Offset<::flatbuffers::String> near_string = 0, + ::flatbuffers::Offset64<::flatbuffers::Vector64> nested_root = 0, + ::flatbuffers::Offset64<::flatbuffers::Vector> far_struct_vector = 0, + ::flatbuffers::Offset64<::flatbuffers::Vector64> big_struct_vector = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> many_vectors = 0, + ::flatbuffers::Offset64<::flatbuffers::Vector64> forced_aligned_vector = 0) { + RootTableBuilder builder_(_fbb); + builder_.add_forced_aligned_vector(forced_aligned_vector); + builder_.add_big_struct_vector(big_struct_vector); + builder_.add_nested_root(nested_root); + builder_.add_big_vector(big_vector); + builder_.add_many_vectors(many_vectors); + builder_.add_far_struct_vector(far_struct_vector); + builder_.add_near_string(near_string); + builder_.add_far_string(far_string); + builder_.add_a(a); + builder_.add_far_vector(far_vector); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateRootTableDirect( + ::flatbuffers::FlatBufferBuilder64 &_fbb, + const std::vector *far_vector = nullptr, + int32_t a = 0, + const char *far_string = nullptr, + const std::vector *big_vector = nullptr, + const char *near_string = nullptr, + const std::vector *nested_root = nullptr, + const std::vector *far_struct_vector = nullptr, + const std::vector *big_struct_vector = nullptr, + const std::vector<::flatbuffers::Offset> *many_vectors = nullptr, + const std::vector *forced_aligned_vector = nullptr) { + auto far_vector__ = far_vector ? _fbb.CreateVector64<::flatbuffers::Vector>(*far_vector) : 0; + auto far_string__ = far_string ? _fbb.CreateString<::flatbuffers::Offset64>(far_string) : 0; + auto big_vector__ = big_vector ? _fbb.CreateVector64(*big_vector) : 0; + auto nested_root__ = nested_root ? _fbb.CreateVector64(*nested_root) : 0; + auto far_struct_vector__ = far_struct_vector ? _fbb.CreateVectorOfStructs64<::flatbuffers::Vector>(*far_struct_vector) : 0; + auto big_struct_vector__ = big_struct_vector ? _fbb.CreateVectorOfStructs64(*big_struct_vector) : 0; + if (forced_aligned_vector) { _fbb.ForceVectorAlignment64(forced_aligned_vector->size(), sizeof(uint8_t), 32); } + auto forced_aligned_vector__ = forced_aligned_vector ? _fbb.CreateVector64(*forced_aligned_vector) : 0; + auto near_string__ = near_string ? _fbb.CreateString(near_string) : 0; + auto many_vectors__ = many_vectors ? _fbb.CreateVector<::flatbuffers::Offset>(*many_vectors) : 0; + return CreateRootTable( + _fbb, + far_vector__, + a, + far_string__, + big_vector__, + near_string__, + nested_root__, + far_struct_vector__, + big_struct_vector__, + many_vectors__, + forced_aligned_vector__); +} + +::flatbuffers::Offset CreateRootTable(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const WrapperTableT &lhs, const WrapperTableT &rhs) { + return + (lhs.vector == rhs.vector); +} + +inline bool operator!=(const WrapperTableT &lhs, const WrapperTableT &rhs) { + return !(lhs == rhs); +} + + +inline WrapperTableT *WrapperTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new WrapperTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void WrapperTable::UnPackTo(WrapperTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = vector(); if (_e) { _o->vector.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->vector.begin()); } } +} + +inline ::flatbuffers::Offset WrapperTable::Pack(::flatbuffers::FlatBufferBuilder64 &_fbb, const WrapperTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateWrapperTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateWrapperTable(::flatbuffers::FlatBufferBuilder64 &_fbb, const WrapperTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder64 *__fbb; const WrapperTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _vector = _o->vector.size() ? _fbb.CreateVector64<::flatbuffers::Vector>(_o->vector) : 0; + return CreateWrapperTable( + _fbb, + _vector); +} + + +inline bool operator==(const RootTableT &lhs, const RootTableT &rhs) { + return + (lhs.far_vector == rhs.far_vector) && + (lhs.a == rhs.a) && + (lhs.far_string == rhs.far_string) && + (lhs.big_vector == rhs.big_vector) && + (lhs.near_string == rhs.near_string) && + (lhs.nested_root == rhs.nested_root) && + (lhs.far_struct_vector == rhs.far_struct_vector) && + (lhs.big_struct_vector == rhs.big_struct_vector) && + (lhs.many_vectors.size() == rhs.many_vectors.size() && std::equal(lhs.many_vectors.cbegin(), lhs.many_vectors.cend(), rhs.many_vectors.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.forced_aligned_vector == rhs.forced_aligned_vector); +} + +inline bool operator!=(const RootTableT &lhs, const RootTableT &rhs) { + return !(lhs == rhs); +} + + +inline RootTableT::RootTableT(const RootTableT &o) + : far_vector(o.far_vector), + a(o.a), + far_string(o.far_string), + big_vector(o.big_vector), + near_string(o.near_string), + nested_root(o.nested_root), + far_struct_vector(o.far_struct_vector), + big_struct_vector(o.big_struct_vector), + forced_aligned_vector(o.forced_aligned_vector) { + many_vectors.reserve(o.many_vectors.size()); + for (const auto &many_vectors_ : o.many_vectors) { many_vectors.emplace_back((many_vectors_) ? new WrapperTableT(*many_vectors_) : nullptr); } +} + +inline RootTableT &RootTableT::operator=(RootTableT o) FLATBUFFERS_NOEXCEPT { + std::swap(far_vector, o.far_vector); + std::swap(a, o.a); + std::swap(far_string, o.far_string); + std::swap(big_vector, o.big_vector); + std::swap(near_string, o.near_string); + std::swap(nested_root, o.nested_root); + std::swap(far_struct_vector, o.far_struct_vector); + std::swap(big_struct_vector, o.big_struct_vector); + std::swap(many_vectors, o.many_vectors); + std::swap(forced_aligned_vector, o.forced_aligned_vector); + return *this; +} + +inline RootTableT *RootTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new RootTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void RootTable::UnPackTo(RootTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = far_vector(); if (_e) { _o->far_vector.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->far_vector.begin()); } } + { auto _e = a(); _o->a = _e; } + { auto _e = far_string(); if (_e) _o->far_string = _e->str(); } + { auto _e = big_vector(); if (_e) { _o->big_vector.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->big_vector.begin()); } } + { auto _e = near_string(); if (_e) _o->near_string = _e->str(); } + { auto _e = nested_root(); if (_e) { _o->nested_root.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->nested_root.begin()); } } + { auto _e = far_struct_vector(); if (_e) { _o->far_struct_vector.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->far_struct_vector[_i] = *_e->Get(_i); } } else { _o->far_struct_vector.resize(0); } } + { auto _e = big_struct_vector(); if (_e) { _o->big_struct_vector.resize(_e->size()); for (::flatbuffers::uoffset64_t _i = 0; _i < _e->size(); _i++) { _o->big_struct_vector[_i] = *_e->Get(_i); } } else { _o->big_struct_vector.resize(0); } } + { auto _e = many_vectors(); if (_e) { _o->many_vectors.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->many_vectors[_i]) { _e->Get(_i)->UnPackTo(_o->many_vectors[_i].get(), _resolver); } else { _o->many_vectors[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->many_vectors.resize(0); } } + { auto _e = forced_aligned_vector(); if (_e) { _o->forced_aligned_vector.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->forced_aligned_vector.begin()); } } +} + +inline ::flatbuffers::Offset RootTable::Pack(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateRootTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateRootTable(::flatbuffers::FlatBufferBuilder64 &_fbb, const RootTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder64 *__fbb; const RootTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _far_vector = _o->far_vector.size() ? _fbb.CreateVector64<::flatbuffers::Vector>(_o->far_vector) : 0; + auto _a = _o->a; + auto _far_string = _o->far_string.empty() ? 0 : _fbb.CreateString<::flatbuffers::Offset64>(_o->far_string); + auto _big_vector = _o->big_vector.size() ? _fbb.CreateVector64(_o->big_vector) : 0; + auto _near_string = _o->near_string.empty() ? 0 : _fbb.CreateString(_o->near_string); + auto _nested_root = _o->nested_root.size() ? _fbb.CreateVector64(_o->nested_root) : 0; + auto _far_struct_vector = _o->far_struct_vector.size() ? _fbb.CreateVectorOfStructs64<::flatbuffers::Vector>(_o->far_struct_vector) : 0; + auto _big_struct_vector = _o->big_struct_vector.size() ? _fbb.CreateVectorOfStructs64(_o->big_struct_vector) : 0; + auto _many_vectors = _o->many_vectors.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->many_vectors.size(), [](size_t i, _VectorArgs *__va) { return CreateWrapperTable(*__va->__fbb, __va->__o->many_vectors[i].get(), __va->__rehasher); }, &_va ) : 0; + _fbb.ForceVectorAlignment64(_o->forced_aligned_vector.size(), sizeof(uint8_t), 32); + auto _forced_aligned_vector = _o->forced_aligned_vector.size() ? _fbb.CreateVector64(_o->forced_aligned_vector) : 0; + return CreateRootTable( + _fbb, + _far_vector, + _a, + _far_string, + _big_vector, + _near_string, + _nested_root, + _far_struct_vector, + _big_struct_vector, + _many_vectors, + _forced_aligned_vector); +} + +inline const ::flatbuffers::TypeTable *LeafStructTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 } + }; + static const int64_t values[] = { 0, 8, 16 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *WrapperTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 1, -1 } + }; + static const char * const names[] = { + "vector" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RootTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + LeafStructTypeTable, + WrapperTableTypeTable + }; + static const char * const names[] = { + "far_vector", + "a", + "far_string", + "big_vector", + "near_string", + "nested_root", + "far_struct_vector", + "big_struct_vector", + "many_vectors", + "forced_aligned_vector" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 10, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const RootTable *GetRootTable(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const RootTable *GetSizePrefixedRootTable(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline RootTable *GetMutableRootTable(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline RootTable *GetMutableSizePrefixedRootTable(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline bool VerifyRootTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedRootTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishRootTableBuffer( + ::flatbuffers::FlatBufferBuilder64 &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedRootTableBuffer( + ::flatbuffers::FlatBufferBuilder64 &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +inline std::unique_ptr UnPackRootTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetRootTable(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedRootTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedRootTable(buf)->UnPack(res)); +} + +#endif // FLATBUFFERS_GENERATED_TEST64BIT_H_ diff --git a/third_party/flatbuffers/tests/Abc.nim b/third_party/flatbuffers/tests/Abc.nim new file mode 100644 index 00000000000..d6db38d0adc --- /dev/null +++ b/third_party/flatbuffers/tests/Abc.nim @@ -0,0 +1,13 @@ +#[ Abc + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : +]# + +type Abc*{.pure.} = enum + A = 0.int32, + B = 1.int32, + C = 2.int32, diff --git a/third_party/flatbuffers/tests/BUILD.bazel b/third_party/flatbuffers/tests/BUILD.bazel new file mode 100644 index 00000000000..ca673175802 --- /dev/null +++ b/third_party/flatbuffers/tests/BUILD.bazel @@ -0,0 +1,270 @@ +load("@aspect_bazel_lib//lib:copy_to_bin.bzl", "copy_to_bin") +load("@rules_cc//cc:defs.bzl", "cc_library", "cc_test") +load("//:build_defs.bzl", "DEFAULT_FLATC_ARGS", "flatbuffer_cc_library") + +package(default_visibility = ["//visibility:private"]) + +exports_files([ + "bazel_repository_test_template.sh", +]) + +# rules_js works around various JS tooling limitations by copying everything +# into the output directory. Make the test data available to the tests this way. +copy_to_bin( + name = "test_data_copied_to_bin", + srcs = glob([ + "*.mon", + "*.json", + ]), + visibility = ["//tests/ts:__subpackages__"], +) + +# Test binary. +cc_test( + name = "flatbuffers_test", + testonly = 1, + srcs = [ + "64bit/evolution/v1_generated.h", + "64bit/evolution/v2_generated.h", + "64bit/offset64_test.cpp", + "64bit/offset64_test.h", + "64bit/test_64bit_bfbs_generated.h", + "64bit/test_64bit_generated.h", + "alignment_test.cpp", + "alignment_test.h", + "alignment_test_generated.h", + "evolution_test.cpp", + "evolution_test.h", + "evolution_test/evolution_v1_generated.h", + "evolution_test/evolution_v2_generated.h", + "flexbuffers_test.cpp", + "flexbuffers_test.h", + "fuzz_test.cpp", + "fuzz_test.h", + "is_quiet_nan.h", + "json_test.cpp", + "json_test.h", + "key_field/key_field_sample_generated.h", + "key_field_test.cpp", + "key_field_test.h", + "monster_test.cpp", + "monster_test.h", + "monster_test_bfbs_generated.h", + "namespace_test/namespace_test1_generated.h", + "namespace_test/namespace_test2_generated.h", + "native_inline_table_test_generated.h", + "native_type_test_impl.cpp", + "native_type_test_impl.h", + "optional_scalars_generated.h", + "optional_scalars_test.cpp", + "optional_scalars_test.h", + "parser_test.cpp", + "parser_test.h", + "proto_test.cpp", + "proto_test.h", + "reflection_test.cpp", + "reflection_test.h", + "test.cpp", + "test_assert.cpp", + "test_assert.h", + "test_builder.cpp", + "test_builder.h", + "union_underlying_type_test_generated.h", + "union_vector/union_vector_generated.h", + "util_test.cpp", + "util_test.h", + ], + copts = [ + "-DFLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE", + ], + data = [ + ":alignment_test.fbs", + ":arrays_test.bfbs", + ":arrays_test.fbs", + ":arrays_test.golden", + ":evolution_test/evolution_v1.fbs", + ":evolution_test/evolution_v1.json", + ":evolution_test/evolution_v2.fbs", + ":evolution_test/evolution_v2.json", + ":include_test/include_test1.fbs", + ":include_test/sub/include_test2.fbs", + ":key_field/key_field_sample.fbs", + ":monster_extra.fbs", + ":monster_test.bfbs", + ":monster_test.fbs", + ":monsterdata_extra.json", + ":monsterdata_test.golden", + ":monsterdata_test.json", + ":name_clash_test/invalid_test1.fbs", + ":name_clash_test/invalid_test2.fbs", + ":name_clash_test/valid_test1.fbs", + ":name_clash_test/valid_test2.fbs", + ":native_type_test.fbs", + ":optional_scalars.fbs", + ":optional_scalars.json", + ":optional_scalars_defaults.json", + ":prototest/imported.proto", + ":prototest/non-positive-id.proto", + ":prototest/test.golden.fbs", + ":prototest/test.proto", + ":prototest/test_id.golden.fbs", + ":prototest/test_include.golden.fbs", + ":prototest/test_include_id.golden.fbs", + ":prototest/test_suffix.golden.fbs", + ":prototest/test_suffix_id.golden.fbs", + ":prototest/test_union.golden.fbs", + ":prototest/test_union_id.golden.fbs", + ":prototest/test_union_include.golden.fbs", + ":prototest/test_union_include_id.golden.fbs", + ":prototest/test_union_suffix.golden.fbs", + ":prototest/test_union_suffix_id.golden.fbs", + ":prototest/twice-id.proto", + ":prototest/use-reserved-id.proto", + ":unicode_test.json", + ":union_vector/union_vector.fbs", + ":union_vector/union_vector.json", + ], + includes = [ + "", + "include/", + ], + deps = [ + ":alignment_test_cc_fbs", + ":arrays_test_cc_fbs", + ":monster_extra_cc_fbs", + ":monster_test_cc_fbs", + ":native_type_test_cc_fbs", + "//:flatbuffers", + "//src:generate_fbs", + ], +) + +# Test bzl rules + +cc_library( + name = "test_assert", + srcs = ["test_assert.cpp"], + hdrs = ["test_assert.h"], + visibility = ["//grpc/tests:__subpackages__"], + deps = ["//:flatbuffers"], +) + +cc_library( + name = "test_builder", + srcs = ["test_builder.cpp"], + hdrs = ["test_builder.h"], + visibility = ["//grpc/tests:__subpackages__"], + deps = [ + ":monster_test_grpc", + ":test_assert", + "//:flatbuffers", + ], +) + +cc_library( + name = "monster_test_grpc", + srcs = [ + "monster_test.grpc.fb.cc", + "monster_test.grpc.fb.h", + "monster_test_generated.h", + ], + hdrs = [ + "monster_test.grpc.fb.h", + "monster_test_bfbs_generated.h", + "monster_test_generated.h", + ], + includes = ["."], + visibility = ["//grpc/tests:__subpackages__"], + deps = [ + "//:flatbuffers", + "@com_github_grpc_grpc//:grpc++", + ], +) + +flatbuffer_cc_library( + name = "include_test_fbs", + srcs = [ + "include_test/include_test1.fbs", + "include_test/sub/include_test2.fbs", + ], + include_paths = ["tests/include_test"], +) + +flatbuffer_cc_library( + name = "monster_test_cc_fbs", + srcs = ["monster_test.fbs"], + outs = ["monster_test_bfbs_generated.h"], + flatc_args = DEFAULT_FLATC_ARGS + [ + "--bfbs-comments", + "--bfbs-builtins", + "--bfbs-gen-embed", + "--bfbs-filenames tests", + ], + include_paths = ["tests/include_test"], + visibility = ["//grpc/tests:__subpackages__"], + deps = [":include_test_fbs"], +) + +# Test that running without --no-includes works properly (monster_test doesn't +# work cleanly due to the circular dependency in the include_tests/ files). +include_test_args = [ + "--gen-object-api", + "--gen-compare", + "--gen-mutable", + "--reflect-names", + "--cpp-ptr-type flatbuffers::unique_ptr", + "--force-empty", +] + +flatbuffer_cc_library( + name = "included_test_fbs", + srcs = ["included_test.fbs"], + flatc_args = include_test_args, +) + +flatbuffer_cc_library( + name = "includer_test_fbs", + srcs = ["includer_test.fbs"], + flatc_args = include_test_args, + deps = [":included_test_fbs"], +) + +cc_library( + name = "include_build_test", + srcs = ["include_build_test.cc"], + deps = [":includer_test_fbs"], +) + +flatbuffer_cc_library( + name = "monster_extra_cc_fbs", + srcs = ["monster_extra.fbs"], +) + +flatbuffer_cc_library( + name = "arrays_test_cc_fbs", + srcs = ["arrays_test.fbs"], + flatc_args = [ + "--gen-object-api", + "--gen-compare", + "--no-includes", + "--gen-mutable", + "--reflect-names", + "--cpp-ptr-type flatbuffers::unique_ptr", + "--scoped-enums", + ], +) + +flatbuffer_cc_library( + name = "native_type_test_cc_fbs", + srcs = ["native_type_test.fbs"], + flatc_args = [ + "--gen-object-api", + "--gen-mutable", + "--cpp-ptr-type flatbuffers::unique_ptr", + ], +) + +flatbuffer_cc_library( + name = "alignment_test_cc_fbs", + srcs = ["alignment_test.fbs"], +) diff --git a/third_party/flatbuffers/tests/DartTest.sh b/third_party/flatbuffers/tests/DartTest.sh new file mode 100755 index 00000000000..6907da823c2 --- /dev/null +++ b/third_party/flatbuffers/tests/DartTest.sh @@ -0,0 +1,41 @@ +#!/bin/sh +set -euo pipefail +# +# Copyright 2016 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +pushd "$(dirname $0)" >/dev/null + +command -v dart >/dev/null 2>&1 || { + echo >&2 "Dart tests require dart to be in path but it's not installed. Aborting." + exit 1 +} +# output required files to the dart folder so that pub will be able to +# distribute them and more people can more easily run the dart tests +../flatc --dart --gen-object-api -I include_test -o ../dart/test monster_test.fbs +../flatc --dart --gen-object-api -I include_test/sub -o ../dart/test include_test/include_test1.fbs +../flatc --dart --gen-object-api -I include_test -o ../dart/test include_test/sub/include_test2.fbs + +cp monsterdata_test.mon ../dart/test +cp monster_test.fbs ../dart/test + +cd ../dart + +../flatc --dart --gen-object-api -o ./test ./test/enums.fbs +../flatc --dart --gen-object-api -o ./test ./test/bool_structs.fbs + +# update packages +dart pub get +# Execute the sample. +dart test diff --git a/third_party/flatbuffers/tests/DictionaryLookup/LongFloatEntry.java b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatEntry.java new file mode 100644 index 00000000000..f12bdb9a088 --- /dev/null +++ b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatEntry.java @@ -0,0 +1,87 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package DictionaryLookup; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class LongFloatEntry extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static LongFloatEntry getRootAsLongFloatEntry(ByteBuffer _bb) { return getRootAsLongFloatEntry(_bb, new LongFloatEntry()); } + public static LongFloatEntry getRootAsLongFloatEntry(ByteBuffer _bb, LongFloatEntry obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public LongFloatEntry __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public long key() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public float value() { int o = __offset(6); return o != 0 ? bb.getFloat(o + bb_pos) : 0.0f; } + + public static int createLongFloatEntry(FlatBufferBuilder builder, + long key, + float value) { + builder.startTable(2); + LongFloatEntry.addKey(builder, key); + LongFloatEntry.addValue(builder, value); + return LongFloatEntry.endLongFloatEntry(builder); + } + + public static void startLongFloatEntry(FlatBufferBuilder builder) { builder.startTable(2); } + public static void addKey(FlatBufferBuilder builder, long key) { builder.addLong(key); builder.slot(0); } + public static void addValue(FlatBufferBuilder builder, float value) { builder.addFloat(1, value, 0.0f); } + public static int endLongFloatEntry(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { + long val_1 = _bb.getLong(__offset(4, o1, _bb)); + long val_2 = _bb.getLong(__offset(4, o2, _bb)); + return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0; + } + + public static LongFloatEntry __lookup_by_key(LongFloatEntry obj, int vectorLocation, long key, ByteBuffer bb) { + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + long val = bb.getLong(__offset(4, bb.capacity() - tableOffset, bb)); + int comp = val > key ? 1 : val < key ? -1 : 0; + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new LongFloatEntry() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public LongFloatEntry get(int j) { return get(new LongFloatEntry(), j); } + public LongFloatEntry get(LongFloatEntry obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public LongFloatEntry getByKey(long key) { return __lookup_by_key(null, __vector(), key, bb); } + public LongFloatEntry getByKey(LongFloatEntry obj, long key) { return __lookup_by_key(obj, __vector(), key, bb); } + } +} + diff --git a/third_party/flatbuffers/tests/DictionaryLookup/LongFloatEntry.kt b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatEntry.kt new file mode 100644 index 00000000000..7869ec7654b --- /dev/null +++ b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatEntry.kt @@ -0,0 +1,92 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package DictionaryLookup + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class LongFloatEntry : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : LongFloatEntry { + __init(_i, _bb) + return this + } + val key : Long + get() { + val o = __offset(4) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + val value : Float + get() { + val o = __offset(6) + return if(o != 0) bb.getFloat(o + bb_pos) else 0.0f + } + override fun keysCompare(o1: Int, o2: Int, _bb: ByteBuffer) : Int { + val val_1 = _bb.getLong(__offset(4, o1, _bb)) + val val_2 = _bb.getLong(__offset(4, o2, _bb)) + return (val_1 - val_2).sign + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsLongFloatEntry(_bb: ByteBuffer): LongFloatEntry = getRootAsLongFloatEntry(_bb, LongFloatEntry()) + fun getRootAsLongFloatEntry(_bb: ByteBuffer, obj: LongFloatEntry): LongFloatEntry { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createLongFloatEntry(builder: FlatBufferBuilder, key: Long, value: Float) : Int { + builder.startTable(2) + addKey(builder, key) + addValue(builder, value) + return endLongFloatEntry(builder) + } + fun startLongFloatEntry(builder: FlatBufferBuilder) = builder.startTable(2) + fun addKey(builder: FlatBufferBuilder, key: Long) { + builder.addLong(key) + builder.slot(0) + } + fun addValue(builder: FlatBufferBuilder, value: Float) = builder.addFloat(1, value, 0.0) + fun endLongFloatEntry(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun __lookup_by_key(obj: LongFloatEntry?, vectorLocation: Int, key: Long, bb: ByteBuffer) : LongFloatEntry? { + var span = bb.getInt(vectorLocation - 4) + var start = 0 + while (span != 0) { + var middle = span / 2 + val tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb) + val value = bb.getLong(__offset(4, bb.capacity() - tableOffset, bb)) + val comp = value.compareTo(key) + when { + comp > 0 -> span = middle + comp < 0 -> { + middle++ + start += middle + span -= middle + } + else -> { + return (obj ?: LongFloatEntry()).__assign(tableOffset, bb) + } + } + } + return null + } + } +} diff --git a/third_party/flatbuffers/tests/DictionaryLookup/LongFloatMap.java b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatMap.java new file mode 100644 index 00000000000..646bb3cfec3 --- /dev/null +++ b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatMap.java @@ -0,0 +1,63 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package DictionaryLookup; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class LongFloatMap extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static LongFloatMap getRootAsLongFloatMap(ByteBuffer _bb) { return getRootAsLongFloatMap(_bb, new LongFloatMap()); } + public static LongFloatMap getRootAsLongFloatMap(ByteBuffer _bb, LongFloatMap obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public LongFloatMap __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public DictionaryLookup.LongFloatEntry entries(int j) { return entries(new DictionaryLookup.LongFloatEntry(), j); } + public DictionaryLookup.LongFloatEntry entries(DictionaryLookup.LongFloatEntry obj, int j) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int entriesLength() { int o = __offset(4); return o != 0 ? __vector_len(o) : 0; } + public DictionaryLookup.LongFloatEntry entriesByKey(long key) { int o = __offset(4); return o != 0 ? DictionaryLookup.LongFloatEntry.__lookup_by_key(null, __vector(o), key, bb) : null; } + public DictionaryLookup.LongFloatEntry entriesByKey(DictionaryLookup.LongFloatEntry obj, long key) { int o = __offset(4); return o != 0 ? DictionaryLookup.LongFloatEntry.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public DictionaryLookup.LongFloatEntry.Vector entriesVector() { return entriesVector(new DictionaryLookup.LongFloatEntry.Vector()); } + public DictionaryLookup.LongFloatEntry.Vector entriesVector(DictionaryLookup.LongFloatEntry.Vector obj) { int o = __offset(4); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createLongFloatMap(FlatBufferBuilder builder, + int entriesOffset) { + builder.startTable(1); + LongFloatMap.addEntries(builder, entriesOffset); + return LongFloatMap.endLongFloatMap(builder); + } + + public static void startLongFloatMap(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addEntries(FlatBufferBuilder builder, int entriesOffset) { builder.addOffset(0, entriesOffset, 0); } + public static int createEntriesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startEntriesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endLongFloatMap(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + public static void finishLongFloatMapBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset); } + public static void finishSizePrefixedLongFloatMapBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public LongFloatMap get(int j) { return get(new LongFloatMap(), j); } + public LongFloatMap get(LongFloatMap obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } +} + diff --git a/third_party/flatbuffers/tests/DictionaryLookup/LongFloatMap.kt b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatMap.kt new file mode 100644 index 00000000000..fb4f1654e7c --- /dev/null +++ b/third_party/flatbuffers/tests/DictionaryLookup/LongFloatMap.kt @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package DictionaryLookup + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class LongFloatMap : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : LongFloatMap { + __init(_i, _bb) + return this + } + fun entries(j: Int) : DictionaryLookup.LongFloatEntry? = entries(DictionaryLookup.LongFloatEntry(), j) + fun entries(obj: DictionaryLookup.LongFloatEntry, j: Int) : DictionaryLookup.LongFloatEntry? { + val o = __offset(4) + return if (o != 0) { + obj.__assign(__indirect(__vector(o) + j * 4), bb) + } else { + null + } + } + val entriesLength : Int + get() { + val o = __offset(4); return if (o != 0) __vector_len(o) else 0 + } + fun entriesByKey(key: Long) : DictionaryLookup.LongFloatEntry? { + val o = __offset(4) + return if (o != 0) { + DictionaryLookup.LongFloatEntry.__lookup_by_key(null, __vector(o), key, bb) + } else { + null + } + } + fun entriesByKey(obj: DictionaryLookup.LongFloatEntry, key: Long) : DictionaryLookup.LongFloatEntry? { + val o = __offset(4) + return if (o != 0) { + DictionaryLookup.LongFloatEntry.__lookup_by_key(obj, __vector(o), key, bb) + } else { + null + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsLongFloatMap(_bb: ByteBuffer): LongFloatMap = getRootAsLongFloatMap(_bb, LongFloatMap()) + fun getRootAsLongFloatMap(_bb: ByteBuffer, obj: LongFloatMap): LongFloatMap { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createLongFloatMap(builder: FlatBufferBuilder, entriesOffset: Int) : Int { + builder.startTable(1) + addEntries(builder, entriesOffset) + return endLongFloatMap(builder) + } + fun startLongFloatMap(builder: FlatBufferBuilder) = builder.startTable(1) + fun addEntries(builder: FlatBufferBuilder, entries: Int) = builder.addOffset(0, entries, 0) + fun createEntriesVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startEntriesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun endLongFloatMap(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun finishLongFloatMapBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset) + fun finishSizePrefixedLongFloatMapBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset) + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/FlatBufferBuilderBenchmark.cs b/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/FlatBufferBuilderBenchmark.cs new file mode 100644 index 00000000000..b3858858e6c --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/FlatBufferBuilderBenchmark.cs @@ -0,0 +1,101 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using BenchmarkDotNet.Attributes; +using MyGame.Example; + +namespace Google.FlatBuffers.Benchmarks +{ + //[EtwProfiler] - needs elevated privileges + [MemoryDiagnoser] + public class FlatBufferBuilderBenchmark + { + private const int NumberOfRows = 10_000; + + [Benchmark] + public void BuildNestedMonster() + { + const string nestedMonsterName = "NestedMonsterName"; + const short nestedMonsterHp = 600; + const short nestedMonsterMana = 1024; + + for (int i = 0; i < NumberOfRows; i++) + { + // Create nested buffer as a Monster type + var fbb1 = new FlatBufferBuilder(16); + var str1 = fbb1.CreateString(nestedMonsterName); + Monster.StartMonster(fbb1); + Monster.AddName(fbb1, str1); + Monster.AddHp(fbb1, nestedMonsterHp); + Monster.AddMana(fbb1, nestedMonsterMana); + var monster1 = Monster.EndMonster(fbb1); + Monster.FinishMonsterBuffer(fbb1, monster1); + var fbb1Bytes = fbb1.SizedByteArray(); + fbb1 = null; + + // Create a Monster which has the first buffer as a nested buffer + var fbb2 = new FlatBufferBuilder(16); + var str2 = fbb2.CreateString("My Monster"); + var nestedBuffer = Monster.CreateTestnestedflatbufferVector(fbb2, fbb1Bytes); + Monster.StartMonster(fbb2); + Monster.AddName(fbb2, str2); + Monster.AddHp(fbb2, 50); + Monster.AddMana(fbb2, 32); + Monster.AddTestnestedflatbuffer(fbb2, nestedBuffer); + var monster = Monster.EndMonster(fbb2); + Monster.FinishMonsterBuffer(fbb2, monster); + } + } + + [Benchmark] + public void BuildMonster() + { + for (int i = 0; i < NumberOfRows; i++) + { + var builder = new FlatBufferBuilder(16); + var str1 = builder.CreateString("MonsterName"); + Monster.StartMonster(builder); + Monster.AddName(builder, str1); + Monster.AddHp(builder, 600); + Monster.AddMana(builder, 1024); + Monster.AddColor(builder, Color.Blue); + Monster.AddTestbool(builder, true); + Monster.AddTestf(builder, 0.3f); + Monster.AddTestf2(builder, 0.2f); + Monster.AddTestf3(builder, 0.1f); + + var monster1 = Monster.EndMonster(builder); + Monster.FinishMonsterBuffer(builder, monster1); + } + } + + [Benchmark] + public void TestTables() + { + FlatBufferBuilder builder = new FlatBufferBuilder(1024 * 1024 * 32); + for (int x = 0; x < 500000; ++x) + { + var offset = builder.CreateString("T"); + builder.StartObject(4); + builder.AddDouble(3.2); + builder.AddDouble(4.2); + builder.AddDouble(5.2); + builder.AddOffset(offset.Value); + builder.EndObject(); + } + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/FlatBuffers.Benchmarks.csproj b/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/FlatBuffers.Benchmarks.csproj new file mode 100644 index 00000000000..b900384bac1 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/FlatBuffers.Benchmarks.csproj @@ -0,0 +1,21 @@ + + + + Exe + netcoreapp2.1 + latest + true + $(DefineConstants);UNSAFE_BYTEBUFFER;BYTEBUFFER_NO_BOUNDS_CHECK;ENABLE_SPAN_T + + + + + + + + + + + + + diff --git a/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/Program.cs b/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/Program.cs new file mode 100644 index 00000000000..fa152caa98c --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Benchmarks/Program.cs @@ -0,0 +1,30 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using BenchmarkDotNet.Running; + +namespace Google.FlatBuffers.Benchmarks +{ + public static class Program + { + public static void Main(string[] args) + { + BenchmarkSwitcher + .FromAssembly(typeof(Program).Assembly) + .Run(args); + } + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/.gitignore b/third_party/flatbuffers/tests/FlatBuffers.Test/.gitignore new file mode 100644 index 00000000000..badc82747ea --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/.gitignore @@ -0,0 +1,4 @@ +dotnet-install.sh +.dotnet_tmp/ +.tmp/ +packages/ \ No newline at end of file diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/Assert.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/Assert.cs new file mode 100644 index 00000000000..b0ecb59dc1d --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/Assert.cs @@ -0,0 +1,156 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Google.FlatBuffers.Test +{ + + public class AssertFailedException : Exception + { + private readonly object _expected; + private readonly object _actual; + + public AssertFailedException(object expected, object actual) + { + _expected = expected; + _actual = actual; + } + + public override string Message + { + get { return string.Format("Expected {0} but saw {1}", _expected, _actual); } + } + } + + public class AssertArrayFailedException : Exception + { + private readonly int _index; + private readonly object _expected; + private readonly object _actual; + + public AssertArrayFailedException(int index, object expected, object actual) + { + _index = index; + _expected = expected; + _actual = actual; + } + + public override string Message + { + get { return string.Format("Expected {0} at index {1} but saw {2}", _expected, _index, _actual); } + } + } + + public class AssertUnexpectedThrowException : Exception + { + private readonly object _expected; + + public AssertUnexpectedThrowException(object expected) + { + _expected = expected; + } + + public override string Message + { + get { return string.Format("Expected exception of type {0}", _expected); } + } + } + + public static class Assert + { + public static void AreEqual(T expected, T actual) + { + if (!expected.Equals(actual)) + { + throw new AssertFailedException(expected, actual); + } + } + + public static void ArrayEqual(T[] expected, T[] actual) + { + if (expected.Length != actual.Length) + { + throw new AssertFailedException(expected, actual); + } + + for(var i = 0; i < expected.Length; ++i) + { + if (!expected[i].Equals(actual[i])) + { + throw new AssertArrayFailedException(i, expected, actual); + } + } + } + + public static void ArrayEqual(ArraySegment expected, T[] actual) + { +#if NETCOREAPP + ArrayEqual(expected.ToArray(), actual); +#else + if (expected.Count != actual.Length) + { + throw new AssertFailedException(expected, actual); + } + + for (var i = 0; i < expected.Count; ++i) + { + if (!expected.Array[expected.Offset + i].Equals(actual[i])) + { + throw new AssertArrayFailedException(i, expected, actual); + } + } +#endif + } + + public static void IsTrue(bool value) + { + if (!value) + { + throw new AssertFailedException(true, value); + } + } + + public static void IsFalse(bool value) + { + if (value) + { + throw new AssertFailedException(false, value); + } + } + + public static void Throws(Action action) where T : Exception + { + var caught = false; + try + { + action(); + } + catch (T) + { + caught = true; + } + + if (!caught) + { + throw new AssertUnexpectedThrowException(typeof (T)); + } + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/ByteBufferTests.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/ByteBufferTests.cs new file mode 100644 index 00000000000..f01c7cad7fb --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/ByteBufferTests.cs @@ -0,0 +1,742 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Runtime.InteropServices; + +namespace Google.FlatBuffers.Test +{ + [FlatBuffersTestClass] + public class ByteBufferTests + { + + [FlatBuffersTestMethod] + public void ByteBuffer_Length_MatchesBufferLength() + { + var buffer = new byte[1000]; + var uut = new ByteBuffer(buffer); + Assert.AreEqual(buffer.Length, uut.Length); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_PutBytePopulatesBufferAtZeroOffset() + { + var buffer = new byte[1]; + var uut = new ByteBuffer(buffer); + uut.PutByte(0, (byte)99); + + Assert.AreEqual((byte)99, buffer[0]); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_PutByteCannotPutAtOffsetPastLength() + { + var uut = new ByteBuffer(1); + Assert.Throws(() => uut.PutByte(1, 99)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_PutShortPopulatesBufferCorrectly() + { + var buffer = new byte[2]; + var uut = new ByteBuffer(buffer); + uut.PutShort(0, (short)1); + + // Ensure Endianness was written correctly + Assert.AreEqual((byte)1, buffer[0]); + Assert.AreEqual((byte)0, buffer[1]); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_PutShortCannotPutAtOffsetPastLength() + { + var uut = new ByteBuffer(2); + Assert.Throws(() => uut.PutShort(2, 99)); + } +#endif + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_PutShortChecksLength() + { + var uut = new ByteBuffer(1); + Assert.Throws(() => uut.PutShort(0, 99)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_PutShortChecksLengthAndOffset() + { + var uut = new ByteBuffer(2); + Assert.Throws(() => uut.PutShort(1, 99)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_PutIntPopulatesBufferCorrectly() + { + var buffer = new byte[4]; + var uut = new ByteBuffer(buffer); + uut.PutInt(0, 0x0A0B0C0D); + + // Ensure Endianness was written correctly + Assert.AreEqual(0x0D, buffer[0]); + Assert.AreEqual(0x0C, buffer[1]); + Assert.AreEqual(0x0B, buffer[2]); + Assert.AreEqual(0x0A, buffer[3]); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_PutIntCannotPutAtOffsetPastLength() + { + var uut = new ByteBuffer(4); + Assert.Throws(() => uut.PutInt(2, 0x0A0B0C0D)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_PutIntChecksLength() + { + var uut = new ByteBuffer(1); + Assert.Throws(() => uut.PutInt(0, 0x0A0B0C0D)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_PutIntChecksLengthAndOffset() + { + var uut = new ByteBuffer(4); + Assert.Throws(() => uut.PutInt(2, 0x0A0B0C0D)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_PutLongPopulatesBufferCorrectly() + { + var buffer = new byte[8]; + var uut = new ByteBuffer(buffer); + uut.PutLong(0, 0x010203040A0B0C0D); + + // Ensure Endianness was written correctly + Assert.AreEqual(0x0D, buffer[0]); + Assert.AreEqual(0x0C, buffer[1]); + Assert.AreEqual(0x0B, buffer[2]); + Assert.AreEqual(0x0A, buffer[3]); + Assert.AreEqual(0x04, buffer[4]); + Assert.AreEqual(0x03, buffer[5]); + Assert.AreEqual(0x02, buffer[6]); + Assert.AreEqual(0x01, buffer[7]); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_PutLongCannotPutAtOffsetPastLength() + { + var uut = new ByteBuffer(8); + Assert.Throws(() => uut.PutLong(2, 0x010203040A0B0C0D)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_PutLongChecksLength() + { + var uut = new ByteBuffer(1); + Assert.Throws(() => uut.PutLong(0, 0x010203040A0B0C0D)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_PutLongChecksLengthAndOffset() + { + var uut = new ByteBuffer(8); + Assert.Throws(() => uut.PutLong(2, 0x010203040A0B0C0D)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_GetByteReturnsCorrectData() + { + var buffer = new byte[1]; + buffer[0] = 99; + var uut = new ByteBuffer(buffer); + Assert.AreEqual((byte)99, uut.Get(0)); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_GetByteChecksOffset() + { + var uut = new ByteBuffer(1); + Assert.Throws(() => uut.Get(1)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_GetShortReturnsCorrectData() + { + var buffer = new byte[2]; + buffer[0] = 1; + buffer[1] = 0; + var uut = new ByteBuffer(buffer); + Assert.AreEqual(1, uut.GetShort(0)); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_GetShortChecksOffset() + { + var uut = new ByteBuffer(2); + Assert.Throws(() => uut.GetShort(2)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_GetShortChecksLength() + { + var uut = new ByteBuffer(2); + Assert.Throws(() => uut.GetShort(1)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_GetIntReturnsCorrectData() + { + var buffer = new byte[4]; + buffer[0] = 0x0D; + buffer[1] = 0x0C; + buffer[2] = 0x0B; + buffer[3] = 0x0A; + var uut = new ByteBuffer(buffer); + Assert.AreEqual(0x0A0B0C0D, uut.GetInt(0)); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_GetIntChecksOffset() + { + var uut = new ByteBuffer(4); + Assert.Throws(() => uut.GetInt(4)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_GetIntChecksLength() + { + var uut = new ByteBuffer(2); + Assert.Throws(() => uut.GetInt(0)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_GetLongReturnsCorrectData() + { + var buffer = new byte[8]; + buffer[0] = 0x0D; + buffer[1] = 0x0C; + buffer[2] = 0x0B; + buffer[3] = 0x0A; + buffer[4] = 0x04; + buffer[5] = 0x03; + buffer[6] = 0x02; + buffer[7] = 0x01; + var uut = new ByteBuffer(buffer); + Assert.AreEqual(0x010203040A0B0C0D, uut.GetLong(0)); + } + +#if !BYTEBUFFER_NO_BOUNDS_CHECK + [FlatBuffersTestMethod] + public void ByteBuffer_GetLongChecksOffset() + { + var uut = new ByteBuffer(8); + Assert.Throws(() => uut.GetLong(8)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_GetLongChecksLength() + { + var uut = new ByteBuffer(7); + Assert.Throws(() => uut.GetLong(0)); + } +#endif + + [FlatBuffersTestMethod] + public void ByteBuffer_ReverseBytesUshort() + { + const ushort original = (ushort)0x1234U; + var reverse = ByteBuffer.ReverseBytes(original); + Assert.AreEqual(0x3412U, reverse); + + var rereverse = ByteBuffer.ReverseBytes(reverse); + Assert.AreEqual(original, rereverse); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_ReverseBytesUint() + { + const uint original = 0x12345678; + var reverse = ByteBuffer.ReverseBytes(original); + Assert.AreEqual(0x78563412U, reverse); + + var rereverse = ByteBuffer.ReverseBytes(reverse); + Assert.AreEqual(original, rereverse); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_ReverseBytesUlong() + { + const ulong original = 0x1234567890ABCDEFUL; + var reverse = ByteBuffer.ReverseBytes(original); + Assert.AreEqual(0xEFCDAB9078563412UL, reverse); + + var rereverse = ByteBuffer.ReverseBytes(reverse); + Assert.AreEqual(original, rereverse); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_ToFullArray_MatchesBuffer() + { + var buffer = new byte[4]; + buffer[0] = 0x0D; + buffer[1] = 0x0C; + buffer[2] = 0x0B; + buffer[3] = 0x0A; + var uut = new ByteBuffer(buffer); + Assert.ArrayEqual(buffer, uut.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_ToSizedArray_MatchesBuffer() + { + var buffer = new byte[4]; + buffer[0] = 0x0D; + buffer[1] = 0x0C; + buffer[2] = 0x0B; + buffer[3] = 0x0A; + var uut = new ByteBuffer(buffer); + Assert.ArrayEqual(buffer, uut.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Duplicate_MatchesBuffer() + { + var buffer = new byte[4]; + buffer[0] = 0x0D; + buffer[1] = 0x0C; + buffer[2] = 0x0B; + buffer[3] = 0x0A; + var uut = new ByteBuffer(buffer); + Assert.AreEqual(0x0A0B0C0D, uut.GetInt(0)); + + // Advance by two bytes + uut.Position = 2; uut = uut.Duplicate(); + Assert.AreEqual(0x0A0B, uut.GetShort(2)); + + // Advance by one more byte + uut.Position = 1; uut = uut.Duplicate(); + Assert.AreEqual(0x0A, uut.Get(3)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_To_Array_Float() + { + const int len = 9; + + // Construct the data array + var fData = new float[len]; + fData[0] = 1.0079F; + fData[1] = 4.0026F; + fData[2] = 6.941F; + fData[3] = 9.0122F; + fData[4] = 10.811F; + fData[5] = 12.0107F; + fData[6] = 14.0067F; + fData[7] = 15.9994F; + fData[8] = 18.9984F; + + // Tranfer it to a byte array + var buffer = new byte[sizeof(float) * fData.Length]; + Buffer.BlockCopy(fData, 0, buffer, 0, buffer.Length); + + // Create the Byte Buffer from byte array + var uut = new ByteBuffer(buffer); + + // Get the full array back out and ensure they are equivalent + var bbArray = uut.ToArray(0, len); + Assert.ArrayEqual(fData, bbArray); + + // Get a portion of the full array back out and ensure the + // subrange agrees + var bbArray2 = uut.ToArray(4, len - 1); + Assert.AreEqual(bbArray2.Length, len - 1); + for (int i = 1; i < len - 1; i++) + { + Assert.AreEqual(fData[i], bbArray2[i - 1]); + } + + // Get a sub portion of the full array back out and ensure the + // subrange agrees + var bbArray3 = uut.ToArray(8, len - 4); + Assert.AreEqual(bbArray3.Length, len - 4); + for (int i = 2; i < len - 4; i++) + { + Assert.AreEqual(fData[i], bbArray3[i - 2]); + } + } + + public void ByteBuffer_Put_Array_Helper(T[] data, int typeSize) + where T : struct + { + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // Put the data into the buffer and make sure the offset is + // calculated correctly + int nOffset = uut.Put(1024, data); + Assert.AreEqual(1024 - typeSize * data.Length, nOffset); + + // Get the full array back out and ensure they are equivalent + var bbArray = uut.ToArray(nOffset, data.Length); + Assert.ArrayEqual(data, bbArray); + } + + public void ByteBuffer_Put_ArraySegment_Helper(ArraySegment data, int typeSize) + where T : struct + { + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // Put the data into the buffer and make sure the offset is + // calculated correctly + int nOffset = uut.Put(1024, data); + Assert.AreEqual(1024 - typeSize * data.Count, nOffset); + + // Get the full array back out and ensure they are equivalent + var bbArray = uut.ToArray(nOffset, data.Count); + Assert.ArrayEqual(data, bbArray); + } + + public unsafe void ByteBuffer_Put_IntPtr_Helper(T[] data, int typeSize) + where T : struct + { + GCHandle handle = GCHandle.Alloc(data, GCHandleType.Pinned); + try + { + var dataPtr = handle.AddrOfPinnedObject(); + var sizeInBytes = data.Length * typeSize; + + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // Put the data into the buffer and make sure the offset is + // calculated correctly + int nOffset = uut.Put(1024, dataPtr, sizeInBytes); + Assert.AreEqual(1024 - sizeInBytes, nOffset); + + // Get the full array back out and ensure they are equivalent + var bbArray = uut.ToArray(nOffset, data.Length); + Assert.ArrayEqual(data, bbArray); + } + finally + { + handle.Free(); + } + } + + public void ByteBuffer_Put_ArrayTypes_Helper(T[] data, int typeSize) + where T : struct + { + ByteBuffer_Put_Array_Helper(data, typeSize); + + var arraySegment = CreateArraySegment(data); + ByteBuffer_Put_ArraySegment_Helper(arraySegment, typeSize); + + ByteBuffer_Put_IntPtr_Helper(data, typeSize); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Float() + { + const int len = 9; + + // Construct the data array + var data = new float[len]; + data[0] = 1.0079F; + data[1] = 4.0026F; + data[2] = 6.941F; + data[3] = 9.0122F; + data[4] = 10.811F; + data[5] = 12.0107F; + data[6] = 14.0067F; + data[7] = 15.9994F; + data[8] = 18.9984F; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(float)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Double() + { + const int len = 9; + + // Construct the data array + var data = new double[len]; + data[0] = 1.0079; + data[1] = 4.0026; + data[2] = 6.941; + data[3] = 9.0122; + data[4] = 10.811; + data[5] = 12.0107; + data[6] = 14.0067; + data[7] = 15.9994; + data[8] = 18.9984; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(double)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Int() + { + const int len = 9; + + // Construct the data array + var data = new int[len]; + data[0] = 1; + data[1] = 4; + data[2] = 6; + data[3] = 9; + data[4] = 10; + data[5] = 12; + data[6] = 14; + data[7] = 15; + data[8] = 18; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(int)); + } + + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_UInt() + { + const int len = 9; + + // Construct the data array + var data = new uint[len]; + data[0] = 1; + data[1] = 4; + data[2] = 6; + data[3] = 9; + data[4] = 10; + data[5] = 12; + data[6] = 14; + data[7] = 15; + data[8] = 18; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(uint)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Bool() + { + const int len = 9; + + // Construct the data array + var data = new bool[len]; + data[0] = true; + data[1] = true; + data[2] = false; + data[3] = true; + data[4] = false; + data[5] = true; + data[6] = true; + data[7] = true; + data[8] = false; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(bool)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Long() + { + const int len = 9; + + // Construct the data array + var data = new long[len]; + data[0] = 1; + data[1] = 4; + data[2] = 6; + data[3] = 9; + data[4] = 10; + data[5] = 12; + data[6] = 14; + data[7] = 15; + data[8] = 18; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(long)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Byte() + { + const int len = 9; + + // Construct the data array + var data = new byte[len]; + data[0] = 1; + data[1] = 4; + data[2] = 6; + data[3] = 9; + data[4] = 10; + data[5] = 12; + data[6] = 14; + data[7] = 15; + data[8] = 18; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(byte)); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_SByte() + { + const int len = 9; + + // Construct the data array + var data = new sbyte[len]; + data[0] = 1; + data[1] = 4; + data[2] = 6; + data[3] = 9; + data[4] = 10; + data[5] = 12; + data[6] = 14; + data[7] = 15; + data[8] = 18; + + ByteBuffer_Put_ArrayTypes_Helper(data, sizeof(sbyte)); + } + + private static ArraySegment CreateArraySegment(T[] data) + where T : struct + { + const int arraySegmentPadding = 7; + var newData = new T[data.Length + 2 * arraySegmentPadding]; + Array.Copy(data, 0, newData, arraySegmentPadding, data.Length); + return new ArraySegment(newData, arraySegmentPadding, data.Length); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Put_Array_Null_Throws() + { + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // create a null array and try to put it into the buffer + float[] data = null; + Assert.Throws(() => uut.Put(1024, data)); + + ArraySegment dataArraySegment = default(ArraySegment); + Assert.Throws(() => uut.Put(1024, dataArraySegment)); + + IntPtr dataPtr = IntPtr.Zero; + int dataPtrLength = 100; + Assert.Throws(() => uut.Put(1024, dataPtr, dataPtrLength)); + } + + [FlatBuffersTestMethod] + public unsafe void ByteBuffer_Put_Array_Empty_Throws() + { + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // create an array of length == 0, and try to put it into the buffer + float[] data = new float[0]; + Assert.Throws(() => uut.Put(1024, data)); + + var dataArraySegment = new ArraySegment(new float[10], 5, 0); + Assert.Throws(() => uut.Put(1024, dataArraySegment)); + + fixed(float* floatPtr = data) + { + var dataPtr = (IntPtr)floatPtr; + var dataPtrLength = 0; + Assert.Throws(() => uut.Put(1024, dataPtr, dataPtrLength)); + } + } + + [FlatBuffersTestMethod] + public unsafe void ByteBuffer_Put_IntPtr_NegativeSize_Throws() + { + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // create an array of length == 0, and try to put it into the buffer + float[] data = new float[10]; + fixed(float* floatPtr = data) + { + var dataPtr = (IntPtr)floatPtr; + var dataPtrLength = -1; + Assert.Throws(() => uut.Put(1024, dataPtr, dataPtrLength)); + } + } + + #pragma warning disable 0169 + // These are purposely not used and the warning is suppress + private struct dummyStruct + { + int a; + float b; + } + #pragma warning restore 0169 + + [FlatBuffersTestMethod] + public unsafe void ByteBuffer_Put_Array_IncorrectType_Throws() + { + // Create the Byte Buffer + var uut = new ByteBuffer(1024); + + // Create an array of dummy structures that shouldn't be + // able to be put into the buffer + var data = new dummyStruct[10]; + Assert.Throws(() => uut.Put(1024, data)); + + var dataArraySegment = new ArraySegment(data); + Assert.Throws(() => uut.Put(1024, dataArraySegment)); + + fixed(dummyStruct* floatPtr = data) + { + var dataPtr = (IntPtr)floatPtr; + var dataPtrLength = data.Length * sizeof(dummyStruct); + Assert.Throws(() => uut.Put(1024, dataPtr, dataPtrLength)); + } + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Get_Double() + { + var uut = new ByteBuffer(1024); + double value = 3.14159265; + uut.PutDouble(900, value); + double getValue = uut.GetDouble(900); + Assert.AreEqual(value, getValue); + } + + [FlatBuffersTestMethod] + public void ByteBuffer_Get_Float() + { + var uut = new ByteBuffer(1024); + float value = 3.14159265F; + uut.PutFloat(900, value); + double getValue = uut.GetFloat(900); + Assert.AreEqual(value, getValue); + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBufferBuilderTests.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBufferBuilderTests.cs new file mode 100644 index 00000000000..71fd1d04d0d --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBufferBuilderTests.cs @@ -0,0 +1,766 @@ +/* + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Diagnostics; + +namespace Google.FlatBuffers.Test +{ + [FlatBuffersTestClass] + public class FlatBufferBuilderTests + { + private FlatBufferBuilder CreateBuffer(bool forceDefaults = true) + { + var fbb = new FlatBufferBuilder(16) {ForceDefaults = forceDefaults}; + fbb.StartTable(1); + return fbb; + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddBool_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddBool(0, false, false); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(bool), endOffset-storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddSByte_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddSbyte(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(sbyte), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddByte_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddByte(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(byte), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddShort_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddShort(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(short), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddUShort_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddUshort(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(ushort), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddInt_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddInt(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(int), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddUInt_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddUint(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(uint), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddLong_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddLong(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(long), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddULong_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddUlong(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(ulong), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddFloat_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddFloat(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(float), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WithForceDefaults_WhenAddDouble_AndDefaultValue_OffsetIncreasesBySize() + { + var fbb = CreateBuffer(); + var storedOffset = fbb.Offset; + fbb.AddDouble(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(double), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddBool_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddBool(0, false, false); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddSByte_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddSbyte(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddByte_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddByte(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddShort_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddShort(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddUShort_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUshort(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddInt_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddInt(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddUInt_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUint(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddLong_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddLong(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddULong_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUlong(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddFloat_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddFloat(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddDouble_AndDefaultValue_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddDouble(0, 0, 0); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableBool_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddBool(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableSbyte_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddSbyte(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableByte_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddByte(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableShort_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddShort(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableUShort_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUshort(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableInt_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddInt(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableUInt_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUint(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableLong_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddLong(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableULong_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUlong(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableFloat_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddFloat(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableDouble_OffsetIsUnchanged() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddDouble(0, null); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableBool_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddBool(0, true); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(bool), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableSbyte_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddSbyte(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(sbyte), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableByte_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddByte(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(byte), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableShort_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddShort(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(short), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableUShort_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUshort(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(ushort), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableInt_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddInt(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(int), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableUInt_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUint(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(uint), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableLong_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddLong(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(long), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableULong_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddUlong(0, 1); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(ulong), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableFloat_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddFloat(0, 1.0F); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(float), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_WhenAddNullableDouble_OffsetIsChangedBySize() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + fbb.AddDouble(0, 1.0); + var endOffset = fbb.Offset; + Assert.AreEqual(sizeof(double), endOffset - storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_Array_Float() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + + const int len = 9; + + // Construct the data array + var data = new float[len]; + data[0] = 1.0079F; + data[1] = 4.0026F; + data[2] = 6.941F; + data[3] = 9.0122F; + data[4] = 10.811F; + data[5] = 12.0107F; + data[6] = 14.0067F; + data[7] = 15.9994F; + data[8] = 18.9984F; + + fbb.Add(data); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset + sizeof(float) * data.Length); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_Array_Bool() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + + const int len = 9; + + // Construct the data array + var data = new bool[len]; + data[0] = true; + data[1] = true; + data[2] = false; + data[3] = true; + data[4] = false; + data[5] = true; + data[6] = true; + data[7] = true; + data[8] = false; + + fbb.Add(data); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset + sizeof(bool) * data.Length); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_Array_Double() + { + var fbb = CreateBuffer(false); + var storedOffset = fbb.Offset; + + const int len = 9; + + // Construct the data array + var data = new double[len]; + data[0] = 1.0079; + data[1] = 4.0026; + data[2] = 6.941; + data[3] = 9.0122; + data[4] = 10.811; + data[5] = 12.0107; + data[6] = 14.0067; + data[7] = 15.9994; + data[8] = 18.9984; + + fbb.Add(data); + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset + sizeof(double) * data.Length); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_Array_Null_Throws() + { + var fbb = CreateBuffer(false); + + // Construct the data array + float[] data = null; + + Assert.Throws(() => fbb.Add(data)); + } + + [FlatBuffersTestMethod] + public unsafe void FlatBufferBuilder_Add_Array_UnsupportedType_Throws() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var data = new DummyStruct[10]; + Assert.Throws(() => fbb.Add(data)); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_Array_Empty_Noop() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct an empty data array + float[] data = new float[0]; + fbb.Add(data); + + // Make sure the offset didn't change since nothing + // was really added + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_ArraySegment_Default_Throws() + { +#if NETCOREAPP + var fbb = CreateBuffer(false); + + // Construct the data array + ArraySegment data = default(ArraySegment); + + Assert.Throws(() => fbb.Add(data)); +#endif + } + + [FlatBuffersTestMethod] + public unsafe void FlatBufferBuilder_Add_ArraySegment_UnsupportedType_Throws() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var array = new DummyStruct[10]; + var data = new ArraySegment(array); + Assert.Throws(() => fbb.Add(data)); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_ArraySegment_Empty_Noop() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var array = new float[10]; + var data = new ArraySegment(array, 5, 0); + fbb.Add(data); + + // Make sure the offset didn't change since nothing + // was really added + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_IntPtr_Zero_Throws() + { + var fbb = CreateBuffer(false); + + // Construct the data array + var data = IntPtr.Zero; + var length = 100; + + Assert.Throws(() => fbb.Add(data, length)); + } + + [FlatBuffersTestMethod] + public unsafe void FlatBufferBuilder_Add_IntPtr_SizeNegative_Throws() + { + var fbb = CreateBuffer(false); + + // Construct the data array + var array = new float[10]; + fixed(float* ptr = array) + { + var data = (IntPtr)ptr; + var length = -1; + Assert.Throws(() => fbb.Add(data, length)); + } + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_IntPtr_Zero_Empty_Noop() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var data = IntPtr.Zero; + var length = 0; + + fbb.Add(data, length); + + // make sure that a length of 0 doesn't throw also if ptr is Zero as well + // and that nothing was really added + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public unsafe void FlatBufferBuilder_Add_IntPtr_Empty_Noop() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var array = new float[10]; + fixed(float* ptr = array) + { + var data = (IntPtr)ptr; + var length = 0; + fbb.Add(data, length); + } + + // Make sure the offset didn't change since nothing + // was really added + var endOffset = fbb.Offset; + Assert.AreEqual(endOffset, storedOffset); + } + + [FlatBuffersTestMethod] + public unsafe void FlatBufferBuilder_Add_IntPtr_SizeInBytesNotMatchingDataType_Throws() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var array = new float[10]; + fixed(float* ptr = array) + { + const int invalidBytes = 1; + var data = (IntPtr)ptr; + // add some invalid bytes to the length + var length = 2 * sizeof(float) + invalidBytes; + + Assert.Throws(() => fbb.Add(data, length)); + } + } + + [FlatBuffersTestMethod] + public unsafe void FlatBufferBuilder_Add_IntPtr_UnsupportedType_Throws() + { + var fbb = CreateBuffer(false); + + var storedOffset = fbb.Offset; + + // Construct the data array + var array = new DummyStruct[10]; + fixed(DummyStruct* ptr = array) + { + var data = (IntPtr)ptr; + var length = 10 * sizeof(DummyStruct); + + Assert.Throws(() => fbb.Add(data, length)); + } + } + + private struct DummyStruct + { + int value; + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Add_null_String() + { + var fbb = new FlatBufferBuilder(16); + string s = null; + Assert.AreEqual(fbb.CreateSharedString(s).Value, 0); + Assert.AreEqual(fbb.CreateString(s).Value, 0); + } + + [FlatBuffersTestMethod] + public void FlatBufferBuilder_Empty_Builder() + { + var fbb = new FlatBufferBuilder(16); + var str = "Hello"; + var flatbuffer = "Flatbuffers!"; + var strOffset = fbb.CreateSharedString(str); + var flatbufferOffset = fbb.CreateSharedString(flatbuffer); + fbb.Clear(); + var flatbufferOffset2 = fbb.CreateSharedString(flatbuffer); + var strOffset2 = fbb.CreateSharedString(str); + Assert.IsFalse(strOffset.Value == strOffset2.Value); + Assert.IsFalse(flatbufferOffset.Value == flatbufferOffset2.Value); + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffers.Test.csproj b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffers.Test.csproj new file mode 100644 index 00000000000..d6bf6c8aa4e --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffers.Test.csproj @@ -0,0 +1,203 @@ + + + + Exe + net6.0;net8.0 + + + + + + + + true + $(DefineConstants);UNSAFE_BYTEBUFFER + + + + true + $(DefineConstants);ENABLE_SPAN_T + + + + true + + + + true + + + + + FlatBuffers\ByteBuffer.cs + + + FlatBuffers\ByteBufferUtil.cs + + + FlatBuffers\IFlatbufferObject.cs + + + FlatBuffers\Offset.cs + + + FlatBuffers\FlatBufferBuilder.cs + + + FlatBuffers\FlatBufferConstants.cs + + + FlatBuffers\FlatBufferVerify.cs + + + FlatBuffers\Struct.cs + + + FlatBuffers\Table.cs + + + MyGame\Example2\Monster.cs + + + MyGame\Example\Any.cs + + + MyGame\Example\AnyAmbiguousAliases.cs + + + MyGame\Example\AnyUniqueAliases.cs + + + MyGame\Example\Color.cs + + + MyGame\Example\Race.cs + + + MyGame\Example\Monster.cs + + + MyGame\Example\Referrable.cs + + + MyGame\Example\Stat.cs + + + MyGame\Example\Test.cs + + + MyGame\Example\TestSimpleTableWithEnum.cs + + + MyGame\Example\TypeAliases.cs + + + MyGame\Example\Vec3.cs + + + MyGame\Example\Ability.cs + + + MyGame\Example\ArrayTable.cs + + + MyGame\Example\ArrayStruct.cs + + + MyGame\Example\NestedStruct.cs + + + MyGame\Example\LongEnum.cs + + + MyGame\Example\TestEnum.cs + + + MyGame\InParentNamespace.cs + + + NamespaceA\NamespaceB\EnumInNestedNS.cs + + + NamespaceA\NamespaceB\StructInNestedNS.cs + + + NamespaceA\NamespaceB\TableInNestedNS.cs + + + NamespaceA\NamespaceB\UnionInNestedNS.cs + + + NamespaceA\TableInFirstNS.cs + + + union_vector\Attacker.cs + + + union_vector\BookReader.cs + + + union_vector\Character.cs + + + union_vector\Movie.cs + + + union_vector\Rapunzel.cs + + + optional_scalars\OptionalByte.cs + + + optional_scalars\ScalarStuff.cs + + + KeywordTest\ABC.cs + + + KeywordTest\public.cs + + + KeywordTest\KeywordsInTable.cs + + + KeywordTest\KeywordsInUnion.cs + + + nested_namespace_test\nested_namespace_test1_generated.cs + + + nested_namespace_test\nested_namespace_test2_generated.cs + + + nested_namespace_test\nested_namespace_test3_generated.cs + + + union_value_collsion\union_value_collision_generated.cs + + + + + + + + + + + + + + monsterdata_test.mon + PreserveNewest + + + monsterdata_test.json + PreserveNewest + + + + + + + + diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs new file mode 100644 index 00000000000..33d524358fb --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersExampleTests.cs @@ -0,0 +1,1198 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.IO; +using System.Text; +using System.Threading; +using MyGame.Example; +using optional_scalars; +using KeywordTest; + +namespace Google.FlatBuffers.Test +{ + [FlatBuffersTestClass] + public class FlatBuffersExampleTests + { + public void RunTests() + { + CanCreateNewFlatBufferFromScratch(); + CanReadCppGeneratedWireFile(); + TestEnums(); + } + + [FlatBuffersTestMethod] + public void CanCreateNewFlatBufferFromScratch() + { + CanCreateNewFlatBufferFromScratch(true); + CanCreateNewFlatBufferFromScratch(false); + } + + private void CanCreateNewFlatBufferFromScratch(bool sizePrefix) + { + // Second, let's create a FlatBuffer from scratch in C#, and test it also. + // We use an initial size of 1 to exercise the reallocation algorithm, + // normally a size larger than the typical FlatBuffer you generate would be + // better for performance. + var fbb = new FlatBufferBuilder(1); + + StringOffset[] names = { fbb.CreateString("Frodo"), fbb.CreateString("Barney"), fbb.CreateString("Wilma") }; + Offset[] off = new Offset[3]; + Monster.StartMonster(fbb); + Monster.AddName(fbb, names[0]); + off[0] = Monster.EndMonster(fbb); + Monster.StartMonster(fbb); + Monster.AddName(fbb, names[1]); + off[1] = Monster.EndMonster(fbb); + Monster.StartMonster(fbb); + Monster.AddName(fbb, names[2]); + off[2] = Monster.EndMonster(fbb); + var sortMons = Monster.CreateSortedVectorOfMonster(fbb, off); + + // We set up the same values as monsterdata.json: + + var str = fbb.CreateString("MyMonster"); + var test1 = fbb.CreateString("test1"); + var test2 = fbb.CreateString("test2"); + + + Monster.StartInventoryVector(fbb, 5); + for (int i = 4; i >= 0; i--) + { + fbb.AddByte((byte)i); + } + var inv = fbb.EndVector(); + + var fred = fbb.CreateString("Fred"); + Monster.StartMonster(fbb); + Monster.AddName(fbb, fred); + var mon2 = Monster.EndMonster(fbb); + + Monster.StartTest4Vector(fbb, 2); + MyGame.Example.Test.CreateTest(fbb, (short)10, (sbyte)20); + MyGame.Example.Test.CreateTest(fbb, (short)30, (sbyte)40); + var test4 = fbb.EndVector(); + + Monster.StartTestarrayofstringVector(fbb, 2); + fbb.AddOffset(test2.Value); + fbb.AddOffset(test1.Value); + var testArrayOfString = fbb.EndVector(); + + Monster.StartMonster(fbb); + Monster.AddPos(fbb, Vec3.CreateVec3(fbb, 1.0f, 2.0f, 3.0f, 3.0, + Color.Green, (short)5, (sbyte)6)); + Monster.AddHp(fbb, (short)80); + Monster.AddName(fbb, str); + Monster.AddInventory(fbb, inv); + Monster.AddTestType(fbb, Any.Monster); + Monster.AddTest(fbb, mon2.Value); + Monster.AddTest4(fbb, test4); + Monster.AddTestarrayofstring(fbb, testArrayOfString); + Monster.AddTestbool(fbb, true); + Monster.AddTestarrayoftables(fbb, sortMons); + var mon = Monster.EndMonster(fbb); + + if (sizePrefix) + { + Monster.FinishSizePrefixedMonsterBuffer(fbb, mon); + } + else + { + Monster.FinishMonsterBuffer(fbb, mon); + } + + // Dump to output directory so we can inspect later, if needed + #if ENABLE_SPAN_T + var data = fbb.DataBuffer.ToSizedArray(); + string filename = @"monsterdata_cstest" + (sizePrefix ? "_sp" : "") + ".mon"; + File.WriteAllBytes(filename, data); + #else + using (var ms = fbb.DataBuffer.ToMemoryStream(fbb.DataBuffer.Position, fbb.Offset)) + { + var data = ms.ToArray(); + string filename = @"monsterdata_cstest" + (sizePrefix ? "_sp" : "") + ".mon"; + File.WriteAllBytes(filename, data); + } + #endif + + // Remove the size prefix if necessary for further testing + ByteBuffer dataBuffer = fbb.DataBuffer; + if (sizePrefix) + { + Assert.AreEqual(ByteBufferUtil.GetSizePrefix(dataBuffer) + FlatBufferConstants.SizePrefixLength, + dataBuffer.Length - dataBuffer.Position); + dataBuffer = ByteBufferUtil.RemoveSizePrefix(dataBuffer); + } + + // Now assert the buffer + TestBuffer(dataBuffer); + + //Attempt to mutate Monster fields and check whether the buffer has been mutated properly + // revert to original values after testing + Monster monster = Monster.GetRootAsMonster(dataBuffer); + + + // mana is optional and does not exist in the buffer so the mutation should fail + // the mana field should retain its default value + Assert.AreEqual(monster.MutateMana((short)10), false); + Assert.AreEqual(monster.Mana, (short)150); + + // Accessing a vector of sorted by the key tables + Assert.AreEqual(monster.Testarrayoftables(0).Value.Name, "Barney"); + Assert.AreEqual(monster.Testarrayoftables(1).Value.Name, "Frodo"); + Assert.AreEqual(monster.Testarrayoftables(2).Value.Name, "Wilma"); + + // Example of searching for a table by the key + Assert.IsTrue(monster.TestarrayoftablesByKey("Frodo") != null); + Assert.AreEqual(monster.TestarrayoftablesByKey("Frodo").Value.Name, "Frodo"); + Assert.IsTrue(monster.TestarrayoftablesByKey("Barney") != null); + Assert.AreEqual(monster.TestarrayoftablesByKey("Barney").Value.Name, "Barney"); + Assert.IsTrue(monster.TestarrayoftablesByKey("Wilma") != null); + Assert.AreEqual(monster.TestarrayoftablesByKey("Wilma").Value.Name, "Wilma"); + + // testType is an existing field + Assert.AreEqual(monster.TestType, Any.Monster); + + //mutate the inventory vector + Assert.AreEqual(monster.MutateInventory(0, 1), true); + Assert.AreEqual(monster.MutateInventory(1, 2), true); + Assert.AreEqual(monster.MutateInventory(2, 3), true); + Assert.AreEqual(monster.MutateInventory(3, 4), true); + Assert.AreEqual(monster.MutateInventory(4, 5), true); + + for (int i = 0; i < monster.InventoryLength; i++) + { + Assert.AreEqual(monster.Inventory(i), i + 1); + } + + //reverse mutation + Assert.AreEqual(monster.MutateInventory(0, 0), true); + Assert.AreEqual(monster.MutateInventory(1, 1), true); + Assert.AreEqual(monster.MutateInventory(2, 2), true); + Assert.AreEqual(monster.MutateInventory(3, 3), true); + Assert.AreEqual(monster.MutateInventory(4, 4), true); + + // get a struct field and edit one of its fields + Vec3 pos = (Vec3)monster.Pos; + Assert.AreEqual(pos.X, 1.0f); + pos.MutateX(55.0f); + Assert.AreEqual(pos.X, 55.0f); + pos.MutateX(1.0f); + Assert.AreEqual(pos.X, 1.0f); + + TestBuffer(dataBuffer); + TestObjectAPI(Monster.GetRootAsMonster(dataBuffer)); + } + + private void TestBuffer(ByteBuffer bb) + { + bool test = Monster.VerifyMonster(bb); + Assert.AreEqual(true, test); + + Monster monster = Monster.GetRootAsMonster(bb); + + Assert.AreEqual(80, monster.Hp); + Assert.AreEqual(150, monster.Mana); + Assert.AreEqual("MyMonster", monster.Name); + + var pos = monster.Pos.Value; + Assert.AreEqual(1.0f, pos.X); + Assert.AreEqual(2.0f, pos.Y); + Assert.AreEqual(3.0f, pos.Z); + + Assert.AreEqual(3.0f, pos.Test1); + Assert.AreEqual(Color.Green, pos.Test2); + var t = (MyGame.Example.Test)pos.Test3; + Assert.AreEqual((short)5, t.A); + Assert.AreEqual((sbyte)6, t.B); + + Assert.AreEqual(Any.Monster, monster.TestType); + + var monster2 = monster.Test().Value; + Assert.AreEqual("Fred", monster2.Name); + + + Assert.AreEqual(5, monster.InventoryLength); + var invsum = 0; + for (var i = 0; i < monster.InventoryLength; i++) + { + invsum += monster.Inventory(i); + } + Assert.AreEqual(10, invsum); + + // Get the inventory as an array and subtract the + // sum to get it back to 0 + var inventoryArray = monster.GetInventoryArray(); + Assert.AreEqual(5, inventoryArray.Length); + foreach(var inv in inventoryArray) + { + invsum -= inv; + } + Assert.AreEqual(0, invsum); + + var test0 = monster.Test4(0).Value; + var test1 = monster.Test4(1).Value; + Assert.AreEqual(2, monster.Test4Length); + + Assert.AreEqual(100, test0.A + test0.B + test1.A + test1.B); + + Assert.AreEqual(2, monster.TestarrayofstringLength); + Assert.AreEqual("test1", monster.Testarrayofstring(0)); + Assert.AreEqual("test2", monster.Testarrayofstring(1)); + + Assert.AreEqual(true, monster.Testbool); + + #if ENABLE_SPAN_T + var nameBytes = monster.GetNameBytes(); + Assert.AreEqual("MyMonster", Encoding.UTF8.GetString(nameBytes.ToArray(), 0, nameBytes.Length)); + + if (0 == monster.TestarrayofboolsLength) + { + Assert.IsFalse(monster.GetTestarrayofboolsBytes().Length != 0); + } + else + { + Assert.IsTrue(monster.GetTestarrayofboolsBytes().Length != 0); + } + + var longArrayBytes = monster.GetVectorOfLongsBytes(); + Assert.IsTrue(monster.VectorOfLongsLength * 8 == longArrayBytes.Length); + + var doubleArrayBytes = monster.GetVectorOfDoublesBytes(); + Assert.IsTrue(monster.VectorOfDoublesLength * 8 == doubleArrayBytes.Length); + #else + var nameBytes = monster.GetNameBytes().Value; + Assert.AreEqual("MyMonster", Encoding.UTF8.GetString(nameBytes.Array, nameBytes.Offset, nameBytes.Count)); + + if (0 == monster.TestarrayofboolsLength) + { + Assert.IsFalse(monster.GetTestarrayofboolsBytes().HasValue); + } + else + { + Assert.IsTrue(monster.GetTestarrayofboolsBytes().HasValue); + } + #endif + } + + [FlatBuffersTestMethod] + public void CanReadCppGeneratedWireFile() + { + var data = File.ReadAllBytes(@"monsterdata_test.mon"); + var bb = new ByteBuffer(data); + TestBuffer(bb); + TestObjectAPI(Monster.GetRootAsMonster(bb)); + } + + [FlatBuffersTestMethod] + public void CanReadJsonFile() + { + var jsonText = File.ReadAllText(@"monsterdata_test.json"); + var mon = MonsterT.DeserializeFromJson(jsonText); + var fbb = new FlatBufferBuilder(1); + Monster.FinishMonsterBuffer(fbb, Monster.Pack(fbb, mon)); + TestBuffer(fbb.DataBuffer); + } + + [FlatBuffersTestMethod] + public void TestEnums() + { + Assert.AreEqual("Red", Color.Red.ToString()); + Assert.AreEqual("Blue", Color.Blue.ToString()); + Assert.AreEqual("NONE", Any.NONE.ToString()); + Assert.AreEqual("Monster", Any.Monster.ToString()); + } + + [FlatBuffersTestMethod] + public void TestVectorOfEnums() + { + const string monsterName = "TestVectorOfEnumsMonster"; + var colorVec = new Color[] { Color.Red, Color.Green, Color.Blue }; + var fbb = new FlatBufferBuilder(32); + var str1 = fbb.CreateString(monsterName); + var vec1 = Monster.CreateVectorOfEnumsVector(fbb, colorVec); + Monster.StartMonster(fbb); + Monster.AddName(fbb, str1); + Monster.AddVectorOfEnums(fbb, vec1); + var monster1 = Monster.EndMonster(fbb); + Monster.FinishMonsterBuffer(fbb, monster1); + + var mons = Monster.GetRootAsMonster(fbb.DataBuffer); + var colors = mons.GetVectorOfEnumsArray(); + Assert.ArrayEqual(colorVec, colors); + + TestObjectAPI(mons); + } + + [FlatBuffersTestMethod] + public void TestNestedFlatBuffer() + { + const string nestedMonsterName = "NestedMonsterName"; + const short nestedMonsterHp = 600; + const short nestedMonsterMana = 1024; + // Create nested buffer as a Monster type + var fbb1 = new FlatBufferBuilder(16); + var str1 = fbb1.CreateString(nestedMonsterName); + Monster.StartMonster(fbb1); + Monster.AddName(fbb1, str1); + Monster.AddHp(fbb1, nestedMonsterHp); + Monster.AddMana(fbb1, nestedMonsterMana); + var monster1 = Monster.EndMonster(fbb1); + Monster.FinishMonsterBuffer(fbb1, monster1); + var fbb1Bytes = fbb1.SizedByteArray(); + fbb1 = null; + + // Create a Monster which has the first buffer as a nested buffer + var fbb2 = new FlatBufferBuilder(16); + var str2 = fbb2.CreateString("My Monster"); + var nestedBuffer = Monster.CreateTestnestedflatbufferVector(fbb2, fbb1Bytes); + Monster.StartMonster(fbb2); + Monster.AddName(fbb2, str2); + Monster.AddHp(fbb2, 50); + Monster.AddMana(fbb2, 32); + Monster.AddTestnestedflatbuffer(fbb2, nestedBuffer); + var monster = Monster.EndMonster(fbb2); + Monster.FinishMonsterBuffer(fbb2, monster); + + // Now test the data extracted from the nested buffer + var mons = Monster.GetRootAsMonster(fbb2.DataBuffer); + var nestedMonster = mons.GetTestnestedflatbufferAsMonster().Value; + + Assert.AreEqual(nestedMonsterMana, nestedMonster.Mana); + Assert.AreEqual(nestedMonsterHp, nestedMonster.Hp); + Assert.AreEqual(nestedMonsterName, nestedMonster.Name); + + TestObjectAPI(mons); + TestObjectAPI(nestedMonster); + } + + [FlatBuffersTestMethod] + public void TestFixedLenghtArrays() + { + FlatBufferBuilder builder = new FlatBufferBuilder(100); + + float a; + int[] b = new int[15]; + sbyte c; + int[,] d_a = new int[2, 2]; + TestEnum[] d_b = new TestEnum[2]; + TestEnum[,] d_c = new TestEnum[2, 2]; + long[,] d_d = new long[2, 2]; + int e; + long[] f = new long[2]; + + a = 0.5f; + for (int i = 0; i < 15; i++) b[i] = i; + c = 1; + d_a[0, 0] = 1; + d_a[0, 1] = 2; + d_a[1, 0] = 3; + d_a[1, 1] = 4; + d_b[0] = TestEnum.B; + d_b[1] = TestEnum.C; + d_c[0, 0] = TestEnum.A; + d_c[0, 1] = TestEnum.B; + d_c[1, 0] = TestEnum.C; + d_c[1, 1] = TestEnum.B; + d_d[0, 0] = -1; + d_d[0, 1] = 1; + d_d[1, 0] = -2; + d_d[1, 1] = 2; + e = 2; + f[0] = -1; + f[1] = 1; + + Offset arrayOffset = ArrayStruct.CreateArrayStruct( + builder, a, b, c, d_a, d_b, d_c, d_d, e, f); + + // Create a table with the ArrayStruct. + ArrayTable.StartArrayTable(builder); + ArrayTable.AddA(builder, arrayOffset); + Offset tableOffset = ArrayTable.EndArrayTable(builder); + + ArrayTable.FinishArrayTableBuffer(builder, tableOffset); + + ArrayTable table = ArrayTable.GetRootAsArrayTable(builder.DataBuffer); + + Assert.AreEqual(table.A.Value.A, 0.5f); + for (int i = 0; i < 15; i++) Assert.AreEqual(table.A.Value.B(i), i); + Assert.AreEqual(table.A.Value.C, (sbyte)1); + Assert.AreEqual(table.A.Value.D(0).A(0), 1); + Assert.AreEqual(table.A.Value.D(0).A(1), 2); + Assert.AreEqual(table.A.Value.D(1).A(0), 3); + Assert.AreEqual(table.A.Value.D(1).A(1), 4); + Assert.AreEqual(table.A.Value.D(0).B, TestEnum.B); + Assert.AreEqual(table.A.Value.D(1).B, TestEnum.C); + Assert.AreEqual(table.A.Value.D(0).C(0), TestEnum.A); + Assert.AreEqual(table.A.Value.D(0).C(1), TestEnum.B); + Assert.AreEqual(table.A.Value.D(1).C(0), TestEnum.C); + Assert.AreEqual(table.A.Value.D(1).C(1), TestEnum.B); + Assert.AreEqual(table.A.Value.D(0).D(0), -1); + Assert.AreEqual(table.A.Value.D(0).D(1), 1); + Assert.AreEqual(table.A.Value.D(1).D(0), -2); + Assert.AreEqual(table.A.Value.D(1).D(1), 2); + Assert.AreEqual(table.A.Value.E, 2); + Assert.AreEqual(table.A.Value.F(0), -1); + Assert.AreEqual(table.A.Value.F(1), 1); + + TestObjectAPI(table); + } + + [FlatBuffersTestMethod] + public void TestUnionVector() + { + var fbb = new FlatBufferBuilder(100); + var rapunzel = Rapunzel.CreateRapunzel(fbb, 40).Value; + + var characterTypes = new[] + { + Character.MuLan, + Character.Belle, + Character.Other, + }; + var characterTypesOffset = Movie.CreateCharactersTypeVector(fbb, characterTypes); + + var characters = new[] + { + Attacker.CreateAttacker(fbb, 10).Value, + BookReader.CreateBookReader(fbb, 20).Value, + fbb.CreateSharedString("Chip").Value, + }; + var charactersOffset = Movie.CreateCharactersVector(fbb, characters); + + var movieOffset = Movie.CreateMovie( + fbb, + Character.Rapunzel, + rapunzel, + characterTypesOffset, + charactersOffset); + Movie.FinishMovieBuffer(fbb, movieOffset); + + var movie = Movie.GetRootAsMovie(fbb.DataBuffer); + Assert.AreEqual(Character.Rapunzel, movie.MainCharacterType); + Assert.AreEqual(40, movie.MainCharacter().Value.HairLength); + + Assert.AreEqual(3, movie.CharactersLength); + Assert.AreEqual(Character.MuLan, movie.CharactersType(0)); + Assert.AreEqual(10, movie.Characters(0).Value.SwordAttackDamage); + Assert.AreEqual(Character.Belle, movie.CharactersType(1)); + Assert.AreEqual(20, movie.Characters(1).Value.BooksRead); + Assert.AreEqual(Character.Other, movie.CharactersType(2)); + Assert.AreEqual("Chip", movie.CharactersAsString(2)); + + TestObjectAPI(movie); + } + + [FlatBuffersTestMethod] + public void TestUnionUtility() + { + var movie = new MovieT + { + MainCharacter = CharacterUnion.FromRapunzel(new RapunzelT { HairLength = 40 }), + Characters = new System.Collections.Generic.List + { + CharacterUnion.FromMuLan(new AttackerT { SwordAttackDamage = 10 }), + CharacterUnion.FromBelle(new BookReaderT { BooksRead = 20 }), + CharacterUnion.FromOther("Chip"), + }, + }; + + var fbb = new FlatBufferBuilder(100); + Movie.FinishMovieBuffer(fbb, Movie.Pack(fbb, movie)); + + TestObjectAPI(Movie.GetRootAsMovie(fbb.DataBuffer)); + } + + private void AreEqual(Monster a, MonsterT b) + { + Assert.AreEqual(a.Hp, b.Hp); + Assert.AreEqual(a.Mana, b.Mana); + Assert.AreEqual(a.Name, b.Name); + + var posA = a.Pos; + var posB = b.Pos; + if (posA != null) + { + Assert.AreEqual(posA.Value.X, posB.X); + Assert.AreEqual(posA.Value.Y, posB.Y); + Assert.AreEqual(posA.Value.Z, posB.Z); + + Assert.AreEqual(posA.Value.Test1, posB.Test1); + Assert.AreEqual(posA.Value.Test2, posB.Test2); + var tA = posA.Value.Test3; + var tB = posB.Test3; + Assert.AreEqual(tA.A, tB.A); + Assert.AreEqual(tA.B, tB.B); + } + + Assert.AreEqual(a.TestType, b.Test.Type); + if (a.TestType == Any.Monster) + { + var monster2A = a.Test().Value; + var monster2B = b.Test.AsMonster(); + Assert.AreEqual(monster2A.Name, monster2B.Name); + } + + Assert.AreEqual(a.InventoryLength, b.Inventory.Count); + for (var i = 0; i < a.InventoryLength; ++i) + { + Assert.AreEqual(a.Inventory(i), b.Inventory[i]); + } + + var inventoryArray = a.GetInventoryArray(); + var inventoryArrayLength = inventoryArray == null ? 0 : inventoryArray.Length; + Assert.AreEqual(inventoryArrayLength, b.Inventory.Count); + for (var i = 0; i < inventoryArrayLength; ++i) + { + Assert.AreEqual(inventoryArray[i], b.Inventory[i]); + } + + Assert.AreEqual(a.Test4Length, b.Test4.Count); + for (var i = 0; i < a.Test4Length; ++i) + { + var t4A = a.Test4(i); + var t4B = b.Test4[i]; + Assert.AreEqual(t4A.Value.A, t4B.A); + Assert.AreEqual(t4A.Value.B, t4B.B); + } + + Assert.AreEqual(a.TestarrayofstringLength, b.Testarrayofstring.Count); + for (var i = 0; i < a.TestarrayofstringLength; ++i) + { + Assert.AreEqual(a.Testarrayofstring(i), b.Testarrayofstring[i]); + } + + Assert.AreEqual(a.Testbool, b.Testbool); + + Assert.AreEqual(a.TestarrayofboolsLength, b.Testarrayofbools.Count); + for (var i = 0; i < a.TestarrayofboolsLength; ++i) + { + Assert.AreEqual(a.Testarrayofbools(i), b.Testarrayofbools[i]); + } + + Assert.AreEqual(a.VectorOfLongsLength, b.VectorOfLongs.Count); + for (var i = 0; i < a.VectorOfLongsLength; ++i) + { + Assert.AreEqual(a.VectorOfLongs(i), b.VectorOfLongs[i]); + } + + Assert.AreEqual(a.VectorOfDoublesLength, b.VectorOfDoubles.Count); + for (var i = 0; i < a.VectorOfDoublesLength; ++i) + { + Assert.AreEqual(a.VectorOfDoubles(i), b.VectorOfDoubles[i]); + } + + Assert.AreEqual(a.VectorOfEnumsLength, b.VectorOfEnums.Count); + for (var i = 0; i < a.VectorOfEnumsLength; ++i) + { + Assert.AreEqual(a.VectorOfEnums(i), b.VectorOfEnums[i]); + } + } + + private void AreEqual(Monster a, Monster b) + { + Assert.AreEqual(a.Hp, b.Hp); + Assert.AreEqual(a.Mana, b.Mana); + Assert.AreEqual(a.Name, b.Name); + + var posA = a.Pos; + var posB = b.Pos; + if (posA != null) + { + Assert.AreEqual(posA.Value.X, posB.Value.X); + Assert.AreEqual(posA.Value.Y, posB.Value.Y); + Assert.AreEqual(posA.Value.Z, posB.Value.Z); + + Assert.AreEqual(posA.Value.Test1, posB.Value.Test1); + Assert.AreEqual(posA.Value.Test2, posB.Value.Test2); + var tA = posA.Value.Test3; + var tB = posB.Value.Test3; + Assert.AreEqual(tA.A, tB.A); + Assert.AreEqual(tA.B, tB.B); + } + + Assert.AreEqual(a.TestType, b.TestType); + if (a.TestType == Any.Monster) + { + var monster2A = a.Test().Value; + var monster2B = b.Test().Value; + Assert.AreEqual(monster2A.Name, monster2B.Name); + } + + Assert.AreEqual(a.InventoryLength, b.InventoryLength); + for (var i = 0; i < a.InventoryLength; ++i) + { + Assert.AreEqual(a.Inventory(i), b.Inventory(i)); + } + + var inventoryArrayA = a.GetInventoryArray(); + var inventoryArrayALength = inventoryArrayA == null ? 0 : inventoryArrayA.Length; + var inventoryArrayB = b.GetInventoryArray(); + var inventoryArrayBLength = inventoryArrayB == null ? 0 : inventoryArrayB.Length; + Assert.AreEqual(inventoryArrayALength, inventoryArrayBLength); + for (var i = 0; i < inventoryArrayALength; ++i) + { + Assert.AreEqual(inventoryArrayA[i], inventoryArrayB[i]); + } + + Assert.AreEqual(a.Test4Length, b.Test4Length); + for (var i = 0; i < a.Test4Length; ++i) + { + var t4A = a.Test4(i); + var t4B = b.Test4(i); + Assert.AreEqual(t4A.Value.A, t4B.Value.A); + Assert.AreEqual(t4A.Value.B, t4B.Value.B); + } + + Assert.AreEqual(a.TestarrayofstringLength, b.TestarrayofstringLength); + for (var i = 0; i < a.TestarrayofstringLength; ++i) + { + Assert.AreEqual(a.Testarrayofstring(i), b.Testarrayofstring(i)); + } + + Assert.AreEqual(a.Testbool, b.Testbool); + + Assert.AreEqual(a.TestarrayofboolsLength, b.TestarrayofboolsLength); + for (var i = 0; i < a.TestarrayofboolsLength; ++i) + { + Assert.AreEqual(a.Testarrayofbools(i), b.Testarrayofbools(i)); + } + + Assert.AreEqual(a.VectorOfLongsLength, b.VectorOfLongsLength); + for (var i = 0; i < a.VectorOfLongsLength; ++i) + { + Assert.AreEqual(a.VectorOfLongs(i), b.VectorOfLongs(i)); + } + + Assert.AreEqual(a.VectorOfDoublesLength, b.VectorOfDoublesLength); + for (var i = 0; i < a.VectorOfDoublesLength; ++i) + { + Assert.AreEqual(a.VectorOfDoubles(i), b.VectorOfDoubles(i)); + } + + Assert.AreEqual(a.VectorOfEnumsLength, b.VectorOfEnumsLength); + for (var i = 0; i < a.VectorOfEnumsLength; ++i) + { + Assert.AreEqual(a.VectorOfEnums(i), b.VectorOfEnums(i)); + } + } + + private void TestObjectAPI(Monster a) + { + var b = a.UnPack(); + AreEqual(a, b); + + var fbb = new FlatBufferBuilder(1); + fbb.Finish(Monster.Pack(fbb, b).Value); + var c = Monster.GetRootAsMonster(fbb.DataBuffer); + AreEqual(a, c); + + var jsonText = b.SerializeToJson(); + var d = MonsterT.DeserializeFromJson(jsonText); + AreEqual(a, d); + + var fbBuffer = b.SerializeToBinary(); + Assert.IsTrue(Monster.MonsterBufferHasIdentifier(new ByteBuffer(fbBuffer))); + var e = MonsterT.DeserializeFromBinary(fbBuffer); + AreEqual(a, e); + } + + private void AreEqual(ArrayTable a, ArrayTableT b) + { + Assert.AreEqual(a.A.Value.A, b.A.A); + + for (int i = 0; i < 15; ++i) + { + Assert.AreEqual(a.A.Value.B(i), b.A.B[i]); + } + + Assert.AreEqual(a.A.Value.C, b.A.C); + + for (int i = 0; i < 2; ++i) + { + var ad = a.A.Value.D(i); + var bd = b.A.D[i]; + + for (int j = 0; j < 2; ++j) + { + Assert.AreEqual(ad.A(j), bd.A[j]); + } + + Assert.AreEqual(ad.B, bd.B); + + for (int j = 0; j < 2; ++j) + { + Assert.AreEqual(ad.C(j), bd.C[j]); + } + + for (int j = 0; j < 2; ++j) + { + Assert.AreEqual(ad.D(j), bd.D[j]); + } + } + + Assert.AreEqual(a.A.Value.E, b.A.E); + + for (int i = 0; i < 2; ++i) + { + Assert.AreEqual(a.A.Value.F(i), b.A.F[i]); + } + } + + private void AreEqual(ArrayTable a, ArrayTable b) + { + Assert.AreEqual(a.A.Value.A, b.A.Value.A); + + for (int i = 0; i < 15; ++i) + { + Assert.AreEqual(a.A.Value.B(i), b.A.Value.B(i)); + } + + Assert.AreEqual(a.A.Value.C, b.A.Value.C); + + for (int i = 0; i < 2; ++i) + { + var ad = a.A.Value.D(i); + var bd = b.A.Value.D(i); + + for (int j = 0; j < 2; ++j) + { + Assert.AreEqual(ad.A(j), bd.A(j)); + } + + Assert.AreEqual(ad.B, bd.B); + + for (int j = 0; j < 2; ++j) + { + Assert.AreEqual(ad.C(j), bd.C(j)); + } + + for (int j = 0; j < 2; ++j) + { + Assert.AreEqual(ad.D(j), bd.D(j)); + } + } + + Assert.AreEqual(a.A.Value.E, b.A.Value.E); + + for (int i = 0; i < 2; ++i) + { + Assert.AreEqual(a.A.Value.F(i), b.A.Value.F(i)); + } + } + + private void TestObjectAPI(ArrayTable a) + { + var b = a.UnPack(); + AreEqual(a, b); + + var fbb = new FlatBufferBuilder(1); + fbb.Finish(ArrayTable.Pack(fbb, b).Value); + var c = ArrayTable.GetRootAsArrayTable(fbb.DataBuffer); + AreEqual(a, c); + + var jsonText = b.SerializeToJson(); + var d = ArrayTableT.DeserializeFromJson(jsonText); + AreEqual(a, d); + + var fbBuffer = b.SerializeToBinary(); + Assert.IsTrue(ArrayTable.ArrayTableBufferHasIdentifier(new ByteBuffer(fbBuffer))); + var e = ArrayTableT.DeserializeFromBinary(fbBuffer); + AreEqual(a, e); + } + + private void AreEqual(Movie a, MovieT b) + { + Assert.AreEqual(a.MainCharacterType, b.MainCharacter.Type); + Assert.AreEqual(a.MainCharacter().Value.HairLength, b.MainCharacter.AsRapunzel().HairLength); + + Assert.AreEqual(a.CharactersLength, b.Characters.Count); + Assert.AreEqual(a.CharactersType(0), b.Characters[0].Type); + Assert.AreEqual(a.Characters(0).Value.SwordAttackDamage, b.Characters[0].AsMuLan().SwordAttackDamage); + Assert.AreEqual(a.CharactersType(1), b.Characters[1].Type); + Assert.AreEqual(a.Characters(1).Value.BooksRead, b.Characters[1].AsBelle().BooksRead); + Assert.AreEqual(a.CharactersType(2), b.Characters[2].Type); + Assert.AreEqual(a.CharactersAsString(2), b.Characters[2].AsOther()); + } + + private void AreEqual(Movie a, Movie b) + { + Assert.AreEqual(a.MainCharacterType, b.MainCharacterType); + Assert.AreEqual(a.MainCharacter().Value.HairLength, b.MainCharacter().Value.HairLength); + + Assert.AreEqual(a.CharactersLength, b.CharactersLength); + Assert.AreEqual(a.CharactersType(0), b.CharactersType(0)); + Assert.AreEqual(a.Characters(0).Value.SwordAttackDamage, b.Characters(0).Value.SwordAttackDamage); + Assert.AreEqual(a.CharactersType(1), b.CharactersType(1)); + Assert.AreEqual(a.Characters(1).Value.BooksRead, b.Characters(1).Value.BooksRead); + Assert.AreEqual(a.CharactersType(2), b.CharactersType(2)); + Assert.AreEqual(a.CharactersAsString(2), b.CharactersAsString(2)); + } + + private void TestObjectAPI(Movie a) + { + var b = a.UnPack(); + AreEqual(a, b); + + var fbb = new FlatBufferBuilder(1); + fbb.Finish(Movie.Pack(fbb, b).Value); + var c = Movie.GetRootAsMovie(fbb.DataBuffer); + AreEqual(a, c); + + var jsonText = b.SerializeToJson(); + var d = MovieT.DeserializeFromJson(jsonText); + AreEqual(a, d); + + var fbBuffer = b.SerializeToBinary(); + Assert.IsTrue(Movie.MovieBufferHasIdentifier(new ByteBuffer(fbBuffer))); + var e = MovieT.DeserializeFromBinary(fbBuffer); + AreEqual(a, e); + } + + // For use in TestParallelAccess test case. + static private int _comparisons = 0; + static private int _failures = 0; + static private void KeepComparing(Monster mon, int count, float floatValue, double doubleValue) + { + int i = 0; + while (++i <= count) + { + Interlocked.Add(ref _comparisons, 1); + if(mon.Pos.Value.Test1 != doubleValue || mon.Pos.Value.Z != floatValue) { + Interlocked.Add(ref _failures, 1); + } + } + } + + [FlatBuffersTestMethod] + public void TestParallelAccess() { + // Tests that reading from a flatbuffer over multiple threads is thread-safe in regard to double and float + // values, since they previously were non-thread safe + const float floatValue = 3.141592F; + const double doubleValue = 1.618033988; + + var fbb = new FlatBufferBuilder(1); + var str = fbb.CreateString("ParallelTest"); + Monster.StartMonster(fbb); + Monster.AddPos(fbb, Vec3.CreateVec3(fbb, 1.0f, 2.0f, floatValue, doubleValue, + Color.Green, (short)5, (sbyte)6)); + + Monster.AddName(fbb, str); + Monster.FinishMonsterBuffer(fbb, Monster.EndMonster(fbb)); + + var mon = Monster.GetRootAsMonster(fbb.DataBuffer); + + var pos = mon.Pos.Value; + Assert.AreEqual(pos.Test1, doubleValue); + Assert.AreEqual(pos.Z, floatValue); + + const int thread_count = 10; + const int reps = 1000000; + + // Need to use raw Threads since Tasks are not supported in .NET 3.5 + Thread[] threads = new Thread[thread_count]; + for(int i = 0; i < thread_count; i++) { + threads[i] = new Thread(() => KeepComparing(mon, reps, floatValue, doubleValue)); + } + for(int i = 0; i < thread_count; i++) { + threads[i].Start(); + } + for(int i = 0; i < thread_count; i++) { + threads[i].Join(); + } + + // Make sure the threads actually did the comparisons. + Assert.AreEqual(thread_count * reps, _comparisons); + + // Make sure we never read the values incorrectly. + Assert.AreEqual(0, _failures); + } + + [FlatBuffersTestMethod] + public void TestScalarOptional_EmptyBuffer() { + var fbb = new FlatBufferBuilder(1); + ScalarStuff.StartScalarStuff(fbb); + var offset = ScalarStuff.EndScalarStuff(fbb); + ScalarStuff.FinishScalarStuffBuffer(fbb, offset); + + ScalarStuff scalarStuff = ScalarStuff.GetRootAsScalarStuff(fbb.DataBuffer); + Assert.AreEqual((sbyte)0, scalarStuff.JustI8); + Assert.AreEqual(null, scalarStuff.MaybeI8); + Assert.AreEqual((sbyte)42, scalarStuff.DefaultI8); + Assert.AreEqual((byte)0, scalarStuff.JustU8); + Assert.AreEqual(null, scalarStuff.MaybeU8); + Assert.AreEqual((byte)42, scalarStuff.DefaultU8); + + Assert.AreEqual((short)0, scalarStuff.JustI16); + Assert.AreEqual(null, scalarStuff.MaybeI16); + Assert.AreEqual((short)42, scalarStuff.DefaultI16); + Assert.AreEqual((ushort)0, scalarStuff.JustU16); + Assert.AreEqual(null, scalarStuff.MaybeU16); + Assert.AreEqual((ushort)42, scalarStuff.DefaultU16); + + Assert.AreEqual((int)0, scalarStuff.JustI32); + Assert.AreEqual(null, scalarStuff.MaybeI32); + Assert.AreEqual((int)42, scalarStuff.DefaultI32); + Assert.AreEqual((uint)0, scalarStuff.JustU32); + Assert.AreEqual(null, scalarStuff.MaybeU32); + Assert.AreEqual((uint)42, scalarStuff.DefaultU32); + + Assert.AreEqual((long)0, scalarStuff.JustI64); + Assert.AreEqual(null, scalarStuff.MaybeI64); + Assert.AreEqual((long)42, scalarStuff.DefaultI64); + Assert.AreEqual((ulong)0, scalarStuff.JustU64); + Assert.AreEqual(null, scalarStuff.MaybeU64); + Assert.AreEqual((ulong)42, scalarStuff.DefaultU64); + + Assert.AreEqual((float)0.0F, scalarStuff.JustF32); + Assert.AreEqual(null, scalarStuff.MaybeF32); + Assert.AreEqual((float)42.0F, scalarStuff.DefaultF32); + + Assert.AreEqual((double)0.0, scalarStuff.JustF64); + Assert.AreEqual(null, scalarStuff.MaybeF64); + Assert.AreEqual((double)42.0, scalarStuff.DefaultF64); + + Assert.AreEqual(false, scalarStuff.JustBool); + Assert.AreEqual(null, scalarStuff.MaybeBool); + Assert.AreEqual(true, scalarStuff.DefaultBool); + + Assert.AreEqual(OptionalByte.None, scalarStuff.JustEnum); + Assert.AreEqual(null, scalarStuff.MaybeEnum); + Assert.AreEqual(OptionalByte.One, scalarStuff.DefaultEnum); + } + + [FlatBuffersTestMethod] + public void TestScalarOptional_Construction() { + var fbb = new FlatBufferBuilder(1); + ScalarStuff.StartScalarStuff(fbb); + ScalarStuff.AddJustI8(fbb, 5); + ScalarStuff.AddMaybeI8(fbb, 5); + ScalarStuff.AddDefaultI8(fbb, 5); + ScalarStuff.AddJustU8(fbb, 6); + ScalarStuff.AddMaybeU8(fbb, 6); + ScalarStuff.AddDefaultU8(fbb, 6); + + ScalarStuff.AddJustI16(fbb, 7); + ScalarStuff.AddMaybeI16(fbb, 7); + ScalarStuff.AddDefaultI16(fbb, 7); + ScalarStuff.AddJustU16(fbb, 8); + ScalarStuff.AddMaybeU16(fbb, 8); + ScalarStuff.AddDefaultU16(fbb, 8); + + ScalarStuff.AddJustI32(fbb, 9); + ScalarStuff.AddMaybeI32(fbb, 9); + ScalarStuff.AddDefaultI32(fbb, 9); + ScalarStuff.AddJustU32(fbb, 10); + ScalarStuff.AddMaybeU32(fbb, 10); + ScalarStuff.AddDefaultU32(fbb, 10); + + ScalarStuff.AddJustI64(fbb, 11); + ScalarStuff.AddMaybeI64(fbb, 11); + ScalarStuff.AddDefaultI64(fbb, 11); + ScalarStuff.AddJustU64(fbb, 12); + ScalarStuff.AddMaybeU64(fbb, 12); + ScalarStuff.AddDefaultU64(fbb, 12); + + ScalarStuff.AddJustF32(fbb, 13.0f); + ScalarStuff.AddMaybeF32(fbb, 13.0f); + ScalarStuff.AddDefaultF32(fbb, 13.0f); + ScalarStuff.AddJustF64(fbb, 14.0); + ScalarStuff.AddMaybeF64(fbb, 14.0); + ScalarStuff.AddDefaultF64(fbb, 14.0); + + ScalarStuff.AddJustBool(fbb, true); + ScalarStuff.AddMaybeBool(fbb, true); + ScalarStuff.AddDefaultBool(fbb, false); // note this is the opposite + + ScalarStuff.AddJustEnum(fbb, OptionalByte.Two); + ScalarStuff.AddMaybeEnum(fbb, OptionalByte.Two); + ScalarStuff.AddDefaultEnum(fbb, OptionalByte.Two); + + var offset = ScalarStuff.EndScalarStuff(fbb); + ScalarStuff.FinishScalarStuffBuffer(fbb, offset); + + ScalarStuff scalarStuff = ScalarStuff.GetRootAsScalarStuff(fbb.DataBuffer); + Assert.AreEqual((sbyte)5, scalarStuff.JustI8); + Assert.AreEqual((sbyte)5, scalarStuff.MaybeI8); + Assert.AreEqual((sbyte)5, scalarStuff.DefaultI8); + Assert.AreEqual((byte)6, scalarStuff.JustU8); + Assert.AreEqual((byte)6, scalarStuff.MaybeU8); + Assert.AreEqual((byte)6, scalarStuff.DefaultU8); + + Assert.AreEqual((short)7, scalarStuff.JustI16); + Assert.AreEqual((short)7, scalarStuff.MaybeI16); + Assert.AreEqual((short)7, scalarStuff.DefaultI16); + Assert.AreEqual((ushort)8, scalarStuff.JustU16); + Assert.AreEqual((ushort)8, scalarStuff.MaybeU16); + Assert.AreEqual((ushort)8, scalarStuff.DefaultU16); + + Assert.AreEqual((int)9, scalarStuff.JustI32); + Assert.AreEqual((int)9, scalarStuff.MaybeI32); + Assert.AreEqual((int)9, scalarStuff.DefaultI32); + Assert.AreEqual((uint)10, scalarStuff.JustU32); + Assert.AreEqual((uint)10, scalarStuff.MaybeU32); + Assert.AreEqual((uint)10, scalarStuff.DefaultU32); + + Assert.AreEqual((long)11, scalarStuff.JustI64); + Assert.AreEqual((long)11, scalarStuff.MaybeI64); + Assert.AreEqual((long)11, scalarStuff.DefaultI64); + Assert.AreEqual((ulong)12, scalarStuff.JustU64); + Assert.AreEqual((ulong)12, scalarStuff.MaybeU64); + Assert.AreEqual((ulong)12, scalarStuff.DefaultU64); + + Assert.AreEqual((float)13.0F, scalarStuff.JustF32); + Assert.AreEqual((float)13.0F, scalarStuff.MaybeF32); + Assert.AreEqual((float)13.0F, scalarStuff.DefaultF32); + + Assert.AreEqual((double)14.0, scalarStuff.JustF64); + Assert.AreEqual((double)14.0, scalarStuff.MaybeF64); + Assert.AreEqual((double)14.0, scalarStuff.DefaultF64); + + Assert.AreEqual(true, scalarStuff.JustBool); + Assert.AreEqual(true, scalarStuff.MaybeBool); + Assert.AreEqual(false, scalarStuff.DefaultBool); + + Assert.AreEqual(OptionalByte.Two, scalarStuff.JustEnum); + Assert.AreEqual(OptionalByte.Two, scalarStuff.MaybeEnum); + Assert.AreEqual(OptionalByte.Two, scalarStuff.DefaultEnum); + } + + [FlatBuffersTestMethod] + public void TestScalarOptional_Construction_CreatorMethod() { + var fbb = new FlatBufferBuilder(1); + + var offset = ScalarStuff.CreateScalarStuff(fbb,5,5,5,6,6,6,7,7,7, + 8,8,8,9,9,9,10,10,10,11,11,11,12,12,12,13.0f,13.0f,13.0f,14.0, + 14.0,14.0,true,true,false,OptionalByte.Two,OptionalByte.Two, + OptionalByte.Two); + ScalarStuff.FinishScalarStuffBuffer(fbb, offset); + + ScalarStuff scalarStuff = ScalarStuff.GetRootAsScalarStuff(fbb.DataBuffer); + Assert.AreEqual((sbyte)5, scalarStuff.JustI8); + Assert.AreEqual((sbyte)5, scalarStuff.MaybeI8); + Assert.AreEqual((sbyte)5, scalarStuff.DefaultI8); + Assert.AreEqual((byte)6, scalarStuff.JustU8); + Assert.AreEqual((byte)6, scalarStuff.MaybeU8); + Assert.AreEqual((byte)6, scalarStuff.DefaultU8); + + Assert.AreEqual((short)7, scalarStuff.JustI16); + Assert.AreEqual((short)7, scalarStuff.MaybeI16); + Assert.AreEqual((short)7, scalarStuff.DefaultI16); + Assert.AreEqual((ushort)8, scalarStuff.JustU16); + Assert.AreEqual((ushort)8, scalarStuff.MaybeU16); + Assert.AreEqual((ushort)8, scalarStuff.DefaultU16); + + Assert.AreEqual((int)9, scalarStuff.JustI32); + Assert.AreEqual((int)9, scalarStuff.MaybeI32); + Assert.AreEqual((int)9, scalarStuff.DefaultI32); + Assert.AreEqual((uint)10, scalarStuff.JustU32); + Assert.AreEqual((uint)10, scalarStuff.MaybeU32); + Assert.AreEqual((uint)10, scalarStuff.DefaultU32); + + Assert.AreEqual((long)11, scalarStuff.JustI64); + Assert.AreEqual((long)11, scalarStuff.MaybeI64); + Assert.AreEqual((long)11, scalarStuff.DefaultI64); + Assert.AreEqual((ulong)12, scalarStuff.JustU64); + Assert.AreEqual((ulong)12, scalarStuff.MaybeU64); + Assert.AreEqual((ulong)12, scalarStuff.DefaultU64); + + Assert.AreEqual((float)13.0F, scalarStuff.JustF32); + Assert.AreEqual((float)13.0F, scalarStuff.MaybeF32); + Assert.AreEqual((float)13.0F, scalarStuff.DefaultF32); + + Assert.AreEqual((double)14.0, scalarStuff.JustF64); + Assert.AreEqual((double)14.0, scalarStuff.MaybeF64); + Assert.AreEqual((double)14.0, scalarStuff.DefaultF64); + + Assert.AreEqual(true, scalarStuff.JustBool); + Assert.AreEqual(true, scalarStuff.MaybeBool); + Assert.AreEqual(false, scalarStuff.DefaultBool); + + Assert.AreEqual(OptionalByte.Two, scalarStuff.JustEnum); + Assert.AreEqual(OptionalByte.Two, scalarStuff.MaybeEnum); + Assert.AreEqual(OptionalByte.Two, scalarStuff.DefaultEnum); + } + + + [FlatBuffersTestMethod] + public void TestKeywordEscaping() { + Assert.AreEqual((int)KeywordTest.@public.NONE, 0); + + Assert.AreEqual((int)KeywordTest.ABC.@void, 0); + Assert.AreEqual((int)KeywordTest.ABC.where, 1); + Assert.AreEqual((int)KeywordTest.ABC.@stackalloc, 2); + + var fbb = new FlatBufferBuilder(1); + var offset = KeywordsInTable.CreateKeywordsInTable( + fbb, KeywordTest.ABC.@stackalloc, KeywordTest.@public.NONE); + fbb.Finish(offset.Value); + + KeywordsInTable keywordsInTable = + KeywordsInTable.GetRootAsKeywordsInTable(fbb.DataBuffer); + + Assert.AreEqual(keywordsInTable.Is, KeywordTest.ABC.@stackalloc); + Assert.AreEqual(keywordsInTable.Private, KeywordTest.@public.NONE); + } + + + [FlatBuffersTestMethod] + public void AddOptionalEnum_WhenPassNull_ShouldWorkProperly() { + var fbb = new FlatBufferBuilder(1); + ScalarStuff.StartScalarStuff(fbb); + ScalarStuff.AddMaybeEnum(fbb, null); + var offset = ScalarStuff.EndScalarStuff(fbb); + ScalarStuff.FinishScalarStuffBuffer(fbb, offset); + + ScalarStuff scalarStuff = ScalarStuff.GetRootAsScalarStuff(fbb.DataBuffer); + Assert.AreEqual(null, scalarStuff.MaybeEnum); + } + + + [FlatBuffersTestMethod] + public void SortKey_WithDefaultedValue_IsFindable() { + // This checks if using the `key` attribute that includes the + // default value (e.g., 0) is still searchable. This is a regression + // test for https://github.com/google/flatbuffers/issues/7380. + var fbb = new FlatBufferBuilder(1); + + // Create a vector of Stat objects, with Count being the key. + var stat_offsets = new Offset[4]; + for(ushort i = 0; i < stat_offsets.Length; i++) { + Stat.StartStat(fbb); + Stat.AddCount(fbb, i); + stat_offsets[stat_offsets.Length - 1 - i] = Stat.EndStat(fbb); + } + + // Ensure the sort works. + var sort = Stat.CreateSortedVectorOfStat(fbb, stat_offsets); + + // Create the monster with the sorted vector of Stat objects. + var str = fbb.CreateString("MyMonster"); + Monster.StartMonster(fbb); + Monster.AddName(fbb, str); + Monster.AddScalarKeySortedTables(fbb, sort); + fbb.Finish(Monster.EndMonster(fbb).Value); + + // Get the monster. + var monster = Monster.GetRootAsMonster(fbb.DataBuffer); + + // Ensure each key is findable. + for(ushort i =0 ; i < stat_offsets.Length; i++) { + Assert.IsTrue(monster.ScalarKeySortedTablesByKey(i) != null); + Assert.AreEqual(monster.ScalarKeySortedTablesByKey(i).Value.Count, i); + } + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs new file mode 100644 index 00000000000..fb6c4836be5 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersFuzzTests.cs @@ -0,0 +1,1052 @@ +/* + * Copyright 2015 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using Google.FlatBuffers; + +namespace Google.FlatBuffers.Test +{ + [FlatBuffersTestClass] + public class FlatBuffersFuzzTests + { + private readonly Lcg _lcg = new Lcg(); + + [FlatBuffersTestMethod] + public void TestObjects() + { + CheckObjects(11, 100); + } + + [FlatBuffersTestMethod] + public void TestNumbers() + { + var builder = new FlatBufferBuilder(1); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.AddBool(true); + Assert.ArrayEqual(new byte[] { 1 }, builder.DataBuffer.ToFullArray()); + builder.AddSbyte(-127); + Assert.ArrayEqual(new byte[] { 129, 1 }, builder.DataBuffer.ToFullArray()); + builder.AddByte(255); + Assert.ArrayEqual(new byte[] { 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // First pad + builder.AddShort(-32222); + Assert.ArrayEqual(new byte[] { 0, 0, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // Second pad + builder.AddUshort(0xFEEE); + Assert.ArrayEqual(new byte[] { 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // no pad + builder.AddInt(-53687092); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // third pad + builder.AddUint(0x98765432); + Assert.ArrayEqual(new byte[] { 0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1 }, builder.DataBuffer.ToFullArray()); // no pad + } + + [FlatBuffersTestMethod] + public void TestNumbers64() + { + var builder = new FlatBufferBuilder(1); + builder.AddUlong(0x1122334455667788); + Assert.ArrayEqual(new byte[] { 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, builder.DataBuffer.ToFullArray()); + + builder = new FlatBufferBuilder(1); + builder.AddLong(0x1122334455667788); + Assert.ArrayEqual(new byte[] { 0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11 }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestVector_1xUInt8() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(byte), 1, 1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.AddByte(1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.EndVector(); + Assert.ArrayEqual(new byte[] { 1, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestVector_2xUint8() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(byte), 2, 1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.AddByte(1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 1, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.AddByte(2); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 2, 1, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.EndVector(); + Assert.ArrayEqual(new byte[] { 2, 0, 0, 0, 2, 1, 0, 0 }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestVector_1xUInt16() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(ushort), 1, 1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.AddUshort(1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.EndVector(); + Assert.ArrayEqual(new byte[] { 1, 0, 0, 0, 1, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestVector_2xUInt16() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(ushort), 2, 1); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0 }, builder.DataBuffer.ToFullArray()); + builder.AddUshort(0xABCD); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0, 0, 0xCD, 0xAB }, builder.DataBuffer.ToFullArray()); + builder.AddUshort(0xDCBA); + Assert.ArrayEqual(new byte[] { 0, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB }, builder.DataBuffer.ToFullArray()); + builder.EndVector(); + Assert.ArrayEqual(new byte[] { 2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestCreateAsciiString() + { + var builder = new FlatBufferBuilder(1); + builder.CreateString("foo"); + Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.ToFullArray()); + + builder.CreateString("moop"); + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, // Padding to 32 bytes + 4, 0, 0, 0, + (byte)'m', (byte)'o', (byte)'o', (byte)'p', + 0, 0, 0, 0, // zero terminator with 3 byte pad + 3, 0, 0, 0, + (byte)'f', (byte)'o', (byte)'o', 0 + }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestCreateSharedAsciiString() + { + var builder = new FlatBufferBuilder(1); + builder.CreateSharedString("foo"); + Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.ToFullArray()); + + builder.CreateSharedString("foo"); + Assert.ArrayEqual(new byte[] { 3, 0, 0, 0, (byte)'f', (byte)'o', (byte)'o', 0 }, builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestCreateArbitarytring() + { + var builder = new FlatBufferBuilder(1); + builder.CreateString("\x01\x02\x03"); + Assert.ArrayEqual(new byte[] + { + 3, 0, 0, 0, + 0x01, 0x02, 0x03, 0 + }, builder.DataBuffer.ToFullArray()); // No padding + builder.CreateString("\x04\x05\x06\x07"); + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, // Padding to 32 bytes + 4, 0, 0, 0, + 0x04, 0x05, 0x06, 0x07, + 0, 0, 0, 0, // zero terminator with 3 byte pad + 3, 0, 0, 0, + 0x01, 0x02, 0x03, 0 + }, builder.DataBuffer.ToFullArray()); // No padding + } + + [FlatBuffersTestMethod] + public void TestEmptyVTable() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(0); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 4, 0, 4, 0, + 4, 0, 0, 0 + }, + builder.DataBuffer.ToFullArray()); + } + + [FlatBuffersTestMethod] + public void TestVTableWithOneBool() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(1); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.AddBool(0, true, false); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 0, 0, // padding to 16 bytes + 6, 0, // vtable bytes + 8, 0, // object length inc vtable offset + 7, 0, // start of bool value + 6, 0, 0, 0, // int32 offset for start of vtable + 0, 0, 0, // padding + 1, // value 0 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + var offset = 8; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart((uint)offset)); + // First field must be bool + Assert.IsTrue(verifier.VerifyField((uint)offset, 4, 1, 1, true)); + // Check Error: Second field + Assert.IsFalse(verifier.VerifyField((uint)offset, 6, 1, 1, true)); + // Check Error: First field too big alignment + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 1, 2, true)); + // Check Error: First size to big + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 2, 1, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithOneBool_DefaultValue() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(1); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.AddBool(0, false, false); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + // No padding. + 4, 0, // vtable bytes + 4, 0, // end of object from here + // entry 0 is not stored (trimmed end of vtable) + 4, 0, 0, 0, // int32 offset for start of vtable + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + var offset = 4; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart((uint)offset)); + // First field must be bool + Assert.IsTrue(verifier.VerifyField((uint)offset, 4, 1, 1, false)); + // Error Check: First field not present + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 1, 1, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithOneInt16() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(1); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.AddShort(0, 0x789A, 0); + int offset = builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 0, 0, // padding to 16 bytes + 6, 0, // vtable bytes + 8, 0, // object length inc vtable offset + 6, 0, // start of int16 value + 6, 0, 0, 0, // int32 offset for start of vtable + 0, 0, // padding + 0x9A, 0x78, //value 0 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + offset += builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart((uint)offset)); + // First field must be ushort + Assert.IsTrue(verifier.VerifyField((uint)offset, 4, 2, 2, true)); + // Check Error: Second field + Assert.IsFalse(verifier.VerifyField((uint)offset, 6, 2, 2, true)); + // Check Error: First field too big alignment + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 4, 2, true)); + // Check Error: First field size to big + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 2, 4, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithTwoInt16() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(2); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.AddShort(0, 0x3456, 0); + builder.AddShort(1, 0x789A, 0); + int offset = builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 8, 0, // vtable bytes + 8, 0, // object length inc vtable offset + 6, 0, // start of int16 value 0 + 4, 0, // start of int16 value 1 + 8, 0, 0, 0, // int32 offset for start of vtable + 0x9A, 0x78, // value 1 + 0x56, 0x34, // value 0 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + offset += builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart((uint)offset)); + // First field must be ushort + Assert.IsTrue(verifier.VerifyField((uint)offset, 4, 2, 2, true)); + // Check Error: Second field + Assert.IsTrue(verifier.VerifyField((uint)offset, 6, 2, 2, true)); + // Check Error: Second field too big alignment + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 4, 2, true)); + // Check Error: Second field size to big + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 2, 4, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithInt16AndBool() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(2); + Assert.ArrayEqual(new byte[] { 0 }, builder.DataBuffer.ToFullArray()); + builder.AddShort(0, 0x3456, 0); + builder.AddBool(1, true, false); + int offset = builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 8, 0, // vtable bytes + 8, 0, // object length inc vtable offset + 6, 0, // start of int16 value 0 + 5, 0, // start of bool value 1 + 8, 0, 0, 0, // int32 offset for start of vtable + 0, 1, // padding + value 1 + 0x56, 0x34, // value 0 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + offset += builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart((uint)offset)); + // First field must be ushort + Assert.IsTrue(verifier.VerifyField((uint)offset, 4, 2, 2, true)); + // Check Error: Second field must be bool + Assert.IsTrue(verifier.VerifyField((uint)offset, 6, 1, 1, true)); + // Check Error: Second field too big alignment + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 4, 2, true)); + // Check Error: Second field size to big + Assert.IsFalse(verifier.VerifyField((uint)offset, 4, 2, 4, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithEmptyVector() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(byte), 0, 1); + var vecEnd = builder.EndVector(); + + builder.StartTable(1); + + builder.AddOffset(0, vecEnd.Value, 0); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, // Padding to 32 bytes + 6, 0, // vtable bytes + 8, 0, // object length inc vtable offset + 4, 0, // start of vector offset value 0 + 6, 0, 0, 0, // int32 offset for start of vtable + 4, 0, 0, 0, + 0, 0, 0, 0, + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = 20; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be vector with element size 1 + Assert.IsTrue(verifier.VerifyVectorOfData(checkOffset, 4, 1, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithEmptyVectorAndScalars() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(byte), 0, 1); + var vecEnd = builder.EndVector(); + + builder.StartTable(2); + builder.AddShort(0, 55, 0); + builder.AddOffset(1, vecEnd.Value, 0); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, // Padding to 32 bytes + 8, 0, // vtable bytes + 12, 0, // object length inc vtable offset + 10, 0, // offset to int16 value 0 + 4, 0, // start of vector offset value 1 + 8, 0, 0, 0, // int32 offset for start of vtable + 8, 0, 0, 0, // value 1 + 0, 0, 55, 0, // value 0 + 0, 0, 0, 0, // length of vector (not in sctruc) + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = 16; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be short + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 2, 2, true)); + // Second field must be vector with element size 1 + Assert.IsTrue(verifier.VerifyVectorOfData(checkOffset, 6, 2, true)); + } + + + [FlatBuffersTestMethod] + public void TestVTableWith_1xInt16_and_Vector_or_2xInt16() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(short), 2, 1); + builder.AddShort(0x1234); + builder.AddShort(0x5678); + var vecEnd = builder.EndVector(); + + builder.StartTable(2); + builder.AddOffset(1, vecEnd.Value, 0); + builder.AddShort(0, 55, 0); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, // Padding to 32 bytes + 8, 0, // vtable bytes + 12, 0, // object length + 6, 0, // start of value 0 from end of vtable + 8, 0, // start of value 1 from end of buffer + 8, 0, 0, 0, // int32 offset for start of vtable + 0, 0, 55, 0, // padding + value 0 + 4, 0, 0, 0, // position of vector from here + 2, 0, 0, 0, // length of vector + 0x78, 0x56, // vector value 0 + 0x34, 0x12, // vector value 1 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = 12; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // Second field must be vector with element size 2 + Assert.IsTrue(verifier.VerifyVectorOfData(checkOffset, 6, 2, true)); + // Check Error: Second field with too big size + Assert.IsFalse(verifier.VerifyVectorOfData(checkOffset, 6, 4, true)); + // First field must be short + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 2, 2, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithAStruct_of_int8_int16_int32() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(1); + builder.Prep(4+4+4, 0); + builder.AddSbyte(55); + builder.Pad(3); + builder.AddShort(0x1234); + builder.Pad(2); + builder.AddInt(0x12345678); + var structStart = builder.Offset; + builder.AddStruct(0, structStart, 0); + builder.EndTable(); + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, // Padding to 32 bytes + 6, 0, // vtable bytes + 16, 0, // object length + 4, 0, // start of struct from here + 6, 0, 0, 0, // int32 offset for start of vtable + 0x78, 0x56, 0x34, 0x12, // struct value 2 + 0x00, 0x00, 0x34, 0x12, // struct value 1 + 0x00, 0x00, 0x00, 55, // struct value 0 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = 16; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 12, 4, true)); + // Check Error: First field with more than 12 bytes + Assert.IsFalse(verifier.VerifyField(checkOffset, 4, 16, 4, true)); + } + + + [FlatBuffersTestMethod] + public void TestVTableWithAVectorOf_2xStructOf_2xInt8() + { + var builder = new FlatBufferBuilder(1); + builder.StartVector(sizeof(byte)*2, 2, 1); + builder.AddByte(33); + builder.AddByte(44); + builder.AddByte(55); + builder.AddByte(66); + var vecEnd = builder.EndVector(); + + builder.StartTable(1); + builder.AddOffset(0, vecEnd.Value, 0); + builder.EndTable(); + + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, // Padding to 32 bytes + 6, 0, // vtable bytes + 8, 0, // object length + 4, 0, // offset of vector offset + 6, 0, 0, 0, // int32 offset for start of vtable + 4, 0, 0, 0, // Vector start offset + 2, 0, 0, 0, // Vector len + 66, // vector 1, 1 + 55, // vector 1, 0 + 44, // vector 0, 1 + 33, // vector 0, 0 + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = 16; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be vector with element size 2 + Assert.IsTrue(verifier.VerifyVectorOfData(checkOffset, 4, 2, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithSomeElements() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(2); + builder.AddByte(0, 33, 0); + builder.AddShort(1, 66, 0); + var off = builder.EndTable(); + builder.Finish(off); + + byte[] padded = new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, //Padding to 32 bytes + 12, 0, 0, 0, // root of table, pointing to vtable offset + 8, 0, // vtable bytes + 8, 0, // object length + 7, 0, // start of value 0 + 4, 0, // start of value 1 + 8, 0, 0, 0, // int32 offset for start of vtable + 66, 0, // value 1 + 0, 33, // value 0 + + }; + Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray()); + + // no padding in sized array + byte[] unpadded = new byte[padded.Length - 12]; + Buffer.BlockCopy(padded, 12, unpadded, 0, unpadded.Length); + Assert.ArrayEqual(unpadded, builder.DataBuffer.ToSizedArray()); + + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = builder.DataBuffer.GetUint(builder.DataBuffer.Position) + (uint)builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 1, 1, true)); + // Second field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 6, 2, 2, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithStrings() + { + var builder = new FlatBufferBuilder(64); + var str1 = builder.CreateString("foo"); + var str2 = builder.CreateString("foobar"); + builder.StartTable(2); + builder.AddOffset(0, str1.Value, 0); + builder.AddOffset(1, str2.Value, 0); + var off = builder.EndTable(); + builder.Finish(off); + + byte[] padded = new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, //Padding to 32 bytes + 12, 0, 0, 0, // root of table, pointing to vtable offset + 8, 0, // vtable bytes + 12, 0, // object length + 8, 0, // start of value 0 + 4, 0, // start of value 1 + 8, 0, 0, 0, // int32 offset for start of vtable + 8, 0, 0, 0, // pointer to string + 16, 0, 0, 0, // pointer to string + 6, 0, 0, 0, // length of string + 102, 111, 111, 98, 97, 114, 0, 0, // "foobar" + padding + 3, 0, 0, 0, // length of string + 102, 111, 111, 0 // "bar" + }; + Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray()); + + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = builder.DataBuffer.GetUint(builder.DataBuffer.Position) + (uint)builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field string check + Assert.IsTrue(verifier.VerifyString(checkOffset, 4, true)); + // Second field string check + Assert.IsTrue(verifier.VerifyString(checkOffset, 6, true)); + } + + [FlatBuffersTestMethod] + public void TestVTableWithVectorOfStrings() + { + var builder = new FlatBufferBuilder(64); + var str1 = builder.CreateString("foo"); + var str2 = builder.CreateString("foobar"); + builder.StartVector(sizeof(int), 2, 1); + builder.AddOffset(str1.Value); + builder.AddOffset(str2.Value); + var vec = builder.EndVector(); + builder.StartTable(1); + builder.AddOffset(0, vec.Value, 0); + var off = builder.EndTable(); + builder.Finish(off); + + byte[] padded = new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, //Padding to 32 bytes + 12, 0, 0, 0, // root of table, pointing to vtable offset + 0, 0, // padding + 6, 0, // vtable bytes + 8, 0, // object length + 4, 0, // start of value 0 + 6, 0, 0, 0, // int32 offset for start of vtable + 4, 0, 0, 0, // pointer to vector + 2, 0, 0, 0, // length of vector + 8, 0, 0, 0, // int32 offset to string 1 + 16, 0, 0, 0, // int32 offset to string 2 + 6, 0, 0, 0, // length of string + 102, 111, 111, 98, 97, 114, 0, 0, // "foobar" + padding + 3, 0, 0, 0, // length of string + 102, 111, 111, 0 // "bar" + }; + Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray()); + + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = builder.DataBuffer.GetUint(builder.DataBuffer.Position) + (uint)builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field string check + Assert.IsTrue(verifier.VerifyVectorOfStrings(checkOffset, 4, true)); + } + + [FlatBuffersTestMethod] + public void TestTwoFinishTable() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(2); + builder.AddByte(0, 33, 0); + builder.AddByte(1, 44, 0); + var off0 = builder.EndTable(); + builder.Finish(off0); + + builder.StartTable(3); + builder.AddByte(0, 55, 0); + builder.AddByte(1, 66, 0); + builder.AddByte(2, 77, 0); + var off1 = builder.EndTable(); + builder.Finish(off1); + + Assert.ArrayEqual(new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, // padding to 64 bytes + 16, 0, 0, 0, // root of table, pointing to vtable offset (obj1) + 0, 0, // padding + + 10, 0, // vtable bytes + 8, 0, // object length + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 5, 0, // start of value 2 + 10, 0, 0, 0, // int32 offset for start of vtable + 0, // pad + 77, // values 2, 1, 0 + 66, + 55, + + 12, 0, 0, 0, // root of table, pointing to vtable offset (obj0) + 8, 0, // vtable bytes + 8, 0, // object length + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 8, 0, 0, 0, // int32 offset for start of vtable + 0, 0, // pad + 44, // value 1, 0 + 33, + }, + builder.DataBuffer.ToFullArray()); + + // check obj1 + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = builder.DataBuffer.GetUint(builder.DataBuffer.Position) + (uint)builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 1, 1, true)); + // Second field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 6, 1, 1, true)); + // Third field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 8, 1, 1, true)); + // Check Error: 4. field did not exist + Assert.IsFalse(verifier.VerifyField(checkOffset, 10, 1, 1, true)); + + // check obj0 + checkOffset = 56; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 1, 1, true)); + // Second field must be a struct with 12 bytes + Assert.IsTrue(verifier.VerifyField(checkOffset, 6, 1, 1, true)); + // Check Error: 3. field did not exist + Assert.IsFalse(verifier.VerifyField(checkOffset, 8, 1, 1, true)); + // Check Error: 4. field did not exist + Assert.IsFalse(verifier.VerifyField(checkOffset, 10, 1, 1, true)); + } + + [FlatBuffersTestMethod] + public void TestBunchOfBools() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(8); + for (var i = 0; i < 8; i++) + { + builder.AddBool(i, true, false); + } + var off = builder.EndTable(); + builder.Finish(off); + + byte[] padded = new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, // padding to 64 bytes + + 24, 0, 0, 0, // root of table, pointing to vtable offset (obj0) + 20, 0, // vtable bytes + 12, 0, // object length + 11, 0, // start of value 0 + 10, 0, // start of value 1 + 9, 0, // start of value 2 + 8, 0, // start of value 3 + 7, 0, // start of value 4 + 6, 0, // start of value 5 + 5, 0, // start of value 6 + 4, 0, // start of value 7 + + 20, 0, 0, 0, // int32 offset for start of vtable + + 1, 1, 1, 1, // values + 1, 1, 1, 1, + + }; + Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray()); + + // no padding in sized array + byte[] unpadded = new byte[padded.Length - 28]; + Buffer.BlockCopy(padded, 28, unpadded, 0, unpadded.Length); + Assert.ArrayEqual(unpadded, builder.DataBuffer.ToSizedArray()); + + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = builder.DataBuffer.GetUint(builder.DataBuffer.Position) + (uint)builder.DataBuffer.Position; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + for (var i = 0; i < 8; i++) + { + Assert.IsTrue(verifier.VerifyField(checkOffset, (short)(4 + i * 2), 1, 1, true)); + } + Assert.IsFalse(verifier.VerifyField(checkOffset, (short)(4 + 8 * 2), 1, 1, true)); + } + + [FlatBuffersTestMethod] + public void TestBunchOfBoolsSizePrefixed() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(8); + for (var i = 0; i < 8; i++) + { + builder.AddBool(i, true, false); + } + var off = builder.EndTable(); + builder.FinishSizePrefixed(off); + + byte[] padded = new byte[] + { + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, // padding to 64 bytes + + 36, 0, 0, 0, // size prefix + 24, 0, 0, 0, // root of table, pointing to vtable offset (obj0) + 20, 0, // vtable bytes + 12, 0, // object length + 11, 0, // start of value 0 + 10, 0, // start of value 1 + 9, 0, // start of value 2 + 8, 0, // start of value 3 + 7, 0, // start of value 4 + 6, 0, // start of value 5 + 5, 0, // start of value 6 + 4, 0, // start of value 7 + + 20, 0, 0, 0, // int32 offset for start of vtable + + 1, 1, 1, 1, // values + 1, 1, 1, 1, + + }; + Assert.ArrayEqual(padded, builder.DataBuffer.ToFullArray()); + + // no padding in sized array + byte[] unpadded = new byte[padded.Length - 24]; + Buffer.BlockCopy(padded, 24, unpadded, 0, unpadded.Length); + Assert.ArrayEqual(unpadded, builder.DataBuffer.ToSizedArray()); + } + + [FlatBuffersTestMethod] + public void TestWithFloat() + { + var builder = new FlatBufferBuilder(1); + builder.StartTable(1); + builder.AddFloat(0, 1, 0); + builder.EndTable(); + + + Assert.ArrayEqual(new byte[] + { + 0, 0, + 6, 0, // vtable bytes + 8, 0, // object length + 4, 0, // start of value 0 + 6, 0, 0, 0, // int32 offset for start of vtable + 0, 0, 128, 63, // value + + }, + builder.DataBuffer.ToFullArray()); + var verifier = new Verifier(builder.DataBuffer); + uint checkOffset = 8; + // table must be ok + Assert.IsTrue(verifier.VerifyTableStart(checkOffset)); + // First Field must be float + Assert.IsTrue(verifier.VerifyField(checkOffset, 4, 4, 4, true)); + // Check Error: First Field with to big size + Assert.IsFalse(verifier.VerifyField(checkOffset, 4, 8, 4, true)); + // Check Error: First Field with to big padding + Assert.IsFalse(verifier.VerifyField(checkOffset, 4, 4, 8, true)); + } + + private void CheckObjects(int fieldCount, int objectCount) + { + _lcg.Reset(); + + const int testValuesMax = 11; + + var builder = new FlatBufferBuilder(1); + + var objects = new int[objectCount]; + + for (var i = 0; i < objectCount; ++i) + { + builder.StartTable(fieldCount); + + for (var j = 0; j < fieldCount; ++j) + { + var fieldType = _lcg.Next()%testValuesMax; + + switch (fieldType) + { + case 0: + { + builder.AddBool(j, FuzzTestData.BoolValue, false); + break; + } + case 1: + { + builder.AddSbyte(j, FuzzTestData.Int8Value, 0); + break; + } + case 2: + { + builder.AddByte(j, FuzzTestData.UInt8Value, 0); + break; + } + case 3: + { + builder.AddShort(j, FuzzTestData.Int16Value, 0); + break; + } + case 4: + { + builder.AddUshort(j, FuzzTestData.UInt16Value, 0); + break; + } + case 5: + { + builder.AddInt(j, FuzzTestData.Int32Value, 0); + break; + } + case 6: + { + builder.AddUint(j, FuzzTestData.UInt32Value, 0); + break; + } + case 7: + { + builder.AddLong(j, FuzzTestData.Int64Value, 0); + break; + } + case 8: + { + builder.AddUlong(j, FuzzTestData.UInt64Value, 0); + break; + } + case 9: + { + builder.AddFloat(j, FuzzTestData.Float32Value, 0); + break; + } + case 10: + { + builder.AddDouble(j, FuzzTestData.Float64Value, 0); + break; + } + default: + throw new Exception("Unreachable"); + } + + } + + var offset = builder.EndTable(); + + // Store the object offset + objects[i] = offset; + } + + _lcg.Reset(); + + // Test all objects are readable and return expected values... + for (var i = 0; i < objectCount; ++i) + { + var table = new TestTable(builder.DataBuffer, builder.DataBuffer.Length - objects[i]); + + for (var j = 0; j < fieldCount; ++j) + { + var fieldType = _lcg.Next() % testValuesMax; + var fc = 2 + j; // 2 == VtableMetadataFields + var f = fc * 2; + + switch (fieldType) + { + case 0: + { + Assert.AreEqual(FuzzTestData.BoolValue, table.GetSlot(f, false)); + break; + } + case 1: + { + Assert.AreEqual(FuzzTestData.Int8Value, table.GetSlot(f, (sbyte)0)); + break; + } + case 2: + { + Assert.AreEqual(FuzzTestData.UInt8Value, table.GetSlot(f, (byte)0)); + break; + } + case 3: + { + Assert.AreEqual(FuzzTestData.Int16Value, table.GetSlot(f, (short)0)); + break; + } + case 4: + { + Assert.AreEqual(FuzzTestData.UInt16Value, table.GetSlot(f, (ushort)0)); + break; + } + case 5: + { + Assert.AreEqual(FuzzTestData.Int32Value, table.GetSlot(f, (int)0)); + break; + } + case 6: + { + Assert.AreEqual(FuzzTestData.UInt32Value, table.GetSlot(f, (uint)0)); + break; + } + case 7: + { + Assert.AreEqual(FuzzTestData.Int64Value, table.GetSlot(f, (long)0)); + break; + } + case 8: + { + Assert.AreEqual(FuzzTestData.UInt64Value, table.GetSlot(f, (ulong)0)); + break; + } + case 9: + { + Assert.AreEqual(FuzzTestData.Float32Value, table.GetSlot(f, (float)0)); + break; + } + case 10: + { + Assert.AreEqual(FuzzTestData.Float64Value, table.GetSlot(f, (double)0)); + break; + } + default: + throw new Exception("Unreachable"); + } + + } + + } + + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersTestClassAttribute.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersTestClassAttribute.cs new file mode 100644 index 00000000000..7ad7df60fe7 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersTestClassAttribute.cs @@ -0,0 +1,28 @@ +/* + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace Google.FlatBuffers.Test +{ + [AttributeUsage(AttributeTargets.Class)] + public class FlatBuffersTestClassAttribute : Attribute + { + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersTestMethodAttribute.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersTestMethodAttribute.cs new file mode 100644 index 00000000000..4276b74ed66 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FlatBuffersTestMethodAttribute.cs @@ -0,0 +1,25 @@ +/* + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + + using System; + +namespace Google.FlatBuffers.Test +{ + [AttributeUsage(AttributeTargets.Method)] + public class FlatBuffersTestMethodAttribute : Attribute + { + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/FuzzTestData.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/FuzzTestData.cs new file mode 100644 index 00000000000..186e312da54 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/FuzzTestData.cs @@ -0,0 +1,38 @@ +/* + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; + +namespace Google.FlatBuffers.Test +{ + internal static class FuzzTestData + { + private static readonly byte[] _overflowInt32 = new byte[] {0x83, 0x33, 0x33, 0x33}; + private static readonly byte[] _overflowInt64 = new byte[] { 0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44 }; + + public static readonly bool BoolValue = true; + public static readonly sbyte Int8Value = -127; // 0x81 + public static readonly byte UInt8Value = 255; // 0xFF + public static readonly short Int16Value = -32222; // 0x8222; + public static readonly ushort UInt16Value = 65262; // 0xFEEE + public static readonly int Int32Value = BitConverter.ToInt32(_overflowInt32, 0); + public static readonly uint UInt32Value = 0xFDDDDDDD; + public static readonly long Int64Value = BitConverter.ToInt64(_overflowInt64, 0); + public static readonly ulong UInt64Value = 0xFCCCCCCCCCCCCCCC; + public static readonly float Float32Value = 3.14159f; + public static readonly double Float64Value = 3.14159265359; + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/Lcg.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/Lcg.cs new file mode 100644 index 00000000000..c6322d51b09 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/Lcg.cs @@ -0,0 +1,42 @@ +/* + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Google.FlatBuffers.Test +{ + /// + /// Lcg Pseudo RNG + /// + internal sealed class Lcg + { + private const uint InitialValue = 10000; + private uint _state; + + public Lcg() + { + _state = InitialValue; + } + + public uint Next() + { + return (_state = 69069 * _state + 362437); + } + + public void Reset() + { + _state = InitialValue; + } + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/NetTest.bat b/third_party/flatbuffers/tests/FlatBuffers.Test/NetTest.bat new file mode 100644 index 00000000000..a7097a509e1 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/NetTest.bat @@ -0,0 +1,20 @@ +@echo off +@REM Builds a .NET solution file, adds the project, builds it +@REM and executes it. Cleans up all generated files and directories. + +set TEMP_BIN=.tmp + +@REM Run the .NET tests +set CORE_FILE=FlatBuffers.Test +set CORE_PROJ_FILE=%CORE_FILE%.csproj +set CORE_SLN_FILE=%CORE_FILE%.sln +dotnet new sln --force --name %CORE_FILE% +dotnet sln %CORE_SLN_FILE% add %CORE_PROJ_FILE% +dotnet build -c Release -o %TEMP_BIN% -v quiet %CORE_PROJ_FILE% +%TEMP_BIN%\%CORE_FILE%.exe +del /f %CORE_SLN_FILE% + +@REM TODO(dbaileychess): Support the other configurations in NetTest.sh + +@REM remove the temp bin directory, with files (/S) and quietly (/Q) +RD /S /Q %TEMP_BIN% diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/NetTest.sh b/third_party/flatbuffers/tests/FlatBuffers.Test/NetTest.sh new file mode 100755 index 00000000000..f2f678674d5 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/NetTest.sh @@ -0,0 +1,36 @@ +#!/bin/sh + +PROJ_FILE=FlatBuffers.Test.csproj + +TEMP_DOTNET_DIR=.dotnet_tmp +TEMP_BIN=.tmp + +[ -d $TEMP_DOTNET_DIR ] || mkdir $TEMP_DOTNET_DIR + +[ -f dotnet-install.sh ] || curl -OL https://dot.net/v1/dotnet-install.sh + +./dotnet-install.sh --version latest --install-dir $TEMP_DOTNET_DIR + +DOTNET=$TEMP_DOTNET_DIR/dotnet + +$DOTNET new sln +$DOTNET sln add $PROJ_FILE +$DOTNET restore -r linux-x64 $PROJ_FILE + +# Testing with default options. +msbuild -property:Configuration=Release,OutputPath=$TEMP_BIN -verbosity:quiet $PROJ_FILE +$TEMP_BIN/FlatBuffers.Core.Test.exe +rm -fr $TEMP_BIN + +# Repeat with unsafe versions +msbuild -property:Configuration=Release,UnsafeByteBuffer=true,OutputPath=$TEMP_BIN -verbosity:quiet $PROJ_FILE +$TEMP_BIN/FlatBuffers.Core.Test.exe +rm -fr $TEMP_BIN + +# Repeat with SpanT versions +msbuild -property:Configuration=Release,EnableSpanT=true,OutputPath=$TEMP_BIN -verbosity:quiet $PROJ_FILE +$TEMP_BIN/FlatBuffers.Core.Test.exe +rm -fr $TEMP_BIN + +rm FlatBuffers.Test.sln +rm -rf obj diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/Program.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/Program.cs new file mode 100644 index 00000000000..cd04d25b606 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/Program.cs @@ -0,0 +1,68 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System; +using System.Collections.Generic; +using System.Linq; +using System.Reflection; + +namespace Google.FlatBuffers.Test +{ + static class Program + { + public static int Main(string[] args) + { + var testResults = new List(); + + var testClasses = Assembly.GetExecutingAssembly().GetExportedTypes() + .Where(t => t.IsClass && t.GetCustomAttributes(typeof (FlatBuffersTestClassAttribute), false).Length > 0); + + foreach (var testClass in testClasses) + { + var methods = testClass.GetMethods(BindingFlags.Public | + BindingFlags.Instance) + .Where(m => m.GetCustomAttributes(typeof(FlatBuffersTestMethodAttribute), false).Length > 0); + + var inst = Activator.CreateInstance(testClass); + + foreach (var method in methods) + { + try + { + method.Invoke(inst, new object[] { }); + testResults.Add(true); + } + catch (Exception ex) + { + Console.WriteLine("{0}: FAILED when invoking {1} with error {2}", + testClass.Name ,method.Name, ex.GetBaseException()); + testResults.Add(false); + } + } + } + + var failedCount = testResults.Count(i => i == false); + + Console.WriteLine("{0} tests run, {1} failed", testResults.Count, failedCount); + + if (failedCount > 0) + { + return -1; + } + return 0; + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/Properties/AssemblyInfo.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/Properties/AssemblyInfo.cs new file mode 100644 index 00000000000..2e33f08280b --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/Properties/AssemblyInfo.cs @@ -0,0 +1,52 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; + +// General Information about an assembly is controlled through the following +// set of attributes. Change these attribute values to modify the information +// associated with an assembly. +[assembly: AssemblyTitle("FlatBuffers.Test")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("FlatBuffers.Test")] +[assembly: AssemblyCopyright("Copyright (c) 2014 Google Inc")] +[assembly: AssemblyTrademark("")] +[assembly: AssemblyCulture("")] + +// Setting ComVisible to false makes the types in this assembly not visible +// to COM components. If you need to access a type in this assembly from +// COM, set the ComVisible attribute to true on that type. +[assembly: ComVisible(false)] + +// The following GUID is for the ID of the typelib if this project is exposed to COM +[assembly: Guid("a1d58a51-3e74-4ae9-aac7-5a399c9eed1a")] + +// Version information for an assembly consists of the following four values: +// +// Major Version +// Minor Version +// Build Number +// Revision +// +// You can specify all the values or you can default the Build and Revision Numbers +// by using the '*' as shown below: +// [assembly: AssemblyVersion("1.0.*")] +[assembly: AssemblyVersion("1.0.0.0")] +[assembly: AssemblyFileVersion("1.0.0.0")] diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/README.md b/third_party/flatbuffers/tests/FlatBuffers.Test/README.md new file mode 100644 index 00000000000..41b6983ea20 --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/README.md @@ -0,0 +1,38 @@ +# .NET Tests + +## Running on Linux + +### Prerequisites +To run the tests on a Linux a few prerequisites are needed: + +1) mono +2) msbuild + +### Running + +To run the tests: + +``` +./NetTest.sh +``` + +This will download the .NET installer and core SDK if those are not already +installed. Then it will build the tests using `msbuild` and run the resulting +test binary with `mono`. + +After running the tests, the downloaded .NET installer and SDK are *not* removed +as they can be reused in subsequent invocations. The files are ignored by git by +default, and can remain in the working directory. + +### Cleaning + +If you want to clean up the downloaded .NET installer and SDK, run: + +``` +./clean.sh +``` + +This will wipe away the downloaded files and directories. Those will be +automatically re-downloaded when running `NetTest.sh`. + + diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/TestTable.cs b/third_party/flatbuffers/tests/FlatBuffers.Test/TestTable.cs new file mode 100644 index 00000000000..659ac8f6ecf --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/TestTable.cs @@ -0,0 +1,152 @@ +/* + * Copyright 2016 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +namespace Google.FlatBuffers.Test +{ + /// + /// A test Table object that gives easy access to the slot data + /// + internal struct TestTable + { + Table t; + + public TestTable(ByteBuffer bb, int pos) + { + t = new Table(pos, bb); + } + + public bool GetSlot(int slot, bool def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetSbyte(t.bb_pos + off) != 0; + } + + public sbyte GetSlot(int slot, sbyte def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetSbyte(t.bb_pos + off); + } + + public byte GetSlot(int slot, byte def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.Get(t.bb_pos + off); + } + + public short GetSlot(int slot, short def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetShort(t.bb_pos + off); + } + + public ushort GetSlot(int slot, ushort def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetUshort(t.bb_pos + off); + } + + public int GetSlot(int slot, int def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetInt(t.bb_pos + off); + } + + public uint GetSlot(int slot, uint def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetUint(t.bb_pos + off); + } + + public long GetSlot(int slot, long def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetLong(t.bb_pos + off); + } + + public ulong GetSlot(int slot, ulong def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetUlong(t.bb_pos + off); + } + + public float GetSlot(int slot, float def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetFloat(t.bb_pos + off); + } + + public double GetSlot(int slot, double def) + { + var off = t.__offset(slot); + + if (off == 0) + { + return def; + } + return t.bb.GetDouble(t.bb_pos + off); + } + } +} diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/clean.sh b/third_party/flatbuffers/tests/FlatBuffers.Test/clean.sh new file mode 100755 index 00000000000..41f6a4a590d --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/clean.sh @@ -0,0 +1,10 @@ +#!/bin/sh + +# Remove files and directory that are needed to build and run the .NET tests. +# The script NetTest.sh installs these as needed. + +[ -d .dotnet_tmp ] && rm -rf .dotnet_tmp +[ -d packages ] && rm -rf packages +[ -d .tmp ] && rm -rf .tmp +[ -f nuget.exe ] && rm nuget.exe +[ -f dotnet-intall.sh ] && rm dotnet-install.sh diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/monsterdata_cstest.mon b/third_party/flatbuffers/tests/FlatBuffers.Test/monsterdata_cstest.mon new file mode 100644 index 00000000000..d18dc034792 Binary files /dev/null and b/third_party/flatbuffers/tests/FlatBuffers.Test/monsterdata_cstest.mon differ diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/monsterdata_cstest_sp.mon b/third_party/flatbuffers/tests/FlatBuffers.Test/monsterdata_cstest_sp.mon new file mode 100644 index 00000000000..da3c80353f5 Binary files /dev/null and b/third_party/flatbuffers/tests/FlatBuffers.Test/monsterdata_cstest_sp.mon differ diff --git a/third_party/flatbuffers/tests/FlatBuffers.Test/packages.config b/third_party/flatbuffers/tests/FlatBuffers.Test/packages.config new file mode 100644 index 00000000000..be414a394be --- /dev/null +++ b/third_party/flatbuffers/tests/FlatBuffers.Test/packages.config @@ -0,0 +1,4 @@ + + + + diff --git a/third_party/flatbuffers/tests/FromInclude.py b/third_party/flatbuffers/tests/FromInclude.py new file mode 100644 index 00000000000..dbfcbffe797 --- /dev/null +++ b/third_party/flatbuffers/tests/FromInclude.py @@ -0,0 +1,5 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: OtherNameSpace + +# NOTE FromInclude.py does not declare any structs or enums diff --git a/third_party/flatbuffers/tests/GoTest.sh b/third_party/flatbuffers/tests/GoTest.sh new file mode 100755 index 00000000000..b55cad5770c --- /dev/null +++ b/third_party/flatbuffers/tests/GoTest.sh @@ -0,0 +1,77 @@ +#!/bin/bash -eu +# +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +pushd "$(dirname $0)" >/dev/null +test_dir="$(pwd)" +go_path=${test_dir}/go_gen +go_src=${go_path}/src + +# Emit Go code for the example schemas in the test dir: +../flatc -g --gen-object-api -I include_test -o ${go_src} monster_test.fbs optional_scalars.fbs +../flatc -g --gen-object-api -I include_test/sub -o ${go_src} include_test/order.fbs +../flatc -g --gen-object-api -o ${go_src}/Pizza include_test/sub/no_namespace.fbs + +# Go requires a particular layout of files in order to link multiple packages. +# Copy flatbuffer Go files to their own package directories to compile the +# test binary: +mkdir -p ${go_src}/github.com/google/flatbuffers/go +mkdir -p ${go_src}/flatbuffers_test + +cp -a ../go/* ./go_gen/src/github.com/google/flatbuffers/go +cp -a ./go_test.go ./go_gen/src/flatbuffers_test/ + +# https://stackoverflow.com/a/63545857/7024978 +# We need to turn off go modules for this script +# to work. +go env -w GO111MODULE=off + +# Run tests with necessary flags. +# Developers may wish to see more detail by appending the verbosity flag +# -test.v to arguments for this command, as in: +# go -test -test.v ... +# Developers may also wish to run benchmarks, which may be achieved with the +# flag -test.bench and the wildcard regexp ".": +# go -test -test.bench=. ... +GOPATH=${go_path} go test flatbuffers_test \ + --coverpkg=github.com/google/flatbuffers/go \ + --cpp_data=${test_dir}/monsterdata_test.mon \ + --out_data=${test_dir}/monsterdata_go_wire.mon \ + --bench=. \ + --benchtime=3s \ + --fuzz=true \ + --fuzz_fields=4 \ + --fuzz_objects=10000 + +GO_TEST_RESULT=$? +rm -rf ${go_path}/{pkg,src} +if [[ $GO_TEST_RESULT == 0 ]]; then + echo "OK: Go tests passed." +else + echo "KO: Go tests failed." + exit 1 +fi + +NOT_FMT_FILES=$(gofmt -l .) +if [[ ${NOT_FMT_FILES} != "" ]]; then + echo "These files are not well gofmt'ed:" + echo + echo "${NOT_FMT_FILES}" + # enable this when enums are properly formated + # exit 1 +fi + +# Re-enable go modules when done tests +go env -w GO111MODULE=on diff --git a/third_party/flatbuffers/tests/KeywordTest/ABC.cs b/third_party/flatbuffers/tests/KeywordTest/ABC.cs new file mode 100644 index 00000000000..3d7ceff74d6 --- /dev/null +++ b/third_party/flatbuffers/tests/KeywordTest/ABC.cs @@ -0,0 +1,17 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace KeywordTest +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum ABC : int +{ + @void = 0, + where = 1, + @stackalloc = 2, +}; + + +} diff --git a/third_party/flatbuffers/tests/KeywordTest/KeywordsInTable.cs b/third_party/flatbuffers/tests/KeywordTest/KeywordsInTable.cs new file mode 100644 index 00000000000..2665341e893 --- /dev/null +++ b/third_party/flatbuffers/tests/KeywordTest/KeywordsInTable.cs @@ -0,0 +1,108 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace KeywordTest +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct KeywordsInTable : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static KeywordsInTable GetRootAsKeywordsInTable(ByteBuffer _bb) { return GetRootAsKeywordsInTable(_bb, new KeywordsInTable()); } + public static KeywordsInTable GetRootAsKeywordsInTable(ByteBuffer _bb, KeywordsInTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public KeywordsInTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public KeywordTest.ABC Is { get { int o = __p.__offset(4); return o != 0 ? (KeywordTest.ABC)__p.bb.GetInt(o + __p.bb_pos) : KeywordTest.ABC.@void; } } + public bool MutateIs(KeywordTest.ABC @is) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, (int)@is); return true; } else { return false; } } + public KeywordTest.@public Private { get { int o = __p.__offset(6); return o != 0 ? (KeywordTest.@public)__p.bb.GetInt(o + __p.bb_pos) : KeywordTest.@public.NONE; } } + public bool MutatePrivate(KeywordTest.@public @private) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, (int)@private); return true; } else { return false; } } + public int Type { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateType(int type) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, type); return true; } else { return false; } } + public bool Default { get { int o = __p.__offset(10); return o != 0 ? 0!=__p.bb.Get(o + __p.bb_pos) : (bool)false; } } + public bool MutateDefault(bool @default) { int o = __p.__offset(10); if (o != 0) { __p.bb.Put(o + __p.bb_pos, (byte)(@default ? 1 : 0)); return true; } else { return false; } } + + public static Offset CreateKeywordsInTable(FlatBufferBuilder builder, + KeywordTest.ABC @is = KeywordTest.ABC.@void, + KeywordTest.@public @private = KeywordTest.@public.NONE, + int type = 0, + bool @default = false) { + builder.StartTable(4); + KeywordsInTable.AddType(builder, type); + KeywordsInTable.AddPrivate(builder, @private); + KeywordsInTable.AddIs(builder, @is); + KeywordsInTable.AddDefault(builder, @default); + return KeywordsInTable.EndKeywordsInTable(builder); + } + + public static void StartKeywordsInTable(FlatBufferBuilder builder) { builder.StartTable(4); } + public static void AddIs(FlatBufferBuilder builder, KeywordTest.ABC @is) { builder.AddInt(0, (int)@is, 0); } + public static void AddPrivate(FlatBufferBuilder builder, KeywordTest.@public @private) { builder.AddInt(1, (int)@private, 0); } + public static void AddType(FlatBufferBuilder builder, int type) { builder.AddInt(2, type, 0); } + public static void AddDefault(FlatBufferBuilder builder, bool @default) { builder.AddBool(3, @default, false); } + public static Offset EndKeywordsInTable(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public KeywordsInTableT UnPack() { + var _o = new KeywordsInTableT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(KeywordsInTableT _o) { + _o.Is = this.Is; + _o.Private = this.Private; + _o.Type = this.Type; + _o.Default = this.Default; + } + public static Offset Pack(FlatBufferBuilder builder, KeywordsInTableT _o) { + if (_o == null) return default(Offset); + return CreateKeywordsInTable( + builder, + _o.Is, + _o.Private, + _o.Type, + _o.Default); + } +} + +public class KeywordsInTableT +{ + [Newtonsoft.Json.JsonProperty("is")] + public KeywordTest.ABC Is { get; set; } + [Newtonsoft.Json.JsonProperty("private")] + public KeywordTest.@public Private { get; set; } + [Newtonsoft.Json.JsonProperty("type")] + public int Type { get; set; } + [Newtonsoft.Json.JsonProperty("default")] + public bool Default { get; set; } + + public KeywordsInTableT() { + this.Is = KeywordTest.ABC.@void; + this.Private = KeywordTest.@public.NONE; + this.Type = 0; + this.Default = false; + } +} + + +static public class KeywordsInTableVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Is*/, 4 /*KeywordTest.ABC*/, 4, false) + && verifier.VerifyField(tablePos, 6 /*Private*/, 4 /*KeywordTest.@public*/, 4, false) + && verifier.VerifyField(tablePos, 8 /*Type*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 10 /*Default*/, 1 /*bool*/, 1, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/KeywordTest/KeywordsInUnion.cs b/third_party/flatbuffers/tests/KeywordTest/KeywordsInUnion.cs new file mode 100644 index 00000000000..3fccb13bef3 --- /dev/null +++ b/third_party/flatbuffers/tests/KeywordTest/KeywordsInUnion.cs @@ -0,0 +1,105 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace KeywordTest +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum KeywordsInUnion : byte +{ + NONE = 0, + @static = 1, + @internal = 2, +}; + +public class KeywordsInUnionUnion { + public KeywordsInUnion Type { get; set; } + public object Value { get; set; } + + public KeywordsInUnionUnion() { + this.Type = KeywordsInUnion.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public KeywordTest.KeywordsInTableT Asstatic() { return this.As(); } + public static KeywordsInUnionUnion Fromstatic(KeywordTest.KeywordsInTableT _static) { return new KeywordsInUnionUnion{ Type = KeywordsInUnion.@static, Value = _static }; } + public KeywordTest.KeywordsInTableT Asinternal() { return this.As(); } + public static KeywordsInUnionUnion Frominternal(KeywordTest.KeywordsInTableT _internal) { return new KeywordsInUnionUnion{ Type = KeywordsInUnion.@internal, Value = _internal }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, KeywordsInUnionUnion _o) { + switch (_o.Type) { + default: return 0; + case KeywordsInUnion.@static: return KeywordTest.KeywordsInTable.Pack(builder, _o.Asstatic()).Value; + case KeywordsInUnion.@internal: return KeywordTest.KeywordsInTable.Pack(builder, _o.Asinternal()).Value; + } + } +} + +public class KeywordsInUnionUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(KeywordsInUnionUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as KeywordsInUnionUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, KeywordsInUnionUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as KeywordsInUnionUnion, serializer); + } + } + public KeywordsInUnionUnion ReadJson(Newtonsoft.Json.JsonReader reader, KeywordsInUnionUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case KeywordsInUnion.@static: _o.Value = serializer.Deserialize(reader); break; + case KeywordsInUnion.@internal: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class KeywordsInUnionVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((KeywordsInUnion)typeId) + { + case KeywordsInUnion.@static: + result = KeywordTest.KeywordsInTableVerify.Verify(verifier, tablePos); + break; + case KeywordsInUnion.@internal: + result = KeywordTest.KeywordsInTableVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + + +} diff --git a/third_party/flatbuffers/tests/KeywordTest/Table2.cs b/third_party/flatbuffers/tests/KeywordTest/Table2.cs new file mode 100644 index 00000000000..aca39cb794e --- /dev/null +++ b/third_party/flatbuffers/tests/KeywordTest/Table2.cs @@ -0,0 +1,105 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace KeywordTest +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Table2 : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Table2 GetRootAsTable2(ByteBuffer _bb) { return GetRootAsTable2(_bb, new Table2()); } + public static Table2 GetRootAsTable2(ByteBuffer _bb, Table2 obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Table2 __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public KeywordTest.KeywordsInUnion TypeType { get { int o = __p.__offset(4); return o != 0 ? (KeywordTest.KeywordsInUnion)__p.bb.Get(o + __p.bb_pos) : KeywordTest.KeywordsInUnion.NONE; } } + public TTable? Type() where TTable : struct, IFlatbufferObject { int o = __p.__offset(6); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public KeywordTest.KeywordsInTable TypeAsstatic() { return Type().Value; } + public KeywordTest.KeywordsInTable TypeAsinternal() { return Type().Value; } + + public static Offset CreateTable2(FlatBufferBuilder builder, + KeywordTest.KeywordsInUnion type_type = KeywordTest.KeywordsInUnion.NONE, + int typeOffset = 0) { + builder.StartTable(2); + Table2.AddType(builder, typeOffset); + Table2.AddTypeType(builder, type_type); + return Table2.EndTable2(builder); + } + + public static void StartTable2(FlatBufferBuilder builder) { builder.StartTable(2); } + public static void AddTypeType(FlatBufferBuilder builder, KeywordTest.KeywordsInUnion typeType) { builder.AddByte(0, (byte)typeType, 0); } + public static void AddType(FlatBufferBuilder builder, int typeOffset) { builder.AddOffset(1, typeOffset, 0); } + public static Offset EndTable2(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public Table2T UnPack() { + var _o = new Table2T(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(Table2T _o) { + _o.Type = new KeywordTest.KeywordsInUnionUnion(); + _o.Type.Type = this.TypeType; + switch (this.TypeType) { + default: break; + case KeywordTest.KeywordsInUnion.static: + _o.Type.Value = this.Type().HasValue ? this.Type().Value.UnPack() : null; + break; + case KeywordTest.KeywordsInUnion.internal: + _o.Type.Value = this.Type().HasValue ? this.Type().Value.UnPack() : null; + break; + } + } + public static Offset Pack(FlatBufferBuilder builder, Table2T _o) { + if (_o == null) return default(Offset); + var _type_type = _o.Type == null ? KeywordTest.KeywordsInUnion.NONE : _o.Type.Type; + var _type = _o.Type == null ? 0 : KeywordTest.KeywordsInUnionUnion.Pack(builder, _o.Type); + return CreateTable2( + builder, + _type_type, + _type); + } +} + +public class Table2T +{ + [Newtonsoft.Json.JsonProperty("type_type")] + private KeywordTest.KeywordsInUnion TypeType { + get { + return this.Type != null ? this.Type.Type : KeywordTest.KeywordsInUnion.NONE; + } + set { + this.Type = new KeywordTest.KeywordsInUnionUnion(); + this.Type.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("type")] + [Newtonsoft.Json.JsonConverter(typeof(KeywordTest.KeywordsInUnionUnion_JsonConverter))] + public KeywordTest.KeywordsInUnionUnion Type { get; set; } + + public Table2T() { + this.Type = null; + } +} + + +static public class Table2Verify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*TypeType*/, 1 /*KeywordTest.KeywordsInUnion*/, 1, false) + && verifier.VerifyUnion(tablePos, 4, 6 /*Type*/, KeywordTest.KeywordsInUnionVerify.Verify, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/KeywordTest/public.cs b/third_party/flatbuffers/tests/KeywordTest/public.cs new file mode 100644 index 00000000000..4d7684cf02e --- /dev/null +++ b/third_party/flatbuffers/tests/KeywordTest/public.cs @@ -0,0 +1,15 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace KeywordTest +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum @public : int +{ + NONE = 0, +}; + + +} diff --git a/third_party/flatbuffers/tests/KotlinTest.kt b/third_party/flatbuffers/tests/KotlinTest.kt new file mode 100644 index 00000000000..9a8fe5fcd73 --- /dev/null +++ b/third_party/flatbuffers/tests/KotlinTest.kt @@ -0,0 +1,622 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import DictionaryLookup.*; +import MyGame.Example.* +import optional_scalars.* +import com.google.flatbuffers.ByteBufferUtil +import com.google.flatbuffers.FlatBufferBuilder +import NamespaceA.* +import NamespaceA.NamespaceB.* +import NamespaceA.NamespaceB.TableInNestedNS +import java.io.File +import java.io.FileOutputStream +import java.io.InputStream +import java.io.RandomAccessFile +import java.nio.ByteBuffer +import java.nio.ByteOrder +import java.nio.channels.FileChannel + +import com.google.flatbuffers.Constants.SIZE_PREFIX_LENGTH + +@kotlin.ExperimentalUnsignedTypes +class KotlinTest { + + companion object { + @JvmStatic + fun main(args: Array) { + + // First, let's test reading a FlatBuffer generated by C++ code: + // This file was generated from monsterdata_test.json + + val data = RandomAccessFile(File("monsterdata_test.mon"), "r").use { + val temp = ByteArray(it.length().toInt()) + it.readFully(temp) + temp + } + + // Now test it: + + val bb = ByteBuffer.wrap(data) + TestBuffer(bb) + + // Second, let's create a FlatBuffer from scratch in Java, and test it also. + // We use an initial size of 1 to exercise the reallocation algorithm, + // normally a size larger than the typical FlatBuffer you generate would be + // better for performance. + val fbb = FlatBufferBuilder(1) + + TestBuilderBasics(fbb, true) + TestBuilderBasics(fbb, false) + + TestExtendedBuffer(fbb.dataBuffer().asReadOnlyBuffer()) + + TestNamespaceNesting() + + TestNestedFlatBuffer() + + TestCreateByteVector() + + TestCreateUninitializedVector() + + TestByteBufferFactory() + + TestSizedInputStream() + + TestVectorOfUnions() + + TestSharedStringPool() + TestScalarOptional() + TestDictionaryLookup() + println("FlatBuffers test: completed successfully") + } + + fun TestDictionaryLookup() { + val fbb = FlatBufferBuilder(16) + val lfIndex = LongFloatEntry.createLongFloatEntry(fbb, 0, 99.0f) + val vectorEntriesIdx = LongFloatMap.createEntriesVector(fbb, intArrayOf(lfIndex)) + val rootIdx = LongFloatMap.createLongFloatMap(fbb, vectorEntriesIdx) + + LongFloatMap.finishLongFloatMapBuffer(fbb, rootIdx) + val map = LongFloatMap.getRootAsLongFloatMap(fbb.dataBuffer()) + assert(map.entriesLength == 1) + + val e = map.entries(0)!! + assert(e.key == 0L) + assert(e.value == 99.0f) + + val e2 = map.entriesByKey(0)!! + assert(e2.key == 0L) + assert(e2.value == 99.0f) + } + + fun TestEnums() { + assert(Color.name(Color.Red.toInt()) == "Red") + assert(Color.name(Color.Blue.toInt()) == "Blue") + assert(Any_.name(Any_.NONE.toInt()) == "NONE") + assert(Any_.name(Any_.Monster.toInt()) == "Monster") + } + + fun TestBuffer(bb: ByteBuffer) { + assert(Monster.MonsterBufferHasIdentifier(bb) == true) + + val monster = Monster.getRootAsMonster(bb) + + assert(monster.hp == 80.toShort()) + assert(monster.mana == 150.toShort()) // default + + assert(monster.name == "MyMonster") + // monster.friendly() // can't access, deprecated + + val pos = monster.pos!! + assert(pos.x == 1.0f) + assert(pos.y == 2.0f) + assert(pos.z == 3.0f) + assert(pos.test1 == 3.0) + // issue: int != byte + assert(pos.test2 == Color.Green) + val t = pos.test3!! + assert(t.a == 5.toShort()) + assert(t.b == 6.toByte()) + + assert(monster.testType == Any_.Monster) + val monster2 = Monster() + assert(monster.test(monster2) != null == true) + assert(monster2.name == "Fred") + + assert(monster.inventoryLength == 5) + var invsum = 0u + for (i in 0 until monster.inventoryLength) + invsum += monster.inventory(i) + assert(invsum == 10u) + + // Alternative way of accessing a vector: + val ibb = monster.inventoryAsByteBuffer + invsum = 0u + while (ibb.position() < ibb.limit()) + invsum += ibb.get().toUInt() + assert(invsum == 10u) + + + val test_0 = monster.test4(0)!! + val test_1 = monster.test4(1)!! + assert(monster.test4Length == 2) + assert(test_0.a + test_0.b + test_1.a + test_1.b == 100) + + assert(monster.testarrayofstringLength == 2) + assert(monster.testarrayofstring(0) == "test1") + assert(monster.testarrayofstring(1) == "test2") + + assert(monster.testbool == true) + } + + // this method checks additional fields not present in the binary buffer read from file + // these new tests are performed on top of the regular tests + fun TestExtendedBuffer(bb: ByteBuffer) { + TestBuffer(bb) + + val monster = Monster.getRootAsMonster(bb) + + assert(monster.testhashu32Fnv1 == (Integer.MAX_VALUE + 1L).toUInt()) + } + + fun TestNamespaceNesting() { + // reference / manipulate these to verify compilation + val fbb = FlatBufferBuilder(1) + + TableInNestedNS.startTableInNestedNS(fbb) + TableInNestedNS.addFoo(fbb, 1234) + val nestedTableOff = TableInNestedNS.endTableInNestedNS(fbb) + + TableInFirstNS.startTableInFirstNS(fbb) + TableInFirstNS.addFooTable(fbb, nestedTableOff) + } + + fun TestNestedFlatBuffer() { + val nestedMonsterName = "NestedMonsterName" + val nestedMonsterHp: Short = 600 + val nestedMonsterMana: Short = 1024 + + var fbb1: FlatBufferBuilder? = FlatBufferBuilder(16) + val str1 = fbb1!!.createString(nestedMonsterName) + Monster.startMonster(fbb1) + Monster.addName(fbb1, str1) + Monster.addHp(fbb1, nestedMonsterHp) + Monster.addMana(fbb1, nestedMonsterMana) + val monster1 = Monster.endMonster(fbb1) + Monster.finishMonsterBuffer(fbb1, monster1) + val fbb1Bytes = fbb1.sizedByteArray() + + val fbb2 = FlatBufferBuilder(16) + val str2 = fbb2.createString("My Monster") + val nestedBuffer = Monster.createTestnestedflatbufferVector(fbb2, fbb1Bytes.asUByteArray()) + Monster.startMonster(fbb2) + Monster.addName(fbb2, str2) + Monster.addHp(fbb2, 50.toShort()) + Monster.addMana(fbb2, 32.toShort()) + Monster.addTestnestedflatbuffer(fbb2, nestedBuffer) + val monster = Monster.endMonster(fbb2) + Monster.finishMonsterBuffer(fbb2, monster) + + // Now test the data extracted from the nested buffer + val mons = Monster.getRootAsMonster(fbb2.dataBuffer()) + val nestedMonster = mons.testnestedflatbufferAsMonster!! + + assert(nestedMonsterMana == nestedMonster.mana) + assert(nestedMonsterHp == nestedMonster.hp) + assert(nestedMonsterName == nestedMonster.name) + } + + fun TestCreateByteVector() { + val fbb = FlatBufferBuilder(16) + val str = fbb.createString("MyMonster") + val inventory = byteArrayOf(0, 1, 2, 3, 4) + val vec = fbb.createByteVector(inventory) + Monster.startMonster(fbb) + Monster.addInventory(fbb, vec) + Monster.addName(fbb, str) + val monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + val monsterObject = Monster.getRootAsMonster(fbb.dataBuffer()) + + assert(monsterObject.inventory(1) == inventory[1].toUByte()) + assert(monsterObject.inventoryLength == inventory.size) + assert(ByteBuffer.wrap(inventory) == monsterObject.inventoryAsByteBuffer) + } + + fun TestCreateUninitializedVector() { + val fbb = FlatBufferBuilder(16) + val str = fbb.createString("MyMonster") + val inventory = byteArrayOf(0, 1, 2, 3, 4) + val bb = fbb.createUnintializedVector(1, inventory.size, 1) + for (i in inventory) { + bb.put(i) + } + val vec = fbb.endVector() + Monster.startMonster(fbb) + Monster.addInventory(fbb, vec) + Monster.addName(fbb, str) + val monster1 = Monster.endMonster(fbb) + Monster.finishMonsterBuffer(fbb, monster1) + val monsterObject = Monster.getRootAsMonster(fbb.dataBuffer()) + + assert(monsterObject.inventory(1) == inventory[1].toUByte()) + assert(monsterObject.inventoryLength == inventory.size) + assert(ByteBuffer.wrap(inventory) == monsterObject.inventoryAsByteBuffer) + } + + fun TestByteBufferFactory() { + class MappedByteBufferFactory : FlatBufferBuilder.ByteBufferFactory() { + override fun newByteBuffer(capacity: Int): ByteBuffer? { + var bb: ByteBuffer? + try { + bb = RandomAccessFile("javatest.bin", "rw").channel.map( + FileChannel.MapMode.READ_WRITE, + 0, + capacity.toLong() + ).order(ByteOrder.LITTLE_ENDIAN) + } catch (e: Throwable) { + println("FlatBuffers test: couldn't map ByteBuffer to a file") + bb = null + } + + return bb + } + } + + val fbb = FlatBufferBuilder(1, MappedByteBufferFactory()) + + TestBuilderBasics(fbb, false) + } + + fun TestSizedInputStream() { + // Test on default FlatBufferBuilder that uses HeapByteBuffer + val fbb = FlatBufferBuilder(1) + + TestBuilderBasics(fbb, false) + + val `in` = fbb.sizedInputStream() + val array = fbb.sizedByteArray() + var count = 0 + var currentVal = 0 + + while (currentVal != -1 && count < array.size) { + try { + currentVal = `in`.read() + } catch (e: java.io.IOException) { + println("FlatBuffers test: couldn't read from InputStream") + return + } + + assert(currentVal.toByte() == array[count]) + count++ + } + assert(count == array.size) + } + + fun TestBuilderBasics(fbb: FlatBufferBuilder, sizePrefix: Boolean) { + val names = intArrayOf(fbb.createString("Frodo"), fbb.createString("Barney"), fbb.createString("Wilma")) + val off = IntArray(3) + Monster.startMonster(fbb) + Monster.addName(fbb, names[0]) + off[0] = Monster.endMonster(fbb) + Monster.startMonster(fbb) + Monster.addName(fbb, names[1]) + off[1] = Monster.endMonster(fbb) + Monster.startMonster(fbb) + Monster.addName(fbb, names[2]) + off[2] = Monster.endMonster(fbb) + val sortMons = fbb.createSortedVectorOfTables(Monster(), off) + + // We set up the same values as monsterdata.json: + + val str = fbb.createString("MyMonster") + + val inv = Monster.createInventoryVector(fbb, byteArrayOf(0, 1, 2, 3, 4).asUByteArray()) + + val fred = fbb.createString("Fred") + Monster.startMonster(fbb) + Monster.addName(fbb, fred) + val mon2 = Monster.endMonster(fbb) + + Monster.startTest4Vector(fbb, 2) + Test.createTest(fbb, 10.toShort(), 20.toByte()) + Test.createTest(fbb, 30.toShort(), 40.toByte()) + val test4 = fbb.endVector() + + val testArrayOfString = + Monster.createTestarrayofstringVector(fbb, intArrayOf(fbb.createString("test1"), fbb.createString("test2"))) + + Monster.startMonster(fbb) + Monster.addPos( + fbb, Vec3.createVec3( + fbb, 1.0f, 2.0f, 3.0f, 3.0, + Color.Green, 5.toShort(), 6.toByte() + ) + ) + Monster.addHp(fbb, 80.toShort()) + Monster.addName(fbb, str) + Monster.addInventory(fbb, inv) + Monster.addTestType(fbb, Any_.Monster) + Monster.addTest(fbb, mon2) + Monster.addTest4(fbb, test4) + Monster.addTestarrayofstring(fbb, testArrayOfString) + Monster.addTestbool(fbb, true) + Monster.addTesthashu32Fnv1(fbb, (Integer.MAX_VALUE + 1L).toUInt()) + Monster.addTestarrayoftables(fbb, sortMons) + val mon = Monster.endMonster(fbb) + + if (sizePrefix) { + Monster.finishSizePrefixedMonsterBuffer(fbb, mon) + } else { + Monster.finishMonsterBuffer(fbb, mon) + } + + // Write the result to a file for debugging purposes: + // Note that the binaries are not necessarily identical, since the JSON + // parser may serialize in a slightly different order than the above + // Java code. They are functionally equivalent though. + + try { + val filename = "monsterdata_java_wire" + (if (sizePrefix) "_sp" else "") + ".mon" + val fc = FileOutputStream(filename).channel + fc.write(fbb.dataBuffer().duplicate()) + fc.close() + } catch (e: java.io.IOException) { + println("FlatBuffers test: couldn't write file") + return + } + + // Test it: + var dataBuffer = fbb.dataBuffer() + if (sizePrefix) { + assert( + ByteBufferUtil.getSizePrefix(dataBuffer) + SIZE_PREFIX_LENGTH == + dataBuffer.remaining() + ) + dataBuffer = ByteBufferUtil.removeSizePrefix(dataBuffer) + } + TestExtendedBuffer(dataBuffer) + + // Make sure it also works with read only ByteBuffers. This is slower, + // since creating strings incurs an additional copy + // (see Table.__string). + TestExtendedBuffer(dataBuffer.asReadOnlyBuffer()) + + TestEnums() + + //Attempt to mutate Monster fields and check whether the buffer has been mutated properly + // revert to original values after testing + val monster = Monster.getRootAsMonster(dataBuffer) + + // mana is optional and does not exist in the buffer so the mutation should fail + // the mana field should retain its default value + assert(monster.mutateMana(10.toShort()) == false) + assert(monster.mana == 150.toShort()) + + // Accessing a vector of sorted by the key tables + assert(monster.testarrayoftables(0)!!.name == "Barney") + assert(monster.testarrayoftables(1)!!.name == "Frodo") + assert(monster.testarrayoftables(2)!!.name == "Wilma") + + // Example of searching for a table by the key + assert(monster.testarrayoftablesByKey("Frodo")!!.name == "Frodo") + assert(monster.testarrayoftablesByKey("Barney")!!.name == "Barney") + assert(monster.testarrayoftablesByKey("Wilma")!!.name == "Wilma") + + // testType is an existing field and mutating it should succeed + assert(monster.testType == Any_.Monster) + assert(monster.mutateTestType(Any_.NONE) == true) + assert(monster.testType == Any_.NONE) + assert(monster.mutateTestType(Any_.Monster) == true) + assert(monster.testType == Any_.Monster) + + //mutate the inventory vector + assert(monster.mutateInventory(0, 1u) == true) + assert(monster.mutateInventory(1, 2u) == true) + assert(monster.mutateInventory(2, 3u) == true) + assert(monster.mutateInventory(3, 4u) == true) + assert(monster.mutateInventory(4, 5u) == true) + + for (i in 0 until monster.inventoryLength) { + assert(monster.inventory(i) == (i.toUByte() + 1u).toUByte()) + } + + //reverse mutation + assert(monster.mutateInventory(0, 0u) == true) + assert(monster.mutateInventory(1, 1u) == true) + assert(monster.mutateInventory(2, 2u) == true) + assert(monster.mutateInventory(3, 3u) == true) + assert(monster.mutateInventory(4, 4u) == true) + + // get a struct field and edit one of its fields + val pos = monster.pos!! + assert(pos.x == 1.0f) + pos.mutateX(55.0f) + assert(pos.x == 55.0f) + pos.mutateX(1.0f) + assert(pos.x == 1.0f) + } + + fun TestVectorOfUnions() { + val fbb = FlatBufferBuilder() + + val swordAttackDamage = 1 + + val characterVector = intArrayOf(Attacker.createAttacker(fbb, swordAttackDamage)) + + val characterTypeVector = ubyteArrayOf(Character_.MuLan) + + Movie.finishMovieBuffer( + fbb, + Movie.createMovie( + fbb, + 0u, + 0, + Movie.createCharactersTypeVector(fbb, characterTypeVector), + Movie.createCharactersVector(fbb, characterVector) + ) + ) + + val movie = Movie.getRootAsMovie(fbb.dataBuffer()) + + assert(movie.charactersTypeLength == characterTypeVector.size) + assert(movie.charactersLength == characterVector.size) + + assert(movie.charactersType(0) == characterTypeVector[0]) + + assert((movie.characters(Attacker(), 0) as Attacker).swordAttackDamage == swordAttackDamage) + } + + fun TestSharedStringPool() { + val fb = FlatBufferBuilder(1); + val testString = "My string"; + val offset = fb.createSharedString(testString); + for (i in 0..10) { + assert(offset == fb.createSharedString(testString)); + } + } + + fun TestScalarOptional() { + val fbb = FlatBufferBuilder(1) + ScalarStuff.startScalarStuff(fbb) + var pos = ScalarStuff.endScalarStuff(fbb) + fbb.finish(pos) + + var scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer()) + + assert(scalarStuff.justI8 == 0.toByte()) + assert(scalarStuff.maybeI8 == null) + assert(scalarStuff.defaultI8 == 42.toByte()) + assert(scalarStuff.justU8 == 0.toUByte()) + assert(scalarStuff.maybeU8 == null) + assert(scalarStuff.defaultU8 == 42.toUByte()) + assert(scalarStuff.justI16 == 0.toShort()) + assert(scalarStuff.maybeI16 == null) + assert(scalarStuff.defaultI16 == 42.toShort()) + assert(scalarStuff.justU16 == 0.toUShort()) + assert(scalarStuff.maybeU16 == null) + assert(scalarStuff.defaultU16 == 42.toUShort()) + assert(scalarStuff.justI32 == 0) + assert(scalarStuff.maybeI32 == null) + assert(scalarStuff.defaultI32 == 42) + assert(scalarStuff.justU32 == 0.toUInt()) + assert(scalarStuff.maybeU32 == null) + assert(scalarStuff.defaultU32 == 42U) + assert(scalarStuff.justI64 == 0L) + assert(scalarStuff.maybeI64 == null) + assert(scalarStuff.defaultI64 == 42L) + assert(scalarStuff.justU64 == 0UL) + assert(scalarStuff.maybeU64 == null) + assert(scalarStuff.defaultU64 == 42UL) + assert(scalarStuff.justF32 == 0.0f) + assert(scalarStuff.maybeF32 == null) + assert(scalarStuff.defaultF32 == 42.0f) + assert(scalarStuff.justF64 == 0.0) + assert(scalarStuff.maybeF64 == null) + assert(scalarStuff.defaultF64 == 42.0) + assert(scalarStuff.justBool == false) + assert(scalarStuff.maybeBool == null) + assert(scalarStuff.defaultBool == true) + assert(scalarStuff.justEnum == OptionalByte.None) + assert(scalarStuff.maybeEnum == null) + assert(scalarStuff.defaultEnum == OptionalByte.One) + + fbb.clear() + + ScalarStuff.startScalarStuff(fbb) + ScalarStuff.addJustI8(fbb, 5.toByte()) + ScalarStuff.addMaybeI8(fbb, 5.toByte()) + ScalarStuff.addDefaultI8(fbb, 5.toByte()) + ScalarStuff.addJustU8(fbb, 6.toUByte()) + ScalarStuff.addMaybeU8(fbb, 6.toUByte()) + ScalarStuff.addDefaultU8(fbb, 6.toUByte()) + ScalarStuff.addJustI16(fbb, 7.toShort()) + ScalarStuff.addMaybeI16(fbb, 7.toShort()) + ScalarStuff.addDefaultI16(fbb, 7.toShort()) + ScalarStuff.addJustU16(fbb, 8.toUShort()) + ScalarStuff.addMaybeU16(fbb, 8.toUShort()) + ScalarStuff.addDefaultU16(fbb, 8.toUShort()) + ScalarStuff.addJustI32(fbb, 9) + ScalarStuff.addMaybeI32(fbb, 9) + ScalarStuff.addDefaultI32(fbb, 9) + ScalarStuff.addJustU32(fbb, 10.toUInt()) + ScalarStuff.addMaybeU32(fbb, 10.toUInt()) + ScalarStuff.addDefaultU32(fbb, 10.toUInt()) + ScalarStuff.addJustI64(fbb, 11L) + ScalarStuff.addMaybeI64(fbb, 11L) + ScalarStuff.addDefaultI64(fbb, 11L) + ScalarStuff.addJustU64(fbb, 12UL) + ScalarStuff.addMaybeU64(fbb, 12UL) + ScalarStuff.addDefaultU64(fbb, 12UL) + ScalarStuff.addJustF32(fbb, 13.0f) + ScalarStuff.addMaybeF32(fbb, 13.0f) + ScalarStuff.addDefaultF32(fbb, 13.0f) + ScalarStuff.addJustF64(fbb, 14.0) + ScalarStuff.addMaybeF64(fbb, 14.0) + ScalarStuff.addDefaultF64(fbb, 14.0) + ScalarStuff.addJustBool(fbb, true) + ScalarStuff.addMaybeBool(fbb, true) + ScalarStuff.addDefaultBool(fbb, true) + ScalarStuff.addJustEnum(fbb, OptionalByte.Two) + ScalarStuff.addMaybeEnum(fbb, OptionalByte.Two) + ScalarStuff.addDefaultEnum(fbb, OptionalByte.Two) + + pos = ScalarStuff.endScalarStuff(fbb) + + fbb.finish(pos) + + scalarStuff = ScalarStuff.getRootAsScalarStuff(fbb.dataBuffer()) + + assert(scalarStuff.justI8 == 5.toByte()) + assert(scalarStuff.maybeI8 == 5.toByte()) + assert(scalarStuff.defaultI8 == 5.toByte()) + assert(scalarStuff.justU8 == 6.toUByte()) + assert(scalarStuff.maybeU8 == 6.toUByte()) + assert(scalarStuff.defaultU8 == 6.toUByte()) + assert(scalarStuff.justI16 == 7.toShort()) + assert(scalarStuff.maybeI16 == 7.toShort()) + assert(scalarStuff.defaultI16 == 7.toShort()) + assert(scalarStuff.justU16 == 8.toUShort()) + assert(scalarStuff.maybeU16 == 8.toUShort()) + assert(scalarStuff.defaultU16 == 8.toUShort()) + assert(scalarStuff.justI32 == 9) + assert(scalarStuff.maybeI32 == 9) + assert(scalarStuff.defaultI32 == 9) + assert(scalarStuff.justU32 == 10u) + assert(scalarStuff.maybeU32 == 10u) + assert(scalarStuff.defaultU32 == 10u) + assert(scalarStuff.justI64 == 11L) + assert(scalarStuff.maybeI64 == 11L) + assert(scalarStuff.defaultI64 == 11L) + assert(scalarStuff.justU64 == 12UL) + assert(scalarStuff.maybeU64 == 12UL) + assert(scalarStuff.defaultU64 == 12UL) + assert(scalarStuff.justF32 == 13.0f) + assert(scalarStuff.maybeF32 == 13.0f) + assert(scalarStuff.defaultF32 == 13.0f) + assert(scalarStuff.justF64 == 14.0) + assert(scalarStuff.maybeF64 == 14.0) + assert(scalarStuff.defaultF64 == 14.0) + assert(scalarStuff.justBool == true) + assert(scalarStuff.maybeBool == true) + assert(scalarStuff.defaultBool == true) + assert(scalarStuff.justEnum == OptionalByte.Two) + assert(scalarStuff.maybeEnum == OptionalByte.Two) + assert(scalarStuff.defaultEnum == OptionalByte.Two) + } + } +} diff --git a/third_party/flatbuffers/tests/KotlinTest.sh b/third_party/flatbuffers/tests/KotlinTest.sh new file mode 100755 index 00000000000..2b41d5cb1bb --- /dev/null +++ b/third_party/flatbuffers/tests/KotlinTest.sh @@ -0,0 +1,46 @@ +#!/bin/sh + +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +echo Compile then run the Kotlin test. + +testdir=$(dirname $0) +targetdir="${testdir}/kotlin" + +if [[ -e "${targetdir}" ]]; then + echo "cleaning target" + rm -rf "${targetdir}" +fi + +mkdir -v "${targetdir}" + +if ! find "${testdir}/../java" -type f -name "*.class" -delete; then + echo "failed to clean .class files from java directory" >&2 + exit 1 +fi + +all_kt_files=`find . -name "*.kt" -print` + +# Compile java FlatBuffer library +javac ${testdir}/../java/src/main/java/com/google/flatbuffers/*.java -d $targetdir +# Compile Kotlin files +kotlinc $all_kt_files -classpath $targetdir -include-runtime -d $targetdir +# Make jar +jar cvf ${testdir}/kotlin_test.jar -C $targetdir . > /dev/null +# Run test +kotlin -J"-ea" -cp ${testdir}/kotlin_test.jar KotlinTest +# clean up +rm -rf $targetdir +rm ${testdir}/kotlin_test.jar diff --git a/third_party/flatbuffers/tests/LobsterTest.bat b/third_party/flatbuffers/tests/LobsterTest.bat new file mode 100644 index 00000000000..785f34c6536 --- /dev/null +++ b/third_party/flatbuffers/tests/LobsterTest.bat @@ -0,0 +1,3 @@ +..\Release\flatc.exe --lobster -I include_test monster_test.fbs +..\Release\flatc.exe --lobster -I include_test optional_scalars.fbs +..\..\lobster\bin\lobster.exe .\lobstertest.lobster diff --git a/third_party/flatbuffers/tests/LuaTest.bat b/third_party/flatbuffers/tests/LuaTest.bat new file mode 100644 index 00000000000..39c5d8fd951 --- /dev/null +++ b/third_party/flatbuffers/tests/LuaTest.bat @@ -0,0 +1,7 @@ +set buildtype=Release +if "%1"=="-b" set buildtype=%2 + +echo Run with LuaJIT: +luajit.exe luatest.lua +echo Run with Lua 5.3: +lua53.exe luatest.lua \ No newline at end of file diff --git a/third_party/flatbuffers/tests/LuaTest.sh b/third_party/flatbuffers/tests/LuaTest.sh new file mode 100755 index 00000000000..af34b697ed5 --- /dev/null +++ b/third_party/flatbuffers/tests/LuaTest.sh @@ -0,0 +1,29 @@ +#!/bin/bash -eu +# +# Copyright 2019 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +pushd "$(dirname $0)" >/dev/null +test_dir="$(pwd)" + +declare -a versions=(luajit lua5.1 lua5.2 lua5.3 lua5.4) + +for i in "${versions[@]}" +do + if command -v $i &> /dev/null + then + echo "[$i]" + $i luatest.lua + fi +done diff --git a/third_party/flatbuffers/tests/MoreDefaults.nim b/third_party/flatbuffers/tests/MoreDefaults.nim new file mode 100644 index 00000000000..38b65f6d561 --- /dev/null +++ b/third_party/flatbuffers/tests/MoreDefaults.nim @@ -0,0 +1,103 @@ +#[ MoreDefaults + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : +]# + +import Abc as Abc +import flatbuffers + +type MoreDefaults* = object of FlatObj +func intsLength*(self: MoreDefaults): int = + let o = self.tab.Offset(4) + if o != 0: + return self.tab.VectorLen(o) +func ints*(self: MoreDefaults, j: int): int32 = + let o = self.tab.Offset(4) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return Get[int32](self.tab, x) +func ints*(self: MoreDefaults): seq[int32] = + let len = self.intsLength + for i in countup(0, len - 1): + result.add(self.ints(i)) +func floatsLength*(self: MoreDefaults): int = + let o = self.tab.Offset(6) + if o != 0: + return self.tab.VectorLen(o) +func floats*(self: MoreDefaults, j: int): float32 = + let o = self.tab.Offset(6) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return Get[float32](self.tab, x) +func floats*(self: MoreDefaults): seq[float32] = + let len = self.floatsLength + for i in countup(0, len - 1): + result.add(self.floats(i)) +func emptyString*(self: MoreDefaults): string = + let o = self.tab.Offset(8) + if o != 0: + return self.tab.String(self.tab.Pos + o) + return "" +func someString*(self: MoreDefaults): string = + let o = self.tab.Offset(10) + if o != 0: + return self.tab.String(self.tab.Pos + o) + return "" +func abcsLength*(self: MoreDefaults): int = + let o = self.tab.Offset(12) + if o != 0: + return self.tab.VectorLen(o) +func abcs*(self: MoreDefaults, j: int): Abc.Abc = + let o = self.tab.Offset(12) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return Abc.Abc(Get[int32](self.tab, x)) +func abcs*(self: MoreDefaults): seq[Abc.Abc] = + let len = self.abcsLength + for i in countup(0, len - 1): + result.add(self.abcs(i)) +func boolsLength*(self: MoreDefaults): int = + let o = self.tab.Offset(14) + if o != 0: + return self.tab.VectorLen(o) +func bools*(self: MoreDefaults, j: int): bool = + let o = self.tab.Offset(14) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[bool](self.tab, x) +func bools*(self: MoreDefaults): seq[bool] = + let len = self.boolsLength + for i in countup(0, len - 1): + result.add(self.bools(i)) +proc MoreDefaultsStart*(builder: var Builder) = + builder.StartObject(6) +proc MoreDefaultsAddints*(builder: var Builder, ints: uoffset) = + builder.PrependSlot(0, ints, default(uoffset)) +proc MoreDefaultsStartintsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MoreDefaultsAddfloats*(builder: var Builder, floats: uoffset) = + builder.PrependSlot(1, floats, default(uoffset)) +proc MoreDefaultsStartfloatsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MoreDefaultsAddemptyString*(builder: var Builder, emptyString: uoffset) = + builder.PrependSlot(2, emptyString, default(uoffset)) +proc MoreDefaultsAddsomeString*(builder: var Builder, someString: uoffset) = + builder.PrependSlot(3, someString, default(uoffset)) +proc MoreDefaultsAddabcs*(builder: var Builder, abcs: uoffset) = + builder.PrependSlot(4, abcs, default(uoffset)) +proc MoreDefaultsStartabcsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MoreDefaultsAddbools*(builder: var Builder, bools: uoffset) = + builder.PrependSlot(5, bools, default(uoffset)) +proc MoreDefaultsStartboolsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MoreDefaultsEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MutatingBool.fbs b/third_party/flatbuffers/tests/MutatingBool.fbs new file mode 100644 index 00000000000..961db6edbf8 --- /dev/null +++ b/third_party/flatbuffers/tests/MutatingBool.fbs @@ -0,0 +1,8 @@ + +struct Property { + property: bool; +} + +table TestMutatingBool { + b: Property; +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.cs b/third_party/flatbuffers/tests/MyGame/Example/Ability.cs new file mode 100644 index 00000000000..e19406351ee --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.cs @@ -0,0 +1,62 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Ability : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public Ability __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public uint Id { get { return __p.bb.GetUint(__p.bb_pos + 0); } } + public void MutateId(uint id) { __p.bb.PutUint(__p.bb_pos + 0, id); } + public uint Distance { get { return __p.bb.GetUint(__p.bb_pos + 4); } } + public void MutateDistance(uint distance) { __p.bb.PutUint(__p.bb_pos + 4, distance); } + + public static Offset CreateAbility(FlatBufferBuilder builder, uint Id, uint Distance) { + builder.Prep(4, 8); + builder.PutUint(Distance); + builder.PutUint(Id); + return new Offset(builder.Offset); + } + public AbilityT UnPack() { + var _o = new AbilityT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(AbilityT _o) { + _o.Id = this.Id; + _o.Distance = this.Distance; + } + public static Offset Pack(FlatBufferBuilder builder, AbilityT _o) { + if (_o == null) return default(Offset); + return CreateAbility( + builder, + _o.Id, + _o.Distance); + } +} + +public class AbilityT +{ + [Newtonsoft.Json.JsonProperty("id")] + public uint Id { get; set; } + [Newtonsoft.Json.JsonProperty("distance")] + public uint Distance { get; set; } + + public AbilityT() { + this.Id = 0; + this.Distance = 0; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.go b/third_party/flatbuffers/tests/MyGame/Example/Ability.go new file mode 100644 index 00000000000..922c0e4aeaf --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.go @@ -0,0 +1,66 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type AbilityT struct { + Id uint32 `json:"id"` + Distance uint32 `json:"distance"` +} + +func (t *AbilityT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + return CreateAbility(builder, t.Id, t.Distance) +} +func (rcv *Ability) UnPackTo(t *AbilityT) { + t.Id = rcv.Id() + t.Distance = rcv.Distance() +} + +func (rcv *Ability) UnPack() *AbilityT { + if rcv == nil { + return nil + } + t := &AbilityT{} + rcv.UnPackTo(t) + return t +} + +type Ability struct { + _tab flatbuffers.Struct +} + +func (rcv *Ability) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Ability) Table() flatbuffers.Table { + return rcv._tab.Table +} + +func (rcv *Ability) Id() uint32 { + return rcv._tab.GetUint32(rcv._tab.Pos + flatbuffers.UOffsetT(0)) +} +func (rcv *Ability) MutateId(n uint32) bool { + return rcv._tab.MutateUint32(rcv._tab.Pos+flatbuffers.UOffsetT(0), n) +} + +func (rcv *Ability) Distance() uint32 { + return rcv._tab.GetUint32(rcv._tab.Pos + flatbuffers.UOffsetT(4)) +} +func (rcv *Ability) MutateDistance(n uint32) bool { + return rcv._tab.MutateUint32(rcv._tab.Pos+flatbuffers.UOffsetT(4), n) +} + +func CreateAbility(builder *flatbuffers.Builder, id uint32, distance uint32) flatbuffers.UOffsetT { + builder.Prep(4, 8) + builder.PrependUint32(distance) + builder.PrependUint32(id) + return builder.Offset() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.java b/third_party/flatbuffers/tests/MyGame/Example/Ability.java new file mode 100644 index 00000000000..8b8c38f1147 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.java @@ -0,0 +1,64 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Ability extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Ability __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public long id() { return (long)bb.getInt(bb_pos + 0) & 0xFFFFFFFFL; } + public void mutateId(long id) { bb.putInt(bb_pos + 0, (int) id); } + public long distance() { return (long)bb.getInt(bb_pos + 4) & 0xFFFFFFFFL; } + public void mutateDistance(long distance) { bb.putInt(bb_pos + 4, (int) distance); } + + public static int createAbility(FlatBufferBuilder builder, long id, long distance) { + builder.prep(4, 8); + builder.putInt((int) distance); + builder.putInt((int) id); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Ability get(int j) { return get(new Ability(), j); } + public Ability get(Ability obj, int j) { return obj.__assign(__element(j), bb); } + } + public AbilityT unpack() { + AbilityT _o = new AbilityT(); + unpackTo(_o); + return _o; + } + public void unpackTo(AbilityT _o) { + long _oId = id(); + _o.setId(_oId); + long _oDistance = distance(); + _o.setDistance(_oDistance); + } + public static int pack(FlatBufferBuilder builder, AbilityT _o) { + if (_o == null) return 0; + return createAbility( + builder, + _o.getId(), + _o.getDistance()); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.kt b/third_party/flatbuffers/tests/MyGame/Example/Ability.kt new file mode 100644 index 00000000000..dc2b0b8640b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.kt @@ -0,0 +1,43 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Ability : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Ability { + __init(_i, _bb) + return this + } + val id : UInt get() = bb.getInt(bb_pos + 0).toUInt() + fun mutateId(id: UInt) : ByteBuffer = bb.putInt(bb_pos + 0, id.toInt()) + val distance : UInt get() = bb.getInt(bb_pos + 4).toUInt() + fun mutateDistance(distance: UInt) : ByteBuffer = bb.putInt(bb_pos + 4, distance.toInt()) + companion object { + fun createAbility(builder: FlatBufferBuilder, id: UInt, distance: UInt) : Int { + builder.prep(4, 8) + builder.putInt(distance.toInt()) + builder.putInt(id.toInt()) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.lua b/third_party/flatbuffers/tests/MyGame/Example/Ability.lua new file mode 100644 index 00000000000..af2915c7c24 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.lua @@ -0,0 +1,43 @@ +--[[ MyGame.Example.Ability + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Ability = {} +local mt = {} + +function Ability.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:Id() + return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 0) +end + +function mt:Distance() + return self.view:Get(flatbuffers.N.Uint32, self.view.pos + 4) +end + +function Ability.CreateAbility(builder, id, distance) + builder:Prep(4, 8) + builder:PrependUint32(distance) + builder:PrependUint32(id) + return builder:Offset() +end + +return Ability \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.nim b/third_party/flatbuffers/tests/MyGame/Example/Ability.nim new file mode 100644 index 00000000000..769bf61e3b5 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.nim @@ -0,0 +1,26 @@ +#[ MyGame.Example.Ability + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers + +type Ability* = object of FlatObj +func id*(self: Ability): uint32 = + return Get[uint32](self.tab, self.tab.Pos + 0) +func `id=`*(self: var Ability, n: uint32): bool = + return self.tab.Mutate(self.tab.Pos + 0, n) +func distance*(self: Ability): uint32 = + return Get[uint32](self.tab, self.tab.Pos + 4) +func `distance=`*(self: var Ability, n: uint32): bool = + return self.tab.Mutate(self.tab.Pos + 4, n) +proc AbilityCreate*(self: var Builder, id: uint32, distance: uint32): uoffset = + self.Prep(4, 8) + self.Prepend(distance) + self.Prepend(id) + return self.Offset() diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.php b/third_party/flatbuffers/tests/MyGame/Example/Ability.php new file mode 100644 index 00000000000..c09eca31818 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.php @@ -0,0 +1,52 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return uint + */ + public function GetId() + { + return $this->bb->getUint($this->bb_pos + 0); + } + + /** + * @return uint + */ + public function GetDistance() + { + return $this->bb->getUint($this->bb_pos + 4); + } + + + /** + * @return int offset + */ + public static function createAbility(FlatBufferBuilder $builder, $id, $distance) + { + $builder->prep(4, 8); + $builder->putUint($distance); + $builder->putUint($id); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Ability.py b/third_party/flatbuffers/tests/MyGame/Example/Ability.py new file mode 100644 index 00000000000..e0344e5fd0e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Ability.py @@ -0,0 +1,65 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Ability(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 8 + + # Ability + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Ability + def Id(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Ability + def Distance(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4)) + +def CreateAbility(builder, id, distance): + builder.Prep(4, 8) + builder.PrependUint32(distance) + builder.PrependUint32(id) + return builder.Offset() + + +class AbilityT(object): + + # AbilityT + def __init__(self): + self.id = 0 # type: int + self.distance = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + ability = Ability() + ability.Init(buf, pos) + return cls.InitFromObj(ability) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, ability): + x = AbilityT() + x._UnPack(ability) + return x + + # AbilityT + def _UnPack(self, ability): + if ability is None: + return + self.id = ability.Id() + self.distance = ability.Distance() + + # AbilityT + def Pack(self, builder): + return CreateAbility(builder, self.id, self.distance) diff --git a/third_party/flatbuffers/tests/MyGame/Example/AbilityT.java b/third_party/flatbuffers/tests/MyGame/Example/AbilityT.java new file mode 100644 index 00000000000..73c23622404 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AbilityT.java @@ -0,0 +1,40 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class AbilityT { + private long id; + private long distance; + + public long getId() { return id; } + + public void setId(long id) { this.id = id; } + + public long getDistance() { return distance; } + + public void setDistance(long distance) { this.distance = distance; } + + + public AbilityT() { + this.id = 0L; + this.distance = 0L; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.cs b/third_party/flatbuffers/tests/MyGame/Example/Any.cs new file mode 100644 index 00000000000..ce583f0f363 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.cs @@ -0,0 +1,113 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Any : byte +{ + NONE = 0, + Monster = 1, + TestSimpleTableWithEnum = 2, + MyGame_Example2_Monster = 3, +}; + +public class AnyUnion { + public Any Type { get; set; } + public object Value { get; set; } + + public AnyUnion() { + this.Type = Any.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public MyGame.Example.MonsterT AsMonster() { return this.As(); } + public static AnyUnion FromMonster(MyGame.Example.MonsterT _monster) { return new AnyUnion{ Type = Any.Monster, Value = _monster }; } + internal MyGame.Example.TestSimpleTableWithEnumT AsTestSimpleTableWithEnum() { return this.As(); } + internal static AnyUnion FromTestSimpleTableWithEnum(MyGame.Example.TestSimpleTableWithEnumT _testsimpletablewithenum) { return new AnyUnion{ Type = Any.TestSimpleTableWithEnum, Value = _testsimpletablewithenum }; } + public MyGame.Example2.MonsterT AsMyGame_Example2_Monster() { return this.As(); } + public static AnyUnion FromMyGame_Example2_Monster(MyGame.Example2.MonsterT _mygame_example2_monster) { return new AnyUnion{ Type = Any.MyGame_Example2_Monster, Value = _mygame_example2_monster }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, AnyUnion _o) { + switch (_o.Type) { + default: return 0; + case Any.Monster: return MyGame.Example.Monster.Pack(builder, _o.AsMonster()).Value; + case Any.TestSimpleTableWithEnum: return MyGame.Example.TestSimpleTableWithEnum.Pack(builder, _o.AsTestSimpleTableWithEnum()).Value; + case Any.MyGame_Example2_Monster: return MyGame.Example2.Monster.Pack(builder, _o.AsMyGame_Example2_Monster()).Value; + } + } +} + +public class AnyUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(AnyUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as AnyUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, AnyUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as AnyUnion, serializer); + } + } + public AnyUnion ReadJson(Newtonsoft.Json.JsonReader reader, AnyUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case Any.Monster: _o.Value = serializer.Deserialize(reader); break; + case Any.TestSimpleTableWithEnum: _o.Value = serializer.Deserialize(reader); break; + case Any.MyGame_Example2_Monster: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class AnyVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((Any)typeId) + { + case Any.Monster: + result = MyGame.Example.MonsterVerify.Verify(verifier, tablePos); + break; + case Any.TestSimpleTableWithEnum: + result = MyGame.Example.TestSimpleTableWithEnumVerify.Verify(verifier, tablePos); + break; + case Any.MyGame_Example2_Monster: + result = MyGame.Example2.MonsterVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.go b/third_party/flatbuffers/tests/MyGame/Example/Any.go new file mode 100644 index 00000000000..9d56df27573 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.go @@ -0,0 +1,78 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" + "strconv" + + MyGame__Example2 "MyGame/Example2" +) + +type Any byte + +const ( + AnyNONE Any = 0 + AnyMonster Any = 1 + AnyTestSimpleTableWithEnum Any = 2 + AnyMyGame_Example2_Monster Any = 3 +) + +var EnumNamesAny = map[Any]string{ + AnyNONE: "NONE", + AnyMonster: "Monster", + AnyTestSimpleTableWithEnum: "TestSimpleTableWithEnum", + AnyMyGame_Example2_Monster: "MyGame_Example2_Monster", +} + +var EnumValuesAny = map[string]Any{ + "NONE": AnyNONE, + "Monster": AnyMonster, + "TestSimpleTableWithEnum": AnyTestSimpleTableWithEnum, + "MyGame_Example2_Monster": AnyMyGame_Example2_Monster, +} + +func (v Any) String() string { + if s, ok := EnumNamesAny[v]; ok { + return s + } + return "Any(" + strconv.FormatInt(int64(v), 10) + ")" +} + +type AnyT struct { + Type Any + Value interface{} +} + +func (t *AnyT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + switch t.Type { + case AnyMonster: + return t.Value.(*MonsterT).Pack(builder) + case AnyTestSimpleTableWithEnum: + return t.Value.(*TestSimpleTableWithEnumT).Pack(builder) + case AnyMyGame_Example2_Monster: + return t.Value.(*MyGame__Example2.MonsterT).Pack(builder) + } + return 0 +} + +func (rcv Any) UnPack(table flatbuffers.Table) *AnyT { + switch rcv { + case AnyMonster: + var x Monster + x.Init(table.Bytes, table.Pos) + return &AnyT{Type: AnyMonster, Value: x.UnPack()} + case AnyTestSimpleTableWithEnum: + var x TestSimpleTableWithEnum + x.Init(table.Bytes, table.Pos) + return &AnyT{Type: AnyTestSimpleTableWithEnum, Value: x.UnPack()} + case AnyMyGame_Example2_Monster: + var x MyGame__Example2.Monster + x.Init(table.Bytes, table.Pos) + return &AnyT{Type: AnyMyGame_Example2_Monster, Value: x.UnPack()} + } + return nil +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.java b/third_party/flatbuffers/tests/MyGame/Example/Any.java new file mode 100644 index 00000000000..a42a15ae91b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.java @@ -0,0 +1,17 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +@SuppressWarnings("unused") +public final class Any { + private Any() { } + public static final byte NONE = 0; + public static final byte Monster = 1; + public static final byte TestSimpleTableWithEnum = 2; + public static final byte MyGame_Example2_Monster = 3; + + public static final String[] names = { "NONE", "Monster", "TestSimpleTableWithEnum", "MyGame_Example2_Monster", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.kt b/third_party/flatbuffers/tests/MyGame/Example/Any.kt new file mode 100644 index 00000000000..d7dd7bbe1d8 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.kt @@ -0,0 +1,15 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +@Suppress("unused") +class Any_ private constructor() { + companion object { + const val NONE: UByte = 0u + const val Monster: UByte = 1u + const val TestSimpleTableWithEnum: UByte = 2u + const val MyGame_Example2_Monster: UByte = 3u + val names : Array = arrayOf("NONE", "Monster", "TestSimpleTableWithEnum", "MyGame_Example2_Monster") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.lua b/third_party/flatbuffers/tests/MyGame/Example/Any.lua new file mode 100644 index 00000000000..4ff198cf3b8 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.lua @@ -0,0 +1,20 @@ +--[[ MyGame.Example.Any + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local Any = { + NONE = 0, + Monster = 1, + TestSimpleTableWithEnum = 2, + MyGame_Example2_Monster = 3, +} + +return Any \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.nim b/third_party/flatbuffers/tests/MyGame/Example/Any.nim new file mode 100644 index 00000000000..b2185a09501 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.nim @@ -0,0 +1,15 @@ +#[ MyGame.Example.Any + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +type Any*{.pure.} = enum + None = 0.uint8, + Monster = 1.uint8, + TestSimpleTableWithEnum = 2.uint8, + MyGameExample2Monster = 3.uint8, diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.php b/third_party/flatbuffers/tests/MyGame/Example/Any.php new file mode 100644 index 00000000000..929caaf669b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.php @@ -0,0 +1,27 @@ +"NONE", + Any::Monster=>"Monster", + Any::TestSimpleTableWithEnum=>"TestSimpleTableWithEnum", + Any::MyGame_Example2_Monster=>"MyGame_Example2_Monster", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Any.py b/third_party/flatbuffers/tests/MyGame/Example/Any.py new file mode 100644 index 00000000000..17ce5503280 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Any.py @@ -0,0 +1,24 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +class Any(object): + NONE = 0 + Monster = 1 + TestSimpleTableWithEnum = 2 + MyGame_Example2_Monster = 3 + +def AnyCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == Any.Monster: + import MyGame.Example.Monster + return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == Any.TestSimpleTableWithEnum: + import MyGame.Example.TestSimpleTableWithEnum + return MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + if unionType == Any.MyGame_Example2_Monster: + import MyGame.Example2.Monster + return MyGame.Example2.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + return None diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.cs b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.cs new file mode 100644 index 00000000000..e85b055c664 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.cs @@ -0,0 +1,113 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum AnyAmbiguousAliases : byte +{ + NONE = 0, + M1 = 1, + M2 = 2, + M3 = 3, +}; + +public class AnyAmbiguousAliasesUnion { + public AnyAmbiguousAliases Type { get; set; } + public object Value { get; set; } + + public AnyAmbiguousAliasesUnion() { + this.Type = AnyAmbiguousAliases.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public MyGame.Example.MonsterT AsM1() { return this.As(); } + public static AnyAmbiguousAliasesUnion FromM1(MyGame.Example.MonsterT _m1) { return new AnyAmbiguousAliasesUnion{ Type = AnyAmbiguousAliases.M1, Value = _m1 }; } + public MyGame.Example.MonsterT AsM2() { return this.As(); } + public static AnyAmbiguousAliasesUnion FromM2(MyGame.Example.MonsterT _m2) { return new AnyAmbiguousAliasesUnion{ Type = AnyAmbiguousAliases.M2, Value = _m2 }; } + public MyGame.Example.MonsterT AsM3() { return this.As(); } + public static AnyAmbiguousAliasesUnion FromM3(MyGame.Example.MonsterT _m3) { return new AnyAmbiguousAliasesUnion{ Type = AnyAmbiguousAliases.M3, Value = _m3 }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, AnyAmbiguousAliasesUnion _o) { + switch (_o.Type) { + default: return 0; + case AnyAmbiguousAliases.M1: return MyGame.Example.Monster.Pack(builder, _o.AsM1()).Value; + case AnyAmbiguousAliases.M2: return MyGame.Example.Monster.Pack(builder, _o.AsM2()).Value; + case AnyAmbiguousAliases.M3: return MyGame.Example.Monster.Pack(builder, _o.AsM3()).Value; + } + } +} + +public class AnyAmbiguousAliasesUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(AnyAmbiguousAliasesUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as AnyAmbiguousAliasesUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, AnyAmbiguousAliasesUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as AnyAmbiguousAliasesUnion, serializer); + } + } + public AnyAmbiguousAliasesUnion ReadJson(Newtonsoft.Json.JsonReader reader, AnyAmbiguousAliasesUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case AnyAmbiguousAliases.M1: _o.Value = serializer.Deserialize(reader); break; + case AnyAmbiguousAliases.M2: _o.Value = serializer.Deserialize(reader); break; + case AnyAmbiguousAliases.M3: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class AnyAmbiguousAliasesVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((AnyAmbiguousAliases)typeId) + { + case AnyAmbiguousAliases.M1: + result = MyGame.Example.MonsterVerify.Verify(verifier, tablePos); + break; + case AnyAmbiguousAliases.M2: + result = MyGame.Example.MonsterVerify.Verify(verifier, tablePos); + break; + case AnyAmbiguousAliases.M3: + result = MyGame.Example.MonsterVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.go b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.go new file mode 100644 index 00000000000..6cfb12f7436 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.go @@ -0,0 +1,76 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" + "strconv" +) + +type AnyAmbiguousAliases byte + +const ( + AnyAmbiguousAliasesNONE AnyAmbiguousAliases = 0 + AnyAmbiguousAliasesM1 AnyAmbiguousAliases = 1 + AnyAmbiguousAliasesM2 AnyAmbiguousAliases = 2 + AnyAmbiguousAliasesM3 AnyAmbiguousAliases = 3 +) + +var EnumNamesAnyAmbiguousAliases = map[AnyAmbiguousAliases]string{ + AnyAmbiguousAliasesNONE: "NONE", + AnyAmbiguousAliasesM1: "M1", + AnyAmbiguousAliasesM2: "M2", + AnyAmbiguousAliasesM3: "M3", +} + +var EnumValuesAnyAmbiguousAliases = map[string]AnyAmbiguousAliases{ + "NONE": AnyAmbiguousAliasesNONE, + "M1": AnyAmbiguousAliasesM1, + "M2": AnyAmbiguousAliasesM2, + "M3": AnyAmbiguousAliasesM3, +} + +func (v AnyAmbiguousAliases) String() string { + if s, ok := EnumNamesAnyAmbiguousAliases[v]; ok { + return s + } + return "AnyAmbiguousAliases(" + strconv.FormatInt(int64(v), 10) + ")" +} + +type AnyAmbiguousAliasesT struct { + Type AnyAmbiguousAliases + Value interface{} +} + +func (t *AnyAmbiguousAliasesT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + switch t.Type { + case AnyAmbiguousAliasesM1: + return t.Value.(*MonsterT).Pack(builder) + case AnyAmbiguousAliasesM2: + return t.Value.(*MonsterT).Pack(builder) + case AnyAmbiguousAliasesM3: + return t.Value.(*MonsterT).Pack(builder) + } + return 0 +} + +func (rcv AnyAmbiguousAliases) UnPack(table flatbuffers.Table) *AnyAmbiguousAliasesT { + switch rcv { + case AnyAmbiguousAliasesM1: + var x Monster + x.Init(table.Bytes, table.Pos) + return &AnyAmbiguousAliasesT{Type: AnyAmbiguousAliasesM1, Value: x.UnPack()} + case AnyAmbiguousAliasesM2: + var x Monster + x.Init(table.Bytes, table.Pos) + return &AnyAmbiguousAliasesT{Type: AnyAmbiguousAliasesM2, Value: x.UnPack()} + case AnyAmbiguousAliasesM3: + var x Monster + x.Init(table.Bytes, table.Pos) + return &AnyAmbiguousAliasesT{Type: AnyAmbiguousAliasesM3, Value: x.UnPack()} + } + return nil +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.java b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.java new file mode 100644 index 00000000000..1b97b2c9ee3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.java @@ -0,0 +1,17 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +@SuppressWarnings("unused") +public final class AnyAmbiguousAliases { + private AnyAmbiguousAliases() { } + public static final byte NONE = 0; + public static final byte M1 = 1; + public static final byte M2 = 2; + public static final byte M3 = 3; + + public static final String[] names = { "NONE", "M1", "M2", "M3", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.kt b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.kt new file mode 100644 index 00000000000..c38923b9e98 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.kt @@ -0,0 +1,15 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +@Suppress("unused") +class AnyAmbiguousAliases private constructor() { + companion object { + const val NONE: UByte = 0u + const val M1: UByte = 1u + const val M2: UByte = 2u + const val M3: UByte = 3u + val names : Array = arrayOf("NONE", "M1", "M2", "M3") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.lua b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.lua new file mode 100644 index 00000000000..8866b671f06 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.lua @@ -0,0 +1,20 @@ +--[[ MyGame.Example.AnyAmbiguousAliases + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local AnyAmbiguousAliases = { + NONE = 0, + M1 = 1, + M2 = 2, + M3 = 3, +} + +return AnyAmbiguousAliases \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.nim b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.nim new file mode 100644 index 00000000000..48c683e7f2e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.nim @@ -0,0 +1,15 @@ +#[ MyGame.Example.AnyAmbiguousAliases + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +type AnyAmbiguousAliases*{.pure.} = enum + None = 0.uint8, + M1 = 1.uint8, + M2 = 2.uint8, + M3 = 3.uint8, diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.php b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.php new file mode 100644 index 00000000000..13d318a06d6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.php @@ -0,0 +1,27 @@ +"NONE", + AnyAmbiguousAliases::M1=>"M1", + AnyAmbiguousAliases::M2=>"M2", + AnyAmbiguousAliases::M3=>"M3", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.py b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.py new file mode 100644 index 00000000000..3a685f9a19b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliases.py @@ -0,0 +1,24 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +class AnyAmbiguousAliases(object): + NONE = 0 + M1 = 1 + M2 = 2 + M3 = 3 + +def AnyAmbiguousAliasesCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == AnyAmbiguousAliases.M1: + import MyGame.Example.Monster + return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyAmbiguousAliases.M2: + import MyGame.Example.Monster + return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyAmbiguousAliases.M3: + import MyGame.Example.Monster + return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + return None diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliasesUnion.java b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliasesUnion.java new file mode 100644 index 00000000000..879d5811c84 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyAmbiguousAliasesUnion.java @@ -0,0 +1,37 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.FlatBufferBuilder; + +public class AnyAmbiguousAliasesUnion { + private byte type; + private Object value; + + public byte getType() { return type; } + + public void setType(byte type) { this.type = type; } + + public Object getValue() { return value; } + + public void setValue(Object value) { this.value = value; } + + public AnyAmbiguousAliasesUnion() { + this.type = AnyAmbiguousAliases.NONE; + this.value = null; + } + + public MyGame.Example.MonsterT asM1() { return (MyGame.Example.MonsterT) value; } + public MyGame.Example.MonsterT asM2() { return (MyGame.Example.MonsterT) value; } + public MyGame.Example.MonsterT asM3() { return (MyGame.Example.MonsterT) value; } + + public static int pack(FlatBufferBuilder builder, AnyAmbiguousAliasesUnion _o) { + switch (_o.type) { + case AnyAmbiguousAliases.M1: return MyGame.Example.Monster.pack(builder, _o.asM1()); + case AnyAmbiguousAliases.M2: return MyGame.Example.Monster.pack(builder, _o.asM2()); + case AnyAmbiguousAliases.M3: return MyGame.Example.Monster.pack(builder, _o.asM3()); + default: return 0; + } + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUnion.java b/third_party/flatbuffers/tests/MyGame/Example/AnyUnion.java new file mode 100644 index 00000000000..b0125155db1 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUnion.java @@ -0,0 +1,37 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.FlatBufferBuilder; + +public class AnyUnion { + private byte type; + private Object value; + + public byte getType() { return type; } + + public void setType(byte type) { this.type = type; } + + public Object getValue() { return value; } + + public void setValue(Object value) { this.value = value; } + + public AnyUnion() { + this.type = Any.NONE; + this.value = null; + } + + public MyGame.Example.MonsterT asMonster() { return (MyGame.Example.MonsterT) value; } + MyGame.Example.TestSimpleTableWithEnumT asTestSimpleTableWithEnum() { return (MyGame.Example.TestSimpleTableWithEnumT) value; } + public MyGame.Example2.MonsterT asMyGame_Example2_Monster() { return (MyGame.Example2.MonsterT) value; } + + public static int pack(FlatBufferBuilder builder, AnyUnion _o) { + switch (_o.type) { + case Any.Monster: return MyGame.Example.Monster.pack(builder, _o.asMonster()); + case Any.TestSimpleTableWithEnum: return MyGame.Example.TestSimpleTableWithEnum.pack(builder, _o.asTestSimpleTableWithEnum()); + case Any.MyGame_Example2_Monster: return MyGame.Example2.Monster.pack(builder, _o.asMyGame_Example2_Monster()); + default: return 0; + } + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.cs b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.cs new file mode 100644 index 00000000000..099046de501 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.cs @@ -0,0 +1,113 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum AnyUniqueAliases : byte +{ + NONE = 0, + M = 1, + TS = 2, + M2 = 3, +}; + +public class AnyUniqueAliasesUnion { + public AnyUniqueAliases Type { get; set; } + public object Value { get; set; } + + public AnyUniqueAliasesUnion() { + this.Type = AnyUniqueAliases.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public MyGame.Example.MonsterT AsM() { return this.As(); } + public static AnyUniqueAliasesUnion FromM(MyGame.Example.MonsterT _m) { return new AnyUniqueAliasesUnion{ Type = AnyUniqueAliases.M, Value = _m }; } + internal MyGame.Example.TestSimpleTableWithEnumT AsTS() { return this.As(); } + internal static AnyUniqueAliasesUnion FromTS(MyGame.Example.TestSimpleTableWithEnumT _ts) { return new AnyUniqueAliasesUnion{ Type = AnyUniqueAliases.TS, Value = _ts }; } + public MyGame.Example2.MonsterT AsM2() { return this.As(); } + public static AnyUniqueAliasesUnion FromM2(MyGame.Example2.MonsterT _m2) { return new AnyUniqueAliasesUnion{ Type = AnyUniqueAliases.M2, Value = _m2 }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, AnyUniqueAliasesUnion _o) { + switch (_o.Type) { + default: return 0; + case AnyUniqueAliases.M: return MyGame.Example.Monster.Pack(builder, _o.AsM()).Value; + case AnyUniqueAliases.TS: return MyGame.Example.TestSimpleTableWithEnum.Pack(builder, _o.AsTS()).Value; + case AnyUniqueAliases.M2: return MyGame.Example2.Monster.Pack(builder, _o.AsM2()).Value; + } + } +} + +public class AnyUniqueAliasesUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(AnyUniqueAliasesUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as AnyUniqueAliasesUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, AnyUniqueAliasesUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as AnyUniqueAliasesUnion, serializer); + } + } + public AnyUniqueAliasesUnion ReadJson(Newtonsoft.Json.JsonReader reader, AnyUniqueAliasesUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case AnyUniqueAliases.M: _o.Value = serializer.Deserialize(reader); break; + case AnyUniqueAliases.TS: _o.Value = serializer.Deserialize(reader); break; + case AnyUniqueAliases.M2: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class AnyUniqueAliasesVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((AnyUniqueAliases)typeId) + { + case AnyUniqueAliases.M: + result = MyGame.Example.MonsterVerify.Verify(verifier, tablePos); + break; + case AnyUniqueAliases.TS: + result = MyGame.Example.TestSimpleTableWithEnumVerify.Verify(verifier, tablePos); + break; + case AnyUniqueAliases.M2: + result = MyGame.Example2.MonsterVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.go b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.go new file mode 100644 index 00000000000..0bf17b09f95 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.go @@ -0,0 +1,78 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" + "strconv" + + MyGame__Example2 "MyGame/Example2" +) + +type AnyUniqueAliases byte + +const ( + AnyUniqueAliasesNONE AnyUniqueAliases = 0 + AnyUniqueAliasesM AnyUniqueAliases = 1 + AnyUniqueAliasesTS AnyUniqueAliases = 2 + AnyUniqueAliasesM2 AnyUniqueAliases = 3 +) + +var EnumNamesAnyUniqueAliases = map[AnyUniqueAliases]string{ + AnyUniqueAliasesNONE: "NONE", + AnyUniqueAliasesM: "M", + AnyUniqueAliasesTS: "TS", + AnyUniqueAliasesM2: "M2", +} + +var EnumValuesAnyUniqueAliases = map[string]AnyUniqueAliases{ + "NONE": AnyUniqueAliasesNONE, + "M": AnyUniqueAliasesM, + "TS": AnyUniqueAliasesTS, + "M2": AnyUniqueAliasesM2, +} + +func (v AnyUniqueAliases) String() string { + if s, ok := EnumNamesAnyUniqueAliases[v]; ok { + return s + } + return "AnyUniqueAliases(" + strconv.FormatInt(int64(v), 10) + ")" +} + +type AnyUniqueAliasesT struct { + Type AnyUniqueAliases + Value interface{} +} + +func (t *AnyUniqueAliasesT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + switch t.Type { + case AnyUniqueAliasesM: + return t.Value.(*MonsterT).Pack(builder) + case AnyUniqueAliasesTS: + return t.Value.(*TestSimpleTableWithEnumT).Pack(builder) + case AnyUniqueAliasesM2: + return t.Value.(*MyGame__Example2.MonsterT).Pack(builder) + } + return 0 +} + +func (rcv AnyUniqueAliases) UnPack(table flatbuffers.Table) *AnyUniqueAliasesT { + switch rcv { + case AnyUniqueAliasesM: + var x Monster + x.Init(table.Bytes, table.Pos) + return &AnyUniqueAliasesT{Type: AnyUniqueAliasesM, Value: x.UnPack()} + case AnyUniqueAliasesTS: + var x TestSimpleTableWithEnum + x.Init(table.Bytes, table.Pos) + return &AnyUniqueAliasesT{Type: AnyUniqueAliasesTS, Value: x.UnPack()} + case AnyUniqueAliasesM2: + var x MyGame__Example2.Monster + x.Init(table.Bytes, table.Pos) + return &AnyUniqueAliasesT{Type: AnyUniqueAliasesM2, Value: x.UnPack()} + } + return nil +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.java b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.java new file mode 100644 index 00000000000..a06423a267a --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.java @@ -0,0 +1,17 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +@SuppressWarnings("unused") +public final class AnyUniqueAliases { + private AnyUniqueAliases() { } + public static final byte NONE = 0; + public static final byte M = 1; + public static final byte TS = 2; + public static final byte M2 = 3; + + public static final String[] names = { "NONE", "M", "TS", "M2", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.kt b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.kt new file mode 100644 index 00000000000..2db45a6c2cb --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.kt @@ -0,0 +1,15 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +@Suppress("unused") +class AnyUniqueAliases private constructor() { + companion object { + const val NONE: UByte = 0u + const val M: UByte = 1u + const val TS: UByte = 2u + const val M2: UByte = 3u + val names : Array = arrayOf("NONE", "M", "TS", "M2") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.lua b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.lua new file mode 100644 index 00000000000..94fe7d372ab --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.lua @@ -0,0 +1,20 @@ +--[[ MyGame.Example.AnyUniqueAliases + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local AnyUniqueAliases = { + NONE = 0, + M = 1, + TS = 2, + M2 = 3, +} + +return AnyUniqueAliases \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.nim b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.nim new file mode 100644 index 00000000000..037eb921b75 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.nim @@ -0,0 +1,15 @@ +#[ MyGame.Example.AnyUniqueAliases + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +type AnyUniqueAliases*{.pure.} = enum + None = 0.uint8, + M = 1.uint8, + Ts = 2.uint8, + M2 = 3.uint8, diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.php b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.php new file mode 100644 index 00000000000..830d8b52995 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.php @@ -0,0 +1,27 @@ +"NONE", + AnyUniqueAliases::M=>"M", + AnyUniqueAliases::TS=>"TS", + AnyUniqueAliases::M2=>"M2", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.py b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.py new file mode 100644 index 00000000000..837505e4055 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliases.py @@ -0,0 +1,24 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +class AnyUniqueAliases(object): + NONE = 0 + M = 1 + TS = 2 + M2 = 3 + +def AnyUniqueAliasesCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == AnyUniqueAliases.M: + import MyGame.Example.Monster + return MyGame.Example.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyUniqueAliases.TS: + import MyGame.Example.TestSimpleTableWithEnum + return MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyUniqueAliases.M2: + import MyGame.Example2.Monster + return MyGame.Example2.Monster.MonsterT.InitFromBuf(table.Bytes, table.Pos) + return None diff --git a/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliasesUnion.java b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliasesUnion.java new file mode 100644 index 00000000000..71bf4914677 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/AnyUniqueAliasesUnion.java @@ -0,0 +1,37 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.FlatBufferBuilder; + +public class AnyUniqueAliasesUnion { + private byte type; + private Object value; + + public byte getType() { return type; } + + public void setType(byte type) { this.type = type; } + + public Object getValue() { return value; } + + public void setValue(Object value) { this.value = value; } + + public AnyUniqueAliasesUnion() { + this.type = AnyUniqueAliases.NONE; + this.value = null; + } + + public MyGame.Example.MonsterT asM() { return (MyGame.Example.MonsterT) value; } + MyGame.Example.TestSimpleTableWithEnumT asTS() { return (MyGame.Example.TestSimpleTableWithEnumT) value; } + public MyGame.Example2.MonsterT asM2() { return (MyGame.Example2.MonsterT) value; } + + public static int pack(FlatBufferBuilder builder, AnyUniqueAliasesUnion _o) { + switch (_o.type) { + case AnyUniqueAliases.M: return MyGame.Example.Monster.pack(builder, _o.asM()); + case AnyUniqueAliases.TS: return MyGame.Example.TestSimpleTableWithEnum.pack(builder, _o.asTS()); + case AnyUniqueAliases.M2: return MyGame.Example2.Monster.pack(builder, _o.asM2()); + default: return 0; + } + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.cs b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.cs new file mode 100644 index 00000000000..70a8bddd194 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.cs @@ -0,0 +1,128 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct ArrayStruct : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public ArrayStruct __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public float A { get { return __p.bb.GetFloat(__p.bb_pos + 0); } } + public void MutateA(float a) { __p.bb.PutFloat(__p.bb_pos + 0, a); } + public int B(int j) { return __p.bb.GetInt(__p.bb_pos + 4 + j * 4); } + public void MutateB(int j, int b) { __p.bb.PutInt(__p.bb_pos + 4 + j * 4, b); } + public sbyte C { get { return __p.bb.GetSbyte(__p.bb_pos + 64); } } + public void MutateC(sbyte c) { __p.bb.PutSbyte(__p.bb_pos + 64, c); } + public MyGame.Example.NestedStruct D(int j) { return (new MyGame.Example.NestedStruct()).__assign(__p.bb_pos + 72 + j * 32, __p.bb); } + public int E { get { return __p.bb.GetInt(__p.bb_pos + 136); } } + public void MutateE(int e) { __p.bb.PutInt(__p.bb_pos + 136, e); } + public long F(int j) { return __p.bb.GetLong(__p.bb_pos + 144 + j * 8); } + public void MutateF(int j, long f) { __p.bb.PutLong(__p.bb_pos + 144 + j * 8, f); } + + public static Offset CreateArrayStruct(FlatBufferBuilder builder, float A, int[] B, sbyte C, int[,] d_A, MyGame.Example.TestEnum[] d_B, MyGame.Example.TestEnum[,] d_C, long[,] d_D, int E, long[] F) { + builder.Prep(8, 160); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.PutLong(F[_idx0-1]); + } + builder.Pad(4); + builder.PutInt(E); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.Prep(8, 32); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.PutLong(d_D[_idx0-1,_idx1-1]); + } + builder.Pad(5); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.PutSbyte((sbyte)d_C[_idx0-1,_idx1-1]); + } + builder.PutSbyte((sbyte)d_B[_idx0-1]); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.PutInt(d_A[_idx0-1,_idx1-1]); + } + } + builder.Pad(7); + builder.PutSbyte(C); + for (int _idx0 = 15; _idx0 > 0; _idx0--) { + builder.PutInt(B[_idx0-1]); + } + builder.PutFloat(A); + return new Offset(builder.Offset); + } + public ArrayStructT UnPack() { + var _o = new ArrayStructT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(ArrayStructT _o) { + _o.A = this.A; + _o.B = new int[15]; + for (var _j = 0; _j < 15; ++_j) { _o.B[_j] = this.B(_j); } + _o.C = this.C; + _o.D = new MyGame.Example.NestedStructT[2]; + for (var _j = 0; _j < 2; ++_j) { _o.D[_j] = this.D(_j).UnPack(); } + _o.E = this.E; + _o.F = new long[2]; + for (var _j = 0; _j < 2; ++_j) { _o.F[_j] = this.F(_j); } + } + public static Offset Pack(FlatBufferBuilder builder, ArrayStructT _o) { + if (_o == null) return default(Offset); + var _b = _o.B; + var _d_a = new int[2,2]; + for (var idx0 = 0; idx0 < 2; ++idx0) {for (var idx1 = 0; idx1 < 2; ++idx1) {_d_a[idx0,idx1] = _o.D[idx0].A[idx1];}} + var _d_b = new MyGame.Example.TestEnum[2]; + for (var idx0 = 0; idx0 < 2; ++idx0) {_d_b[idx0] = _o.D[idx0].B;} + var _d_c = new MyGame.Example.TestEnum[2,2]; + for (var idx0 = 0; idx0 < 2; ++idx0) {for (var idx1 = 0; idx1 < 2; ++idx1) {_d_c[idx0,idx1] = _o.D[idx0].C[idx1];}} + var _d_d = new long[2,2]; + for (var idx0 = 0; idx0 < 2; ++idx0) {for (var idx1 = 0; idx1 < 2; ++idx1) {_d_d[idx0,idx1] = _o.D[idx0].D[idx1];}} + var _f = _o.F; + return CreateArrayStruct( + builder, + _o.A, + _b, + _o.C, + _d_a, + _d_b, + _d_c, + _d_d, + _o.E, + _f); + } +} + +public class ArrayStructT +{ + [Newtonsoft.Json.JsonProperty("a")] + public float A { get; set; } + [Newtonsoft.Json.JsonProperty("b")] + public int[] B { get; set; } + [Newtonsoft.Json.JsonProperty("c")] + public sbyte C { get; set; } + [Newtonsoft.Json.JsonProperty("d")] + public MyGame.Example.NestedStructT[] D { get; set; } + [Newtonsoft.Json.JsonProperty("e")] + public int E { get; set; } + [Newtonsoft.Json.JsonProperty("f")] + public long[] F { get; set; } + + public ArrayStructT() { + this.A = 0.0f; + this.B = new int[15]; + this.C = 0; + this.D = new MyGame.Example.NestedStructT[2]; + this.E = 0; + this.F = new long[2]; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.java b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.java new file mode 100644 index 00000000000..b859560bdc6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.java @@ -0,0 +1,120 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class ArrayStruct extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public ArrayStruct __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public float a() { return bb.getFloat(bb_pos + 0); } + public void mutateA(float a) { bb.putFloat(bb_pos + 0, a); } + public int b(int j) { return bb.getInt(bb_pos + 4 + j * 4); } + public void mutateB(int j, int b) { bb.putInt(bb_pos + 4 + j * 4, b); } + public byte c() { return bb.get(bb_pos + 64); } + public void mutateC(byte c) { bb.put(bb_pos + 64, c); } + public MyGame.Example.NestedStruct d(int j) { return d(new MyGame.Example.NestedStruct(), j); } + public MyGame.Example.NestedStruct d(MyGame.Example.NestedStruct obj, int j) { return obj.__assign(bb_pos + 72 + j * 32, bb); } + public int e() { return bb.getInt(bb_pos + 136); } + public void mutateE(int e) { bb.putInt(bb_pos + 136, e); } + public long f(int j) { return bb.getLong(bb_pos + 144 + j * 8); } + public void mutateF(int j, long f) { bb.putLong(bb_pos + 144 + j * 8, f); } + + public static int createArrayStruct(FlatBufferBuilder builder, float a, int[] b, byte c, int[][] d_a, byte[] d_b, byte[][] d_c, long[][] d_d, int e, long[] f) { + builder.prep(8, 160); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.putLong(f[_idx0-1]); + } + builder.pad(4); + builder.putInt(e); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.prep(8, 32); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.putLong(d_d[_idx0-1][_idx1-1]); + } + builder.pad(5); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.putByte(d_c[_idx0-1][_idx1-1]); + } + builder.putByte(d_b[_idx0-1]); + for (int _idx1 = 2; _idx1 > 0; _idx1--) { + builder.putInt(d_a[_idx0-1][_idx1-1]); + } + } + builder.pad(7); + builder.putByte(c); + for (int _idx0 = 15; _idx0 > 0; _idx0--) { + builder.putInt(b[_idx0-1]); + } + builder.putFloat(a); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public ArrayStruct get(int j) { return get(new ArrayStruct(), j); } + public ArrayStruct get(ArrayStruct obj, int j) { return obj.__assign(__element(j), bb); } + } + public ArrayStructT unpack() { + ArrayStructT _o = new ArrayStructT(); + unpackTo(_o); + return _o; + } + public void unpackTo(ArrayStructT _o) { + float _oA = a(); + _o.setA(_oA); + int[] _oB = _o.getB(); + for (int _j = 0; _j < 15; ++_j) { _oB[_j] = b(_j); } + byte _oC = c(); + _o.setC(_oC); + MyGame.Example.NestedStructT[] _oD = _o.getD(); + for (int _j = 0; _j < 2; ++_j) { _oD[_j] = d(_j).unpack(); } + int _oE = e(); + _o.setE(_oE); + long[] _oF = _o.getF(); + for (int _j = 0; _j < 2; ++_j) { _oF[_j] = f(_j); } + } + public static int pack(FlatBufferBuilder builder, ArrayStructT _o) { + if (_o == null) return 0; + int[] _b = _o.getB(); + int[][] _d_a = new int[2][2]; + for (int idx0 = 0; idx0 < 2; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_d_a[idx0][idx1] = _o.getD()[idx0].getA()[idx1];}} + byte[] _d_b = new byte[2]; + for (int idx0 = 0; idx0 < 2; ++idx0) {_d_b[idx0] = _o.getD()[idx0].getB();} + byte[][] _d_c = new byte[2][2]; + for (int idx0 = 0; idx0 < 2; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_d_c[idx0][idx1] = _o.getD()[idx0].getC()[idx1];}} + long[][] _d_d = new long[2][2]; + for (int idx0 = 0; idx0 < 2; ++idx0) {for (int idx1 = 0; idx1 < 2; ++idx1) {_d_d[idx0][idx1] = _o.getD()[idx0].getD()[idx1];}} + long[] _f = _o.getF(); + return createArrayStruct( + builder, + _o.getA(), + _b, + _o.getC(), + _d_a, + _d_b, + _d_c, + _d_d, + _o.getE(), + _f); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.py b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.py new file mode 100644 index 00000000000..a839c09f9c1 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.py @@ -0,0 +1,174 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +from MyGame.Example.NestedStruct import NestedStruct +np = import_numpy() + +class ArrayStruct(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls) -> int: + return 160 + + # ArrayStruct + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # ArrayStruct + def A(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # ArrayStruct + def B(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4 + i * 4)) for i in range(self.BLength())] + elif j >= 0 and j < self.BLength(): + return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4 + j * 4)) + else: + return None + + # ArrayStruct + def BAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int32Flags, self._tab.Pos + 4, self.BLength()) + + # ArrayStruct + def BLength(self) -> int: + return 15 + + # ArrayStruct + def BIsNone(self) -> bool: + return False + + # ArrayStruct + def C(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(64)) + # ArrayStruct + def D(self, i: int) -> NestedStruct: + obj = NestedStruct() + obj.Init(self._tab.Bytes, self._tab.Pos + 72 + i * 32) + return obj + + # ArrayStruct + def DLength(self) -> int: + return 2 + + # ArrayStruct + def DIsNone(self) -> bool: + return False + + # ArrayStruct + def E(self): return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(136)) + # ArrayStruct + def F(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Int64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(144 + i * 8)) for i in range(self.FLength())] + elif j >= 0 and j < self.FLength(): + return self._tab.Get(flatbuffers.number_types.Int64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(144 + j * 8)) + else: + return None + + # ArrayStruct + def FAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int64Flags, self._tab.Pos + 144, self.FLength()) + + # ArrayStruct + def FLength(self) -> int: + return 2 + + # ArrayStruct + def FIsNone(self) -> bool: + return False + + +def CreateArrayStruct(builder, a, b, c, d_a, d_b, d_c, d_d, e, f): + builder.Prep(8, 160) + for _idx0 in range(2 , 0, -1): + builder.PrependInt64(f[_idx0-1]) + builder.Pad(4) + builder.PrependInt32(e) + for _idx0 in range(2 , 0, -1): + builder.Prep(8, 32) + for _idx1 in range(2 , 0, -1): + builder.PrependInt64(d_d[_idx0-1][_idx1-1]) + builder.Pad(5) + for _idx1 in range(2 , 0, -1): + builder.PrependInt8(d_c[_idx0-1][_idx1-1]) + builder.PrependInt8(d_b[_idx0-1]) + for _idx1 in range(2 , 0, -1): + builder.PrependInt32(d_a[_idx0-1][_idx1-1]) + builder.Pad(7) + builder.PrependInt8(c) + for _idx0 in range(15 , 0, -1): + builder.PrependInt32(b[_idx0-1]) + builder.PrependFloat32(a) + return builder.Offset() + +import MyGame.Example.NestedStruct +try: + from typing import List +except: + pass + +class ArrayStructT(object): + + # ArrayStructT + def __init__(self): + self.a = 0.0 # type: float + self.b = None # type: List[int] + self.c = 0 # type: int + self.d = None # type: List[MyGame.Example.NestedStruct.NestedStructT] + self.e = 0 # type: int + self.f = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + arrayStruct = ArrayStruct() + arrayStruct.Init(buf, pos) + return cls.InitFromObj(arrayStruct) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, arrayStruct): + x = ArrayStructT() + x._UnPack(arrayStruct) + return x + + # ArrayStructT + def _UnPack(self, arrayStruct): + if arrayStruct is None: + return + self.a = arrayStruct.A() + if not arrayStruct.BIsNone(): + if np is None: + self.b = [] + for i in range(arrayStruct.BLength()): + self.b.append(arrayStruct.B(i)) + else: + self.b = arrayStruct.BAsNumpy() + self.c = arrayStruct.C() + if not arrayStruct.DIsNone(): + self.d = [] + for i in range(arrayStruct.DLength()): + if arrayStruct.D(i) is None: + self.d.append(None) + else: + nestedStruct_ = MyGame.Example.NestedStruct.NestedStructT.InitFromObj(arrayStruct.D(i)) + self.d.append(nestedStruct_) + self.e = arrayStruct.E() + if not arrayStruct.FIsNone(): + if np is None: + self.f = [] + for i in range(arrayStruct.FLength()): + self.f.append(arrayStruct.F(i)) + else: + self.f = arrayStruct.FAsNumpy() + + # ArrayStructT + def Pack(self, builder): + return CreateArrayStruct(builder, self.a, self.b, self.c, self.d.a, self.d.b, self.d.c, self.d.d, self.e, self.f) diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.pyi b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.pyi new file mode 100644 index 00000000000..29bb83c6762 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayStruct.pyi @@ -0,0 +1,50 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.ArrayStruct import ArrayStruct +from MyGame.Example.NestedStruct import NestedStruct, NestedStructT +from MyGame.Example.TestEnum import TestEnum + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class ArrayStruct(object): + @classmethod + def SizeOf(cls) -> int: ... + + def Init(self, buf: bytes, pos: int) -> None: ... + def A(self) -> float: ... + def B(self, i: int) -> typing.List[int]: ... + def BAsNumpy(self) -> np.ndarray: ... + def BLength(self) -> int: ... + def BIsNone(self) -> bool: ... + def C(self) -> int: ... + def D(self, i: int) -> NestedStruct | None: ... + def DLength(self) -> int: ... + def DIsNone(self) -> bool: ... + def E(self) -> int: ... + def F(self, i: int) -> typing.List[int]: ... + def FAsNumpy(self) -> np.ndarray: ... + def FLength(self) -> int: ... + def FIsNone(self) -> bool: ... +class ArrayStructT(object): + a: float + b: typing.List[int] + c: int + d: typing.List[NestedStructT] + e: int + f: typing.List[int] + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> ArrayStructT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> ArrayStructT: ... + @classmethod + def InitFromObj(cls, arrayStruct: ArrayStruct) -> ArrayStructT: ... + def _UnPack(self, arrayStruct: ArrayStruct) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... + +def CreateArrayStruct(builder: flatbuffers.Builder, a: float, b: int, c: int, d_a: int, d_b: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C], d_c: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C], d_d: int, e: int, f: int) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayStructT.java b/third_party/flatbuffers/tests/MyGame/Example/ArrayStructT.java new file mode 100644 index 00000000000..99922be98a0 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayStructT.java @@ -0,0 +1,64 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class ArrayStructT { + private float a; + private int[] b; + private byte c; + private MyGame.Example.NestedStructT[] d; + private int e; + private long[] f; + + public float getA() { return a; } + + public void setA(float a) { this.a = a; } + + public int[] getB() { return b; } + + public void setB(int[] b) { if (b != null && b.length == 15) this.b = b; } + + public byte getC() { return c; } + + public void setC(byte c) { this.c = c; } + + public MyGame.Example.NestedStructT[] getD() { return d; } + + public void setD(MyGame.Example.NestedStructT[] d) { if (d != null && d.length == 2) this.d = d; } + + public int getE() { return e; } + + public void setE(int e) { this.e = e; } + + public long[] getF() { return f; } + + public void setF(long[] f) { if (f != null && f.length == 2) this.f = f; } + + + public ArrayStructT() { + this.a = 0.0f; + this.b = new int[15]; + this.c = 0; + this.d = new MyGame.Example.NestedStructT[2]; + this.e = 0; + this.f = new long[2]; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.cs b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.cs new file mode 100644 index 00000000000..086915e7ca6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.cs @@ -0,0 +1,86 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct ArrayTable : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static ArrayTable GetRootAsArrayTable(ByteBuffer _bb) { return GetRootAsArrayTable(_bb, new ArrayTable()); } + public static ArrayTable GetRootAsArrayTable(ByteBuffer _bb, ArrayTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool ArrayTableBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "ARRT"); } + public static bool VerifyArrayTable(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("ARRT", false, ArrayTableVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public ArrayTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.ArrayStruct? A { get { int o = __p.__offset(4); return o != 0 ? (MyGame.Example.ArrayStruct?)(new MyGame.Example.ArrayStruct()).__assign(o + __p.bb_pos, __p.bb) : null; } } + + public static void StartArrayTable(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddA(FlatBufferBuilder builder, Offset aOffset) { builder.AddStruct(0, aOffset.Value, 0); } + public static Offset EndArrayTable(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishArrayTableBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value, "ARRT"); } + public static void FinishSizePrefixedArrayTableBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value, "ARRT"); } + public ArrayTableT UnPack() { + var _o = new ArrayTableT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(ArrayTableT _o) { + _o.A = this.A.HasValue ? this.A.Value.UnPack() : null; + } + public static Offset Pack(FlatBufferBuilder builder, ArrayTableT _o) { + if (_o == null) return default(Offset); + StartArrayTable(builder); + AddA(builder, MyGame.Example.ArrayStruct.Pack(builder, _o.A)); + return EndArrayTable(builder); + } +} + +public class ArrayTableT +{ + [Newtonsoft.Json.JsonProperty("a")] + public MyGame.Example.ArrayStructT A { get; set; } + + public ArrayTableT() { + this.A = new MyGame.Example.ArrayStructT(); + } + + public static ArrayTableT DeserializeFromJson(string jsonText) { + return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText); + } + public string SerializeToJson() { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + public static ArrayTableT DeserializeFromBinary(byte[] fbBuffer) { + return ArrayTable.GetRootAsArrayTable(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + ArrayTable.FinishArrayTableBuffer(fbb, ArrayTable.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class ArrayTableVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*A*/, 160 /*MyGame.Example.ArrayStruct*/, 8, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.java b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.java new file mode 100644 index 00000000000..9653e4aa185 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.java @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class ArrayTable extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static ArrayTable getRootAsArrayTable(ByteBuffer _bb) { return getRootAsArrayTable(_bb, new ArrayTable()); } + public static ArrayTable getRootAsArrayTable(ByteBuffer _bb, ArrayTable obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public static boolean ArrayTableBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "ARRT"); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public ArrayTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.ArrayStruct a() { return a(new MyGame.Example.ArrayStruct()); } + public MyGame.Example.ArrayStruct a(MyGame.Example.ArrayStruct obj) { int o = __offset(4); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; } + + public static void startArrayTable(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addA(FlatBufferBuilder builder, int aOffset) { builder.addStruct(0, aOffset, 0); } + public static int endArrayTable(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + public static void finishArrayTableBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "ARRT"); } + public static void finishSizePrefixedArrayTableBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "ARRT"); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public ArrayTable get(int j) { return get(new ArrayTable(), j); } + public ArrayTable get(ArrayTable obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public ArrayTableT unpack() { + ArrayTableT _o = new ArrayTableT(); + unpackTo(_o); + return _o; + } + public void unpackTo(ArrayTableT _o) { + if (a() != null) a().unpackTo(_o.getA()); + else _o.setA(null); + } + public static int pack(FlatBufferBuilder builder, ArrayTableT _o) { + if (_o == null) return 0; + startArrayTable(builder); + addA(builder, MyGame.Example.ArrayStruct.pack(builder, _o.getA())); + return endArrayTable(builder); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.py b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.py new file mode 100644 index 00000000000..7d314dfd517 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.py @@ -0,0 +1,105 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +from MyGame.Example.ArrayStruct import ArrayStruct +from typing import Optional +np = import_numpy() + +class ArrayTable(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ArrayTable() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsArrayTable(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ArrayTableBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x41\x52\x52\x54", size_prefixed=size_prefixed) + + # ArrayTable + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # ArrayTable + def A(self) -> Optional[ArrayStruct]: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = o + self._tab.Pos + obj = ArrayStruct() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def ArrayTableStart(builder: flatbuffers.Builder): + builder.StartObject(1) + +def Start(builder: flatbuffers.Builder): + ArrayTableStart(builder) + +def ArrayTableAddA(builder: flatbuffers.Builder, a: Any): + builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(a), 0) + +def AddA(builder: flatbuffers.Builder, a: Any): + ArrayTableAddA(builder, a) + +def ArrayTableEnd(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + +def End(builder: flatbuffers.Builder) -> int: + return ArrayTableEnd(builder) + +import MyGame.Example.ArrayStruct +try: + from typing import Optional +except: + pass + +class ArrayTableT(object): + + # ArrayTableT + def __init__(self): + self.a = None # type: Optional[MyGame.Example.ArrayStruct.ArrayStructT] + + @classmethod + def InitFromBuf(cls, buf, pos): + arrayTable = ArrayTable() + arrayTable.Init(buf, pos) + return cls.InitFromObj(arrayTable) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, arrayTable): + x = ArrayTableT() + x._UnPack(arrayTable) + return x + + # ArrayTableT + def _UnPack(self, arrayTable): + if arrayTable is None: + return + if arrayTable.A() is not None: + self.a = MyGame.Example.ArrayStruct.ArrayStructT.InitFromObj(arrayTable.A()) + + # ArrayTableT + def Pack(self, builder): + ArrayTableStart(builder) + if self.a is not None: + a = self.a.Pack(builder) + ArrayTableAddA(builder, a) + arrayTable = ArrayTableEnd(builder) + return arrayTable diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.pyi b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.pyi new file mode 100644 index 00000000000..10f2af31951 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayTable.pyi @@ -0,0 +1,37 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.ArrayStruct import ArrayStruct, ArrayStructT +from MyGame.Example.ArrayTable import ArrayTable + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class ArrayTable(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> ArrayTable: ... + @classmethod + def GetRootAsArrayTable(cls, buf: bytes, offset: int) -> ArrayTable: ... + @classmethod + def ArrayTableBufferHasIdentifier(cls, buf: bytes, offset: int, size_prefixed: bool) -> bool: ... + def Init(self, buf: bytes, pos: int) -> None: ... + def A(self) -> ArrayStruct | None: ... +class ArrayTableT(object): + a: ArrayStructT | None + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> ArrayTableT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> ArrayTableT: ... + @classmethod + def InitFromObj(cls, arrayTable: ArrayTable) -> ArrayTableT: ... + def _UnPack(self, arrayTable: ArrayTable) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... +def ArrayTableStart(builder: flatbuffers.Builder) -> None: ... +def Start(builder: flatbuffers.Builder) -> None: ... +def ArrayTableAddA(builder: flatbuffers.Builder, a: uoffset) -> None: ... +def ArrayTableEnd(builder: flatbuffers.Builder) -> uoffset: ... +def End(builder: flatbuffers.Builder) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/ArrayTableT.java b/third_party/flatbuffers/tests/MyGame/Example/ArrayTableT.java new file mode 100644 index 00000000000..645538148d0 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ArrayTableT.java @@ -0,0 +1,42 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class ArrayTableT { + private MyGame.Example.ArrayStructT a; + + public MyGame.Example.ArrayStructT getA() { return a; } + + public void setA(MyGame.Example.ArrayStructT a) { this.a = a; } + + + public ArrayTableT() { + this.a = new MyGame.Example.ArrayStructT(); + } + public static ArrayTableT deserializeFromBinary(byte[] fbBuffer) { + return ArrayTable.getRootAsArrayTable(ByteBuffer.wrap(fbBuffer)).unpack(); + } + public byte[] serializeToBinary() { + FlatBufferBuilder fbb = new FlatBufferBuilder(); + ArrayTable.finishArrayTableBuffer(fbb, ArrayTable.pack(fbb, this)); + return fbb.sizedByteArray(); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.cs b/third_party/flatbuffers/tests/MyGame/Example/Color.cs new file mode 100644 index 00000000000..1137a276865 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.cs @@ -0,0 +1,22 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +/// Composite components of Monster color. +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +[System.FlagsAttribute] +public enum Color : byte +{ + Red = 1, + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Green = 2, + /// \brief color Blue (1u << 3) + Blue = 8, +}; + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.go b/third_party/flatbuffers/tests/MyGame/Example/Color.go new file mode 100644 index 00000000000..9570ae47e77 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.go @@ -0,0 +1,36 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import "strconv" + +/// Composite components of Monster color. +type Color byte + +const ( + ColorRed Color = 1 + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + ColorGreen Color = 2 + /// \brief color Blue (1u << 3) + ColorBlue Color = 8 +) + +var EnumNamesColor = map[Color]string{ + ColorRed: "Red", + ColorGreen: "Green", + ColorBlue: "Blue", +} + +var EnumValuesColor = map[string]Color{ + "Red": ColorRed, + "Green": ColorGreen, + "Blue": ColorBlue, +} + +func (v Color) String() string { + if s, ok := EnumNamesColor[v]; ok { + return s + } + return "Color(" + strconv.FormatInt(int64(v), 10) + ")" +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.java b/third_party/flatbuffers/tests/MyGame/Example/Color.java new file mode 100644 index 00000000000..d86d382bef5 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.java @@ -0,0 +1,26 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +/** + * Composite components of Monster color. + */ +@SuppressWarnings("unused") +public final class Color { + private Color() { } + public static final int Red = 1; + /** + * \brief color Green + * Green is bit_flag with value (1u << 1) + */ + public static final int Green = 2; + /** + * \brief color Blue (1u << 3) + */ + public static final int Blue = 8; + + public static final String[] names = { "Red", "Green", "", "", "", "", "", "Blue", }; + + public static String name(int e) { return names[e - Red]; } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.kt b/third_party/flatbuffers/tests/MyGame/Example/Color.kt new file mode 100644 index 00000000000..0af56e1ee3f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.kt @@ -0,0 +1,24 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +/** + * Composite components of Monster color. + */ +@Suppress("unused") +class Color private constructor() { + companion object { + const val Red: UByte = 1u + /** + * \brief color Green + * Green is bit_flag with value (1u << 1) + */ + const val Green: UByte = 2u + /** + * \brief color Blue (1u << 3) + */ + const val Blue: UByte = 8u + val names : Array = arrayOf("Red", "Green", "", "", "", "", "", "Blue") + fun name(e: Int) : String = names[e - Red.toInt()] + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.lua b/third_party/flatbuffers/tests/MyGame/Example/Color.lua new file mode 100644 index 00000000000..fba801bcbee --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.lua @@ -0,0 +1,23 @@ +--[[ MyGame.Example.Color + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +-- Composite components of Monster color. +local Color = { + Red = 1, + -- \brief color Green + -- Green is bit_flag with value (1u << 1) + Green = 2, + -- \brief color Blue (1u << 3) + Blue = 8, +} + +return Color \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.nim b/third_party/flatbuffers/tests/MyGame/Example/Color.nim new file mode 100644 index 00000000000..7fc57d9daac --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.nim @@ -0,0 +1,18 @@ +#[ MyGame.Example.Color + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +# Composite components of Monster color. +type Color*{.pure.} = enum + Red = 1.uint8, + # \brief color Green + # Green is bit_flag with value (1u << 1) + Green = 2.uint8, + # \brief color Blue (1u << 3) + Blue = 8.uint8, diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.php b/third_party/flatbuffers/tests/MyGame/Example/Color.php new file mode 100644 index 00000000000..8c329221607 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.php @@ -0,0 +1,29 @@ +"Red", + Color::Green=>"Green", + Color::Blue=>"Blue", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Color.py b/third_party/flatbuffers/tests/MyGame/Example/Color.py new file mode 100644 index 00000000000..4ab9cc9b8f8 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Color.py @@ -0,0 +1,12 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +# Composite components of Monster color. +class Color(object): + Red = 1 + # \brief color Green + # Green is bit_flag with value (1u << 1) + Green = 2 + # \brief color Blue (1u << 3) + Blue = 8 diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.cs b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.cs new file mode 100644 index 00000000000..555109c628c --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.cs @@ -0,0 +1,18 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +[System.FlagsAttribute] +public enum LongEnum : ulong +{ + LongOne = 2, + LongTwo = 4, + LongBig = 1099511627776, +}; + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.go b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.go new file mode 100644 index 00000000000..c7c64327660 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.go @@ -0,0 +1,32 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import "strconv" + +type LongEnum uint64 + +const ( + LongEnumLongOne LongEnum = 2 + LongEnumLongTwo LongEnum = 4 + LongEnumLongBig LongEnum = 1099511627776 +) + +var EnumNamesLongEnum = map[LongEnum]string{ + LongEnumLongOne: "LongOne", + LongEnumLongTwo: "LongTwo", + LongEnumLongBig: "LongBig", +} + +var EnumValuesLongEnum = map[string]LongEnum{ + "LongOne": LongEnumLongOne, + "LongTwo": LongEnumLongTwo, + "LongBig": LongEnumLongBig, +} + +func (v LongEnum) String() string { + if s, ok := EnumNamesLongEnum[v]; ok { + return s + } + return "LongEnum(" + strconv.FormatInt(int64(v), 10) + ")" +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.java b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.java new file mode 100644 index 00000000000..ca2f81af50b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.java @@ -0,0 +1,12 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +@SuppressWarnings("unused") +public final class LongEnum { + private LongEnum() { } + public static final long LongOne = 2L; + public static final long LongTwo = 4L; + public static final long LongBig = 1099511627776L; +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.kt b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.kt new file mode 100644 index 00000000000..ecb5aabf92e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.kt @@ -0,0 +1,12 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +@Suppress("unused") +class LongEnum private constructor() { + companion object { + const val LongOne: ULong = 2UL + const val LongTwo: ULong = 4UL + const val LongBig: ULong = 1099511627776UL + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.lua b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.lua new file mode 100644 index 00000000000..052e7902d8c --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.lua @@ -0,0 +1,19 @@ +--[[ MyGame.Example.LongEnum + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local LongEnum = { + LongOne = 2, + LongTwo = 4, + LongBig = 1099511627776, +} + +return LongEnum \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.nim b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.nim new file mode 100644 index 00000000000..9e8fdbab8ff --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.nim @@ -0,0 +1,14 @@ +#[ MyGame.Example.LongEnum + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +type LongEnum*{.pure.} = enum + LongOne = 2.uint64, + LongTwo = 4.uint64, + LongBig = 1099511627776.uint64, diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.php b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.php new file mode 100644 index 00000000000..900f0d3e489 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.php @@ -0,0 +1,25 @@ +"LongOne", + LongEnum::LongTwo=>"LongTwo", + LongEnum::LongBig=>"LongBig", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/LongEnum.py b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.py new file mode 100644 index 00000000000..f45726ad27e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/LongEnum.py @@ -0,0 +1,8 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +class LongEnum(object): + LongOne = 2 + LongTwo = 4 + LongBig = 1099511627776 diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.cs b/third_party/flatbuffers/tests/MyGame/Example/Monster.cs new file mode 100644 index 00000000000..17327798208 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.cs @@ -0,0 +1,1174 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +/// an example documentation comment: "monster object" +public struct Monster : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Monster GetRootAsMonster(ByteBuffer _bb) { return GetRootAsMonster(_bb, new Monster()); } + public static Monster GetRootAsMonster(ByteBuffer _bb, Monster obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool MonsterBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "MONS"); } + public static bool VerifyMonster(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("MONS", false, MonsterVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Monster __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.Vec3? Pos { get { int o = __p.__offset(4); return o != 0 ? (MyGame.Example.Vec3?)(new MyGame.Example.Vec3()).__assign(o + __p.bb_pos, __p.bb) : null; } } + public short Mana { get { int o = __p.__offset(6); return o != 0 ? __p.bb.GetShort(o + __p.bb_pos) : (short)150; } } + public bool MutateMana(short mana) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutShort(o + __p.bb_pos, mana); return true; } else { return false; } } + public short Hp { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetShort(o + __p.bb_pos) : (short)100; } } + public bool MutateHp(short hp) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutShort(o + __p.bb_pos, hp); return true; } else { return false; } } + public string Name { get { int o = __p.__offset(10); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } } +#if ENABLE_SPAN_T + public Span GetNameBytes() { return __p.__vector_as_span(10, 1); } +#else + public ArraySegment? GetNameBytes() { return __p.__vector_as_arraysegment(10); } +#endif + public byte[] GetNameArray() { return __p.__vector_as_array(10); } + public byte Inventory(int j) { int o = __p.__offset(14); return o != 0 ? __p.bb.Get(__p.__vector(o) + j * 1) : (byte)0; } + public int InventoryLength { get { int o = __p.__offset(14); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetInventoryBytes() { return __p.__vector_as_span(14, 1); } +#else + public ArraySegment? GetInventoryBytes() { return __p.__vector_as_arraysegment(14); } +#endif + public byte[] GetInventoryArray() { return __p.__vector_as_array(14); } + public bool MutateInventory(int j, byte inventory) { int o = __p.__offset(14); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, inventory); return true; } else { return false; } } + public MyGame.Example.Color Color { get { int o = __p.__offset(16); return o != 0 ? (MyGame.Example.Color)__p.bb.Get(o + __p.bb_pos) : MyGame.Example.Color.Blue; } } + public bool MutateColor(MyGame.Example.Color color) { int o = __p.__offset(16); if (o != 0) { __p.bb.Put(o + __p.bb_pos, (byte)color); return true; } else { return false; } } + public MyGame.Example.Any TestType { get { int o = __p.__offset(18); return o != 0 ? (MyGame.Example.Any)__p.bb.Get(o + __p.bb_pos) : MyGame.Example.Any.NONE; } } + public TTable? Test() where TTable : struct, IFlatbufferObject { int o = __p.__offset(20); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public MyGame.Example.Monster TestAsMonster() { return Test().Value; } + internal MyGame.Example.TestSimpleTableWithEnum TestAsTestSimpleTableWithEnum() { return Test().Value; } + public MyGame.Example2.Monster TestAsMyGame_Example2_Monster() { return Test().Value; } + public MyGame.Example.Test? Test4(int j) { int o = __p.__offset(22); return o != 0 ? (MyGame.Example.Test?)(new MyGame.Example.Test()).__assign(__p.__vector(o) + j * 4, __p.bb) : null; } + public int Test4Length { get { int o = __p.__offset(22); return o != 0 ? __p.__vector_len(o) : 0; } } + public string Testarrayofstring(int j) { int o = __p.__offset(24); return o != 0 ? __p.__string(__p.__vector(o) + j * 4) : null; } + public int TestarrayofstringLength { get { int o = __p.__offset(24); return o != 0 ? __p.__vector_len(o) : 0; } } + /// an example documentation comment: this will end up in the generated code + /// multiline too + public MyGame.Example.Monster? Testarrayoftables(int j) { int o = __p.__offset(26); return o != 0 ? (MyGame.Example.Monster?)(new MyGame.Example.Monster()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; } + public int TestarrayoftablesLength { get { int o = __p.__offset(26); return o != 0 ? __p.__vector_len(o) : 0; } } + public MyGame.Example.Monster? TestarrayoftablesByKey(string key) { int o = __p.__offset(26); return o != 0 ? MyGame.Example.Monster.__lookup_by_key(__p.__vector(o), key, __p.bb) : null; } + public MyGame.Example.Monster? Enemy { get { int o = __p.__offset(28); return o != 0 ? (MyGame.Example.Monster?)(new MyGame.Example.Monster()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + public byte Testnestedflatbuffer(int j) { int o = __p.__offset(30); return o != 0 ? __p.bb.Get(__p.__vector(o) + j * 1) : (byte)0; } + public int TestnestedflatbufferLength { get { int o = __p.__offset(30); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetTestnestedflatbufferBytes() { return __p.__vector_as_span(30, 1); } +#else + public ArraySegment? GetTestnestedflatbufferBytes() { return __p.__vector_as_arraysegment(30); } +#endif + public byte[] GetTestnestedflatbufferArray() { return __p.__vector_as_array(30); } + public MyGame.Example.Monster? GetTestnestedflatbufferAsMonster() { int o = __p.__offset(30); return o != 0 ? (MyGame.Example.Monster?)(new MyGame.Example.Monster()).__assign(__p.__indirect(__p.__vector(o)), __p.bb) : null; } + public bool MutateTestnestedflatbuffer(int j, byte testnestedflatbuffer) { int o = __p.__offset(30); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, testnestedflatbuffer); return true; } else { return false; } } + public MyGame.Example.Stat? Testempty { get { int o = __p.__offset(32); return o != 0 ? (MyGame.Example.Stat?)(new MyGame.Example.Stat()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + public bool Testbool { get { int o = __p.__offset(34); return o != 0 ? 0!=__p.bb.Get(o + __p.bb_pos) : (bool)false; } } + public bool MutateTestbool(bool testbool) { int o = __p.__offset(34); if (o != 0) { __p.bb.Put(o + __p.bb_pos, (byte)(testbool ? 1 : 0)); return true; } else { return false; } } + public int Testhashs32Fnv1 { get { int o = __p.__offset(36); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateTesthashs32Fnv1(int testhashs32_fnv1) { int o = __p.__offset(36); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, testhashs32_fnv1); return true; } else { return false; } } + public uint Testhashu32Fnv1 { get { int o = __p.__offset(38); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)0; } } + public bool MutateTesthashu32Fnv1(uint testhashu32_fnv1) { int o = __p.__offset(38); if (o != 0) { __p.bb.PutUint(o + __p.bb_pos, testhashu32_fnv1); return true; } else { return false; } } + public long Testhashs64Fnv1 { get { int o = __p.__offset(40); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } } + public bool MutateTesthashs64Fnv1(long testhashs64_fnv1) { int o = __p.__offset(40); if (o != 0) { __p.bb.PutLong(o + __p.bb_pos, testhashs64_fnv1); return true; } else { return false; } } + public ulong Testhashu64Fnv1 { get { int o = __p.__offset(42); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateTesthashu64Fnv1(ulong testhashu64_fnv1) { int o = __p.__offset(42); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, testhashu64_fnv1); return true; } else { return false; } } + public int Testhashs32Fnv1a { get { int o = __p.__offset(44); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateTesthashs32Fnv1a(int testhashs32_fnv1a) { int o = __p.__offset(44); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, testhashs32_fnv1a); return true; } else { return false; } } + public uint Testhashu32Fnv1a { get { int o = __p.__offset(46); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)0; } } + public bool MutateTesthashu32Fnv1a(uint testhashu32_fnv1a) { int o = __p.__offset(46); if (o != 0) { __p.bb.PutUint(o + __p.bb_pos, testhashu32_fnv1a); return true; } else { return false; } } + public long Testhashs64Fnv1a { get { int o = __p.__offset(48); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } } + public bool MutateTesthashs64Fnv1a(long testhashs64_fnv1a) { int o = __p.__offset(48); if (o != 0) { __p.bb.PutLong(o + __p.bb_pos, testhashs64_fnv1a); return true; } else { return false; } } + public ulong Testhashu64Fnv1a { get { int o = __p.__offset(50); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateTesthashu64Fnv1a(ulong testhashu64_fnv1a) { int o = __p.__offset(50); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, testhashu64_fnv1a); return true; } else { return false; } } + public bool Testarrayofbools(int j) { int o = __p.__offset(52); return o != 0 ? 0!=__p.bb.Get(__p.__vector(o) + j * 1) : false; } + public int TestarrayofboolsLength { get { int o = __p.__offset(52); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetTestarrayofboolsBytes() { return __p.__vector_as_span(52, 1); } +#else + public ArraySegment? GetTestarrayofboolsBytes() { return __p.__vector_as_arraysegment(52); } +#endif + public bool[] GetTestarrayofboolsArray() { return __p.__vector_as_array(52); } + public bool MutateTestarrayofbools(int j, bool testarrayofbools) { int o = __p.__offset(52); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, (byte)(testarrayofbools ? 1 : 0)); return true; } else { return false; } } + public float Testf { get { int o = __p.__offset(54); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)3.14159f; } } + public bool MutateTestf(float testf) { int o = __p.__offset(54); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, testf); return true; } else { return false; } } + public float Testf2 { get { int o = __p.__offset(56); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)3.0f; } } + public bool MutateTestf2(float testf2) { int o = __p.__offset(56); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, testf2); return true; } else { return false; } } + public float Testf3 { get { int o = __p.__offset(58); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)0.0f; } } + public bool MutateTestf3(float testf3) { int o = __p.__offset(58); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, testf3); return true; } else { return false; } } + public string Testarrayofstring2(int j) { int o = __p.__offset(60); return o != 0 ? __p.__string(__p.__vector(o) + j * 4) : null; } + public int Testarrayofstring2Length { get { int o = __p.__offset(60); return o != 0 ? __p.__vector_len(o) : 0; } } + public MyGame.Example.Ability? Testarrayofsortedstruct(int j) { int o = __p.__offset(62); return o != 0 ? (MyGame.Example.Ability?)(new MyGame.Example.Ability()).__assign(__p.__vector(o) + j * 8, __p.bb) : null; } + public int TestarrayofsortedstructLength { get { int o = __p.__offset(62); return o != 0 ? __p.__vector_len(o) : 0; } } + public byte Flex(int j) { int o = __p.__offset(64); return o != 0 ? __p.bb.Get(__p.__vector(o) + j * 1) : (byte)0; } + public int FlexLength { get { int o = __p.__offset(64); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetFlexBytes() { return __p.__vector_as_span(64, 1); } +#else + public ArraySegment? GetFlexBytes() { return __p.__vector_as_arraysegment(64); } +#endif + public byte[] GetFlexArray() { return __p.__vector_as_array(64); } + public bool MutateFlex(int j, byte flex) { int o = __p.__offset(64); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, flex); return true; } else { return false; } } + public MyGame.Example.Test? Test5(int j) { int o = __p.__offset(66); return o != 0 ? (MyGame.Example.Test?)(new MyGame.Example.Test()).__assign(__p.__vector(o) + j * 4, __p.bb) : null; } + public int Test5Length { get { int o = __p.__offset(66); return o != 0 ? __p.__vector_len(o) : 0; } } + public long VectorOfLongs(int j) { int o = __p.__offset(68); return o != 0 ? __p.bb.GetLong(__p.__vector(o) + j * 8) : (long)0; } + public int VectorOfLongsLength { get { int o = __p.__offset(68); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVectorOfLongsBytes() { return __p.__vector_as_span(68, 8); } +#else + public ArraySegment? GetVectorOfLongsBytes() { return __p.__vector_as_arraysegment(68); } +#endif + public long[] GetVectorOfLongsArray() { return __p.__vector_as_array(68); } + public bool MutateVectorOfLongs(int j, long vector_of_longs) { int o = __p.__offset(68); if (o != 0) { __p.bb.PutLong(__p.__vector(o) + j * 8, vector_of_longs); return true; } else { return false; } } + public double VectorOfDoubles(int j) { int o = __p.__offset(70); return o != 0 ? __p.bb.GetDouble(__p.__vector(o) + j * 8) : (double)0; } + public int VectorOfDoublesLength { get { int o = __p.__offset(70); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVectorOfDoublesBytes() { return __p.__vector_as_span(70, 8); } +#else + public ArraySegment? GetVectorOfDoublesBytes() { return __p.__vector_as_arraysegment(70); } +#endif + public double[] GetVectorOfDoublesArray() { return __p.__vector_as_array(70); } + public bool MutateVectorOfDoubles(int j, double vector_of_doubles) { int o = __p.__offset(70); if (o != 0) { __p.bb.PutDouble(__p.__vector(o) + j * 8, vector_of_doubles); return true; } else { return false; } } + public MyGame.InParentNamespace? ParentNamespaceTest { get { int o = __p.__offset(72); return o != 0 ? (MyGame.InParentNamespace?)(new MyGame.InParentNamespace()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + public MyGame.Example.Referrable? VectorOfReferrables(int j) { int o = __p.__offset(74); return o != 0 ? (MyGame.Example.Referrable?)(new MyGame.Example.Referrable()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; } + public int VectorOfReferrablesLength { get { int o = __p.__offset(74); return o != 0 ? __p.__vector_len(o) : 0; } } + public MyGame.Example.Referrable? VectorOfReferrablesByKey(ulong key) { int o = __p.__offset(74); return o != 0 ? MyGame.Example.Referrable.__lookup_by_key(__p.__vector(o), key, __p.bb) : null; } + public ulong SingleWeakReference { get { int o = __p.__offset(76); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateSingleWeakReference(ulong single_weak_reference) { int o = __p.__offset(76); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, single_weak_reference); return true; } else { return false; } } + public ulong VectorOfWeakReferences(int j) { int o = __p.__offset(78); return o != 0 ? __p.bb.GetUlong(__p.__vector(o) + j * 8) : (ulong)0; } + public int VectorOfWeakReferencesLength { get { int o = __p.__offset(78); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVectorOfWeakReferencesBytes() { return __p.__vector_as_span(78, 8); } +#else + public ArraySegment? GetVectorOfWeakReferencesBytes() { return __p.__vector_as_arraysegment(78); } +#endif + public ulong[] GetVectorOfWeakReferencesArray() { return __p.__vector_as_array(78); } + public bool MutateVectorOfWeakReferences(int j, ulong vector_of_weak_references) { int o = __p.__offset(78); if (o != 0) { __p.bb.PutUlong(__p.__vector(o) + j * 8, vector_of_weak_references); return true; } else { return false; } } + public MyGame.Example.Referrable? VectorOfStrongReferrables(int j) { int o = __p.__offset(80); return o != 0 ? (MyGame.Example.Referrable?)(new MyGame.Example.Referrable()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; } + public int VectorOfStrongReferrablesLength { get { int o = __p.__offset(80); return o != 0 ? __p.__vector_len(o) : 0; } } + public MyGame.Example.Referrable? VectorOfStrongReferrablesByKey(ulong key) { int o = __p.__offset(80); return o != 0 ? MyGame.Example.Referrable.__lookup_by_key(__p.__vector(o), key, __p.bb) : null; } + public ulong CoOwningReference { get { int o = __p.__offset(82); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateCoOwningReference(ulong co_owning_reference) { int o = __p.__offset(82); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, co_owning_reference); return true; } else { return false; } } + public ulong VectorOfCoOwningReferences(int j) { int o = __p.__offset(84); return o != 0 ? __p.bb.GetUlong(__p.__vector(o) + j * 8) : (ulong)0; } + public int VectorOfCoOwningReferencesLength { get { int o = __p.__offset(84); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVectorOfCoOwningReferencesBytes() { return __p.__vector_as_span(84, 8); } +#else + public ArraySegment? GetVectorOfCoOwningReferencesBytes() { return __p.__vector_as_arraysegment(84); } +#endif + public ulong[] GetVectorOfCoOwningReferencesArray() { return __p.__vector_as_array(84); } + public bool MutateVectorOfCoOwningReferences(int j, ulong vector_of_co_owning_references) { int o = __p.__offset(84); if (o != 0) { __p.bb.PutUlong(__p.__vector(o) + j * 8, vector_of_co_owning_references); return true; } else { return false; } } + public ulong NonOwningReference { get { int o = __p.__offset(86); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateNonOwningReference(ulong non_owning_reference) { int o = __p.__offset(86); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, non_owning_reference); return true; } else { return false; } } + public ulong VectorOfNonOwningReferences(int j) { int o = __p.__offset(88); return o != 0 ? __p.bb.GetUlong(__p.__vector(o) + j * 8) : (ulong)0; } + public int VectorOfNonOwningReferencesLength { get { int o = __p.__offset(88); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVectorOfNonOwningReferencesBytes() { return __p.__vector_as_span(88, 8); } +#else + public ArraySegment? GetVectorOfNonOwningReferencesBytes() { return __p.__vector_as_arraysegment(88); } +#endif + public ulong[] GetVectorOfNonOwningReferencesArray() { return __p.__vector_as_array(88); } + public bool MutateVectorOfNonOwningReferences(int j, ulong vector_of_non_owning_references) { int o = __p.__offset(88); if (o != 0) { __p.bb.PutUlong(__p.__vector(o) + j * 8, vector_of_non_owning_references); return true; } else { return false; } } + public MyGame.Example.AnyUniqueAliases AnyUniqueType { get { int o = __p.__offset(90); return o != 0 ? (MyGame.Example.AnyUniqueAliases)__p.bb.Get(o + __p.bb_pos) : MyGame.Example.AnyUniqueAliases.NONE; } } + public TTable? AnyUnique() where TTable : struct, IFlatbufferObject { int o = __p.__offset(92); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public MyGame.Example.Monster AnyUniqueAsM() { return AnyUnique().Value; } + internal MyGame.Example.TestSimpleTableWithEnum AnyUniqueAsTS() { return AnyUnique().Value; } + public MyGame.Example2.Monster AnyUniqueAsM2() { return AnyUnique().Value; } + public MyGame.Example.AnyAmbiguousAliases AnyAmbiguousType { get { int o = __p.__offset(94); return o != 0 ? (MyGame.Example.AnyAmbiguousAliases)__p.bb.Get(o + __p.bb_pos) : MyGame.Example.AnyAmbiguousAliases.NONE; } } + public TTable? AnyAmbiguous() where TTable : struct, IFlatbufferObject { int o = __p.__offset(96); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public MyGame.Example.Monster AnyAmbiguousAsM1() { return AnyAmbiguous().Value; } + public MyGame.Example.Monster AnyAmbiguousAsM2() { return AnyAmbiguous().Value; } + public MyGame.Example.Monster AnyAmbiguousAsM3() { return AnyAmbiguous().Value; } + public MyGame.Example.Color VectorOfEnums(int j) { int o = __p.__offset(98); return o != 0 ? (MyGame.Example.Color)__p.bb.Get(__p.__vector(o) + j * 1) : (MyGame.Example.Color)0; } + public int VectorOfEnumsLength { get { int o = __p.__offset(98); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVectorOfEnumsBytes() { return __p.__vector_as_span(98, 1); } +#else + public ArraySegment? GetVectorOfEnumsBytes() { return __p.__vector_as_arraysegment(98); } +#endif + public MyGame.Example.Color[] GetVectorOfEnumsArray() { int o = __p.__offset(98); if (o == 0) return null; int p = __p.__vector(o); int l = __p.__vector_len(o); MyGame.Example.Color[] a = new MyGame.Example.Color[l]; for (int i = 0; i < l; i++) { a[i] = (MyGame.Example.Color)__p.bb.Get(p + i * 1); } return a; } + public bool MutateVectorOfEnums(int j, MyGame.Example.Color vector_of_enums) { int o = __p.__offset(98); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, (byte)vector_of_enums); return true; } else { return false; } } + public MyGame.Example.Race SignedEnum { get { int o = __p.__offset(100); return o != 0 ? (MyGame.Example.Race)__p.bb.GetSbyte(o + __p.bb_pos) : MyGame.Example.Race.None; } } + public bool MutateSignedEnum(MyGame.Example.Race signed_enum) { int o = __p.__offset(100); if (o != 0) { __p.bb.PutSbyte(o + __p.bb_pos, (sbyte)signed_enum); return true; } else { return false; } } + public byte Testrequirednestedflatbuffer(int j) { int o = __p.__offset(102); return o != 0 ? __p.bb.Get(__p.__vector(o) + j * 1) : (byte)0; } + public int TestrequirednestedflatbufferLength { get { int o = __p.__offset(102); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetTestrequirednestedflatbufferBytes() { return __p.__vector_as_span(102, 1); } +#else + public ArraySegment? GetTestrequirednestedflatbufferBytes() { return __p.__vector_as_arraysegment(102); } +#endif + public byte[] GetTestrequirednestedflatbufferArray() { return __p.__vector_as_array(102); } + public MyGame.Example.Monster? GetTestrequirednestedflatbufferAsMonster() { int o = __p.__offset(102); return o != 0 ? (MyGame.Example.Monster?)(new MyGame.Example.Monster()).__assign(__p.__indirect(__p.__vector(o)), __p.bb) : null; } + public bool MutateTestrequirednestedflatbuffer(int j, byte testrequirednestedflatbuffer) { int o = __p.__offset(102); if (o != 0) { __p.bb.Put(__p.__vector(o) + j * 1, testrequirednestedflatbuffer); return true; } else { return false; } } + public MyGame.Example.Stat? ScalarKeySortedTables(int j) { int o = __p.__offset(104); return o != 0 ? (MyGame.Example.Stat?)(new MyGame.Example.Stat()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; } + public int ScalarKeySortedTablesLength { get { int o = __p.__offset(104); return o != 0 ? __p.__vector_len(o) : 0; } } + public MyGame.Example.Stat? ScalarKeySortedTablesByKey(ushort key) { int o = __p.__offset(104); return o != 0 ? MyGame.Example.Stat.__lookup_by_key(__p.__vector(o), key, __p.bb) : null; } + public MyGame.Example.Test? NativeInline { get { int o = __p.__offset(106); return o != 0 ? (MyGame.Example.Test?)(new MyGame.Example.Test()).__assign(o + __p.bb_pos, __p.bb) : null; } } + public MyGame.Example.LongEnum LongEnumNonEnumDefault { get { int o = __p.__offset(108); return o != 0 ? (MyGame.Example.LongEnum)__p.bb.GetUlong(o + __p.bb_pos) : 0; } } + public bool MutateLongEnumNonEnumDefault(MyGame.Example.LongEnum long_enum_non_enum_default) { int o = __p.__offset(108); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, (ulong)long_enum_non_enum_default); return true; } else { return false; } } + public MyGame.Example.LongEnum LongEnumNormalDefault { get { int o = __p.__offset(110); return o != 0 ? (MyGame.Example.LongEnum)__p.bb.GetUlong(o + __p.bb_pos) : MyGame.Example.LongEnum.LongOne; } } + public bool MutateLongEnumNormalDefault(MyGame.Example.LongEnum long_enum_normal_default) { int o = __p.__offset(110); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, (ulong)long_enum_normal_default); return true; } else { return false; } } + public float NanDefault { get { int o = __p.__offset(112); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.NaN; } } + public bool MutateNanDefault(float nan_default) { int o = __p.__offset(112); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, nan_default); return true; } else { return false; } } + public float InfDefault { get { int o = __p.__offset(114); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.PositiveInfinity; } } + public bool MutateInfDefault(float inf_default) { int o = __p.__offset(114); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, inf_default); return true; } else { return false; } } + public float PositiveInfDefault { get { int o = __p.__offset(116); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.PositiveInfinity; } } + public bool MutatePositiveInfDefault(float positive_inf_default) { int o = __p.__offset(116); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, positive_inf_default); return true; } else { return false; } } + public float InfinityDefault { get { int o = __p.__offset(118); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.PositiveInfinity; } } + public bool MutateInfinityDefault(float infinity_default) { int o = __p.__offset(118); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, infinity_default); return true; } else { return false; } } + public float PositiveInfinityDefault { get { int o = __p.__offset(120); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.PositiveInfinity; } } + public bool MutatePositiveInfinityDefault(float positive_infinity_default) { int o = __p.__offset(120); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, positive_infinity_default); return true; } else { return false; } } + public float NegativeInfDefault { get { int o = __p.__offset(122); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.NegativeInfinity; } } + public bool MutateNegativeInfDefault(float negative_inf_default) { int o = __p.__offset(122); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, negative_inf_default); return true; } else { return false; } } + public float NegativeInfinityDefault { get { int o = __p.__offset(124); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.NegativeInfinity; } } + public bool MutateNegativeInfinityDefault(float negative_infinity_default) { int o = __p.__offset(124); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, negative_infinity_default); return true; } else { return false; } } + public double DoubleInfDefault { get { int o = __p.__offset(126); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)Double.PositiveInfinity; } } + public bool MutateDoubleInfDefault(double double_inf_default) { int o = __p.__offset(126); if (o != 0) { __p.bb.PutDouble(o + __p.bb_pos, double_inf_default); return true; } else { return false; } } + + public static Offset CreateMonster(FlatBufferBuilder builder, + MyGame.Example.Vec3T pos = null, + short mana = 150, + short hp = 100, + StringOffset nameOffset = default(StringOffset), + VectorOffset inventoryOffset = default(VectorOffset), + MyGame.Example.Color color = MyGame.Example.Color.Blue, + MyGame.Example.Any test_type = MyGame.Example.Any.NONE, + int testOffset = 0, + VectorOffset test4Offset = default(VectorOffset), + VectorOffset testarrayofstringOffset = default(VectorOffset), + VectorOffset testarrayoftablesOffset = default(VectorOffset), + Offset enemyOffset = default(Offset), + VectorOffset testnestedflatbufferOffset = default(VectorOffset), + Offset testemptyOffset = default(Offset), + bool testbool = false, + int testhashs32_fnv1 = 0, + uint testhashu32_fnv1 = 0, + long testhashs64_fnv1 = 0, + ulong testhashu64_fnv1 = 0, + int testhashs32_fnv1a = 0, + uint testhashu32_fnv1a = 0, + long testhashs64_fnv1a = 0, + ulong testhashu64_fnv1a = 0, + VectorOffset testarrayofboolsOffset = default(VectorOffset), + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + VectorOffset testarrayofstring2Offset = default(VectorOffset), + VectorOffset testarrayofsortedstructOffset = default(VectorOffset), + VectorOffset flexOffset = default(VectorOffset), + VectorOffset test5Offset = default(VectorOffset), + VectorOffset vector_of_longsOffset = default(VectorOffset), + VectorOffset vector_of_doublesOffset = default(VectorOffset), + Offset parent_namespace_testOffset = default(Offset), + VectorOffset vector_of_referrablesOffset = default(VectorOffset), + ulong single_weak_reference = 0, + VectorOffset vector_of_weak_referencesOffset = default(VectorOffset), + VectorOffset vector_of_strong_referrablesOffset = default(VectorOffset), + ulong co_owning_reference = 0, + VectorOffset vector_of_co_owning_referencesOffset = default(VectorOffset), + ulong non_owning_reference = 0, + VectorOffset vector_of_non_owning_referencesOffset = default(VectorOffset), + MyGame.Example.AnyUniqueAliases any_unique_type = MyGame.Example.AnyUniqueAliases.NONE, + int any_uniqueOffset = 0, + MyGame.Example.AnyAmbiguousAliases any_ambiguous_type = MyGame.Example.AnyAmbiguousAliases.NONE, + int any_ambiguousOffset = 0, + VectorOffset vector_of_enumsOffset = default(VectorOffset), + MyGame.Example.Race signed_enum = MyGame.Example.Race.None, + VectorOffset testrequirednestedflatbufferOffset = default(VectorOffset), + VectorOffset scalar_key_sorted_tablesOffset = default(VectorOffset), + MyGame.Example.TestT native_inline = null, + MyGame.Example.LongEnum long_enum_non_enum_default = 0, + MyGame.Example.LongEnum long_enum_normal_default = MyGame.Example.LongEnum.LongOne, + float nan_default = Single.NaN, + float inf_default = Single.PositiveInfinity, + float positive_inf_default = Single.PositiveInfinity, + float infinity_default = Single.PositiveInfinity, + float positive_infinity_default = Single.PositiveInfinity, + float negative_inf_default = Single.NegativeInfinity, + float negative_infinity_default = Single.NegativeInfinity, + double double_inf_default = Double.PositiveInfinity) { + builder.StartTable(62); + Monster.AddDoubleInfDefault(builder, double_inf_default); + Monster.AddLongEnumNormalDefault(builder, long_enum_normal_default); + Monster.AddLongEnumNonEnumDefault(builder, long_enum_non_enum_default); + Monster.AddNonOwningReference(builder, non_owning_reference); + Monster.AddCoOwningReference(builder, co_owning_reference); + Monster.AddSingleWeakReference(builder, single_weak_reference); + Monster.AddTesthashu64Fnv1a(builder, testhashu64_fnv1a); + Monster.AddTesthashs64Fnv1a(builder, testhashs64_fnv1a); + Monster.AddTesthashu64Fnv1(builder, testhashu64_fnv1); + Monster.AddTesthashs64Fnv1(builder, testhashs64_fnv1); + Monster.AddNegativeInfinityDefault(builder, negative_infinity_default); + Monster.AddNegativeInfDefault(builder, negative_inf_default); + Monster.AddPositiveInfinityDefault(builder, positive_infinity_default); + Monster.AddInfinityDefault(builder, infinity_default); + Monster.AddPositiveInfDefault(builder, positive_inf_default); + Monster.AddInfDefault(builder, inf_default); + Monster.AddNanDefault(builder, nan_default); + Monster.AddNativeInline(builder, MyGame.Example.Test.Pack(builder, native_inline)); + Monster.AddScalarKeySortedTables(builder, scalar_key_sorted_tablesOffset); + Monster.AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset); + Monster.AddVectorOfEnums(builder, vector_of_enumsOffset); + Monster.AddAnyAmbiguous(builder, any_ambiguousOffset); + Monster.AddAnyUnique(builder, any_uniqueOffset); + Monster.AddVectorOfNonOwningReferences(builder, vector_of_non_owning_referencesOffset); + Monster.AddVectorOfCoOwningReferences(builder, vector_of_co_owning_referencesOffset); + Monster.AddVectorOfStrongReferrables(builder, vector_of_strong_referrablesOffset); + Monster.AddVectorOfWeakReferences(builder, vector_of_weak_referencesOffset); + Monster.AddVectorOfReferrables(builder, vector_of_referrablesOffset); + Monster.AddParentNamespaceTest(builder, parent_namespace_testOffset); + Monster.AddVectorOfDoubles(builder, vector_of_doublesOffset); + Monster.AddVectorOfLongs(builder, vector_of_longsOffset); + Monster.AddTest5(builder, test5Offset); + Monster.AddFlex(builder, flexOffset); + Monster.AddTestarrayofsortedstruct(builder, testarrayofsortedstructOffset); + Monster.AddTestarrayofstring2(builder, testarrayofstring2Offset); + Monster.AddTestf3(builder, testf3); + Monster.AddTestf2(builder, testf2); + Monster.AddTestf(builder, testf); + Monster.AddTestarrayofbools(builder, testarrayofboolsOffset); + Monster.AddTesthashu32Fnv1a(builder, testhashu32_fnv1a); + Monster.AddTesthashs32Fnv1a(builder, testhashs32_fnv1a); + Monster.AddTesthashu32Fnv1(builder, testhashu32_fnv1); + Monster.AddTesthashs32Fnv1(builder, testhashs32_fnv1); + Monster.AddTestempty(builder, testemptyOffset); + Monster.AddTestnestedflatbuffer(builder, testnestedflatbufferOffset); + Monster.AddEnemy(builder, enemyOffset); + Monster.AddTestarrayoftables(builder, testarrayoftablesOffset); + Monster.AddTestarrayofstring(builder, testarrayofstringOffset); + Monster.AddTest4(builder, test4Offset); + Monster.AddTest(builder, testOffset); + Monster.AddInventory(builder, inventoryOffset); + Monster.AddName(builder, nameOffset); + Monster.AddPos(builder, MyGame.Example.Vec3.Pack(builder, pos)); + Monster.AddHp(builder, hp); + Monster.AddMana(builder, mana); + Monster.AddSignedEnum(builder, signed_enum); + Monster.AddAnyAmbiguousType(builder, any_ambiguous_type); + Monster.AddAnyUniqueType(builder, any_unique_type); + Monster.AddTestbool(builder, testbool); + Monster.AddTestType(builder, test_type); + Monster.AddColor(builder, color); + return Monster.EndMonster(builder); + } + + public static void StartMonster(FlatBufferBuilder builder) { builder.StartTable(62); } + public static void AddPos(FlatBufferBuilder builder, Offset posOffset) { builder.AddStruct(0, posOffset.Value, 0); } + public static void AddMana(FlatBufferBuilder builder, short mana) { builder.AddShort(1, mana, 150); } + public static void AddHp(FlatBufferBuilder builder, short hp) { builder.AddShort(2, hp, 100); } + public static void AddName(FlatBufferBuilder builder, StringOffset nameOffset) { builder.AddOffset(3, nameOffset.Value, 0); } + public static void AddInventory(FlatBufferBuilder builder, VectorOffset inventoryOffset) { builder.AddOffset(5, inventoryOffset.Value, 0); } + public static VectorOffset CreateInventoryVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); } + public static VectorOffset CreateInventoryVectorBlock(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateInventoryVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateInventoryVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartInventoryVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddColor(FlatBufferBuilder builder, MyGame.Example.Color color) { builder.AddByte(6, (byte)color, 8); } + public static void AddTestType(FlatBufferBuilder builder, MyGame.Example.Any testType) { builder.AddByte(7, (byte)testType, 0); } + public static void AddTest(FlatBufferBuilder builder, int testOffset) { builder.AddOffset(8, testOffset, 0); } + public static void AddTest4(FlatBufferBuilder builder, VectorOffset test4Offset) { builder.AddOffset(9, test4Offset.Value, 0); } + public static void StartTest4Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); } + public static void AddTestarrayofstring(FlatBufferBuilder builder, VectorOffset testarrayofstringOffset) { builder.AddOffset(10, testarrayofstringOffset.Value, 0); } + public static VectorOffset CreateTestarrayofstringVector(FlatBufferBuilder builder, StringOffset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofstringVectorBlock(FlatBufferBuilder builder, StringOffset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofstringVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofstringVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddTestarrayoftables(FlatBufferBuilder builder, VectorOffset testarrayoftablesOffset) { builder.AddOffset(11, testarrayoftablesOffset.Value, 0); } + public static VectorOffset CreateTestarrayoftablesVector(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateTestarrayoftablesVectorBlock(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayoftablesVectorBlock(FlatBufferBuilder builder, ArraySegment> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayoftablesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add>(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddEnemy(FlatBufferBuilder builder, Offset enemyOffset) { builder.AddOffset(12, enemyOffset.Value, 0); } + public static void AddTestnestedflatbuffer(FlatBufferBuilder builder, VectorOffset testnestedflatbufferOffset) { builder.AddOffset(13, testnestedflatbufferOffset.Value, 0); } + public static VectorOffset CreateTestnestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); } + public static VectorOffset CreateTestnestedflatbufferVectorBlock(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestnestedflatbufferVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestnestedflatbufferVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddTestempty(FlatBufferBuilder builder, Offset testemptyOffset) { builder.AddOffset(14, testemptyOffset.Value, 0); } + public static void AddTestbool(FlatBufferBuilder builder, bool testbool) { builder.AddBool(15, testbool, false); } + public static void AddTesthashs32Fnv1(FlatBufferBuilder builder, int testhashs32Fnv1) { builder.AddInt(16, testhashs32Fnv1, 0); } + public static void AddTesthashu32Fnv1(FlatBufferBuilder builder, uint testhashu32Fnv1) { builder.AddUint(17, testhashu32Fnv1, 0); } + public static void AddTesthashs64Fnv1(FlatBufferBuilder builder, long testhashs64Fnv1) { builder.AddLong(18, testhashs64Fnv1, 0); } + public static void AddTesthashu64Fnv1(FlatBufferBuilder builder, ulong testhashu64Fnv1) { builder.AddUlong(19, testhashu64Fnv1, 0); } + public static void AddTesthashs32Fnv1a(FlatBufferBuilder builder, int testhashs32Fnv1a) { builder.AddInt(20, testhashs32Fnv1a, 0); } + public static void AddTesthashu32Fnv1a(FlatBufferBuilder builder, uint testhashu32Fnv1a) { builder.AddUint(21, testhashu32Fnv1a, 0); } + public static void AddTesthashs64Fnv1a(FlatBufferBuilder builder, long testhashs64Fnv1a) { builder.AddLong(22, testhashs64Fnv1a, 0); } + public static void AddTesthashu64Fnv1a(FlatBufferBuilder builder, ulong testhashu64Fnv1a) { builder.AddUlong(23, testhashu64Fnv1a, 0); } + public static void AddTestarrayofbools(FlatBufferBuilder builder, VectorOffset testarrayofboolsOffset) { builder.AddOffset(24, testarrayofboolsOffset.Value, 0); } + public static VectorOffset CreateTestarrayofboolsVector(FlatBufferBuilder builder, bool[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddBool(data[i]); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofboolsVectorBlock(FlatBufferBuilder builder, bool[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofboolsVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofboolsVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartTestarrayofboolsVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddTestf(FlatBufferBuilder builder, float testf) { builder.AddFloat(25, testf, 3.14159f); } + public static void AddTestf2(FlatBufferBuilder builder, float testf2) { builder.AddFloat(26, testf2, 3.0f); } + public static void AddTestf3(FlatBufferBuilder builder, float testf3) { builder.AddFloat(27, testf3, 0.0f); } + public static void AddTestarrayofstring2(FlatBufferBuilder builder, VectorOffset testarrayofstring2Offset) { builder.AddOffset(28, testarrayofstring2Offset.Value, 0); } + public static VectorOffset CreateTestarrayofstring2Vector(FlatBufferBuilder builder, StringOffset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofstring2VectorBlock(FlatBufferBuilder builder, StringOffset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofstring2VectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestarrayofstring2VectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartTestarrayofstring2Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddTestarrayofsortedstruct(FlatBufferBuilder builder, VectorOffset testarrayofsortedstructOffset) { builder.AddOffset(29, testarrayofsortedstructOffset.Value, 0); } + public static void StartTestarrayofsortedstructVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 4); } + public static void AddFlex(FlatBufferBuilder builder, VectorOffset flexOffset) { builder.AddOffset(30, flexOffset.Value, 0); } + public static VectorOffset CreateFlexVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); } + public static VectorOffset CreateFlexVectorBlock(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateFlexVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateFlexVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartFlexVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddTest5(FlatBufferBuilder builder, VectorOffset test5Offset) { builder.AddOffset(31, test5Offset.Value, 0); } + public static void StartTest5Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 2); } + public static void AddVectorOfLongs(FlatBufferBuilder builder, VectorOffset vectorOfLongsOffset) { builder.AddOffset(32, vectorOfLongsOffset.Value, 0); } + public static VectorOffset CreateVectorOfLongsVector(FlatBufferBuilder builder, long[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddLong(data[i]); return builder.EndVector(); } + public static VectorOffset CreateVectorOfLongsVectorBlock(FlatBufferBuilder builder, long[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfLongsVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfLongsVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfLongsVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static void AddVectorOfDoubles(FlatBufferBuilder builder, VectorOffset vectorOfDoublesOffset) { builder.AddOffset(33, vectorOfDoublesOffset.Value, 0); } + public static VectorOffset CreateVectorOfDoublesVector(FlatBufferBuilder builder, double[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddDouble(data[i]); return builder.EndVector(); } + public static VectorOffset CreateVectorOfDoublesVectorBlock(FlatBufferBuilder builder, double[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfDoublesVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfDoublesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfDoublesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static void AddParentNamespaceTest(FlatBufferBuilder builder, Offset parentNamespaceTestOffset) { builder.AddOffset(34, parentNamespaceTestOffset.Value, 0); } + public static void AddVectorOfReferrables(FlatBufferBuilder builder, VectorOffset vectorOfReferrablesOffset) { builder.AddOffset(35, vectorOfReferrablesOffset.Value, 0); } + public static VectorOffset CreateVectorOfReferrablesVector(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateVectorOfReferrablesVectorBlock(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfReferrablesVectorBlock(FlatBufferBuilder builder, ArraySegment> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfReferrablesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add>(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfReferrablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddSingleWeakReference(FlatBufferBuilder builder, ulong singleWeakReference) { builder.AddUlong(36, singleWeakReference, 0); } + public static void AddVectorOfWeakReferences(FlatBufferBuilder builder, VectorOffset vectorOfWeakReferencesOffset) { builder.AddOffset(37, vectorOfWeakReferencesOffset.Value, 0); } + public static VectorOffset CreateVectorOfWeakReferencesVector(FlatBufferBuilder builder, ulong[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddUlong(data[i]); return builder.EndVector(); } + public static VectorOffset CreateVectorOfWeakReferencesVectorBlock(FlatBufferBuilder builder, ulong[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfWeakReferencesVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfWeakReferencesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfWeakReferencesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static void AddVectorOfStrongReferrables(FlatBufferBuilder builder, VectorOffset vectorOfStrongReferrablesOffset) { builder.AddOffset(38, vectorOfStrongReferrablesOffset.Value, 0); } + public static VectorOffset CreateVectorOfStrongReferrablesVector(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateVectorOfStrongReferrablesVectorBlock(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfStrongReferrablesVectorBlock(FlatBufferBuilder builder, ArraySegment> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfStrongReferrablesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add>(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfStrongReferrablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddCoOwningReference(FlatBufferBuilder builder, ulong coOwningReference) { builder.AddUlong(39, coOwningReference, 0); } + public static void AddVectorOfCoOwningReferences(FlatBufferBuilder builder, VectorOffset vectorOfCoOwningReferencesOffset) { builder.AddOffset(40, vectorOfCoOwningReferencesOffset.Value, 0); } + public static VectorOffset CreateVectorOfCoOwningReferencesVector(FlatBufferBuilder builder, ulong[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddUlong(data[i]); return builder.EndVector(); } + public static VectorOffset CreateVectorOfCoOwningReferencesVectorBlock(FlatBufferBuilder builder, ulong[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfCoOwningReferencesVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfCoOwningReferencesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfCoOwningReferencesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static void AddNonOwningReference(FlatBufferBuilder builder, ulong nonOwningReference) { builder.AddUlong(41, nonOwningReference, 0); } + public static void AddVectorOfNonOwningReferences(FlatBufferBuilder builder, VectorOffset vectorOfNonOwningReferencesOffset) { builder.AddOffset(42, vectorOfNonOwningReferencesOffset.Value, 0); } + public static VectorOffset CreateVectorOfNonOwningReferencesVector(FlatBufferBuilder builder, ulong[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddUlong(data[i]); return builder.EndVector(); } + public static VectorOffset CreateVectorOfNonOwningReferencesVectorBlock(FlatBufferBuilder builder, ulong[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfNonOwningReferencesVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfNonOwningReferencesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfNonOwningReferencesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static void AddAnyUniqueType(FlatBufferBuilder builder, MyGame.Example.AnyUniqueAliases anyUniqueType) { builder.AddByte(43, (byte)anyUniqueType, 0); } + public static void AddAnyUnique(FlatBufferBuilder builder, int anyUniqueOffset) { builder.AddOffset(44, anyUniqueOffset, 0); } + public static void AddAnyAmbiguousType(FlatBufferBuilder builder, MyGame.Example.AnyAmbiguousAliases anyAmbiguousType) { builder.AddByte(45, (byte)anyAmbiguousType, 0); } + public static void AddAnyAmbiguous(FlatBufferBuilder builder, int anyAmbiguousOffset) { builder.AddOffset(46, anyAmbiguousOffset, 0); } + public static void AddVectorOfEnums(FlatBufferBuilder builder, VectorOffset vectorOfEnumsOffset) { builder.AddOffset(47, vectorOfEnumsOffset.Value, 0); } + public static VectorOffset CreateVectorOfEnumsVector(FlatBufferBuilder builder, MyGame.Example.Color[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte((byte)data[i]); return builder.EndVector(); } + public static VectorOffset CreateVectorOfEnumsVectorBlock(FlatBufferBuilder builder, MyGame.Example.Color[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfEnumsVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVectorOfEnumsVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVectorOfEnumsVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddSignedEnum(FlatBufferBuilder builder, MyGame.Example.Race signedEnum) { builder.AddSbyte(48, (sbyte)signedEnum, -1); } + public static void AddTestrequirednestedflatbuffer(FlatBufferBuilder builder, VectorOffset testrequirednestedflatbufferOffset) { builder.AddOffset(49, testrequirednestedflatbufferOffset.Value, 0); } + public static VectorOffset CreateTestrequirednestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte(data[i]); return builder.EndVector(); } + public static VectorOffset CreateTestrequirednestedflatbufferVectorBlock(FlatBufferBuilder builder, byte[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestrequirednestedflatbufferVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateTestrequirednestedflatbufferVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartTestrequirednestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddScalarKeySortedTables(FlatBufferBuilder builder, VectorOffset scalarKeySortedTablesOffset) { builder.AddOffset(50, scalarKeySortedTablesOffset.Value, 0); } + public static VectorOffset CreateScalarKeySortedTablesVector(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateScalarKeySortedTablesVectorBlock(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateScalarKeySortedTablesVectorBlock(FlatBufferBuilder builder, ArraySegment> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateScalarKeySortedTablesVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add>(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartScalarKeySortedTablesVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static void AddNativeInline(FlatBufferBuilder builder, Offset nativeInlineOffset) { builder.AddStruct(51, nativeInlineOffset.Value, 0); } + public static void AddLongEnumNonEnumDefault(FlatBufferBuilder builder, MyGame.Example.LongEnum longEnumNonEnumDefault) { builder.AddUlong(52, (ulong)longEnumNonEnumDefault, 0); } + public static void AddLongEnumNormalDefault(FlatBufferBuilder builder, MyGame.Example.LongEnum longEnumNormalDefault) { builder.AddUlong(53, (ulong)longEnumNormalDefault, 2); } + public static void AddNanDefault(FlatBufferBuilder builder, float nanDefault) { builder.AddFloat(54, nanDefault, Single.NaN); } + public static void AddInfDefault(FlatBufferBuilder builder, float infDefault) { builder.AddFloat(55, infDefault, Single.PositiveInfinity); } + public static void AddPositiveInfDefault(FlatBufferBuilder builder, float positiveInfDefault) { builder.AddFloat(56, positiveInfDefault, Single.PositiveInfinity); } + public static void AddInfinityDefault(FlatBufferBuilder builder, float infinityDefault) { builder.AddFloat(57, infinityDefault, Single.PositiveInfinity); } + public static void AddPositiveInfinityDefault(FlatBufferBuilder builder, float positiveInfinityDefault) { builder.AddFloat(58, positiveInfinityDefault, Single.PositiveInfinity); } + public static void AddNegativeInfDefault(FlatBufferBuilder builder, float negativeInfDefault) { builder.AddFloat(59, negativeInfDefault, Single.NegativeInfinity); } + public static void AddNegativeInfinityDefault(FlatBufferBuilder builder, float negativeInfinityDefault) { builder.AddFloat(60, negativeInfinityDefault, Single.NegativeInfinity); } + public static void AddDoubleInfDefault(FlatBufferBuilder builder, double doubleInfDefault) { builder.AddDouble(61, doubleInfDefault, Double.PositiveInfinity); } + public static Offset EndMonster(FlatBufferBuilder builder) { + int o = builder.EndTable(); + builder.Required(o, 10); // name + return new Offset(o); + } + public static void FinishMonsterBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value, "MONS"); } + public static void FinishSizePrefixedMonsterBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value, "MONS"); } + + public static VectorOffset CreateSortedVectorOfMonster(FlatBufferBuilder builder, Offset[] offsets) { + Array.Sort(offsets, + (Offset o1, Offset o2) => + new Monster().__assign(builder.DataBuffer.Length - o1.Value, builder.DataBuffer).Name.CompareTo(new Monster().__assign(builder.DataBuffer.Length - o2.Value, builder.DataBuffer).Name)); + return builder.CreateVectorOfTables(offsets); + } + + public static Monster? __lookup_by_key(int vectorLocation, string key, ByteBuffer bb) { + Monster obj_ = new Monster(); + int span = bb.GetInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = Table.__indirect(vectorLocation + 4 * (start + middle), bb); + obj_.__assign(tableOffset, bb); + int comp = obj_.Name.CompareTo(key); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return obj_; + } + } + return null; + } + public MonsterT UnPack() { + var _o = new MonsterT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(MonsterT _o) { + _o.Pos = this.Pos.HasValue ? this.Pos.Value.UnPack() : null; + _o.Mana = this.Mana; + _o.Hp = this.Hp; + _o.Name = this.Name; + _o.Inventory = new List(); + for (var _j = 0; _j < this.InventoryLength; ++_j) {_o.Inventory.Add(this.Inventory(_j));} + _o.Color = this.Color; + _o.Test = new MyGame.Example.AnyUnion(); + _o.Test.Type = this.TestType; + switch (this.TestType) { + default: break; + case MyGame.Example.Any.Monster: + _o.Test.Value = this.Test().HasValue ? this.Test().Value.UnPack() : null; + break; + case MyGame.Example.Any.TestSimpleTableWithEnum: + _o.Test.Value = this.Test().HasValue ? this.Test().Value.UnPack() : null; + break; + case MyGame.Example.Any.MyGame_Example2_Monster: + _o.Test.Value = this.Test().HasValue ? this.Test().Value.UnPack() : null; + break; + } + _o.Test4 = new List(); + for (var _j = 0; _j < this.Test4Length; ++_j) {_o.Test4.Add(this.Test4(_j).HasValue ? this.Test4(_j).Value.UnPack() : null);} + _o.Testarrayofstring = new List(); + for (var _j = 0; _j < this.TestarrayofstringLength; ++_j) {_o.Testarrayofstring.Add(this.Testarrayofstring(_j));} + _o.Testarrayoftables = new List(); + for (var _j = 0; _j < this.TestarrayoftablesLength; ++_j) {_o.Testarrayoftables.Add(this.Testarrayoftables(_j).HasValue ? this.Testarrayoftables(_j).Value.UnPack() : null);} + _o.Enemy = this.Enemy.HasValue ? this.Enemy.Value.UnPack() : null; + _o.Testnestedflatbuffer = new List(); + for (var _j = 0; _j < this.TestnestedflatbufferLength; ++_j) {_o.Testnestedflatbuffer.Add(this.Testnestedflatbuffer(_j));} + _o.Testempty = this.Testempty.HasValue ? this.Testempty.Value.UnPack() : null; + _o.Testbool = this.Testbool; + _o.Testhashs32Fnv1 = this.Testhashs32Fnv1; + _o.Testhashu32Fnv1 = this.Testhashu32Fnv1; + _o.Testhashs64Fnv1 = this.Testhashs64Fnv1; + _o.Testhashu64Fnv1 = this.Testhashu64Fnv1; + _o.Testhashs32Fnv1a = this.Testhashs32Fnv1a; + _o.Testhashu32Fnv1a = this.Testhashu32Fnv1a; + _o.Testhashs64Fnv1a = this.Testhashs64Fnv1a; + _o.Testhashu64Fnv1a = this.Testhashu64Fnv1a; + _o.Testarrayofbools = new List(); + for (var _j = 0; _j < this.TestarrayofboolsLength; ++_j) {_o.Testarrayofbools.Add(this.Testarrayofbools(_j));} + _o.Testf = this.Testf; + _o.Testf2 = this.Testf2; + _o.Testf3 = this.Testf3; + _o.Testarrayofstring2 = new List(); + for (var _j = 0; _j < this.Testarrayofstring2Length; ++_j) {_o.Testarrayofstring2.Add(this.Testarrayofstring2(_j));} + _o.Testarrayofsortedstruct = new List(); + for (var _j = 0; _j < this.TestarrayofsortedstructLength; ++_j) {_o.Testarrayofsortedstruct.Add(this.Testarrayofsortedstruct(_j).HasValue ? this.Testarrayofsortedstruct(_j).Value.UnPack() : null);} + _o.Flex = new List(); + for (var _j = 0; _j < this.FlexLength; ++_j) {_o.Flex.Add(this.Flex(_j));} + _o.Test5 = new List(); + for (var _j = 0; _j < this.Test5Length; ++_j) {_o.Test5.Add(this.Test5(_j).HasValue ? this.Test5(_j).Value.UnPack() : null);} + _o.VectorOfLongs = new List(); + for (var _j = 0; _j < this.VectorOfLongsLength; ++_j) {_o.VectorOfLongs.Add(this.VectorOfLongs(_j));} + _o.VectorOfDoubles = new List(); + for (var _j = 0; _j < this.VectorOfDoublesLength; ++_j) {_o.VectorOfDoubles.Add(this.VectorOfDoubles(_j));} + _o.ParentNamespaceTest = this.ParentNamespaceTest.HasValue ? this.ParentNamespaceTest.Value.UnPack() : null; + _o.VectorOfReferrables = new List(); + for (var _j = 0; _j < this.VectorOfReferrablesLength; ++_j) {_o.VectorOfReferrables.Add(this.VectorOfReferrables(_j).HasValue ? this.VectorOfReferrables(_j).Value.UnPack() : null);} + _o.SingleWeakReference = this.SingleWeakReference; + _o.VectorOfWeakReferences = new List(); + for (var _j = 0; _j < this.VectorOfWeakReferencesLength; ++_j) {_o.VectorOfWeakReferences.Add(this.VectorOfWeakReferences(_j));} + _o.VectorOfStrongReferrables = new List(); + for (var _j = 0; _j < this.VectorOfStrongReferrablesLength; ++_j) {_o.VectorOfStrongReferrables.Add(this.VectorOfStrongReferrables(_j).HasValue ? this.VectorOfStrongReferrables(_j).Value.UnPack() : null);} + _o.CoOwningReference = this.CoOwningReference; + _o.VectorOfCoOwningReferences = new List(); + for (var _j = 0; _j < this.VectorOfCoOwningReferencesLength; ++_j) {_o.VectorOfCoOwningReferences.Add(this.VectorOfCoOwningReferences(_j));} + _o.NonOwningReference = this.NonOwningReference; + _o.VectorOfNonOwningReferences = new List(); + for (var _j = 0; _j < this.VectorOfNonOwningReferencesLength; ++_j) {_o.VectorOfNonOwningReferences.Add(this.VectorOfNonOwningReferences(_j));} + _o.AnyUnique = new MyGame.Example.AnyUniqueAliasesUnion(); + _o.AnyUnique.Type = this.AnyUniqueType; + switch (this.AnyUniqueType) { + default: break; + case MyGame.Example.AnyUniqueAliases.M: + _o.AnyUnique.Value = this.AnyUnique().HasValue ? this.AnyUnique().Value.UnPack() : null; + break; + case MyGame.Example.AnyUniqueAliases.TS: + _o.AnyUnique.Value = this.AnyUnique().HasValue ? this.AnyUnique().Value.UnPack() : null; + break; + case MyGame.Example.AnyUniqueAliases.M2: + _o.AnyUnique.Value = this.AnyUnique().HasValue ? this.AnyUnique().Value.UnPack() : null; + break; + } + _o.AnyAmbiguous = new MyGame.Example.AnyAmbiguousAliasesUnion(); + _o.AnyAmbiguous.Type = this.AnyAmbiguousType; + switch (this.AnyAmbiguousType) { + default: break; + case MyGame.Example.AnyAmbiguousAliases.M1: + _o.AnyAmbiguous.Value = this.AnyAmbiguous().HasValue ? this.AnyAmbiguous().Value.UnPack() : null; + break; + case MyGame.Example.AnyAmbiguousAliases.M2: + _o.AnyAmbiguous.Value = this.AnyAmbiguous().HasValue ? this.AnyAmbiguous().Value.UnPack() : null; + break; + case MyGame.Example.AnyAmbiguousAliases.M3: + _o.AnyAmbiguous.Value = this.AnyAmbiguous().HasValue ? this.AnyAmbiguous().Value.UnPack() : null; + break; + } + _o.VectorOfEnums = new List(); + for (var _j = 0; _j < this.VectorOfEnumsLength; ++_j) {_o.VectorOfEnums.Add(this.VectorOfEnums(_j));} + _o.SignedEnum = this.SignedEnum; + _o.Testrequirednestedflatbuffer = new List(); + for (var _j = 0; _j < this.TestrequirednestedflatbufferLength; ++_j) {_o.Testrequirednestedflatbuffer.Add(this.Testrequirednestedflatbuffer(_j));} + _o.ScalarKeySortedTables = new List(); + for (var _j = 0; _j < this.ScalarKeySortedTablesLength; ++_j) {_o.ScalarKeySortedTables.Add(this.ScalarKeySortedTables(_j).HasValue ? this.ScalarKeySortedTables(_j).Value.UnPack() : null);} + _o.NativeInline = this.NativeInline.HasValue ? this.NativeInline.Value.UnPack() : null; + _o.LongEnumNonEnumDefault = this.LongEnumNonEnumDefault; + _o.LongEnumNormalDefault = this.LongEnumNormalDefault; + _o.NanDefault = this.NanDefault; + _o.InfDefault = this.InfDefault; + _o.PositiveInfDefault = this.PositiveInfDefault; + _o.InfinityDefault = this.InfinityDefault; + _o.PositiveInfinityDefault = this.PositiveInfinityDefault; + _o.NegativeInfDefault = this.NegativeInfDefault; + _o.NegativeInfinityDefault = this.NegativeInfinityDefault; + _o.DoubleInfDefault = this.DoubleInfDefault; + } + public static Offset Pack(FlatBufferBuilder builder, MonsterT _o) { + if (_o == null) return default(Offset); + var _name = _o.Name == null ? default(StringOffset) : builder.CreateString(_o.Name); + var _inventory = default(VectorOffset); + if (_o.Inventory != null) { + var __inventory = _o.Inventory.ToArray(); + _inventory = CreateInventoryVector(builder, __inventory); + } + var _test_type = _o.Test == null ? MyGame.Example.Any.NONE : _o.Test.Type; + var _test = _o.Test == null ? 0 : MyGame.Example.AnyUnion.Pack(builder, _o.Test); + var _test4 = default(VectorOffset); + if (_o.Test4 != null) { + StartTest4Vector(builder, _o.Test4.Count); + for (var _j = _o.Test4.Count - 1; _j >= 0; --_j) { MyGame.Example.Test.Pack(builder, _o.Test4[_j]); } + _test4 = builder.EndVector(); + } + var _testarrayofstring = default(VectorOffset); + if (_o.Testarrayofstring != null) { + var __testarrayofstring = new StringOffset[_o.Testarrayofstring.Count]; + for (var _j = 0; _j < __testarrayofstring.Length; ++_j) { __testarrayofstring[_j] = builder.CreateString(_o.Testarrayofstring[_j]); } + _testarrayofstring = CreateTestarrayofstringVector(builder, __testarrayofstring); + } + var _testarrayoftables = default(VectorOffset); + if (_o.Testarrayoftables != null) { + var __testarrayoftables = new Offset[_o.Testarrayoftables.Count]; + for (var _j = 0; _j < __testarrayoftables.Length; ++_j) { __testarrayoftables[_j] = MyGame.Example.Monster.Pack(builder, _o.Testarrayoftables[_j]); } + _testarrayoftables = CreateTestarrayoftablesVector(builder, __testarrayoftables); + } + var _enemy = _o.Enemy == null ? default(Offset) : MyGame.Example.Monster.Pack(builder, _o.Enemy); + var _testnestedflatbuffer = default(VectorOffset); + if (_o.Testnestedflatbuffer != null) { + var __testnestedflatbuffer = _o.Testnestedflatbuffer.ToArray(); + _testnestedflatbuffer = CreateTestnestedflatbufferVector(builder, __testnestedflatbuffer); + } + var _testempty = _o.Testempty == null ? default(Offset) : MyGame.Example.Stat.Pack(builder, _o.Testempty); + var _testarrayofbools = default(VectorOffset); + if (_o.Testarrayofbools != null) { + var __testarrayofbools = _o.Testarrayofbools.ToArray(); + _testarrayofbools = CreateTestarrayofboolsVector(builder, __testarrayofbools); + } + var _testarrayofstring2 = default(VectorOffset); + if (_o.Testarrayofstring2 != null) { + var __testarrayofstring2 = new StringOffset[_o.Testarrayofstring2.Count]; + for (var _j = 0; _j < __testarrayofstring2.Length; ++_j) { __testarrayofstring2[_j] = builder.CreateString(_o.Testarrayofstring2[_j]); } + _testarrayofstring2 = CreateTestarrayofstring2Vector(builder, __testarrayofstring2); + } + var _testarrayofsortedstruct = default(VectorOffset); + if (_o.Testarrayofsortedstruct != null) { + StartTestarrayofsortedstructVector(builder, _o.Testarrayofsortedstruct.Count); + for (var _j = _o.Testarrayofsortedstruct.Count - 1; _j >= 0; --_j) { MyGame.Example.Ability.Pack(builder, _o.Testarrayofsortedstruct[_j]); } + _testarrayofsortedstruct = builder.EndVector(); + } + var _flex = default(VectorOffset); + if (_o.Flex != null) { + var __flex = _o.Flex.ToArray(); + _flex = CreateFlexVector(builder, __flex); + } + var _test5 = default(VectorOffset); + if (_o.Test5 != null) { + StartTest5Vector(builder, _o.Test5.Count); + for (var _j = _o.Test5.Count - 1; _j >= 0; --_j) { MyGame.Example.Test.Pack(builder, _o.Test5[_j]); } + _test5 = builder.EndVector(); + } + var _vector_of_longs = default(VectorOffset); + if (_o.VectorOfLongs != null) { + var __vector_of_longs = _o.VectorOfLongs.ToArray(); + _vector_of_longs = CreateVectorOfLongsVector(builder, __vector_of_longs); + } + var _vector_of_doubles = default(VectorOffset); + if (_o.VectorOfDoubles != null) { + var __vector_of_doubles = _o.VectorOfDoubles.ToArray(); + _vector_of_doubles = CreateVectorOfDoublesVector(builder, __vector_of_doubles); + } + var _parent_namespace_test = _o.ParentNamespaceTest == null ? default(Offset) : MyGame.InParentNamespace.Pack(builder, _o.ParentNamespaceTest); + var _vector_of_referrables = default(VectorOffset); + if (_o.VectorOfReferrables != null) { + var __vector_of_referrables = new Offset[_o.VectorOfReferrables.Count]; + for (var _j = 0; _j < __vector_of_referrables.Length; ++_j) { __vector_of_referrables[_j] = MyGame.Example.Referrable.Pack(builder, _o.VectorOfReferrables[_j]); } + _vector_of_referrables = CreateVectorOfReferrablesVector(builder, __vector_of_referrables); + } + var _vector_of_weak_references = default(VectorOffset); + if (_o.VectorOfWeakReferences != null) { + var __vector_of_weak_references = _o.VectorOfWeakReferences.ToArray(); + _vector_of_weak_references = CreateVectorOfWeakReferencesVector(builder, __vector_of_weak_references); + } + var _vector_of_strong_referrables = default(VectorOffset); + if (_o.VectorOfStrongReferrables != null) { + var __vector_of_strong_referrables = new Offset[_o.VectorOfStrongReferrables.Count]; + for (var _j = 0; _j < __vector_of_strong_referrables.Length; ++_j) { __vector_of_strong_referrables[_j] = MyGame.Example.Referrable.Pack(builder, _o.VectorOfStrongReferrables[_j]); } + _vector_of_strong_referrables = CreateVectorOfStrongReferrablesVector(builder, __vector_of_strong_referrables); + } + var _vector_of_co_owning_references = default(VectorOffset); + if (_o.VectorOfCoOwningReferences != null) { + var __vector_of_co_owning_references = _o.VectorOfCoOwningReferences.ToArray(); + _vector_of_co_owning_references = CreateVectorOfCoOwningReferencesVector(builder, __vector_of_co_owning_references); + } + var _vector_of_non_owning_references = default(VectorOffset); + if (_o.VectorOfNonOwningReferences != null) { + var __vector_of_non_owning_references = _o.VectorOfNonOwningReferences.ToArray(); + _vector_of_non_owning_references = CreateVectorOfNonOwningReferencesVector(builder, __vector_of_non_owning_references); + } + var _any_unique_type = _o.AnyUnique == null ? MyGame.Example.AnyUniqueAliases.NONE : _o.AnyUnique.Type; + var _any_unique = _o.AnyUnique == null ? 0 : MyGame.Example.AnyUniqueAliasesUnion.Pack(builder, _o.AnyUnique); + var _any_ambiguous_type = _o.AnyAmbiguous == null ? MyGame.Example.AnyAmbiguousAliases.NONE : _o.AnyAmbiguous.Type; + var _any_ambiguous = _o.AnyAmbiguous == null ? 0 : MyGame.Example.AnyAmbiguousAliasesUnion.Pack(builder, _o.AnyAmbiguous); + var _vector_of_enums = default(VectorOffset); + if (_o.VectorOfEnums != null) { + var __vector_of_enums = _o.VectorOfEnums.ToArray(); + _vector_of_enums = CreateVectorOfEnumsVector(builder, __vector_of_enums); + } + var _testrequirednestedflatbuffer = default(VectorOffset); + if (_o.Testrequirednestedflatbuffer != null) { + var __testrequirednestedflatbuffer = _o.Testrequirednestedflatbuffer.ToArray(); + _testrequirednestedflatbuffer = CreateTestrequirednestedflatbufferVector(builder, __testrequirednestedflatbuffer); + } + var _scalar_key_sorted_tables = default(VectorOffset); + if (_o.ScalarKeySortedTables != null) { + var __scalar_key_sorted_tables = new Offset[_o.ScalarKeySortedTables.Count]; + for (var _j = 0; _j < __scalar_key_sorted_tables.Length; ++_j) { __scalar_key_sorted_tables[_j] = MyGame.Example.Stat.Pack(builder, _o.ScalarKeySortedTables[_j]); } + _scalar_key_sorted_tables = CreateScalarKeySortedTablesVector(builder, __scalar_key_sorted_tables); + } + return CreateMonster( + builder, + _o.Pos, + _o.Mana, + _o.Hp, + _name, + _inventory, + _o.Color, + _test_type, + _test, + _test4, + _testarrayofstring, + _testarrayoftables, + _enemy, + _testnestedflatbuffer, + _testempty, + _o.Testbool, + _o.Testhashs32Fnv1, + _o.Testhashu32Fnv1, + _o.Testhashs64Fnv1, + _o.Testhashu64Fnv1, + _o.Testhashs32Fnv1a, + _o.Testhashu32Fnv1a, + _o.Testhashs64Fnv1a, + _o.Testhashu64Fnv1a, + _testarrayofbools, + _o.Testf, + _o.Testf2, + _o.Testf3, + _testarrayofstring2, + _testarrayofsortedstruct, + _flex, + _test5, + _vector_of_longs, + _vector_of_doubles, + _parent_namespace_test, + _vector_of_referrables, + _o.SingleWeakReference, + _vector_of_weak_references, + _vector_of_strong_referrables, + _o.CoOwningReference, + _vector_of_co_owning_references, + _o.NonOwningReference, + _vector_of_non_owning_references, + _any_unique_type, + _any_unique, + _any_ambiguous_type, + _any_ambiguous, + _vector_of_enums, + _o.SignedEnum, + _testrequirednestedflatbuffer, + _scalar_key_sorted_tables, + _o.NativeInline, + _o.LongEnumNonEnumDefault, + _o.LongEnumNormalDefault, + _o.NanDefault, + _o.InfDefault, + _o.PositiveInfDefault, + _o.InfinityDefault, + _o.PositiveInfinityDefault, + _o.NegativeInfDefault, + _o.NegativeInfinityDefault, + _o.DoubleInfDefault); + } +} + +public class MonsterT +{ + [Newtonsoft.Json.JsonProperty("pos")] + public MyGame.Example.Vec3T Pos { get; set; } + [Newtonsoft.Json.JsonProperty("mana")] + public short Mana { get; set; } + [Newtonsoft.Json.JsonProperty("hp")] + public short Hp { get; set; } + [Newtonsoft.Json.JsonProperty("name")] + public string Name { get; set; } + [Newtonsoft.Json.JsonProperty("inventory")] + public List Inventory { get; set; } + [Newtonsoft.Json.JsonProperty("color")] + public MyGame.Example.Color Color { get; set; } + [Newtonsoft.Json.JsonProperty("test_type")] + private MyGame.Example.Any TestType { + get { + return this.Test != null ? this.Test.Type : MyGame.Example.Any.NONE; + } + set { + this.Test = new MyGame.Example.AnyUnion(); + this.Test.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("test")] + [Newtonsoft.Json.JsonConverter(typeof(MyGame.Example.AnyUnion_JsonConverter))] + public MyGame.Example.AnyUnion Test { get; set; } + [Newtonsoft.Json.JsonProperty("test4")] + public List Test4 { get; set; } + [Newtonsoft.Json.JsonProperty("testarrayofstring")] + public List Testarrayofstring { get; set; } + [Newtonsoft.Json.JsonProperty("testarrayoftables")] + public List Testarrayoftables { get; set; } + [Newtonsoft.Json.JsonProperty("enemy")] + public MyGame.Example.MonsterT Enemy { get; set; } + [Newtonsoft.Json.JsonProperty("testnestedflatbuffer")] + public List Testnestedflatbuffer { get; set; } + [Newtonsoft.Json.JsonProperty("testempty")] + public MyGame.Example.StatT Testempty { get; set; } + [Newtonsoft.Json.JsonProperty("testbool")] + public bool Testbool { get; set; } + [Newtonsoft.Json.JsonProperty("testhashs32_fnv1")] + [Newtonsoft.Json.JsonIgnore()] + public int Testhashs32Fnv1 { get; set; } + [Newtonsoft.Json.JsonProperty("testhashu32_fnv1")] + [Newtonsoft.Json.JsonIgnore()] + public uint Testhashu32Fnv1 { get; set; } + [Newtonsoft.Json.JsonProperty("testhashs64_fnv1")] + [Newtonsoft.Json.JsonIgnore()] + public long Testhashs64Fnv1 { get; set; } + [Newtonsoft.Json.JsonProperty("testhashu64_fnv1")] + [Newtonsoft.Json.JsonIgnore()] + public ulong Testhashu64Fnv1 { get; set; } + [Newtonsoft.Json.JsonProperty("testhashs32_fnv1a")] + [Newtonsoft.Json.JsonIgnore()] + public int Testhashs32Fnv1a { get; set; } + [Newtonsoft.Json.JsonProperty("testhashu32_fnv1a")] + [Newtonsoft.Json.JsonIgnore()] + public uint Testhashu32Fnv1a { get; set; } + [Newtonsoft.Json.JsonProperty("testhashs64_fnv1a")] + [Newtonsoft.Json.JsonIgnore()] + public long Testhashs64Fnv1a { get; set; } + [Newtonsoft.Json.JsonProperty("testhashu64_fnv1a")] + [Newtonsoft.Json.JsonIgnore()] + public ulong Testhashu64Fnv1a { get; set; } + [Newtonsoft.Json.JsonProperty("testarrayofbools")] + public List Testarrayofbools { get; set; } + [Newtonsoft.Json.JsonProperty("testf")] + public float Testf { get; set; } + [Newtonsoft.Json.JsonProperty("testf2")] + public float Testf2 { get; set; } + [Newtonsoft.Json.JsonProperty("testf3")] + public float Testf3 { get; set; } + [Newtonsoft.Json.JsonProperty("testarrayofstring2")] + public List Testarrayofstring2 { get; set; } + [Newtonsoft.Json.JsonProperty("testarrayofsortedstruct")] + public List Testarrayofsortedstruct { get; set; } + [Newtonsoft.Json.JsonProperty("flex")] + public List Flex { get; set; } + [Newtonsoft.Json.JsonProperty("test5")] + public List Test5 { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_longs")] + public List VectorOfLongs { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_doubles")] + public List VectorOfDoubles { get; set; } + [Newtonsoft.Json.JsonProperty("parent_namespace_test")] + public MyGame.InParentNamespaceT ParentNamespaceTest { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_referrables")] + public List VectorOfReferrables { get; set; } + [Newtonsoft.Json.JsonProperty("single_weak_reference")] + [Newtonsoft.Json.JsonIgnore()] + public ulong SingleWeakReference { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_weak_references")] + [Newtonsoft.Json.JsonIgnore()] + public List VectorOfWeakReferences { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_strong_referrables")] + public List VectorOfStrongReferrables { get; set; } + [Newtonsoft.Json.JsonProperty("co_owning_reference")] + [Newtonsoft.Json.JsonIgnore()] + public ulong CoOwningReference { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_co_owning_references")] + [Newtonsoft.Json.JsonIgnore()] + public List VectorOfCoOwningReferences { get; set; } + [Newtonsoft.Json.JsonProperty("non_owning_reference")] + [Newtonsoft.Json.JsonIgnore()] + public ulong NonOwningReference { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_non_owning_references")] + [Newtonsoft.Json.JsonIgnore()] + public List VectorOfNonOwningReferences { get; set; } + [Newtonsoft.Json.JsonProperty("any_unique_type")] + private MyGame.Example.AnyUniqueAliases AnyUniqueType { + get { + return this.AnyUnique != null ? this.AnyUnique.Type : MyGame.Example.AnyUniqueAliases.NONE; + } + set { + this.AnyUnique = new MyGame.Example.AnyUniqueAliasesUnion(); + this.AnyUnique.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("any_unique")] + [Newtonsoft.Json.JsonConverter(typeof(MyGame.Example.AnyUniqueAliasesUnion_JsonConverter))] + public MyGame.Example.AnyUniqueAliasesUnion AnyUnique { get; set; } + [Newtonsoft.Json.JsonProperty("any_ambiguous_type")] + private MyGame.Example.AnyAmbiguousAliases AnyAmbiguousType { + get { + return this.AnyAmbiguous != null ? this.AnyAmbiguous.Type : MyGame.Example.AnyAmbiguousAliases.NONE; + } + set { + this.AnyAmbiguous = new MyGame.Example.AnyAmbiguousAliasesUnion(); + this.AnyAmbiguous.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("any_ambiguous")] + [Newtonsoft.Json.JsonConverter(typeof(MyGame.Example.AnyAmbiguousAliasesUnion_JsonConverter))] + public MyGame.Example.AnyAmbiguousAliasesUnion AnyAmbiguous { get; set; } + [Newtonsoft.Json.JsonProperty("vector_of_enums")] + public List VectorOfEnums { get; set; } + [Newtonsoft.Json.JsonProperty("signed_enum")] + public MyGame.Example.Race SignedEnum { get; set; } + [Newtonsoft.Json.JsonProperty("testrequirednestedflatbuffer")] + public List Testrequirednestedflatbuffer { get; set; } + [Newtonsoft.Json.JsonProperty("scalar_key_sorted_tables")] + public List ScalarKeySortedTables { get; set; } + [Newtonsoft.Json.JsonProperty("native_inline")] + public MyGame.Example.TestT NativeInline { get; set; } + [Newtonsoft.Json.JsonProperty("long_enum_non_enum_default")] + public MyGame.Example.LongEnum LongEnumNonEnumDefault { get; set; } + [Newtonsoft.Json.JsonProperty("long_enum_normal_default")] + public MyGame.Example.LongEnum LongEnumNormalDefault { get; set; } + [Newtonsoft.Json.JsonProperty("nan_default")] + public float NanDefault { get; set; } + [Newtonsoft.Json.JsonProperty("inf_default")] + public float InfDefault { get; set; } + [Newtonsoft.Json.JsonProperty("positive_inf_default")] + public float PositiveInfDefault { get; set; } + [Newtonsoft.Json.JsonProperty("infinity_default")] + public float InfinityDefault { get; set; } + [Newtonsoft.Json.JsonProperty("positive_infinity_default")] + public float PositiveInfinityDefault { get; set; } + [Newtonsoft.Json.JsonProperty("negative_inf_default")] + public float NegativeInfDefault { get; set; } + [Newtonsoft.Json.JsonProperty("negative_infinity_default")] + public float NegativeInfinityDefault { get; set; } + [Newtonsoft.Json.JsonProperty("double_inf_default")] + public double DoubleInfDefault { get; set; } + + public MonsterT() { + this.Pos = new MyGame.Example.Vec3T(); + this.Mana = 150; + this.Hp = 100; + this.Name = null; + this.Inventory = null; + this.Color = MyGame.Example.Color.Blue; + this.Test = null; + this.Test4 = null; + this.Testarrayofstring = null; + this.Testarrayoftables = null; + this.Enemy = null; + this.Testnestedflatbuffer = null; + this.Testempty = null; + this.Testbool = false; + this.Testhashs32Fnv1 = 0; + this.Testhashu32Fnv1 = 0; + this.Testhashs64Fnv1 = 0; + this.Testhashu64Fnv1 = 0; + this.Testhashs32Fnv1a = 0; + this.Testhashu32Fnv1a = 0; + this.Testhashs64Fnv1a = 0; + this.Testhashu64Fnv1a = 0; + this.Testarrayofbools = null; + this.Testf = 3.14159f; + this.Testf2 = 3.0f; + this.Testf3 = 0.0f; + this.Testarrayofstring2 = null; + this.Testarrayofsortedstruct = null; + this.Flex = null; + this.Test5 = null; + this.VectorOfLongs = null; + this.VectorOfDoubles = null; + this.ParentNamespaceTest = null; + this.VectorOfReferrables = null; + this.SingleWeakReference = 0; + this.VectorOfWeakReferences = null; + this.VectorOfStrongReferrables = null; + this.CoOwningReference = 0; + this.VectorOfCoOwningReferences = null; + this.NonOwningReference = 0; + this.VectorOfNonOwningReferences = null; + this.AnyUnique = null; + this.AnyAmbiguous = null; + this.VectorOfEnums = null; + this.SignedEnum = MyGame.Example.Race.None; + this.Testrequirednestedflatbuffer = null; + this.ScalarKeySortedTables = null; + this.NativeInline = new MyGame.Example.TestT(); + this.LongEnumNonEnumDefault = 0; + this.LongEnumNormalDefault = MyGame.Example.LongEnum.LongOne; + this.NanDefault = Single.NaN; + this.InfDefault = Single.PositiveInfinity; + this.PositiveInfDefault = Single.PositiveInfinity; + this.InfinityDefault = Single.PositiveInfinity; + this.PositiveInfinityDefault = Single.PositiveInfinity; + this.NegativeInfDefault = Single.NegativeInfinity; + this.NegativeInfinityDefault = Single.NegativeInfinity; + this.DoubleInfDefault = Double.PositiveInfinity; + } + + public static MonsterT DeserializeFromJson(string jsonText) { + return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText); + } + public string SerializeToJson() { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + public static MonsterT DeserializeFromBinary(byte[] fbBuffer) { + return Monster.GetRootAsMonster(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + Monster.FinishMonsterBuffer(fbb, Monster.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class MonsterVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Pos*/, 32 /*MyGame.Example.Vec3*/, 8, false) + && verifier.VerifyField(tablePos, 6 /*Mana*/, 2 /*short*/, 2, false) + && verifier.VerifyField(tablePos, 8 /*Hp*/, 2 /*short*/, 2, false) + && verifier.VerifyString(tablePos, 10 /*Name*/, true) + && verifier.VerifyVectorOfData(tablePos, 14 /*Inventory*/, 1 /*byte*/, false) + && verifier.VerifyField(tablePos, 16 /*Color*/, 1 /*MyGame.Example.Color*/, 1, false) + && verifier.VerifyField(tablePos, 18 /*TestType*/, 1 /*MyGame.Example.Any*/, 1, false) + && verifier.VerifyUnion(tablePos, 18, 20 /*Test*/, MyGame.Example.AnyVerify.Verify, false) + && verifier.VerifyVectorOfData(tablePos, 22 /*Test4*/, 4 /*MyGame.Example.Test*/, false) + && verifier.VerifyVectorOfStrings(tablePos, 24 /*Testarrayofstring*/, false) + && verifier.VerifyVectorOfTables(tablePos, 26 /*Testarrayoftables*/, MyGame.Example.MonsterVerify.Verify, false) + && verifier.VerifyTable(tablePos, 28 /*Enemy*/, MyGame.Example.MonsterVerify.Verify, false) + && verifier.VerifyNestedBuffer(tablePos, 30 /*Testnestedflatbuffer*/, MyGame.Example.MonsterVerify.Verify, false) + && verifier.VerifyTable(tablePos, 32 /*Testempty*/, MyGame.Example.StatVerify.Verify, false) + && verifier.VerifyField(tablePos, 34 /*Testbool*/, 1 /*bool*/, 1, false) + && verifier.VerifyField(tablePos, 36 /*Testhashs32Fnv1*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 38 /*Testhashu32Fnv1*/, 4 /*uint*/, 4, false) + && verifier.VerifyField(tablePos, 40 /*Testhashs64Fnv1*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 42 /*Testhashu64Fnv1*/, 8 /*ulong*/, 8, false) + && verifier.VerifyField(tablePos, 44 /*Testhashs32Fnv1a*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 46 /*Testhashu32Fnv1a*/, 4 /*uint*/, 4, false) + && verifier.VerifyField(tablePos, 48 /*Testhashs64Fnv1a*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 50 /*Testhashu64Fnv1a*/, 8 /*ulong*/, 8, false) + && verifier.VerifyVectorOfData(tablePos, 52 /*Testarrayofbools*/, 1 /*bool*/, false) + && verifier.VerifyField(tablePos, 54 /*Testf*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 56 /*Testf2*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 58 /*Testf3*/, 4 /*float*/, 4, false) + && verifier.VerifyVectorOfStrings(tablePos, 60 /*Testarrayofstring2*/, false) + && verifier.VerifyVectorOfData(tablePos, 62 /*Testarrayofsortedstruct*/, 8 /*MyGame.Example.Ability*/, false) + && verifier.VerifyNestedBuffer(tablePos, 64 /*Flex*/, null, false) + && verifier.VerifyVectorOfData(tablePos, 66 /*Test5*/, 4 /*MyGame.Example.Test*/, false) + && verifier.VerifyVectorOfData(tablePos, 68 /*VectorOfLongs*/, 8 /*long*/, false) + && verifier.VerifyVectorOfData(tablePos, 70 /*VectorOfDoubles*/, 8 /*double*/, false) + && verifier.VerifyTable(tablePos, 72 /*ParentNamespaceTest*/, MyGame.InParentNamespaceVerify.Verify, false) + && verifier.VerifyVectorOfTables(tablePos, 74 /*VectorOfReferrables*/, MyGame.Example.ReferrableVerify.Verify, false) + && verifier.VerifyField(tablePos, 76 /*SingleWeakReference*/, 8 /*ulong*/, 8, false) + && verifier.VerifyVectorOfData(tablePos, 78 /*VectorOfWeakReferences*/, 8 /*ulong*/, false) + && verifier.VerifyVectorOfTables(tablePos, 80 /*VectorOfStrongReferrables*/, MyGame.Example.ReferrableVerify.Verify, false) + && verifier.VerifyField(tablePos, 82 /*CoOwningReference*/, 8 /*ulong*/, 8, false) + && verifier.VerifyVectorOfData(tablePos, 84 /*VectorOfCoOwningReferences*/, 8 /*ulong*/, false) + && verifier.VerifyField(tablePos, 86 /*NonOwningReference*/, 8 /*ulong*/, 8, false) + && verifier.VerifyVectorOfData(tablePos, 88 /*VectorOfNonOwningReferences*/, 8 /*ulong*/, false) + && verifier.VerifyField(tablePos, 90 /*AnyUniqueType*/, 1 /*MyGame.Example.AnyUniqueAliases*/, 1, false) + && verifier.VerifyUnion(tablePos, 90, 92 /*AnyUnique*/, MyGame.Example.AnyUniqueAliasesVerify.Verify, false) + && verifier.VerifyField(tablePos, 94 /*AnyAmbiguousType*/, 1 /*MyGame.Example.AnyAmbiguousAliases*/, 1, false) + && verifier.VerifyUnion(tablePos, 94, 96 /*AnyAmbiguous*/, MyGame.Example.AnyAmbiguousAliasesVerify.Verify, false) + && verifier.VerifyVectorOfData(tablePos, 98 /*VectorOfEnums*/, 1 /*MyGame.Example.Color*/, false) + && verifier.VerifyField(tablePos, 100 /*SignedEnum*/, 1 /*MyGame.Example.Race*/, 1, false) + && verifier.VerifyNestedBuffer(tablePos, 102 /*Testrequirednestedflatbuffer*/, MyGame.Example.MonsterVerify.Verify, false) + && verifier.VerifyVectorOfTables(tablePos, 104 /*ScalarKeySortedTables*/, MyGame.Example.StatVerify.Verify, false) + && verifier.VerifyField(tablePos, 106 /*NativeInline*/, 4 /*MyGame.Example.Test*/, 2, false) + && verifier.VerifyField(tablePos, 108 /*LongEnumNonEnumDefault*/, 8 /*MyGame.Example.LongEnum*/, 8, false) + && verifier.VerifyField(tablePos, 110 /*LongEnumNormalDefault*/, 8 /*MyGame.Example.LongEnum*/, 8, false) + && verifier.VerifyField(tablePos, 112 /*NanDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 114 /*InfDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 116 /*PositiveInfDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 118 /*InfinityDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 120 /*PositiveInfinityDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 122 /*NegativeInfDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 124 /*NegativeInfinityDefault*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 126 /*DoubleInfDefault*/, 8 /*double*/, 8, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.go b/third_party/flatbuffers/tests/MyGame/Example/Monster.go new file mode 100644 index 00000000000..cc6453b1a3d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.go @@ -0,0 +1,1854 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + "bytes" + flatbuffers "github.com/google/flatbuffers/go" + "math" + + MyGame "MyGame" +) + +/// an example documentation comment: "monster object" +type MonsterT struct { + Pos *Vec3T `json:"pos"` + Mana int16 `json:"mana"` + Hp int16 `json:"hp"` + Name string `json:"name"` + Inventory []byte `json:"inventory"` + Color Color `json:"color"` + Test *AnyT `json:"test"` + Test4 []*TestT `json:"test4"` + Testarrayofstring []string `json:"testarrayofstring"` + Testarrayoftables []*MonsterT `json:"testarrayoftables"` + Enemy *MonsterT `json:"enemy"` + Testnestedflatbuffer []byte `json:"testnestedflatbuffer"` + Testempty *StatT `json:"testempty"` + Testbool bool `json:"testbool"` + Testhashs32Fnv1 int32 `json:"testhashs32_fnv1"` + Testhashu32Fnv1 uint32 `json:"testhashu32_fnv1"` + Testhashs64Fnv1 int64 `json:"testhashs64_fnv1"` + Testhashu64Fnv1 uint64 `json:"testhashu64_fnv1"` + Testhashs32Fnv1a int32 `json:"testhashs32_fnv1a"` + Testhashu32Fnv1a uint32 `json:"testhashu32_fnv1a"` + Testhashs64Fnv1a int64 `json:"testhashs64_fnv1a"` + Testhashu64Fnv1a uint64 `json:"testhashu64_fnv1a"` + Testarrayofbools []bool `json:"testarrayofbools"` + Testf float32 `json:"testf"` + Testf2 float32 `json:"testf2"` + Testf3 float32 `json:"testf3"` + Testarrayofstring2 []string `json:"testarrayofstring2"` + Testarrayofsortedstruct []*AbilityT `json:"testarrayofsortedstruct"` + Flex []byte `json:"flex"` + Test5 []*TestT `json:"test5"` + VectorOfLongs []int64 `json:"vector_of_longs"` + VectorOfDoubles []float64 `json:"vector_of_doubles"` + ParentNamespaceTest *MyGame.InParentNamespaceT `json:"parent_namespace_test"` + VectorOfReferrables []*ReferrableT `json:"vector_of_referrables"` + SingleWeakReference uint64 `json:"single_weak_reference"` + VectorOfWeakReferences []uint64 `json:"vector_of_weak_references"` + VectorOfStrongReferrables []*ReferrableT `json:"vector_of_strong_referrables"` + CoOwningReference uint64 `json:"co_owning_reference"` + VectorOfCoOwningReferences []uint64 `json:"vector_of_co_owning_references"` + NonOwningReference uint64 `json:"non_owning_reference"` + VectorOfNonOwningReferences []uint64 `json:"vector_of_non_owning_references"` + AnyUnique *AnyUniqueAliasesT `json:"any_unique"` + AnyAmbiguous *AnyAmbiguousAliasesT `json:"any_ambiguous"` + VectorOfEnums []Color `json:"vector_of_enums"` + SignedEnum Race `json:"signed_enum"` + Testrequirednestedflatbuffer []byte `json:"testrequirednestedflatbuffer"` + ScalarKeySortedTables []*StatT `json:"scalar_key_sorted_tables"` + NativeInline *TestT `json:"native_inline"` + LongEnumNonEnumDefault LongEnum `json:"long_enum_non_enum_default"` + LongEnumNormalDefault LongEnum `json:"long_enum_normal_default"` + NanDefault float32 `json:"nan_default"` + InfDefault float32 `json:"inf_default"` + PositiveInfDefault float32 `json:"positive_inf_default"` + InfinityDefault float32 `json:"infinity_default"` + PositiveInfinityDefault float32 `json:"positive_infinity_default"` + NegativeInfDefault float32 `json:"negative_inf_default"` + NegativeInfinityDefault float32 `json:"negative_infinity_default"` + DoubleInfDefault float64 `json:"double_inf_default"` +} + +func (t *MonsterT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + nameOffset := flatbuffers.UOffsetT(0) + if t.Name != "" { + nameOffset = builder.CreateString(t.Name) + } + inventoryOffset := flatbuffers.UOffsetT(0) + if t.Inventory != nil { + inventoryOffset = builder.CreateByteString(t.Inventory) + } + testOffset := t.Test.Pack(builder) + + test4Offset := flatbuffers.UOffsetT(0) + if t.Test4 != nil { + test4Length := len(t.Test4) + MonsterStartTest4Vector(builder, test4Length) + for j := test4Length - 1; j >= 0; j-- { + t.Test4[j].Pack(builder) + } + test4Offset = builder.EndVector(test4Length) + } + testarrayofstringOffset := flatbuffers.UOffsetT(0) + if t.Testarrayofstring != nil { + testarrayofstringLength := len(t.Testarrayofstring) + testarrayofstringOffsets := make([]flatbuffers.UOffsetT, testarrayofstringLength) + for j := 0; j < testarrayofstringLength; j++ { + testarrayofstringOffsets[j] = builder.CreateString(t.Testarrayofstring[j]) + } + MonsterStartTestarrayofstringVector(builder, testarrayofstringLength) + for j := testarrayofstringLength - 1; j >= 0; j-- { + builder.PrependUOffsetT(testarrayofstringOffsets[j]) + } + testarrayofstringOffset = builder.EndVector(testarrayofstringLength) + } + testarrayoftablesOffset := flatbuffers.UOffsetT(0) + if t.Testarrayoftables != nil { + testarrayoftablesLength := len(t.Testarrayoftables) + testarrayoftablesOffsets := make([]flatbuffers.UOffsetT, testarrayoftablesLength) + for j := 0; j < testarrayoftablesLength; j++ { + testarrayoftablesOffsets[j] = t.Testarrayoftables[j].Pack(builder) + } + MonsterStartTestarrayoftablesVector(builder, testarrayoftablesLength) + for j := testarrayoftablesLength - 1; j >= 0; j-- { + builder.PrependUOffsetT(testarrayoftablesOffsets[j]) + } + testarrayoftablesOffset = builder.EndVector(testarrayoftablesLength) + } + enemyOffset := t.Enemy.Pack(builder) + testnestedflatbufferOffset := flatbuffers.UOffsetT(0) + if t.Testnestedflatbuffer != nil { + testnestedflatbufferOffset = builder.CreateByteString(t.Testnestedflatbuffer) + } + testemptyOffset := t.Testempty.Pack(builder) + testarrayofboolsOffset := flatbuffers.UOffsetT(0) + if t.Testarrayofbools != nil { + testarrayofboolsLength := len(t.Testarrayofbools) + MonsterStartTestarrayofboolsVector(builder, testarrayofboolsLength) + for j := testarrayofboolsLength - 1; j >= 0; j-- { + builder.PrependBool(t.Testarrayofbools[j]) + } + testarrayofboolsOffset = builder.EndVector(testarrayofboolsLength) + } + testarrayofstring2Offset := flatbuffers.UOffsetT(0) + if t.Testarrayofstring2 != nil { + testarrayofstring2Length := len(t.Testarrayofstring2) + testarrayofstring2Offsets := make([]flatbuffers.UOffsetT, testarrayofstring2Length) + for j := 0; j < testarrayofstring2Length; j++ { + testarrayofstring2Offsets[j] = builder.CreateString(t.Testarrayofstring2[j]) + } + MonsterStartTestarrayofstring2Vector(builder, testarrayofstring2Length) + for j := testarrayofstring2Length - 1; j >= 0; j-- { + builder.PrependUOffsetT(testarrayofstring2Offsets[j]) + } + testarrayofstring2Offset = builder.EndVector(testarrayofstring2Length) + } + testarrayofsortedstructOffset := flatbuffers.UOffsetT(0) + if t.Testarrayofsortedstruct != nil { + testarrayofsortedstructLength := len(t.Testarrayofsortedstruct) + MonsterStartTestarrayofsortedstructVector(builder, testarrayofsortedstructLength) + for j := testarrayofsortedstructLength - 1; j >= 0; j-- { + t.Testarrayofsortedstruct[j].Pack(builder) + } + testarrayofsortedstructOffset = builder.EndVector(testarrayofsortedstructLength) + } + flexOffset := flatbuffers.UOffsetT(0) + if t.Flex != nil { + flexOffset = builder.CreateByteString(t.Flex) + } + test5Offset := flatbuffers.UOffsetT(0) + if t.Test5 != nil { + test5Length := len(t.Test5) + MonsterStartTest5Vector(builder, test5Length) + for j := test5Length - 1; j >= 0; j-- { + t.Test5[j].Pack(builder) + } + test5Offset = builder.EndVector(test5Length) + } + vectorOfLongsOffset := flatbuffers.UOffsetT(0) + if t.VectorOfLongs != nil { + vectorOfLongsLength := len(t.VectorOfLongs) + MonsterStartVectorOfLongsVector(builder, vectorOfLongsLength) + for j := vectorOfLongsLength - 1; j >= 0; j-- { + builder.PrependInt64(t.VectorOfLongs[j]) + } + vectorOfLongsOffset = builder.EndVector(vectorOfLongsLength) + } + vectorOfDoublesOffset := flatbuffers.UOffsetT(0) + if t.VectorOfDoubles != nil { + vectorOfDoublesLength := len(t.VectorOfDoubles) + MonsterStartVectorOfDoublesVector(builder, vectorOfDoublesLength) + for j := vectorOfDoublesLength - 1; j >= 0; j-- { + builder.PrependFloat64(t.VectorOfDoubles[j]) + } + vectorOfDoublesOffset = builder.EndVector(vectorOfDoublesLength) + } + parentNamespaceTestOffset := t.ParentNamespaceTest.Pack(builder) + vectorOfReferrablesOffset := flatbuffers.UOffsetT(0) + if t.VectorOfReferrables != nil { + vectorOfReferrablesLength := len(t.VectorOfReferrables) + vectorOfReferrablesOffsets := make([]flatbuffers.UOffsetT, vectorOfReferrablesLength) + for j := 0; j < vectorOfReferrablesLength; j++ { + vectorOfReferrablesOffsets[j] = t.VectorOfReferrables[j].Pack(builder) + } + MonsterStartVectorOfReferrablesVector(builder, vectorOfReferrablesLength) + for j := vectorOfReferrablesLength - 1; j >= 0; j-- { + builder.PrependUOffsetT(vectorOfReferrablesOffsets[j]) + } + vectorOfReferrablesOffset = builder.EndVector(vectorOfReferrablesLength) + } + vectorOfWeakReferencesOffset := flatbuffers.UOffsetT(0) + if t.VectorOfWeakReferences != nil { + vectorOfWeakReferencesLength := len(t.VectorOfWeakReferences) + MonsterStartVectorOfWeakReferencesVector(builder, vectorOfWeakReferencesLength) + for j := vectorOfWeakReferencesLength - 1; j >= 0; j-- { + builder.PrependUint64(t.VectorOfWeakReferences[j]) + } + vectorOfWeakReferencesOffset = builder.EndVector(vectorOfWeakReferencesLength) + } + vectorOfStrongReferrablesOffset := flatbuffers.UOffsetT(0) + if t.VectorOfStrongReferrables != nil { + vectorOfStrongReferrablesLength := len(t.VectorOfStrongReferrables) + vectorOfStrongReferrablesOffsets := make([]flatbuffers.UOffsetT, vectorOfStrongReferrablesLength) + for j := 0; j < vectorOfStrongReferrablesLength; j++ { + vectorOfStrongReferrablesOffsets[j] = t.VectorOfStrongReferrables[j].Pack(builder) + } + MonsterStartVectorOfStrongReferrablesVector(builder, vectorOfStrongReferrablesLength) + for j := vectorOfStrongReferrablesLength - 1; j >= 0; j-- { + builder.PrependUOffsetT(vectorOfStrongReferrablesOffsets[j]) + } + vectorOfStrongReferrablesOffset = builder.EndVector(vectorOfStrongReferrablesLength) + } + vectorOfCoOwningReferencesOffset := flatbuffers.UOffsetT(0) + if t.VectorOfCoOwningReferences != nil { + vectorOfCoOwningReferencesLength := len(t.VectorOfCoOwningReferences) + MonsterStartVectorOfCoOwningReferencesVector(builder, vectorOfCoOwningReferencesLength) + for j := vectorOfCoOwningReferencesLength - 1; j >= 0; j-- { + builder.PrependUint64(t.VectorOfCoOwningReferences[j]) + } + vectorOfCoOwningReferencesOffset = builder.EndVector(vectorOfCoOwningReferencesLength) + } + vectorOfNonOwningReferencesOffset := flatbuffers.UOffsetT(0) + if t.VectorOfNonOwningReferences != nil { + vectorOfNonOwningReferencesLength := len(t.VectorOfNonOwningReferences) + MonsterStartVectorOfNonOwningReferencesVector(builder, vectorOfNonOwningReferencesLength) + for j := vectorOfNonOwningReferencesLength - 1; j >= 0; j-- { + builder.PrependUint64(t.VectorOfNonOwningReferences[j]) + } + vectorOfNonOwningReferencesOffset = builder.EndVector(vectorOfNonOwningReferencesLength) + } + anyUniqueOffset := t.AnyUnique.Pack(builder) + + anyAmbiguousOffset := t.AnyAmbiguous.Pack(builder) + + vectorOfEnumsOffset := flatbuffers.UOffsetT(0) + if t.VectorOfEnums != nil { + vectorOfEnumsLength := len(t.VectorOfEnums) + MonsterStartVectorOfEnumsVector(builder, vectorOfEnumsLength) + for j := vectorOfEnumsLength - 1; j >= 0; j-- { + builder.PrependByte(byte(t.VectorOfEnums[j])) + } + vectorOfEnumsOffset = builder.EndVector(vectorOfEnumsLength) + } + testrequirednestedflatbufferOffset := flatbuffers.UOffsetT(0) + if t.Testrequirednestedflatbuffer != nil { + testrequirednestedflatbufferOffset = builder.CreateByteString(t.Testrequirednestedflatbuffer) + } + scalarKeySortedTablesOffset := flatbuffers.UOffsetT(0) + if t.ScalarKeySortedTables != nil { + scalarKeySortedTablesLength := len(t.ScalarKeySortedTables) + scalarKeySortedTablesOffsets := make([]flatbuffers.UOffsetT, scalarKeySortedTablesLength) + for j := 0; j < scalarKeySortedTablesLength; j++ { + scalarKeySortedTablesOffsets[j] = t.ScalarKeySortedTables[j].Pack(builder) + } + MonsterStartScalarKeySortedTablesVector(builder, scalarKeySortedTablesLength) + for j := scalarKeySortedTablesLength - 1; j >= 0; j-- { + builder.PrependUOffsetT(scalarKeySortedTablesOffsets[j]) + } + scalarKeySortedTablesOffset = builder.EndVector(scalarKeySortedTablesLength) + } + MonsterStart(builder) + posOffset := t.Pos.Pack(builder) + MonsterAddPos(builder, posOffset) + MonsterAddMana(builder, t.Mana) + MonsterAddHp(builder, t.Hp) + MonsterAddName(builder, nameOffset) + MonsterAddInventory(builder, inventoryOffset) + MonsterAddColor(builder, t.Color) + if t.Test != nil { + MonsterAddTestType(builder, t.Test.Type) + } + MonsterAddTest(builder, testOffset) + MonsterAddTest4(builder, test4Offset) + MonsterAddTestarrayofstring(builder, testarrayofstringOffset) + MonsterAddTestarrayoftables(builder, testarrayoftablesOffset) + MonsterAddEnemy(builder, enemyOffset) + MonsterAddTestnestedflatbuffer(builder, testnestedflatbufferOffset) + MonsterAddTestempty(builder, testemptyOffset) + MonsterAddTestbool(builder, t.Testbool) + MonsterAddTesthashs32Fnv1(builder, t.Testhashs32Fnv1) + MonsterAddTesthashu32Fnv1(builder, t.Testhashu32Fnv1) + MonsterAddTesthashs64Fnv1(builder, t.Testhashs64Fnv1) + MonsterAddTesthashu64Fnv1(builder, t.Testhashu64Fnv1) + MonsterAddTesthashs32Fnv1a(builder, t.Testhashs32Fnv1a) + MonsterAddTesthashu32Fnv1a(builder, t.Testhashu32Fnv1a) + MonsterAddTesthashs64Fnv1a(builder, t.Testhashs64Fnv1a) + MonsterAddTesthashu64Fnv1a(builder, t.Testhashu64Fnv1a) + MonsterAddTestarrayofbools(builder, testarrayofboolsOffset) + MonsterAddTestf(builder, t.Testf) + MonsterAddTestf2(builder, t.Testf2) + MonsterAddTestf3(builder, t.Testf3) + MonsterAddTestarrayofstring2(builder, testarrayofstring2Offset) + MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstructOffset) + MonsterAddFlex(builder, flexOffset) + MonsterAddTest5(builder, test5Offset) + MonsterAddVectorOfLongs(builder, vectorOfLongsOffset) + MonsterAddVectorOfDoubles(builder, vectorOfDoublesOffset) + MonsterAddParentNamespaceTest(builder, parentNamespaceTestOffset) + MonsterAddVectorOfReferrables(builder, vectorOfReferrablesOffset) + MonsterAddSingleWeakReference(builder, t.SingleWeakReference) + MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferencesOffset) + MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrablesOffset) + MonsterAddCoOwningReference(builder, t.CoOwningReference) + MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferencesOffset) + MonsterAddNonOwningReference(builder, t.NonOwningReference) + MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferencesOffset) + if t.AnyUnique != nil { + MonsterAddAnyUniqueType(builder, t.AnyUnique.Type) + } + MonsterAddAnyUnique(builder, anyUniqueOffset) + if t.AnyAmbiguous != nil { + MonsterAddAnyAmbiguousType(builder, t.AnyAmbiguous.Type) + } + MonsterAddAnyAmbiguous(builder, anyAmbiguousOffset) + MonsterAddVectorOfEnums(builder, vectorOfEnumsOffset) + MonsterAddSignedEnum(builder, t.SignedEnum) + MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset) + MonsterAddScalarKeySortedTables(builder, scalarKeySortedTablesOffset) + nativeInlineOffset := t.NativeInline.Pack(builder) + MonsterAddNativeInline(builder, nativeInlineOffset) + MonsterAddLongEnumNonEnumDefault(builder, t.LongEnumNonEnumDefault) + MonsterAddLongEnumNormalDefault(builder, t.LongEnumNormalDefault) + MonsterAddNanDefault(builder, t.NanDefault) + MonsterAddInfDefault(builder, t.InfDefault) + MonsterAddPositiveInfDefault(builder, t.PositiveInfDefault) + MonsterAddInfinityDefault(builder, t.InfinityDefault) + MonsterAddPositiveInfinityDefault(builder, t.PositiveInfinityDefault) + MonsterAddNegativeInfDefault(builder, t.NegativeInfDefault) + MonsterAddNegativeInfinityDefault(builder, t.NegativeInfinityDefault) + MonsterAddDoubleInfDefault(builder, t.DoubleInfDefault) + return MonsterEnd(builder) +} + +func (rcv *Monster) UnPackTo(t *MonsterT) { + t.Pos = rcv.Pos(nil).UnPack() + t.Mana = rcv.Mana() + t.Hp = rcv.Hp() + t.Name = string(rcv.Name()) + t.Inventory = rcv.InventoryBytes() + t.Color = rcv.Color() + testTable := flatbuffers.Table{} + if rcv.Test(&testTable) { + t.Test = rcv.TestType().UnPack(testTable) + } + test4Length := rcv.Test4Length() + t.Test4 = make([]*TestT, test4Length) + for j := 0; j < test4Length; j++ { + x := Test{} + rcv.Test4(&x, j) + t.Test4[j] = x.UnPack() + } + testarrayofstringLength := rcv.TestarrayofstringLength() + t.Testarrayofstring = make([]string, testarrayofstringLength) + for j := 0; j < testarrayofstringLength; j++ { + t.Testarrayofstring[j] = string(rcv.Testarrayofstring(j)) + } + testarrayoftablesLength := rcv.TestarrayoftablesLength() + t.Testarrayoftables = make([]*MonsterT, testarrayoftablesLength) + for j := 0; j < testarrayoftablesLength; j++ { + x := Monster{} + rcv.Testarrayoftables(&x, j) + t.Testarrayoftables[j] = x.UnPack() + } + t.Enemy = rcv.Enemy(nil).UnPack() + t.Testnestedflatbuffer = rcv.TestnestedflatbufferBytes() + t.Testempty = rcv.Testempty(nil).UnPack() + t.Testbool = rcv.Testbool() + t.Testhashs32Fnv1 = rcv.Testhashs32Fnv1() + t.Testhashu32Fnv1 = rcv.Testhashu32Fnv1() + t.Testhashs64Fnv1 = rcv.Testhashs64Fnv1() + t.Testhashu64Fnv1 = rcv.Testhashu64Fnv1() + t.Testhashs32Fnv1a = rcv.Testhashs32Fnv1a() + t.Testhashu32Fnv1a = rcv.Testhashu32Fnv1a() + t.Testhashs64Fnv1a = rcv.Testhashs64Fnv1a() + t.Testhashu64Fnv1a = rcv.Testhashu64Fnv1a() + testarrayofboolsLength := rcv.TestarrayofboolsLength() + t.Testarrayofbools = make([]bool, testarrayofboolsLength) + for j := 0; j < testarrayofboolsLength; j++ { + t.Testarrayofbools[j] = rcv.Testarrayofbools(j) + } + t.Testf = rcv.Testf() + t.Testf2 = rcv.Testf2() + t.Testf3 = rcv.Testf3() + testarrayofstring2Length := rcv.Testarrayofstring2Length() + t.Testarrayofstring2 = make([]string, testarrayofstring2Length) + for j := 0; j < testarrayofstring2Length; j++ { + t.Testarrayofstring2[j] = string(rcv.Testarrayofstring2(j)) + } + testarrayofsortedstructLength := rcv.TestarrayofsortedstructLength() + t.Testarrayofsortedstruct = make([]*AbilityT, testarrayofsortedstructLength) + for j := 0; j < testarrayofsortedstructLength; j++ { + x := Ability{} + rcv.Testarrayofsortedstruct(&x, j) + t.Testarrayofsortedstruct[j] = x.UnPack() + } + t.Flex = rcv.FlexBytes() + test5Length := rcv.Test5Length() + t.Test5 = make([]*TestT, test5Length) + for j := 0; j < test5Length; j++ { + x := Test{} + rcv.Test5(&x, j) + t.Test5[j] = x.UnPack() + } + vectorOfLongsLength := rcv.VectorOfLongsLength() + t.VectorOfLongs = make([]int64, vectorOfLongsLength) + for j := 0; j < vectorOfLongsLength; j++ { + t.VectorOfLongs[j] = rcv.VectorOfLongs(j) + } + vectorOfDoublesLength := rcv.VectorOfDoublesLength() + t.VectorOfDoubles = make([]float64, vectorOfDoublesLength) + for j := 0; j < vectorOfDoublesLength; j++ { + t.VectorOfDoubles[j] = rcv.VectorOfDoubles(j) + } + t.ParentNamespaceTest = rcv.ParentNamespaceTest(nil).UnPack() + vectorOfReferrablesLength := rcv.VectorOfReferrablesLength() + t.VectorOfReferrables = make([]*ReferrableT, vectorOfReferrablesLength) + for j := 0; j < vectorOfReferrablesLength; j++ { + x := Referrable{} + rcv.VectorOfReferrables(&x, j) + t.VectorOfReferrables[j] = x.UnPack() + } + t.SingleWeakReference = rcv.SingleWeakReference() + vectorOfWeakReferencesLength := rcv.VectorOfWeakReferencesLength() + t.VectorOfWeakReferences = make([]uint64, vectorOfWeakReferencesLength) + for j := 0; j < vectorOfWeakReferencesLength; j++ { + t.VectorOfWeakReferences[j] = rcv.VectorOfWeakReferences(j) + } + vectorOfStrongReferrablesLength := rcv.VectorOfStrongReferrablesLength() + t.VectorOfStrongReferrables = make([]*ReferrableT, vectorOfStrongReferrablesLength) + for j := 0; j < vectorOfStrongReferrablesLength; j++ { + x := Referrable{} + rcv.VectorOfStrongReferrables(&x, j) + t.VectorOfStrongReferrables[j] = x.UnPack() + } + t.CoOwningReference = rcv.CoOwningReference() + vectorOfCoOwningReferencesLength := rcv.VectorOfCoOwningReferencesLength() + t.VectorOfCoOwningReferences = make([]uint64, vectorOfCoOwningReferencesLength) + for j := 0; j < vectorOfCoOwningReferencesLength; j++ { + t.VectorOfCoOwningReferences[j] = rcv.VectorOfCoOwningReferences(j) + } + t.NonOwningReference = rcv.NonOwningReference() + vectorOfNonOwningReferencesLength := rcv.VectorOfNonOwningReferencesLength() + t.VectorOfNonOwningReferences = make([]uint64, vectorOfNonOwningReferencesLength) + for j := 0; j < vectorOfNonOwningReferencesLength; j++ { + t.VectorOfNonOwningReferences[j] = rcv.VectorOfNonOwningReferences(j) + } + anyUniqueTable := flatbuffers.Table{} + if rcv.AnyUnique(&anyUniqueTable) { + t.AnyUnique = rcv.AnyUniqueType().UnPack(anyUniqueTable) + } + anyAmbiguousTable := flatbuffers.Table{} + if rcv.AnyAmbiguous(&anyAmbiguousTable) { + t.AnyAmbiguous = rcv.AnyAmbiguousType().UnPack(anyAmbiguousTable) + } + vectorOfEnumsLength := rcv.VectorOfEnumsLength() + t.VectorOfEnums = make([]Color, vectorOfEnumsLength) + for j := 0; j < vectorOfEnumsLength; j++ { + t.VectorOfEnums[j] = rcv.VectorOfEnums(j) + } + t.SignedEnum = rcv.SignedEnum() + t.Testrequirednestedflatbuffer = rcv.TestrequirednestedflatbufferBytes() + scalarKeySortedTablesLength := rcv.ScalarKeySortedTablesLength() + t.ScalarKeySortedTables = make([]*StatT, scalarKeySortedTablesLength) + for j := 0; j < scalarKeySortedTablesLength; j++ { + x := Stat{} + rcv.ScalarKeySortedTables(&x, j) + t.ScalarKeySortedTables[j] = x.UnPack() + } + t.NativeInline = rcv.NativeInline(nil).UnPack() + t.LongEnumNonEnumDefault = rcv.LongEnumNonEnumDefault() + t.LongEnumNormalDefault = rcv.LongEnumNormalDefault() + t.NanDefault = rcv.NanDefault() + t.InfDefault = rcv.InfDefault() + t.PositiveInfDefault = rcv.PositiveInfDefault() + t.InfinityDefault = rcv.InfinityDefault() + t.PositiveInfinityDefault = rcv.PositiveInfinityDefault() + t.NegativeInfDefault = rcv.NegativeInfDefault() + t.NegativeInfinityDefault = rcv.NegativeInfinityDefault() + t.DoubleInfDefault = rcv.DoubleInfDefault() +} + +func (rcv *Monster) UnPack() *MonsterT { + if rcv == nil { + return nil + } + t := &MonsterT{} + rcv.UnPackTo(t) + return t +} + +type Monster struct { + _tab flatbuffers.Table +} + +const MonsterIdentifier = "MONS" + +func GetRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Monster{} + x.Init(buf, n+offset) + return x +} + +func FinishMonsterBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + identifierBytes := []byte(MonsterIdentifier) + builder.FinishWithFileIdentifier(offset, identifierBytes) +} + +func MonsterBufferHasIdentifier(buf []byte) bool { + return flatbuffers.BufferHasIdentifier(buf, MonsterIdentifier) +} + +func GetSizePrefixedRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Monster{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedMonsterBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + identifierBytes := []byte(MonsterIdentifier) + builder.FinishSizePrefixedWithFileIdentifier(offset, identifierBytes) +} + +func SizePrefixedMonsterBufferHasIdentifier(buf []byte) bool { + return flatbuffers.SizePrefixedBufferHasIdentifier(buf, MonsterIdentifier) +} + +func (rcv *Monster) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Monster) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Monster) Pos(obj *Vec3) *Vec3 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := o + rcv._tab.Pos + if obj == nil { + obj = new(Vec3) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *Monster) Mana() int16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + return rcv._tab.GetInt16(o + rcv._tab.Pos) + } + return 150 +} + +func (rcv *Monster) MutateMana(n int16) bool { + return rcv._tab.MutateInt16Slot(6, n) +} + +func (rcv *Monster) Hp() int16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) + if o != 0 { + return rcv._tab.GetInt16(o + rcv._tab.Pos) + } + return 100 +} + +func (rcv *Monster) MutateHp(n int16) bool { + return rcv._tab.MutateInt16Slot(8, n) +} + +func (rcv *Monster) Name() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(10)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func MonsterKeyCompare(o1, o2 flatbuffers.UOffsetT, buf []byte) bool { + obj1 := &Monster{} + obj2 := &Monster{} + obj1.Init(buf, flatbuffers.UOffsetT(len(buf))-o1) + obj2.Init(buf, flatbuffers.UOffsetT(len(buf))-o2) + return string(obj1.Name()) < string(obj2.Name()) +} + +func (rcv *Monster) LookupByKey(key string, vectorLocation flatbuffers.UOffsetT, buf []byte) bool { + span := flatbuffers.GetUOffsetT(buf[vectorLocation-4:]) + start := flatbuffers.UOffsetT(0) + bKey := []byte(key) + for span != 0 { + middle := span / 2 + tableOffset := flatbuffers.GetIndirectOffset(buf, vectorLocation+4*(start+middle)) + obj := &Monster{} + obj.Init(buf, tableOffset) + comp := bytes.Compare(obj.Name(), bKey) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + rcv.Init(buf, tableOffset) + return true + } + } + return false +} + +func (rcv *Monster) Inventory(j int) byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) + } + return 0 +} + +func (rcv *Monster) InventoryLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) InventoryBytes() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Monster) MutateInventory(j int, n byte) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) + } + return false +} + +func (rcv *Monster) Color() Color { + o := flatbuffers.UOffsetT(rcv._tab.Offset(16)) + if o != 0 { + return Color(rcv._tab.GetByte(o + rcv._tab.Pos)) + } + return 8 +} + +func (rcv *Monster) MutateColor(n Color) bool { + return rcv._tab.MutateByteSlot(16, byte(n)) +} + +func (rcv *Monster) TestType() Any { + o := flatbuffers.UOffsetT(rcv._tab.Offset(18)) + if o != 0 { + return Any(rcv._tab.GetByte(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *Monster) MutateTestType(n Any) bool { + return rcv._tab.MutateByteSlot(18, byte(n)) +} + +func (rcv *Monster) Test(obj *flatbuffers.Table) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(20)) + if o != 0 { + rcv._tab.Union(obj, o) + return true + } + return false +} + +func (rcv *Monster) Test4(obj *Test, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(22)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) Test4Length() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(22)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) Testarrayofstring(j int) []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.ByteVector(a + flatbuffers.UOffsetT(j*4)) + } + return nil +} + +func (rcv *Monster) TestarrayofstringLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +/// an example documentation comment: this will end up in the generated code +/// multiline too +func (rcv *Monster) Testarrayoftables(obj *Monster, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + x = rcv._tab.Indirect(x) + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) TestarrayoftablesByKey(obj *Monster, key string) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + x := rcv._tab.Vector(o) + return obj.LookupByKey(key, x, rcv._tab.Bytes) + } + return false +} + +func (rcv *Monster) TestarrayoftablesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +/// an example documentation comment: this will end up in the generated code +/// multiline too +func (rcv *Monster) Enemy(obj *Monster) *Monster { + o := flatbuffers.UOffsetT(rcv._tab.Offset(28)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(Monster) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *Monster) Testnestedflatbuffer(j int) byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) + } + return 0 +} + +func (rcv *Monster) TestnestedflatbufferLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) TestnestedflatbufferBytes() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Monster) MutateTestnestedflatbuffer(j int, n byte) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) + } + return false +} + +func (rcv *Monster) Testempty(obj *Stat) *Stat { + o := flatbuffers.UOffsetT(rcv._tab.Offset(32)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(Stat) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *Monster) Testbool() bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(34)) + if o != 0 { + return rcv._tab.GetBool(o + rcv._tab.Pos) + } + return false +} + +func (rcv *Monster) MutateTestbool(n bool) bool { + return rcv._tab.MutateBoolSlot(34, n) +} + +func (rcv *Monster) Testhashs32Fnv1() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(36)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashs32Fnv1(n int32) bool { + return rcv._tab.MutateInt32Slot(36, n) +} + +func (rcv *Monster) Testhashu32Fnv1() uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(38)) + if o != 0 { + return rcv._tab.GetUint32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashu32Fnv1(n uint32) bool { + return rcv._tab.MutateUint32Slot(38, n) +} + +func (rcv *Monster) Testhashs64Fnv1() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(40)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashs64Fnv1(n int64) bool { + return rcv._tab.MutateInt64Slot(40, n) +} + +func (rcv *Monster) Testhashu64Fnv1() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(42)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashu64Fnv1(n uint64) bool { + return rcv._tab.MutateUint64Slot(42, n) +} + +func (rcv *Monster) Testhashs32Fnv1a() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(44)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashs32Fnv1a(n int32) bool { + return rcv._tab.MutateInt32Slot(44, n) +} + +func (rcv *Monster) Testhashu32Fnv1a() uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(46)) + if o != 0 { + return rcv._tab.GetUint32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashu32Fnv1a(n uint32) bool { + return rcv._tab.MutateUint32Slot(46, n) +} + +func (rcv *Monster) Testhashs64Fnv1a() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(48)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashs64Fnv1a(n int64) bool { + return rcv._tab.MutateInt64Slot(48, n) +} + +func (rcv *Monster) Testhashu64Fnv1a() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(50)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateTesthashu64Fnv1a(n uint64) bool { + return rcv._tab.MutateUint64Slot(50, n) +} + +func (rcv *Monster) Testarrayofbools(j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetBool(a + flatbuffers.UOffsetT(j*1)) + } + return false +} + +func (rcv *Monster) TestarrayofboolsLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) MutateTestarrayofbools(j int, n bool) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateBool(a+flatbuffers.UOffsetT(j*1), n) + } + return false +} + +func (rcv *Monster) Testf() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(54)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return 3.14159 +} + +func (rcv *Monster) MutateTestf(n float32) bool { + return rcv._tab.MutateFloat32Slot(54, n) +} + +func (rcv *Monster) Testf2() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(56)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return 3.0 +} + +func (rcv *Monster) MutateTestf2(n float32) bool { + return rcv._tab.MutateFloat32Slot(56, n) +} + +func (rcv *Monster) Testf3() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(58)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return 0.0 +} + +func (rcv *Monster) MutateTestf3(n float32) bool { + return rcv._tab.MutateFloat32Slot(58, n) +} + +func (rcv *Monster) Testarrayofstring2(j int) []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(60)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.ByteVector(a + flatbuffers.UOffsetT(j*4)) + } + return nil +} + +func (rcv *Monster) Testarrayofstring2Length() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(60)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) Testarrayofsortedstruct(obj *Ability, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(62)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 8 + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) TestarrayofsortedstructLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(62)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) Flex(j int) byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) + } + return 0 +} + +func (rcv *Monster) FlexLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) FlexBytes() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Monster) MutateFlex(j int, n byte) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) + } + return false +} + +func (rcv *Monster) Test5(obj *Test, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(66)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) Test5Length() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(66)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) VectorOfLongs(j int) int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetInt64(a + flatbuffers.UOffsetT(j*8)) + } + return 0 +} + +func (rcv *Monster) VectorOfLongsLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) MutateVectorOfLongs(j int, n int64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateInt64(a+flatbuffers.UOffsetT(j*8), n) + } + return false +} + +func (rcv *Monster) VectorOfDoubles(j int) float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetFloat64(a + flatbuffers.UOffsetT(j*8)) + } + return 0 +} + +func (rcv *Monster) VectorOfDoublesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) MutateVectorOfDoubles(j int, n float64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateFloat64(a+flatbuffers.UOffsetT(j*8), n) + } + return false +} + +func (rcv *Monster) ParentNamespaceTest(obj *MyGame.InParentNamespace) *MyGame.InParentNamespace { + o := flatbuffers.UOffsetT(rcv._tab.Offset(72)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(MyGame.InParentNamespace) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *Monster) VectorOfReferrables(obj *Referrable, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(74)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + x = rcv._tab.Indirect(x) + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) VectorOfReferrablesByKey(obj *Referrable, key uint64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(74)) + if o != 0 { + x := rcv._tab.Vector(o) + return obj.LookupByKey(key, x, rcv._tab.Bytes) + } + return false +} + +func (rcv *Monster) VectorOfReferrablesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(74)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) SingleWeakReference() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(76)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateSingleWeakReference(n uint64) bool { + return rcv._tab.MutateUint64Slot(76, n) +} + +func (rcv *Monster) VectorOfWeakReferences(j int) uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(78)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j*8)) + } + return 0 +} + +func (rcv *Monster) VectorOfWeakReferencesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(78)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) MutateVectorOfWeakReferences(j int, n uint64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(78)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateUint64(a+flatbuffers.UOffsetT(j*8), n) + } + return false +} + +func (rcv *Monster) VectorOfStrongReferrables(obj *Referrable, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(80)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + x = rcv._tab.Indirect(x) + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) VectorOfStrongReferrablesByKey(obj *Referrable, key uint64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(80)) + if o != 0 { + x := rcv._tab.Vector(o) + return obj.LookupByKey(key, x, rcv._tab.Bytes) + } + return false +} + +func (rcv *Monster) VectorOfStrongReferrablesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(80)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) CoOwningReference() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(82)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateCoOwningReference(n uint64) bool { + return rcv._tab.MutateUint64Slot(82, n) +} + +func (rcv *Monster) VectorOfCoOwningReferences(j int) uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(84)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j*8)) + } + return 0 +} + +func (rcv *Monster) VectorOfCoOwningReferencesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(84)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) MutateVectorOfCoOwningReferences(j int, n uint64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(84)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateUint64(a+flatbuffers.UOffsetT(j*8), n) + } + return false +} + +func (rcv *Monster) NonOwningReference() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(86)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Monster) MutateNonOwningReference(n uint64) bool { + return rcv._tab.MutateUint64Slot(86, n) +} + +func (rcv *Monster) VectorOfNonOwningReferences(j int) uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(88)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetUint64(a + flatbuffers.UOffsetT(j*8)) + } + return 0 +} + +func (rcv *Monster) VectorOfNonOwningReferencesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(88)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) MutateVectorOfNonOwningReferences(j int, n uint64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(88)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateUint64(a+flatbuffers.UOffsetT(j*8), n) + } + return false +} + +func (rcv *Monster) AnyUniqueType() AnyUniqueAliases { + o := flatbuffers.UOffsetT(rcv._tab.Offset(90)) + if o != 0 { + return AnyUniqueAliases(rcv._tab.GetByte(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *Monster) MutateAnyUniqueType(n AnyUniqueAliases) bool { + return rcv._tab.MutateByteSlot(90, byte(n)) +} + +func (rcv *Monster) AnyUnique(obj *flatbuffers.Table) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(92)) + if o != 0 { + rcv._tab.Union(obj, o) + return true + } + return false +} + +func (rcv *Monster) AnyAmbiguousType() AnyAmbiguousAliases { + o := flatbuffers.UOffsetT(rcv._tab.Offset(94)) + if o != 0 { + return AnyAmbiguousAliases(rcv._tab.GetByte(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *Monster) MutateAnyAmbiguousType(n AnyAmbiguousAliases) bool { + return rcv._tab.MutateByteSlot(94, byte(n)) +} + +func (rcv *Monster) AnyAmbiguous(obj *flatbuffers.Table) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(96)) + if o != 0 { + rcv._tab.Union(obj, o) + return true + } + return false +} + +func (rcv *Monster) VectorOfEnums(j int) Color { + o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) + if o != 0 { + a := rcv._tab.Vector(o) + return Color(rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1))) + } + return 0 +} + +func (rcv *Monster) VectorOfEnumsLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) VectorOfEnumsBytes() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Monster) MutateVectorOfEnums(j int, n Color) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(98)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), byte(n)) + } + return false +} + +func (rcv *Monster) SignedEnum() Race { + o := flatbuffers.UOffsetT(rcv._tab.Offset(100)) + if o != 0 { + return Race(rcv._tab.GetInt8(o + rcv._tab.Pos)) + } + return -1 +} + +func (rcv *Monster) MutateSignedEnum(n Race) bool { + return rcv._tab.MutateInt8Slot(100, int8(n)) +} + +func (rcv *Monster) Testrequirednestedflatbuffer(j int) byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetByte(a + flatbuffers.UOffsetT(j*1)) + } + return 0 +} + +func (rcv *Monster) TestrequirednestedflatbufferLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) TestrequirednestedflatbufferBytes() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Monster) MutateTestrequirednestedflatbuffer(j int, n byte) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(102)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateByte(a+flatbuffers.UOffsetT(j*1), n) + } + return false +} + +func (rcv *Monster) ScalarKeySortedTables(obj *Stat, j int) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(104)) + if o != 0 { + x := rcv._tab.Vector(o) + x += flatbuffers.UOffsetT(j) * 4 + x = rcv._tab.Indirect(x) + obj.Init(rcv._tab.Bytes, x) + return true + } + return false +} + +func (rcv *Monster) ScalarKeySortedTablesByKey(obj *Stat, key uint16) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(104)) + if o != 0 { + x := rcv._tab.Vector(o) + return obj.LookupByKey(key, x, rcv._tab.Bytes) + } + return false +} + +func (rcv *Monster) ScalarKeySortedTablesLength() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(104)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *Monster) NativeInline(obj *Test) *Test { + o := flatbuffers.UOffsetT(rcv._tab.Offset(106)) + if o != 0 { + x := o + rcv._tab.Pos + if obj == nil { + obj = new(Test) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *Monster) LongEnumNonEnumDefault() LongEnum { + o := flatbuffers.UOffsetT(rcv._tab.Offset(108)) + if o != 0 { + return LongEnum(rcv._tab.GetUint64(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *Monster) MutateLongEnumNonEnumDefault(n LongEnum) bool { + return rcv._tab.MutateUint64Slot(108, uint64(n)) +} + +func (rcv *Monster) LongEnumNormalDefault() LongEnum { + o := flatbuffers.UOffsetT(rcv._tab.Offset(110)) + if o != 0 { + return LongEnum(rcv._tab.GetUint64(o + rcv._tab.Pos)) + } + return 2 +} + +func (rcv *Monster) MutateLongEnumNormalDefault(n LongEnum) bool { + return rcv._tab.MutateUint64Slot(110, uint64(n)) +} + +func (rcv *Monster) NanDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(112)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.NaN()) +} + +func (rcv *Monster) MutateNanDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(112, n) +} + +func (rcv *Monster) InfDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(114)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.Inf(1)) +} + +func (rcv *Monster) MutateInfDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(114, n) +} + +func (rcv *Monster) PositiveInfDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(116)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.Inf(1)) +} + +func (rcv *Monster) MutatePositiveInfDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(116, n) +} + +func (rcv *Monster) InfinityDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(118)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.Inf(1)) +} + +func (rcv *Monster) MutateInfinityDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(118, n) +} + +func (rcv *Monster) PositiveInfinityDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(120)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.Inf(1)) +} + +func (rcv *Monster) MutatePositiveInfinityDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(120, n) +} + +func (rcv *Monster) NegativeInfDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(122)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.Inf(-1)) +} + +func (rcv *Monster) MutateNegativeInfDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(122, n) +} + +func (rcv *Monster) NegativeInfinityDefault() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(124)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return float32(math.Inf(-1)) +} + +func (rcv *Monster) MutateNegativeInfinityDefault(n float32) bool { + return rcv._tab.MutateFloat32Slot(124, n) +} + +func (rcv *Monster) DoubleInfDefault() float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(126)) + if o != 0 { + return rcv._tab.GetFloat64(o + rcv._tab.Pos) + } + return float64(math.Inf(1)) +} + +func (rcv *Monster) MutateDoubleInfDefault(n float64) bool { + return rcv._tab.MutateFloat64Slot(126, n) +} + +func MonsterStart(builder *flatbuffers.Builder) { + builder.StartObject(62) +} +func MonsterAddPos(builder *flatbuffers.Builder, pos flatbuffers.UOffsetT) { + builder.PrependStructSlot(0, flatbuffers.UOffsetT(pos), 0) +} +func MonsterAddMana(builder *flatbuffers.Builder, mana int16) { + builder.PrependInt16Slot(1, mana, 150) +} +func MonsterAddHp(builder *flatbuffers.Builder, hp int16) { + builder.PrependInt16Slot(2, hp, 100) +} +func MonsterAddName(builder *flatbuffers.Builder, name flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(3, flatbuffers.UOffsetT(name), 0) +} +func MonsterAddInventory(builder *flatbuffers.Builder, inventory flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(5, flatbuffers.UOffsetT(inventory), 0) +} +func MonsterStartInventoryVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func MonsterAddColor(builder *flatbuffers.Builder, color Color) { + builder.PrependByteSlot(6, byte(color), 8) +} +func MonsterAddTestType(builder *flatbuffers.Builder, testType Any) { + builder.PrependByteSlot(7, byte(testType), 0) +} +func MonsterAddTest(builder *flatbuffers.Builder, test flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(8, flatbuffers.UOffsetT(test), 0) +} +func MonsterAddTest4(builder *flatbuffers.Builder, test4 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(9, flatbuffers.UOffsetT(test4), 0) +} +func MonsterStartTest4Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 2) +} +func MonsterAddTestarrayofstring(builder *flatbuffers.Builder, testarrayofstring flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(10, flatbuffers.UOffsetT(testarrayofstring), 0) +} +func MonsterStartTestarrayofstringVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func MonsterAddTestarrayoftables(builder *flatbuffers.Builder, testarrayoftables flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(11, flatbuffers.UOffsetT(testarrayoftables), 0) +} +func MonsterStartTestarrayoftablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func MonsterAddEnemy(builder *flatbuffers.Builder, enemy flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(12, flatbuffers.UOffsetT(enemy), 0) +} +func MonsterAddTestnestedflatbuffer(builder *flatbuffers.Builder, testnestedflatbuffer flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(13, flatbuffers.UOffsetT(testnestedflatbuffer), 0) +} +func MonsterStartTestnestedflatbufferVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func MonsterAddTestempty(builder *flatbuffers.Builder, testempty flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(14, flatbuffers.UOffsetT(testempty), 0) +} +func MonsterAddTestbool(builder *flatbuffers.Builder, testbool bool) { + builder.PrependBoolSlot(15, testbool, false) +} +func MonsterAddTesthashs32Fnv1(builder *flatbuffers.Builder, testhashs32Fnv1 int32) { + builder.PrependInt32Slot(16, testhashs32Fnv1, 0) +} +func MonsterAddTesthashu32Fnv1(builder *flatbuffers.Builder, testhashu32Fnv1 uint32) { + builder.PrependUint32Slot(17, testhashu32Fnv1, 0) +} +func MonsterAddTesthashs64Fnv1(builder *flatbuffers.Builder, testhashs64Fnv1 int64) { + builder.PrependInt64Slot(18, testhashs64Fnv1, 0) +} +func MonsterAddTesthashu64Fnv1(builder *flatbuffers.Builder, testhashu64Fnv1 uint64) { + builder.PrependUint64Slot(19, testhashu64Fnv1, 0) +} +func MonsterAddTesthashs32Fnv1a(builder *flatbuffers.Builder, testhashs32Fnv1a int32) { + builder.PrependInt32Slot(20, testhashs32Fnv1a, 0) +} +func MonsterAddTesthashu32Fnv1a(builder *flatbuffers.Builder, testhashu32Fnv1a uint32) { + builder.PrependUint32Slot(21, testhashu32Fnv1a, 0) +} +func MonsterAddTesthashs64Fnv1a(builder *flatbuffers.Builder, testhashs64Fnv1a int64) { + builder.PrependInt64Slot(22, testhashs64Fnv1a, 0) +} +func MonsterAddTesthashu64Fnv1a(builder *flatbuffers.Builder, testhashu64Fnv1a uint64) { + builder.PrependUint64Slot(23, testhashu64Fnv1a, 0) +} +func MonsterAddTestarrayofbools(builder *flatbuffers.Builder, testarrayofbools flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(24, flatbuffers.UOffsetT(testarrayofbools), 0) +} +func MonsterStartTestarrayofboolsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func MonsterAddTestf(builder *flatbuffers.Builder, testf float32) { + builder.PrependFloat32Slot(25, testf, 3.14159) +} +func MonsterAddTestf2(builder *flatbuffers.Builder, testf2 float32) { + builder.PrependFloat32Slot(26, testf2, 3.0) +} +func MonsterAddTestf3(builder *flatbuffers.Builder, testf3 float32) { + builder.PrependFloat32Slot(27, testf3, 0.0) +} +func MonsterAddTestarrayofstring2(builder *flatbuffers.Builder, testarrayofstring2 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(28, flatbuffers.UOffsetT(testarrayofstring2), 0) +} +func MonsterStartTestarrayofstring2Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func MonsterAddTestarrayofsortedstruct(builder *flatbuffers.Builder, testarrayofsortedstruct flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(29, flatbuffers.UOffsetT(testarrayofsortedstruct), 0) +} +func MonsterStartTestarrayofsortedstructVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 4) +} +func MonsterAddFlex(builder *flatbuffers.Builder, flex flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(30, flatbuffers.UOffsetT(flex), 0) +} +func MonsterStartFlexVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func MonsterAddTest5(builder *flatbuffers.Builder, test5 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(31, flatbuffers.UOffsetT(test5), 0) +} +func MonsterStartTest5Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 2) +} +func MonsterAddVectorOfLongs(builder *flatbuffers.Builder, vectorOfLongs flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(32, flatbuffers.UOffsetT(vectorOfLongs), 0) +} +func MonsterStartVectorOfLongsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 8) +} +func MonsterAddVectorOfDoubles(builder *flatbuffers.Builder, vectorOfDoubles flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(33, flatbuffers.UOffsetT(vectorOfDoubles), 0) +} +func MonsterStartVectorOfDoublesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 8) +} +func MonsterAddParentNamespaceTest(builder *flatbuffers.Builder, parentNamespaceTest flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(34, flatbuffers.UOffsetT(parentNamespaceTest), 0) +} +func MonsterAddVectorOfReferrables(builder *flatbuffers.Builder, vectorOfReferrables flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(35, flatbuffers.UOffsetT(vectorOfReferrables), 0) +} +func MonsterStartVectorOfReferrablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func MonsterAddSingleWeakReference(builder *flatbuffers.Builder, singleWeakReference uint64) { + builder.PrependUint64Slot(36, singleWeakReference, 0) +} +func MonsterAddVectorOfWeakReferences(builder *flatbuffers.Builder, vectorOfWeakReferences flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(37, flatbuffers.UOffsetT(vectorOfWeakReferences), 0) +} +func MonsterStartVectorOfWeakReferencesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 8) +} +func MonsterAddVectorOfStrongReferrables(builder *flatbuffers.Builder, vectorOfStrongReferrables flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(38, flatbuffers.UOffsetT(vectorOfStrongReferrables), 0) +} +func MonsterStartVectorOfStrongReferrablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func MonsterAddCoOwningReference(builder *flatbuffers.Builder, coOwningReference uint64) { + builder.PrependUint64Slot(39, coOwningReference, 0) +} +func MonsterAddVectorOfCoOwningReferences(builder *flatbuffers.Builder, vectorOfCoOwningReferences flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(40, flatbuffers.UOffsetT(vectorOfCoOwningReferences), 0) +} +func MonsterStartVectorOfCoOwningReferencesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 8) +} +func MonsterAddNonOwningReference(builder *flatbuffers.Builder, nonOwningReference uint64) { + builder.PrependUint64Slot(41, nonOwningReference, 0) +} +func MonsterAddVectorOfNonOwningReferences(builder *flatbuffers.Builder, vectorOfNonOwningReferences flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(42, flatbuffers.UOffsetT(vectorOfNonOwningReferences), 0) +} +func MonsterStartVectorOfNonOwningReferencesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 8) +} +func MonsterAddAnyUniqueType(builder *flatbuffers.Builder, anyUniqueType AnyUniqueAliases) { + builder.PrependByteSlot(43, byte(anyUniqueType), 0) +} +func MonsterAddAnyUnique(builder *flatbuffers.Builder, anyUnique flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(44, flatbuffers.UOffsetT(anyUnique), 0) +} +func MonsterAddAnyAmbiguousType(builder *flatbuffers.Builder, anyAmbiguousType AnyAmbiguousAliases) { + builder.PrependByteSlot(45, byte(anyAmbiguousType), 0) +} +func MonsterAddAnyAmbiguous(builder *flatbuffers.Builder, anyAmbiguous flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(46, flatbuffers.UOffsetT(anyAmbiguous), 0) +} +func MonsterAddVectorOfEnums(builder *flatbuffers.Builder, vectorOfEnums flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(47, flatbuffers.UOffsetT(vectorOfEnums), 0) +} +func MonsterStartVectorOfEnumsVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func MonsterAddSignedEnum(builder *flatbuffers.Builder, signedEnum Race) { + builder.PrependInt8Slot(48, int8(signedEnum), -1) +} +func MonsterAddTestrequirednestedflatbuffer(builder *flatbuffers.Builder, testrequirednestedflatbuffer flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(49, flatbuffers.UOffsetT(testrequirednestedflatbuffer), 0) +} +func MonsterStartTestrequirednestedflatbufferVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func MonsterAddScalarKeySortedTables(builder *flatbuffers.Builder, scalarKeySortedTables flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(50, flatbuffers.UOffsetT(scalarKeySortedTables), 0) +} +func MonsterStartScalarKeySortedTablesVector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(4, numElems, 4) +} +func MonsterAddNativeInline(builder *flatbuffers.Builder, nativeInline flatbuffers.UOffsetT) { + builder.PrependStructSlot(51, flatbuffers.UOffsetT(nativeInline), 0) +} +func MonsterAddLongEnumNonEnumDefault(builder *flatbuffers.Builder, longEnumNonEnumDefault LongEnum) { + builder.PrependUint64Slot(52, uint64(longEnumNonEnumDefault), 0) +} +func MonsterAddLongEnumNormalDefault(builder *flatbuffers.Builder, longEnumNormalDefault LongEnum) { + builder.PrependUint64Slot(53, uint64(longEnumNormalDefault), 2) +} +func MonsterAddNanDefault(builder *flatbuffers.Builder, nanDefault float32) { + builder.PrependFloat32Slot(54, nanDefault, float32(math.NaN())) +} +func MonsterAddInfDefault(builder *flatbuffers.Builder, infDefault float32) { + builder.PrependFloat32Slot(55, infDefault, float32(math.Inf(1))) +} +func MonsterAddPositiveInfDefault(builder *flatbuffers.Builder, positiveInfDefault float32) { + builder.PrependFloat32Slot(56, positiveInfDefault, float32(math.Inf(1))) +} +func MonsterAddInfinityDefault(builder *flatbuffers.Builder, infinityDefault float32) { + builder.PrependFloat32Slot(57, infinityDefault, float32(math.Inf(1))) +} +func MonsterAddPositiveInfinityDefault(builder *flatbuffers.Builder, positiveInfinityDefault float32) { + builder.PrependFloat32Slot(58, positiveInfinityDefault, float32(math.Inf(1))) +} +func MonsterAddNegativeInfDefault(builder *flatbuffers.Builder, negativeInfDefault float32) { + builder.PrependFloat32Slot(59, negativeInfDefault, float32(math.Inf(-1))) +} +func MonsterAddNegativeInfinityDefault(builder *flatbuffers.Builder, negativeInfinityDefault float32) { + builder.PrependFloat32Slot(60, negativeInfinityDefault, float32(math.Inf(-1))) +} +func MonsterAddDoubleInfDefault(builder *flatbuffers.Builder, doubleInfDefault float64) { + builder.PrependFloat64Slot(61, doubleInfDefault, float64(math.Inf(1))) +} +func MonsterEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.java b/third_party/flatbuffers/tests/MyGame/Example/Monster.java new file mode 100644 index 00000000000..2a8d6796edc --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.java @@ -0,0 +1,791 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +/** + * an example documentation comment: "monster object" + */ +@SuppressWarnings("unused") +public final class Monster extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); } + public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public static boolean MonsterBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONS"); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Monster __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.Vec3 pos() { return pos(new MyGame.Example.Vec3()); } + public MyGame.Example.Vec3 pos(MyGame.Example.Vec3 obj) { int o = __offset(4); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; } + public short mana() { int o = __offset(6); return o != 0 ? bb.getShort(o + bb_pos) : 150; } + public boolean mutateMana(short mana) { int o = __offset(6); if (o != 0) { bb.putShort(o + bb_pos, mana); return true; } else { return false; } } + public short hp() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) : 100; } + public boolean mutateHp(short hp) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, hp); return true; } else { return false; } } + public String name() { int o = __offset(10); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer nameAsByteBuffer() { return __vector_as_bytebuffer(10, 1); } + public ByteBuffer nameInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 10, 1); } + public int inventory(int j) { int o = __offset(14); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; } + public int inventoryLength() { int o = __offset(14); return o != 0 ? __vector_len(o) : 0; } + public ByteVector inventoryVector() { return inventoryVector(new ByteVector()); } + public ByteVector inventoryVector(ByteVector obj) { int o = __offset(14); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer inventoryAsByteBuffer() { return __vector_as_bytebuffer(14, 1); } + public ByteBuffer inventoryInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 14, 1); } + public boolean mutateInventory(int j, int inventory) { int o = __offset(14); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) inventory); return true; } else { return false; } } + public int color() { int o = __offset(16); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 8; } + public boolean mutateColor(int color) { int o = __offset(16); if (o != 0) { bb.put(o + bb_pos, (byte) color); return true; } else { return false; } } + public byte testType() { int o = __offset(18); return o != 0 ? bb.get(o + bb_pos) : 0; } + public Table test(Table obj) { int o = __offset(20); return o != 0 ? __union(obj, o + bb_pos) : null; } + public MyGame.Example.Test test4(int j) { return test4(new MyGame.Example.Test(), j); } + public MyGame.Example.Test test4(MyGame.Example.Test obj, int j) { int o = __offset(22); return o != 0 ? obj.__assign(__vector(o) + j * 4, bb) : null; } + public int test4Length() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Test.Vector test4Vector() { return test4Vector(new MyGame.Example.Test.Vector()); } + public MyGame.Example.Test.Vector test4Vector(MyGame.Example.Test.Vector obj) { int o = __offset(22); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public String testarrayofstring(int j) { int o = __offset(24); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int testarrayofstringLength() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; } + public StringVector testarrayofstringVector() { return testarrayofstringVector(new StringVector()); } + public StringVector testarrayofstringVector(StringVector obj) { int o = __offset(24); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + /** + * an example documentation comment: this will end up in the generated code + * multiline too + */ + public MyGame.Example.Monster testarrayoftables(int j) { return testarrayoftables(new MyGame.Example.Monster(), j); } + public MyGame.Example.Monster testarrayoftables(MyGame.Example.Monster obj, int j) { int o = __offset(26); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int testarrayoftablesLength() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Monster testarrayoftablesByKey(String key) { int o = __offset(26); return o != 0 ? MyGame.Example.Monster.__lookup_by_key(null, __vector(o), key, bb) : null; } + public MyGame.Example.Monster testarrayoftablesByKey(MyGame.Example.Monster obj, String key) { int o = __offset(26); return o != 0 ? MyGame.Example.Monster.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public MyGame.Example.Monster.Vector testarrayoftablesVector() { return testarrayoftablesVector(new MyGame.Example.Monster.Vector()); } + public MyGame.Example.Monster.Vector testarrayoftablesVector(MyGame.Example.Monster.Vector obj) { int o = __offset(26); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public MyGame.Example.Monster enemy() { return enemy(new MyGame.Example.Monster()); } + public MyGame.Example.Monster enemy(MyGame.Example.Monster obj) { int o = __offset(28); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public int testnestedflatbuffer(int j) { int o = __offset(30); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; } + public int testnestedflatbufferLength() { int o = __offset(30); return o != 0 ? __vector_len(o) : 0; } + public ByteVector testnestedflatbufferVector() { return testnestedflatbufferVector(new ByteVector()); } + public ByteVector testnestedflatbufferVector(ByteVector obj) { int o = __offset(30); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer testnestedflatbufferAsByteBuffer() { return __vector_as_bytebuffer(30, 1); } + public ByteBuffer testnestedflatbufferInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 30, 1); } + public MyGame.Example.Monster testnestedflatbufferAsMonster() { return testnestedflatbufferAsMonster(new MyGame.Example.Monster()); } + public MyGame.Example.Monster testnestedflatbufferAsMonster(MyGame.Example.Monster obj) { int o = __offset(30); return o != 0 ? obj.__assign(__indirect(__vector(o)), bb) : null; } + public boolean mutateTestnestedflatbuffer(int j, int testnestedflatbuffer) { int o = __offset(30); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) testnestedflatbuffer); return true; } else { return false; } } + public MyGame.Example.Stat testempty() { return testempty(new MyGame.Example.Stat()); } + public MyGame.Example.Stat testempty(MyGame.Example.Stat obj) { int o = __offset(32); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public boolean testbool() { int o = __offset(34); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public boolean mutateTestbool(boolean testbool) { int o = __offset(34); if (o != 0) { bb.put(o + bb_pos, (byte)(testbool ? 1 : 0)); return true; } else { return false; } } + public int testhashs32Fnv1() { int o = __offset(36); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean mutateTesthashs32Fnv1(int testhashs32_fnv1) { int o = __offset(36); if (o != 0) { bb.putInt(o + bb_pos, testhashs32_fnv1); return true; } else { return false; } } + public long testhashu32Fnv1() { int o = __offset(38); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; } + public boolean mutateTesthashu32Fnv1(long testhashu32_fnv1) { int o = __offset(38); if (o != 0) { bb.putInt(o + bb_pos, (int) testhashu32_fnv1); return true; } else { return false; } } + public long testhashs64Fnv1() { int o = __offset(40); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateTesthashs64Fnv1(long testhashs64_fnv1) { int o = __offset(40); if (o != 0) { bb.putLong(o + bb_pos, testhashs64_fnv1); return true; } else { return false; } } + public long testhashu64Fnv1() { int o = __offset(42); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateTesthashu64Fnv1(long testhashu64_fnv1) { int o = __offset(42); if (o != 0) { bb.putLong(o + bb_pos, testhashu64_fnv1); return true; } else { return false; } } + public int testhashs32Fnv1a() { int o = __offset(44); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean mutateTesthashs32Fnv1a(int testhashs32_fnv1a) { int o = __offset(44); if (o != 0) { bb.putInt(o + bb_pos, testhashs32_fnv1a); return true; } else { return false; } } + public long testhashu32Fnv1a() { int o = __offset(46); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; } + public boolean mutateTesthashu32Fnv1a(long testhashu32_fnv1a) { int o = __offset(46); if (o != 0) { bb.putInt(o + bb_pos, (int) testhashu32_fnv1a); return true; } else { return false; } } + public long testhashs64Fnv1a() { int o = __offset(48); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateTesthashs64Fnv1a(long testhashs64_fnv1a) { int o = __offset(48); if (o != 0) { bb.putLong(o + bb_pos, testhashs64_fnv1a); return true; } else { return false; } } + public long testhashu64Fnv1a() { int o = __offset(50); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateTesthashu64Fnv1a(long testhashu64_fnv1a) { int o = __offset(50); if (o != 0) { bb.putLong(o + bb_pos, testhashu64_fnv1a); return true; } else { return false; } } + public boolean testarrayofbools(int j) { int o = __offset(52); return o != 0 ? 0!=bb.get(__vector(o) + j * 1) : false; } + public int testarrayofboolsLength() { int o = __offset(52); return o != 0 ? __vector_len(o) : 0; } + public BooleanVector testarrayofboolsVector() { return testarrayofboolsVector(new BooleanVector()); } + public BooleanVector testarrayofboolsVector(BooleanVector obj) { int o = __offset(52); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer testarrayofboolsAsByteBuffer() { return __vector_as_bytebuffer(52, 1); } + public ByteBuffer testarrayofboolsInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 52, 1); } + public boolean mutateTestarrayofbools(int j, boolean testarrayofbools) { int o = __offset(52); if (o != 0) { bb.put(__vector(o) + j * 1, (byte)(testarrayofbools ? 1 : 0)); return true; } else { return false; } } + public float testf() { int o = __offset(54); return o != 0 ? bb.getFloat(o + bb_pos) : 3.14159f; } + public boolean mutateTestf(float testf) { int o = __offset(54); if (o != 0) { bb.putFloat(o + bb_pos, testf); return true; } else { return false; } } + public float testf2() { int o = __offset(56); return o != 0 ? bb.getFloat(o + bb_pos) : 3.0f; } + public boolean mutateTestf2(float testf2) { int o = __offset(56); if (o != 0) { bb.putFloat(o + bb_pos, testf2); return true; } else { return false; } } + public float testf3() { int o = __offset(58); return o != 0 ? bb.getFloat(o + bb_pos) : 0.0f; } + public boolean mutateTestf3(float testf3) { int o = __offset(58); if (o != 0) { bb.putFloat(o + bb_pos, testf3); return true; } else { return false; } } + public String testarrayofstring2(int j) { int o = __offset(60); return o != 0 ? __string(__vector(o) + j * 4) : null; } + public int testarrayofstring2Length() { int o = __offset(60); return o != 0 ? __vector_len(o) : 0; } + public StringVector testarrayofstring2Vector() { return testarrayofstring2Vector(new StringVector()); } + public StringVector testarrayofstring2Vector(StringVector obj) { int o = __offset(60); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public MyGame.Example.Ability testarrayofsortedstruct(int j) { return testarrayofsortedstruct(new MyGame.Example.Ability(), j); } + public MyGame.Example.Ability testarrayofsortedstruct(MyGame.Example.Ability obj, int j) { int o = __offset(62); return o != 0 ? obj.__assign(__vector(o) + j * 8, bb) : null; } + public int testarrayofsortedstructLength() { int o = __offset(62); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Ability.Vector testarrayofsortedstructVector() { return testarrayofsortedstructVector(new MyGame.Example.Ability.Vector()); } + public MyGame.Example.Ability.Vector testarrayofsortedstructVector(MyGame.Example.Ability.Vector obj) { int o = __offset(62); return o != 0 ? obj.__assign(__vector(o), 8, bb) : null; } + public int flex(int j) { int o = __offset(64); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; } + public int flexLength() { int o = __offset(64); return o != 0 ? __vector_len(o) : 0; } + public ByteVector flexVector() { return flexVector(new ByteVector()); } + public ByteVector flexVector(ByteVector obj) { int o = __offset(64); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer flexAsByteBuffer() { return __vector_as_bytebuffer(64, 1); } + public ByteBuffer flexInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 64, 1); } + public boolean mutateFlex(int j, int flex) { int o = __offset(64); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) flex); return true; } else { return false; } } + public MyGame.Example.Test test5(int j) { return test5(new MyGame.Example.Test(), j); } + public MyGame.Example.Test test5(MyGame.Example.Test obj, int j) { int o = __offset(66); return o != 0 ? obj.__assign(__vector(o) + j * 4, bb) : null; } + public int test5Length() { int o = __offset(66); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Test.Vector test5Vector() { return test5Vector(new MyGame.Example.Test.Vector()); } + public MyGame.Example.Test.Vector test5Vector(MyGame.Example.Test.Vector obj) { int o = __offset(66); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public long vectorOfLongs(int j) { int o = __offset(68); return o != 0 ? bb.getLong(__vector(o) + j * 8) : 0; } + public int vectorOfLongsLength() { int o = __offset(68); return o != 0 ? __vector_len(o) : 0; } + public LongVector vectorOfLongsVector() { return vectorOfLongsVector(new LongVector()); } + public LongVector vectorOfLongsVector(LongVector obj) { int o = __offset(68); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vectorOfLongsAsByteBuffer() { return __vector_as_bytebuffer(68, 8); } + public ByteBuffer vectorOfLongsInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 68, 8); } + public boolean mutateVectorOfLongs(int j, long vector_of_longs) { int o = __offset(68); if (o != 0) { bb.putLong(__vector(o) + j * 8, vector_of_longs); return true; } else { return false; } } + public double vectorOfDoubles(int j) { int o = __offset(70); return o != 0 ? bb.getDouble(__vector(o) + j * 8) : 0; } + public int vectorOfDoublesLength() { int o = __offset(70); return o != 0 ? __vector_len(o) : 0; } + public DoubleVector vectorOfDoublesVector() { return vectorOfDoublesVector(new DoubleVector()); } + public DoubleVector vectorOfDoublesVector(DoubleVector obj) { int o = __offset(70); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vectorOfDoublesAsByteBuffer() { return __vector_as_bytebuffer(70, 8); } + public ByteBuffer vectorOfDoublesInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 70, 8); } + public boolean mutateVectorOfDoubles(int j, double vector_of_doubles) { int o = __offset(70); if (o != 0) { bb.putDouble(__vector(o) + j * 8, vector_of_doubles); return true; } else { return false; } } + public MyGame.InParentNamespace parentNamespaceTest() { return parentNamespaceTest(new MyGame.InParentNamespace()); } + public MyGame.InParentNamespace parentNamespaceTest(MyGame.InParentNamespace obj) { int o = __offset(72); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public MyGame.Example.Referrable vectorOfReferrables(int j) { return vectorOfReferrables(new MyGame.Example.Referrable(), j); } + public MyGame.Example.Referrable vectorOfReferrables(MyGame.Example.Referrable obj, int j) { int o = __offset(74); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int vectorOfReferrablesLength() { int o = __offset(74); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Referrable vectorOfReferrablesByKey(long key) { int o = __offset(74); return o != 0 ? MyGame.Example.Referrable.__lookup_by_key(null, __vector(o), key, bb) : null; } + public MyGame.Example.Referrable vectorOfReferrablesByKey(MyGame.Example.Referrable obj, long key) { int o = __offset(74); return o != 0 ? MyGame.Example.Referrable.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public MyGame.Example.Referrable.Vector vectorOfReferrablesVector() { return vectorOfReferrablesVector(new MyGame.Example.Referrable.Vector()); } + public MyGame.Example.Referrable.Vector vectorOfReferrablesVector(MyGame.Example.Referrable.Vector obj) { int o = __offset(74); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public long singleWeakReference() { int o = __offset(76); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateSingleWeakReference(long single_weak_reference) { int o = __offset(76); if (o != 0) { bb.putLong(o + bb_pos, single_weak_reference); return true; } else { return false; } } + public long vectorOfWeakReferences(int j) { int o = __offset(78); return o != 0 ? bb.getLong(__vector(o) + j * 8) : 0; } + public int vectorOfWeakReferencesLength() { int o = __offset(78); return o != 0 ? __vector_len(o) : 0; } + public LongVector vectorOfWeakReferencesVector() { return vectorOfWeakReferencesVector(new LongVector()); } + public LongVector vectorOfWeakReferencesVector(LongVector obj) { int o = __offset(78); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vectorOfWeakReferencesAsByteBuffer() { return __vector_as_bytebuffer(78, 8); } + public ByteBuffer vectorOfWeakReferencesInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 78, 8); } + public boolean mutateVectorOfWeakReferences(int j, long vector_of_weak_references) { int o = __offset(78); if (o != 0) { bb.putLong(__vector(o) + j * 8, vector_of_weak_references); return true; } else { return false; } } + public MyGame.Example.Referrable vectorOfStrongReferrables(int j) { return vectorOfStrongReferrables(new MyGame.Example.Referrable(), j); } + public MyGame.Example.Referrable vectorOfStrongReferrables(MyGame.Example.Referrable obj, int j) { int o = __offset(80); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int vectorOfStrongReferrablesLength() { int o = __offset(80); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Referrable vectorOfStrongReferrablesByKey(long key) { int o = __offset(80); return o != 0 ? MyGame.Example.Referrable.__lookup_by_key(null, __vector(o), key, bb) : null; } + public MyGame.Example.Referrable vectorOfStrongReferrablesByKey(MyGame.Example.Referrable obj, long key) { int o = __offset(80); return o != 0 ? MyGame.Example.Referrable.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public MyGame.Example.Referrable.Vector vectorOfStrongReferrablesVector() { return vectorOfStrongReferrablesVector(new MyGame.Example.Referrable.Vector()); } + public MyGame.Example.Referrable.Vector vectorOfStrongReferrablesVector(MyGame.Example.Referrable.Vector obj) { int o = __offset(80); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public long coOwningReference() { int o = __offset(82); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateCoOwningReference(long co_owning_reference) { int o = __offset(82); if (o != 0) { bb.putLong(o + bb_pos, co_owning_reference); return true; } else { return false; } } + public long vectorOfCoOwningReferences(int j) { int o = __offset(84); return o != 0 ? bb.getLong(__vector(o) + j * 8) : 0; } + public int vectorOfCoOwningReferencesLength() { int o = __offset(84); return o != 0 ? __vector_len(o) : 0; } + public LongVector vectorOfCoOwningReferencesVector() { return vectorOfCoOwningReferencesVector(new LongVector()); } + public LongVector vectorOfCoOwningReferencesVector(LongVector obj) { int o = __offset(84); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vectorOfCoOwningReferencesAsByteBuffer() { return __vector_as_bytebuffer(84, 8); } + public ByteBuffer vectorOfCoOwningReferencesInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 84, 8); } + public boolean mutateVectorOfCoOwningReferences(int j, long vector_of_co_owning_references) { int o = __offset(84); if (o != 0) { bb.putLong(__vector(o) + j * 8, vector_of_co_owning_references); return true; } else { return false; } } + public long nonOwningReference() { int o = __offset(86); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateNonOwningReference(long non_owning_reference) { int o = __offset(86); if (o != 0) { bb.putLong(o + bb_pos, non_owning_reference); return true; } else { return false; } } + public long vectorOfNonOwningReferences(int j) { int o = __offset(88); return o != 0 ? bb.getLong(__vector(o) + j * 8) : 0; } + public int vectorOfNonOwningReferencesLength() { int o = __offset(88); return o != 0 ? __vector_len(o) : 0; } + public LongVector vectorOfNonOwningReferencesVector() { return vectorOfNonOwningReferencesVector(new LongVector()); } + public LongVector vectorOfNonOwningReferencesVector(LongVector obj) { int o = __offset(88); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vectorOfNonOwningReferencesAsByteBuffer() { return __vector_as_bytebuffer(88, 8); } + public ByteBuffer vectorOfNonOwningReferencesInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 88, 8); } + public boolean mutateVectorOfNonOwningReferences(int j, long vector_of_non_owning_references) { int o = __offset(88); if (o != 0) { bb.putLong(__vector(o) + j * 8, vector_of_non_owning_references); return true; } else { return false; } } + public byte anyUniqueType() { int o = __offset(90); return o != 0 ? bb.get(o + bb_pos) : 0; } + public Table anyUnique(Table obj) { int o = __offset(92); return o != 0 ? __union(obj, o + bb_pos) : null; } + public byte anyAmbiguousType() { int o = __offset(94); return o != 0 ? bb.get(o + bb_pos) : 0; } + public Table anyAmbiguous(Table obj) { int o = __offset(96); return o != 0 ? __union(obj, o + bb_pos) : null; } + public int vectorOfEnums(int j) { int o = __offset(98); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; } + public int vectorOfEnumsLength() { int o = __offset(98); return o != 0 ? __vector_len(o) : 0; } + public ByteVector vectorOfEnumsVector() { return vectorOfEnumsVector(new ByteVector()); } + public ByteVector vectorOfEnumsVector(ByteVector obj) { int o = __offset(98); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vectorOfEnumsAsByteBuffer() { return __vector_as_bytebuffer(98, 1); } + public ByteBuffer vectorOfEnumsInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 98, 1); } + public boolean mutateVectorOfEnums(int j, int vector_of_enums) { int o = __offset(98); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) vector_of_enums); return true; } else { return false; } } + public byte signedEnum() { int o = __offset(100); return o != 0 ? bb.get(o + bb_pos) : -1; } + public boolean mutateSignedEnum(byte signed_enum) { int o = __offset(100); if (o != 0) { bb.put(o + bb_pos, signed_enum); return true; } else { return false; } } + public int testrequirednestedflatbuffer(int j) { int o = __offset(102); return o != 0 ? bb.get(__vector(o) + j * 1) & 0xFF : 0; } + public int testrequirednestedflatbufferLength() { int o = __offset(102); return o != 0 ? __vector_len(o) : 0; } + public ByteVector testrequirednestedflatbufferVector() { return testrequirednestedflatbufferVector(new ByteVector()); } + public ByteVector testrequirednestedflatbufferVector(ByteVector obj) { int o = __offset(102); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer testrequirednestedflatbufferAsByteBuffer() { return __vector_as_bytebuffer(102, 1); } + public ByteBuffer testrequirednestedflatbufferInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 102, 1); } + public MyGame.Example.Monster testrequirednestedflatbufferAsMonster() { return testrequirednestedflatbufferAsMonster(new MyGame.Example.Monster()); } + public MyGame.Example.Monster testrequirednestedflatbufferAsMonster(MyGame.Example.Monster obj) { int o = __offset(102); return o != 0 ? obj.__assign(__indirect(__vector(o)), bb) : null; } + public boolean mutateTestrequirednestedflatbuffer(int j, int testrequirednestedflatbuffer) { int o = __offset(102); if (o != 0) { bb.put(__vector(o) + j * 1, (byte) testrequirednestedflatbuffer); return true; } else { return false; } } + public MyGame.Example.Stat scalarKeySortedTables(int j) { return scalarKeySortedTables(new MyGame.Example.Stat(), j); } + public MyGame.Example.Stat scalarKeySortedTables(MyGame.Example.Stat obj, int j) { int o = __offset(104); return o != 0 ? obj.__assign(__indirect(__vector(o) + j * 4), bb) : null; } + public int scalarKeySortedTablesLength() { int o = __offset(104); return o != 0 ? __vector_len(o) : 0; } + public MyGame.Example.Stat scalarKeySortedTablesByKey(int key) { int o = __offset(104); return o != 0 ? MyGame.Example.Stat.__lookup_by_key(null, __vector(o), key, bb) : null; } + public MyGame.Example.Stat scalarKeySortedTablesByKey(MyGame.Example.Stat obj, int key) { int o = __offset(104); return o != 0 ? MyGame.Example.Stat.__lookup_by_key(obj, __vector(o), key, bb) : null; } + public MyGame.Example.Stat.Vector scalarKeySortedTablesVector() { return scalarKeySortedTablesVector(new MyGame.Example.Stat.Vector()); } + public MyGame.Example.Stat.Vector scalarKeySortedTablesVector(MyGame.Example.Stat.Vector obj) { int o = __offset(104); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + public MyGame.Example.Test nativeInline() { return nativeInline(new MyGame.Example.Test()); } + public MyGame.Example.Test nativeInline(MyGame.Example.Test obj) { int o = __offset(106); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; } + public long longEnumNonEnumDefault() { int o = __offset(108); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateLongEnumNonEnumDefault(long long_enum_non_enum_default) { int o = __offset(108); if (o != 0) { bb.putLong(o + bb_pos, long_enum_non_enum_default); return true; } else { return false; } } + public long longEnumNormalDefault() { int o = __offset(110); return o != 0 ? bb.getLong(o + bb_pos) : 2L; } + public boolean mutateLongEnumNormalDefault(long long_enum_normal_default) { int o = __offset(110); if (o != 0) { bb.putLong(o + bb_pos, long_enum_normal_default); return true; } else { return false; } } + public float nanDefault() { int o = __offset(112); return o != 0 ? bb.getFloat(o + bb_pos) : Float.NaN; } + public boolean mutateNanDefault(float nan_default) { int o = __offset(112); if (o != 0) { bb.putFloat(o + bb_pos, nan_default); return true; } else { return false; } } + public float infDefault() { int o = __offset(114); return o != 0 ? bb.getFloat(o + bb_pos) : Float.POSITIVE_INFINITY; } + public boolean mutateInfDefault(float inf_default) { int o = __offset(114); if (o != 0) { bb.putFloat(o + bb_pos, inf_default); return true; } else { return false; } } + public float positiveInfDefault() { int o = __offset(116); return o != 0 ? bb.getFloat(o + bb_pos) : Float.POSITIVE_INFINITY; } + public boolean mutatePositiveInfDefault(float positive_inf_default) { int o = __offset(116); if (o != 0) { bb.putFloat(o + bb_pos, positive_inf_default); return true; } else { return false; } } + public float infinityDefault() { int o = __offset(118); return o != 0 ? bb.getFloat(o + bb_pos) : Float.POSITIVE_INFINITY; } + public boolean mutateInfinityDefault(float infinity_default) { int o = __offset(118); if (o != 0) { bb.putFloat(o + bb_pos, infinity_default); return true; } else { return false; } } + public float positiveInfinityDefault() { int o = __offset(120); return o != 0 ? bb.getFloat(o + bb_pos) : Float.POSITIVE_INFINITY; } + public boolean mutatePositiveInfinityDefault(float positive_infinity_default) { int o = __offset(120); if (o != 0) { bb.putFloat(o + bb_pos, positive_infinity_default); return true; } else { return false; } } + public float negativeInfDefault() { int o = __offset(122); return o != 0 ? bb.getFloat(o + bb_pos) : Float.NEGATIVE_INFINITY; } + public boolean mutateNegativeInfDefault(float negative_inf_default) { int o = __offset(122); if (o != 0) { bb.putFloat(o + bb_pos, negative_inf_default); return true; } else { return false; } } + public float negativeInfinityDefault() { int o = __offset(124); return o != 0 ? bb.getFloat(o + bb_pos) : Float.NEGATIVE_INFINITY; } + public boolean mutateNegativeInfinityDefault(float negative_infinity_default) { int o = __offset(124); if (o != 0) { bb.putFloat(o + bb_pos, negative_infinity_default); return true; } else { return false; } } + public double doubleInfDefault() { int o = __offset(126); return o != 0 ? bb.getDouble(o + bb_pos) : Double.POSITIVE_INFINITY; } + public boolean mutateDoubleInfDefault(double double_inf_default) { int o = __offset(126); if (o != 0) { bb.putDouble(o + bb_pos, double_inf_default); return true; } else { return false; } } + + public static void startMonster(FlatBufferBuilder builder) { builder.startTable(62); } + public static void addPos(FlatBufferBuilder builder, int posOffset) { builder.addStruct(0, posOffset, 0); } + public static void addMana(FlatBufferBuilder builder, short mana) { builder.addShort(1, mana, 150); } + public static void addHp(FlatBufferBuilder builder, short hp) { builder.addShort(2, hp, 100); } + public static void addName(FlatBufferBuilder builder, int nameOffset) { builder.addOffset(nameOffset); builder.slot(3); } + public static void addInventory(FlatBufferBuilder builder, int inventoryOffset) { builder.addOffset(5, inventoryOffset, 0); } + public static int createInventoryVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); } + public static int createInventoryVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); } + public static void startInventoryVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addColor(FlatBufferBuilder builder, int color) { builder.addByte(6, (byte) color, (byte) 8); } + public static void addTestType(FlatBufferBuilder builder, byte testType) { builder.addByte(7, testType, 0); } + public static void addTest(FlatBufferBuilder builder, int testOffset) { builder.addOffset(8, testOffset, 0); } + public static void addTest4(FlatBufferBuilder builder, int test4Offset) { builder.addOffset(9, test4Offset, 0); } + public static void startTest4Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 2); } + public static void addTestarrayofstring(FlatBufferBuilder builder, int testarrayofstringOffset) { builder.addOffset(10, testarrayofstringOffset, 0); } + public static int createTestarrayofstringVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startTestarrayofstringVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addTestarrayoftables(FlatBufferBuilder builder, int testarrayoftablesOffset) { builder.addOffset(11, testarrayoftablesOffset, 0); } + public static int createTestarrayoftablesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startTestarrayoftablesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addEnemy(FlatBufferBuilder builder, int enemyOffset) { builder.addOffset(12, enemyOffset, 0); } + public static void addTestnestedflatbuffer(FlatBufferBuilder builder, int testnestedflatbufferOffset) { builder.addOffset(13, testnestedflatbufferOffset, 0); } + public static int createTestnestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); } + public static int createTestnestedflatbufferVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); } + public static void startTestnestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addTestempty(FlatBufferBuilder builder, int testemptyOffset) { builder.addOffset(14, testemptyOffset, 0); } + public static void addTestbool(FlatBufferBuilder builder, boolean testbool) { builder.addBoolean(15, testbool, false); } + public static void addTesthashs32Fnv1(FlatBufferBuilder builder, int testhashs32Fnv1) { builder.addInt(16, testhashs32Fnv1, 0); } + public static void addTesthashu32Fnv1(FlatBufferBuilder builder, long testhashu32Fnv1) { builder.addInt(17, (int) testhashu32Fnv1, (int) 0L); } + public static void addTesthashs64Fnv1(FlatBufferBuilder builder, long testhashs64Fnv1) { builder.addLong(18, testhashs64Fnv1, 0L); } + public static void addTesthashu64Fnv1(FlatBufferBuilder builder, long testhashu64Fnv1) { builder.addLong(19, testhashu64Fnv1, 0L); } + public static void addTesthashs32Fnv1a(FlatBufferBuilder builder, int testhashs32Fnv1a) { builder.addInt(20, testhashs32Fnv1a, 0); } + public static void addTesthashu32Fnv1a(FlatBufferBuilder builder, long testhashu32Fnv1a) { builder.addInt(21, (int) testhashu32Fnv1a, (int) 0L); } + public static void addTesthashs64Fnv1a(FlatBufferBuilder builder, long testhashs64Fnv1a) { builder.addLong(22, testhashs64Fnv1a, 0L); } + public static void addTesthashu64Fnv1a(FlatBufferBuilder builder, long testhashu64Fnv1a) { builder.addLong(23, testhashu64Fnv1a, 0L); } + public static void addTestarrayofbools(FlatBufferBuilder builder, int testarrayofboolsOffset) { builder.addOffset(24, testarrayofboolsOffset, 0); } + public static int createTestarrayofboolsVector(FlatBufferBuilder builder, boolean[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addBoolean(data[i]); return builder.endVector(); } + public static void startTestarrayofboolsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addTestf(FlatBufferBuilder builder, float testf) { builder.addFloat(25, testf, 3.14159f); } + public static void addTestf2(FlatBufferBuilder builder, float testf2) { builder.addFloat(26, testf2, 3.0f); } + public static void addTestf3(FlatBufferBuilder builder, float testf3) { builder.addFloat(27, testf3, 0.0f); } + public static void addTestarrayofstring2(FlatBufferBuilder builder, int testarrayofstring2Offset) { builder.addOffset(28, testarrayofstring2Offset, 0); } + public static int createTestarrayofstring2Vector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startTestarrayofstring2Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addTestarrayofsortedstruct(FlatBufferBuilder builder, int testarrayofsortedstructOffset) { builder.addOffset(29, testarrayofsortedstructOffset, 0); } + public static void startTestarrayofsortedstructVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 4); } + public static void addFlex(FlatBufferBuilder builder, int flexOffset) { builder.addOffset(30, flexOffset, 0); } + public static int createFlexVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); } + public static int createFlexVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); } + public static void startFlexVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addTest5(FlatBufferBuilder builder, int test5Offset) { builder.addOffset(31, test5Offset, 0); } + public static void startTest5Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 2); } + public static void addVectorOfLongs(FlatBufferBuilder builder, int vectorOfLongsOffset) { builder.addOffset(32, vectorOfLongsOffset, 0); } + public static int createVectorOfLongsVector(FlatBufferBuilder builder, long[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addLong(data[i]); return builder.endVector(); } + public static void startVectorOfLongsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static void addVectorOfDoubles(FlatBufferBuilder builder, int vectorOfDoublesOffset) { builder.addOffset(33, vectorOfDoublesOffset, 0); } + public static int createVectorOfDoublesVector(FlatBufferBuilder builder, double[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addDouble(data[i]); return builder.endVector(); } + public static void startVectorOfDoublesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static void addParentNamespaceTest(FlatBufferBuilder builder, int parentNamespaceTestOffset) { builder.addOffset(34, parentNamespaceTestOffset, 0); } + public static void addVectorOfReferrables(FlatBufferBuilder builder, int vectorOfReferrablesOffset) { builder.addOffset(35, vectorOfReferrablesOffset, 0); } + public static int createVectorOfReferrablesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startVectorOfReferrablesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addSingleWeakReference(FlatBufferBuilder builder, long singleWeakReference) { builder.addLong(36, singleWeakReference, 0L); } + public static void addVectorOfWeakReferences(FlatBufferBuilder builder, int vectorOfWeakReferencesOffset) { builder.addOffset(37, vectorOfWeakReferencesOffset, 0); } + public static int createVectorOfWeakReferencesVector(FlatBufferBuilder builder, long[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addLong(data[i]); return builder.endVector(); } + public static void startVectorOfWeakReferencesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static void addVectorOfStrongReferrables(FlatBufferBuilder builder, int vectorOfStrongReferrablesOffset) { builder.addOffset(38, vectorOfStrongReferrablesOffset, 0); } + public static int createVectorOfStrongReferrablesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startVectorOfStrongReferrablesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addCoOwningReference(FlatBufferBuilder builder, long coOwningReference) { builder.addLong(39, coOwningReference, 0L); } + public static void addVectorOfCoOwningReferences(FlatBufferBuilder builder, int vectorOfCoOwningReferencesOffset) { builder.addOffset(40, vectorOfCoOwningReferencesOffset, 0); } + public static int createVectorOfCoOwningReferencesVector(FlatBufferBuilder builder, long[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addLong(data[i]); return builder.endVector(); } + public static void startVectorOfCoOwningReferencesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static void addNonOwningReference(FlatBufferBuilder builder, long nonOwningReference) { builder.addLong(41, nonOwningReference, 0L); } + public static void addVectorOfNonOwningReferences(FlatBufferBuilder builder, int vectorOfNonOwningReferencesOffset) { builder.addOffset(42, vectorOfNonOwningReferencesOffset, 0); } + public static int createVectorOfNonOwningReferencesVector(FlatBufferBuilder builder, long[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addLong(data[i]); return builder.endVector(); } + public static void startVectorOfNonOwningReferencesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static void addAnyUniqueType(FlatBufferBuilder builder, byte anyUniqueType) { builder.addByte(43, anyUniqueType, 0); } + public static void addAnyUnique(FlatBufferBuilder builder, int anyUniqueOffset) { builder.addOffset(44, anyUniqueOffset, 0); } + public static void addAnyAmbiguousType(FlatBufferBuilder builder, byte anyAmbiguousType) { builder.addByte(45, anyAmbiguousType, 0); } + public static void addAnyAmbiguous(FlatBufferBuilder builder, int anyAmbiguousOffset) { builder.addOffset(46, anyAmbiguousOffset, 0); } + public static void addVectorOfEnums(FlatBufferBuilder builder, int vectorOfEnumsOffset) { builder.addOffset(47, vectorOfEnumsOffset, 0); } + public static int createVectorOfEnumsVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); } + public static int createVectorOfEnumsVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); } + public static void startVectorOfEnumsVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addSignedEnum(FlatBufferBuilder builder, byte signedEnum) { builder.addByte(48, signedEnum, -1); } + public static void addTestrequirednestedflatbuffer(FlatBufferBuilder builder, int testrequirednestedflatbufferOffset) { builder.addOffset(49, testrequirednestedflatbufferOffset, 0); } + public static int createTestrequirednestedflatbufferVector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); } + public static int createTestrequirednestedflatbufferVector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); } + public static void startTestrequirednestedflatbufferVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addScalarKeySortedTables(FlatBufferBuilder builder, int scalarKeySortedTablesOffset) { builder.addOffset(50, scalarKeySortedTablesOffset, 0); } + public static int createScalarKeySortedTablesVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startScalarKeySortedTablesVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static void addNativeInline(FlatBufferBuilder builder, int nativeInlineOffset) { builder.addStruct(51, nativeInlineOffset, 0); } + public static void addLongEnumNonEnumDefault(FlatBufferBuilder builder, long longEnumNonEnumDefault) { builder.addLong(52, longEnumNonEnumDefault, 0L); } + public static void addLongEnumNormalDefault(FlatBufferBuilder builder, long longEnumNormalDefault) { builder.addLong(53, longEnumNormalDefault, 2L); } + public static void addNanDefault(FlatBufferBuilder builder, float nanDefault) { builder.addFloat(54, nanDefault, Float.NaN); } + public static void addInfDefault(FlatBufferBuilder builder, float infDefault) { builder.addFloat(55, infDefault, Float.POSITIVE_INFINITY); } + public static void addPositiveInfDefault(FlatBufferBuilder builder, float positiveInfDefault) { builder.addFloat(56, positiveInfDefault, Float.POSITIVE_INFINITY); } + public static void addInfinityDefault(FlatBufferBuilder builder, float infinityDefault) { builder.addFloat(57, infinityDefault, Float.POSITIVE_INFINITY); } + public static void addPositiveInfinityDefault(FlatBufferBuilder builder, float positiveInfinityDefault) { builder.addFloat(58, positiveInfinityDefault, Float.POSITIVE_INFINITY); } + public static void addNegativeInfDefault(FlatBufferBuilder builder, float negativeInfDefault) { builder.addFloat(59, negativeInfDefault, Float.NEGATIVE_INFINITY); } + public static void addNegativeInfinityDefault(FlatBufferBuilder builder, float negativeInfinityDefault) { builder.addFloat(60, negativeInfinityDefault, Float.NEGATIVE_INFINITY); } + public static void addDoubleInfDefault(FlatBufferBuilder builder, double doubleInfDefault) { builder.addDouble(61, doubleInfDefault, Double.POSITIVE_INFINITY); } + public static int endMonster(FlatBufferBuilder builder) { + int o = builder.endTable(); + builder.required(o, 10); // name + return o; + } + public static void finishMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "MONS"); } + public static void finishSizePrefixedMonsterBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "MONS"); } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { return compareStrings(__offset(10, o1, _bb), __offset(10, o2, _bb), _bb); } + + public static Monster __lookup_by_key(Monster obj, int vectorLocation, String key, ByteBuffer bb) { + byte[] byteKey = key.getBytes(java.nio.charset.StandardCharsets.UTF_8); + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int comp = compareStrings(__offset(10, bb.capacity() - tableOffset, bb), byteKey, bb); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Monster() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Monster get(int j) { return get(new Monster(), j); } + public Monster get(Monster obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Monster getByKey(String key) { return __lookup_by_key(null, __vector(), key, bb); } + public Monster getByKey(Monster obj, String key) { return __lookup_by_key(obj, __vector(), key, bb); } + } + public MonsterT unpack() { + MonsterT _o = new MonsterT(); + unpackTo(_o); + return _o; + } + public void unpackTo(MonsterT _o) { + if (pos() != null) pos().unpackTo(_o.getPos()); + else _o.setPos(null); + short _oMana = mana(); + _o.setMana(_oMana); + short _oHp = hp(); + _o.setHp(_oHp); + String _oName = name(); + _o.setName(_oName); + int[] _oInventory = new int[inventoryLength()]; + for (int _j = 0; _j < inventoryLength(); ++_j) {_oInventory[_j] = inventory(_j);} + _o.setInventory(_oInventory); + int _oColor = color(); + _o.setColor(_oColor); + MyGame.Example.AnyUnion _oTest = new MyGame.Example.AnyUnion(); + byte _oTestType = testType(); + _oTest.setType(_oTestType); + Table _oTestValue; + switch (_oTestType) { + case MyGame.Example.Any.Monster: + _oTestValue = test(new MyGame.Example.Monster()); + _oTest.setValue(_oTestValue != null ? ((MyGame.Example.Monster) _oTestValue).unpack() : null); + break; + case MyGame.Example.Any.TestSimpleTableWithEnum: + _oTestValue = test(new MyGame.Example.TestSimpleTableWithEnum()); + _oTest.setValue(_oTestValue != null ? ((MyGame.Example.TestSimpleTableWithEnum) _oTestValue).unpack() : null); + break; + case MyGame.Example.Any.MyGame_Example2_Monster: + _oTestValue = test(new MyGame.Example2.Monster()); + _oTest.setValue(_oTestValue != null ? ((MyGame.Example2.Monster) _oTestValue).unpack() : null); + break; + default: break; + } + _o.setTest(_oTest); + MyGame.Example.TestT[] _oTest4 = new MyGame.Example.TestT[test4Length()]; + for (int _j = 0; _j < test4Length(); ++_j) {_oTest4[_j] = (test4(_j) != null ? test4(_j).unpack() : null);} + _o.setTest4(_oTest4); + String[] _oTestarrayofstring = new String[testarrayofstringLength()]; + for (int _j = 0; _j < testarrayofstringLength(); ++_j) {_oTestarrayofstring[_j] = testarrayofstring(_j);} + _o.setTestarrayofstring(_oTestarrayofstring); + MyGame.Example.MonsterT[] _oTestarrayoftables = new MyGame.Example.MonsterT[testarrayoftablesLength()]; + for (int _j = 0; _j < testarrayoftablesLength(); ++_j) {_oTestarrayoftables[_j] = (testarrayoftables(_j) != null ? testarrayoftables(_j).unpack() : null);} + _o.setTestarrayoftables(_oTestarrayoftables); + if (enemy() != null) _o.setEnemy(enemy().unpack()); + else _o.setEnemy(null); + int[] _oTestnestedflatbuffer = new int[testnestedflatbufferLength()]; + for (int _j = 0; _j < testnestedflatbufferLength(); ++_j) {_oTestnestedflatbuffer[_j] = testnestedflatbuffer(_j);} + _o.setTestnestedflatbuffer(_oTestnestedflatbuffer); + if (testempty() != null) _o.setTestempty(testempty().unpack()); + else _o.setTestempty(null); + boolean _oTestbool = testbool(); + _o.setTestbool(_oTestbool); + int _oTesthashs32Fnv1 = testhashs32Fnv1(); + _o.setTesthashs32Fnv1(_oTesthashs32Fnv1); + long _oTesthashu32Fnv1 = testhashu32Fnv1(); + _o.setTesthashu32Fnv1(_oTesthashu32Fnv1); + long _oTesthashs64Fnv1 = testhashs64Fnv1(); + _o.setTesthashs64Fnv1(_oTesthashs64Fnv1); + long _oTesthashu64Fnv1 = testhashu64Fnv1(); + _o.setTesthashu64Fnv1(_oTesthashu64Fnv1); + int _oTesthashs32Fnv1a = testhashs32Fnv1a(); + _o.setTesthashs32Fnv1a(_oTesthashs32Fnv1a); + long _oTesthashu32Fnv1a = testhashu32Fnv1a(); + _o.setTesthashu32Fnv1a(_oTesthashu32Fnv1a); + long _oTesthashs64Fnv1a = testhashs64Fnv1a(); + _o.setTesthashs64Fnv1a(_oTesthashs64Fnv1a); + long _oTesthashu64Fnv1a = testhashu64Fnv1a(); + _o.setTesthashu64Fnv1a(_oTesthashu64Fnv1a); + boolean[] _oTestarrayofbools = new boolean[testarrayofboolsLength()]; + for (int _j = 0; _j < testarrayofboolsLength(); ++_j) {_oTestarrayofbools[_j] = testarrayofbools(_j);} + _o.setTestarrayofbools(_oTestarrayofbools); + float _oTestf = testf(); + _o.setTestf(_oTestf); + float _oTestf2 = testf2(); + _o.setTestf2(_oTestf2); + float _oTestf3 = testf3(); + _o.setTestf3(_oTestf3); + String[] _oTestarrayofstring2 = new String[testarrayofstring2Length()]; + for (int _j = 0; _j < testarrayofstring2Length(); ++_j) {_oTestarrayofstring2[_j] = testarrayofstring2(_j);} + _o.setTestarrayofstring2(_oTestarrayofstring2); + MyGame.Example.AbilityT[] _oTestarrayofsortedstruct = new MyGame.Example.AbilityT[testarrayofsortedstructLength()]; + for (int _j = 0; _j < testarrayofsortedstructLength(); ++_j) {_oTestarrayofsortedstruct[_j] = (testarrayofsortedstruct(_j) != null ? testarrayofsortedstruct(_j).unpack() : null);} + _o.setTestarrayofsortedstruct(_oTestarrayofsortedstruct); + int[] _oFlex = new int[flexLength()]; + for (int _j = 0; _j < flexLength(); ++_j) {_oFlex[_j] = flex(_j);} + _o.setFlex(_oFlex); + MyGame.Example.TestT[] _oTest5 = new MyGame.Example.TestT[test5Length()]; + for (int _j = 0; _j < test5Length(); ++_j) {_oTest5[_j] = (test5(_j) != null ? test5(_j).unpack() : null);} + _o.setTest5(_oTest5); + long[] _oVectorOfLongs = new long[vectorOfLongsLength()]; + for (int _j = 0; _j < vectorOfLongsLength(); ++_j) {_oVectorOfLongs[_j] = vectorOfLongs(_j);} + _o.setVectorOfLongs(_oVectorOfLongs); + double[] _oVectorOfDoubles = new double[vectorOfDoublesLength()]; + for (int _j = 0; _j < vectorOfDoublesLength(); ++_j) {_oVectorOfDoubles[_j] = vectorOfDoubles(_j);} + _o.setVectorOfDoubles(_oVectorOfDoubles); + if (parentNamespaceTest() != null) _o.setParentNamespaceTest(parentNamespaceTest().unpack()); + else _o.setParentNamespaceTest(null); + MyGame.Example.ReferrableT[] _oVectorOfReferrables = new MyGame.Example.ReferrableT[vectorOfReferrablesLength()]; + for (int _j = 0; _j < vectorOfReferrablesLength(); ++_j) {_oVectorOfReferrables[_j] = (vectorOfReferrables(_j) != null ? vectorOfReferrables(_j).unpack() : null);} + _o.setVectorOfReferrables(_oVectorOfReferrables); + long _oSingleWeakReference = singleWeakReference(); + _o.setSingleWeakReference(_oSingleWeakReference); + long[] _oVectorOfWeakReferences = new long[vectorOfWeakReferencesLength()]; + for (int _j = 0; _j < vectorOfWeakReferencesLength(); ++_j) {_oVectorOfWeakReferences[_j] = vectorOfWeakReferences(_j);} + _o.setVectorOfWeakReferences(_oVectorOfWeakReferences); + MyGame.Example.ReferrableT[] _oVectorOfStrongReferrables = new MyGame.Example.ReferrableT[vectorOfStrongReferrablesLength()]; + for (int _j = 0; _j < vectorOfStrongReferrablesLength(); ++_j) {_oVectorOfStrongReferrables[_j] = (vectorOfStrongReferrables(_j) != null ? vectorOfStrongReferrables(_j).unpack() : null);} + _o.setVectorOfStrongReferrables(_oVectorOfStrongReferrables); + long _oCoOwningReference = coOwningReference(); + _o.setCoOwningReference(_oCoOwningReference); + long[] _oVectorOfCoOwningReferences = new long[vectorOfCoOwningReferencesLength()]; + for (int _j = 0; _j < vectorOfCoOwningReferencesLength(); ++_j) {_oVectorOfCoOwningReferences[_j] = vectorOfCoOwningReferences(_j);} + _o.setVectorOfCoOwningReferences(_oVectorOfCoOwningReferences); + long _oNonOwningReference = nonOwningReference(); + _o.setNonOwningReference(_oNonOwningReference); + long[] _oVectorOfNonOwningReferences = new long[vectorOfNonOwningReferencesLength()]; + for (int _j = 0; _j < vectorOfNonOwningReferencesLength(); ++_j) {_oVectorOfNonOwningReferences[_j] = vectorOfNonOwningReferences(_j);} + _o.setVectorOfNonOwningReferences(_oVectorOfNonOwningReferences); + MyGame.Example.AnyUniqueAliasesUnion _oAnyUnique = new MyGame.Example.AnyUniqueAliasesUnion(); + byte _oAnyUniqueType = anyUniqueType(); + _oAnyUnique.setType(_oAnyUniqueType); + Table _oAnyUniqueValue; + switch (_oAnyUniqueType) { + case MyGame.Example.AnyUniqueAliases.M: + _oAnyUniqueValue = anyUnique(new MyGame.Example.Monster()); + _oAnyUnique.setValue(_oAnyUniqueValue != null ? ((MyGame.Example.Monster) _oAnyUniqueValue).unpack() : null); + break; + case MyGame.Example.AnyUniqueAliases.TS: + _oAnyUniqueValue = anyUnique(new MyGame.Example.TestSimpleTableWithEnum()); + _oAnyUnique.setValue(_oAnyUniqueValue != null ? ((MyGame.Example.TestSimpleTableWithEnum) _oAnyUniqueValue).unpack() : null); + break; + case MyGame.Example.AnyUniqueAliases.M2: + _oAnyUniqueValue = anyUnique(new MyGame.Example2.Monster()); + _oAnyUnique.setValue(_oAnyUniqueValue != null ? ((MyGame.Example2.Monster) _oAnyUniqueValue).unpack() : null); + break; + default: break; + } + _o.setAnyUnique(_oAnyUnique); + MyGame.Example.AnyAmbiguousAliasesUnion _oAnyAmbiguous = new MyGame.Example.AnyAmbiguousAliasesUnion(); + byte _oAnyAmbiguousType = anyAmbiguousType(); + _oAnyAmbiguous.setType(_oAnyAmbiguousType); + Table _oAnyAmbiguousValue; + switch (_oAnyAmbiguousType) { + case MyGame.Example.AnyAmbiguousAliases.M1: + _oAnyAmbiguousValue = anyAmbiguous(new MyGame.Example.Monster()); + _oAnyAmbiguous.setValue(_oAnyAmbiguousValue != null ? ((MyGame.Example.Monster) _oAnyAmbiguousValue).unpack() : null); + break; + case MyGame.Example.AnyAmbiguousAliases.M2: + _oAnyAmbiguousValue = anyAmbiguous(new MyGame.Example.Monster()); + _oAnyAmbiguous.setValue(_oAnyAmbiguousValue != null ? ((MyGame.Example.Monster) _oAnyAmbiguousValue).unpack() : null); + break; + case MyGame.Example.AnyAmbiguousAliases.M3: + _oAnyAmbiguousValue = anyAmbiguous(new MyGame.Example.Monster()); + _oAnyAmbiguous.setValue(_oAnyAmbiguousValue != null ? ((MyGame.Example.Monster) _oAnyAmbiguousValue).unpack() : null); + break; + default: break; + } + _o.setAnyAmbiguous(_oAnyAmbiguous); + int[] _oVectorOfEnums = new int[vectorOfEnumsLength()]; + for (int _j = 0; _j < vectorOfEnumsLength(); ++_j) {_oVectorOfEnums[_j] = vectorOfEnums(_j);} + _o.setVectorOfEnums(_oVectorOfEnums); + byte _oSignedEnum = signedEnum(); + _o.setSignedEnum(_oSignedEnum); + int[] _oTestrequirednestedflatbuffer = new int[testrequirednestedflatbufferLength()]; + for (int _j = 0; _j < testrequirednestedflatbufferLength(); ++_j) {_oTestrequirednestedflatbuffer[_j] = testrequirednestedflatbuffer(_j);} + _o.setTestrequirednestedflatbuffer(_oTestrequirednestedflatbuffer); + MyGame.Example.StatT[] _oScalarKeySortedTables = new MyGame.Example.StatT[scalarKeySortedTablesLength()]; + for (int _j = 0; _j < scalarKeySortedTablesLength(); ++_j) {_oScalarKeySortedTables[_j] = (scalarKeySortedTables(_j) != null ? scalarKeySortedTables(_j).unpack() : null);} + _o.setScalarKeySortedTables(_oScalarKeySortedTables); + if (nativeInline() != null) nativeInline().unpackTo(_o.getNativeInline()); + else _o.setNativeInline(null); + long _oLongEnumNonEnumDefault = longEnumNonEnumDefault(); + _o.setLongEnumNonEnumDefault(_oLongEnumNonEnumDefault); + long _oLongEnumNormalDefault = longEnumNormalDefault(); + _o.setLongEnumNormalDefault(_oLongEnumNormalDefault); + float _oNanDefault = nanDefault(); + _o.setNanDefault(_oNanDefault); + float _oInfDefault = infDefault(); + _o.setInfDefault(_oInfDefault); + float _oPositiveInfDefault = positiveInfDefault(); + _o.setPositiveInfDefault(_oPositiveInfDefault); + float _oInfinityDefault = infinityDefault(); + _o.setInfinityDefault(_oInfinityDefault); + float _oPositiveInfinityDefault = positiveInfinityDefault(); + _o.setPositiveInfinityDefault(_oPositiveInfinityDefault); + float _oNegativeInfDefault = negativeInfDefault(); + _o.setNegativeInfDefault(_oNegativeInfDefault); + float _oNegativeInfinityDefault = negativeInfinityDefault(); + _o.setNegativeInfinityDefault(_oNegativeInfinityDefault); + double _oDoubleInfDefault = doubleInfDefault(); + _o.setDoubleInfDefault(_oDoubleInfDefault); + } + public static int pack(FlatBufferBuilder builder, MonsterT _o) { + if (_o == null) return 0; + int _name = _o.getName() == null ? 0 : builder.createString(_o.getName()); + int _inventory = 0; + if (_o.getInventory() != null) { + byte[] __inventory = new byte[_o.getInventory().length]; + int _j = 0; + for (int _e : _o.getInventory()) { __inventory[_j] = (byte) _e; _j++;} + _inventory = createInventoryVector(builder, __inventory); + } + byte _testType = _o.getTest() == null ? MyGame.Example.Any.NONE : _o.getTest().getType(); + int _test = _o.getTest() == null ? 0 : MyGame.Example.AnyUnion.pack(builder, _o.getTest()); + int _test4 = 0; + MyGame.Example.TestT[] _oTest4 = _o.getTest4(); + if (_oTest4 != null) { + int _unused_offset = 0; + startTest4Vector(builder, _oTest4.length); + for (int _j = _oTest4.length - 1; _j >=0; _j--) { _unused_offset = MyGame.Example.Test.pack(builder, _oTest4[_j]);} + _test4 = builder.endVector(); + } + int _testarrayofstring = 0; + if (_o.getTestarrayofstring() != null) { + int[] __testarrayofstring = new int[_o.getTestarrayofstring().length]; + int _j = 0; + for (String _e : _o.getTestarrayofstring()) { __testarrayofstring[_j] = builder.createString(_e); _j++;} + _testarrayofstring = createTestarrayofstringVector(builder, __testarrayofstring); + } + int _testarrayoftables = 0; + if (_o.getTestarrayoftables() != null) { + int[] __testarrayoftables = new int[_o.getTestarrayoftables().length]; + int _j = 0; + for (MyGame.Example.MonsterT _e : _o.getTestarrayoftables()) { __testarrayoftables[_j] = MyGame.Example.Monster.pack(builder, _e); _j++;} + _testarrayoftables = createTestarrayoftablesVector(builder, __testarrayoftables); + } + int _enemy = _o.getEnemy() == null ? 0 : MyGame.Example.Monster.pack(builder, _o.getEnemy()); + int _testnestedflatbuffer = 0; + if (_o.getTestnestedflatbuffer() != null) { + byte[] __testnestedflatbuffer = new byte[_o.getTestnestedflatbuffer().length]; + int _j = 0; + for (int _e : _o.getTestnestedflatbuffer()) { __testnestedflatbuffer[_j] = (byte) _e; _j++;} + _testnestedflatbuffer = createTestnestedflatbufferVector(builder, __testnestedflatbuffer); + } + int _testempty = _o.getTestempty() == null ? 0 : MyGame.Example.Stat.pack(builder, _o.getTestempty()); + int _testarrayofbools = 0; + if (_o.getTestarrayofbools() != null) { + _testarrayofbools = createTestarrayofboolsVector(builder, _o.getTestarrayofbools()); + } + int _testarrayofstring2 = 0; + if (_o.getTestarrayofstring2() != null) { + int[] __testarrayofstring2 = new int[_o.getTestarrayofstring2().length]; + int _j = 0; + for (String _e : _o.getTestarrayofstring2()) { __testarrayofstring2[_j] = builder.createString(_e); _j++;} + _testarrayofstring2 = createTestarrayofstring2Vector(builder, __testarrayofstring2); + } + int _testarrayofsortedstruct = 0; + MyGame.Example.AbilityT[] _oTestarrayofsortedstruct = _o.getTestarrayofsortedstruct(); + if (_oTestarrayofsortedstruct != null) { + int _unused_offset = 0; + startTestarrayofsortedstructVector(builder, _oTestarrayofsortedstruct.length); + for (int _j = _oTestarrayofsortedstruct.length - 1; _j >=0; _j--) { _unused_offset = MyGame.Example.Ability.pack(builder, _oTestarrayofsortedstruct[_j]);} + _testarrayofsortedstruct = builder.endVector(); + } + int _flex = 0; + if (_o.getFlex() != null) { + byte[] __flex = new byte[_o.getFlex().length]; + int _j = 0; + for (int _e : _o.getFlex()) { __flex[_j] = (byte) _e; _j++;} + _flex = createFlexVector(builder, __flex); + } + int _test5 = 0; + MyGame.Example.TestT[] _oTest5 = _o.getTest5(); + if (_oTest5 != null) { + int _unused_offset = 0; + startTest5Vector(builder, _oTest5.length); + for (int _j = _oTest5.length - 1; _j >=0; _j--) { _unused_offset = MyGame.Example.Test.pack(builder, _oTest5[_j]);} + _test5 = builder.endVector(); + } + int _vectorOfLongs = 0; + if (_o.getVectorOfLongs() != null) { + _vectorOfLongs = createVectorOfLongsVector(builder, _o.getVectorOfLongs()); + } + int _vectorOfDoubles = 0; + if (_o.getVectorOfDoubles() != null) { + _vectorOfDoubles = createVectorOfDoublesVector(builder, _o.getVectorOfDoubles()); + } + int _parentNamespaceTest = _o.getParentNamespaceTest() == null ? 0 : MyGame.InParentNamespace.pack(builder, _o.getParentNamespaceTest()); + int _vectorOfReferrables = 0; + if (_o.getVectorOfReferrables() != null) { + int[] __vectorOfReferrables = new int[_o.getVectorOfReferrables().length]; + int _j = 0; + for (MyGame.Example.ReferrableT _e : _o.getVectorOfReferrables()) { __vectorOfReferrables[_j] = MyGame.Example.Referrable.pack(builder, _e); _j++;} + _vectorOfReferrables = createVectorOfReferrablesVector(builder, __vectorOfReferrables); + } + int _vectorOfWeakReferences = 0; + if (_o.getVectorOfWeakReferences() != null) { + _vectorOfWeakReferences = createVectorOfWeakReferencesVector(builder, _o.getVectorOfWeakReferences()); + } + int _vectorOfStrongReferrables = 0; + if (_o.getVectorOfStrongReferrables() != null) { + int[] __vectorOfStrongReferrables = new int[_o.getVectorOfStrongReferrables().length]; + int _j = 0; + for (MyGame.Example.ReferrableT _e : _o.getVectorOfStrongReferrables()) { __vectorOfStrongReferrables[_j] = MyGame.Example.Referrable.pack(builder, _e); _j++;} + _vectorOfStrongReferrables = createVectorOfStrongReferrablesVector(builder, __vectorOfStrongReferrables); + } + int _vectorOfCoOwningReferences = 0; + if (_o.getVectorOfCoOwningReferences() != null) { + _vectorOfCoOwningReferences = createVectorOfCoOwningReferencesVector(builder, _o.getVectorOfCoOwningReferences()); + } + int _vectorOfNonOwningReferences = 0; + if (_o.getVectorOfNonOwningReferences() != null) { + _vectorOfNonOwningReferences = createVectorOfNonOwningReferencesVector(builder, _o.getVectorOfNonOwningReferences()); + } + byte _anyUniqueType = _o.getAnyUnique() == null ? MyGame.Example.AnyUniqueAliases.NONE : _o.getAnyUnique().getType(); + int _anyUnique = _o.getAnyUnique() == null ? 0 : MyGame.Example.AnyUniqueAliasesUnion.pack(builder, _o.getAnyUnique()); + byte _anyAmbiguousType = _o.getAnyAmbiguous() == null ? MyGame.Example.AnyAmbiguousAliases.NONE : _o.getAnyAmbiguous().getType(); + int _anyAmbiguous = _o.getAnyAmbiguous() == null ? 0 : MyGame.Example.AnyAmbiguousAliasesUnion.pack(builder, _o.getAnyAmbiguous()); + int _vectorOfEnums = 0; + if (_o.getVectorOfEnums() != null) { + byte[] __vectorOfEnums = new byte[_o.getVectorOfEnums().length]; + int _j = 0; + for (int _e : _o.getVectorOfEnums()) { __vectorOfEnums[_j] = (byte) _e; _j++;} + _vectorOfEnums = createVectorOfEnumsVector(builder, __vectorOfEnums); + } + int _testrequirednestedflatbuffer = 0; + if (_o.getTestrequirednestedflatbuffer() != null) { + byte[] __testrequirednestedflatbuffer = new byte[_o.getTestrequirednestedflatbuffer().length]; + int _j = 0; + for (int _e : _o.getTestrequirednestedflatbuffer()) { __testrequirednestedflatbuffer[_j] = (byte) _e; _j++;} + _testrequirednestedflatbuffer = createTestrequirednestedflatbufferVector(builder, __testrequirednestedflatbuffer); + } + int _scalarKeySortedTables = 0; + if (_o.getScalarKeySortedTables() != null) { + int[] __scalarKeySortedTables = new int[_o.getScalarKeySortedTables().length]; + int _j = 0; + for (MyGame.Example.StatT _e : _o.getScalarKeySortedTables()) { __scalarKeySortedTables[_j] = MyGame.Example.Stat.pack(builder, _e); _j++;} + _scalarKeySortedTables = createScalarKeySortedTablesVector(builder, __scalarKeySortedTables); + } + startMonster(builder); + addPos(builder, MyGame.Example.Vec3.pack(builder, _o.getPos())); + addMana(builder, _o.getMana()); + addHp(builder, _o.getHp()); + addName(builder, _name); + addInventory(builder, _inventory); + addColor(builder, _o.getColor()); + addTestType(builder, _testType); + addTest(builder, _test); + addTest4(builder, _test4); + addTestarrayofstring(builder, _testarrayofstring); + addTestarrayoftables(builder, _testarrayoftables); + addEnemy(builder, _enemy); + addTestnestedflatbuffer(builder, _testnestedflatbuffer); + addTestempty(builder, _testempty); + addTestbool(builder, _o.getTestbool()); + addTesthashs32Fnv1(builder, _o.getTesthashs32Fnv1()); + addTesthashu32Fnv1(builder, _o.getTesthashu32Fnv1()); + addTesthashs64Fnv1(builder, _o.getTesthashs64Fnv1()); + addTesthashu64Fnv1(builder, _o.getTesthashu64Fnv1()); + addTesthashs32Fnv1a(builder, _o.getTesthashs32Fnv1a()); + addTesthashu32Fnv1a(builder, _o.getTesthashu32Fnv1a()); + addTesthashs64Fnv1a(builder, _o.getTesthashs64Fnv1a()); + addTesthashu64Fnv1a(builder, _o.getTesthashu64Fnv1a()); + addTestarrayofbools(builder, _testarrayofbools); + addTestf(builder, _o.getTestf()); + addTestf2(builder, _o.getTestf2()); + addTestf3(builder, _o.getTestf3()); + addTestarrayofstring2(builder, _testarrayofstring2); + addTestarrayofsortedstruct(builder, _testarrayofsortedstruct); + addFlex(builder, _flex); + addTest5(builder, _test5); + addVectorOfLongs(builder, _vectorOfLongs); + addVectorOfDoubles(builder, _vectorOfDoubles); + addParentNamespaceTest(builder, _parentNamespaceTest); + addVectorOfReferrables(builder, _vectorOfReferrables); + addSingleWeakReference(builder, _o.getSingleWeakReference()); + addVectorOfWeakReferences(builder, _vectorOfWeakReferences); + addVectorOfStrongReferrables(builder, _vectorOfStrongReferrables); + addCoOwningReference(builder, _o.getCoOwningReference()); + addVectorOfCoOwningReferences(builder, _vectorOfCoOwningReferences); + addNonOwningReference(builder, _o.getNonOwningReference()); + addVectorOfNonOwningReferences(builder, _vectorOfNonOwningReferences); + addAnyUniqueType(builder, _anyUniqueType); + addAnyUnique(builder, _anyUnique); + addAnyAmbiguousType(builder, _anyAmbiguousType); + addAnyAmbiguous(builder, _anyAmbiguous); + addVectorOfEnums(builder, _vectorOfEnums); + addSignedEnum(builder, _o.getSignedEnum()); + addTestrequirednestedflatbuffer(builder, _testrequirednestedflatbuffer); + addScalarKeySortedTables(builder, _scalarKeySortedTables); + addNativeInline(builder, MyGame.Example.Test.pack(builder, _o.getNativeInline())); + addLongEnumNonEnumDefault(builder, _o.getLongEnumNonEnumDefault()); + addLongEnumNormalDefault(builder, _o.getLongEnumNormalDefault()); + addNanDefault(builder, _o.getNanDefault()); + addInfDefault(builder, _o.getInfDefault()); + addPositiveInfDefault(builder, _o.getPositiveInfDefault()); + addInfinityDefault(builder, _o.getInfinityDefault()); + addPositiveInfinityDefault(builder, _o.getPositiveInfinityDefault()); + addNegativeInfDefault(builder, _o.getNegativeInfDefault()); + addNegativeInfinityDefault(builder, _o.getNegativeInfinityDefault()); + addDoubleInfDefault(builder, _o.getDoubleInfDefault()); + return endMonster(builder); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.kt b/third_party/flatbuffers/tests/MyGame/Example/Monster.kt new file mode 100644 index 00000000000..fbbcd8a70dd --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.kt @@ -0,0 +1,1254 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +/** + * an example documentation comment: "monster object" + */ +@Suppress("unused") +class Monster : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Monster { + __init(_i, _bb) + return this + } + val pos : MyGame.Example.Vec3? get() = pos(MyGame.Example.Vec3()) + fun pos(obj: MyGame.Example.Vec3) : MyGame.Example.Vec3? { + val o = __offset(4) + return if (o != 0) { + obj.__assign(o + bb_pos, bb) + } else { + null + } + } + val mana : Short + get() { + val o = __offset(6) + return if(o != 0) bb.getShort(o + bb_pos) else 150 + } + fun mutateMana(mana: Short) : Boolean { + val o = __offset(6) + return if (o != 0) { + bb.putShort(o + bb_pos, mana) + true + } else { + false + } + } + val hp : Short + get() { + val o = __offset(8) + return if(o != 0) bb.getShort(o + bb_pos) else 100 + } + fun mutateHp(hp: Short) : Boolean { + val o = __offset(8) + return if (o != 0) { + bb.putShort(o + bb_pos, hp) + true + } else { + false + } + } + val name : String + get() { + val o = __offset(10) + return if (o != 0) { + __string(o + bb_pos) + } else { + throw AssertionError("No value for (required) field name") + } + } + val nameAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(10, 1) + fun nameInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 10, 1) + fun inventory(j: Int) : UByte { + val o = __offset(14) + return if (o != 0) { + bb.get(__vector(o) + j * 1).toUByte() + } else { + 0u + } + } + val inventoryLength : Int + get() { + val o = __offset(14); return if (o != 0) __vector_len(o) else 0 + } + val inventoryAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(14, 1) + fun inventoryInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 14, 1) + fun mutateInventory(j: Int, inventory: UByte) : Boolean { + val o = __offset(14) + return if (o != 0) { + bb.put(__vector(o) + j * 1, inventory.toByte()) + true + } else { + false + } + } + val color : UByte + get() { + val o = __offset(16) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 8u + } + fun mutateColor(color: UByte) : Boolean { + val o = __offset(16) + return if (o != 0) { + bb.put(o + bb_pos, color.toByte()) + true + } else { + false + } + } + val testType : UByte + get() { + val o = __offset(18) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + fun mutateTestType(testType: UByte) : Boolean { + val o = __offset(18) + return if (o != 0) { + bb.put(o + bb_pos, testType.toByte()) + true + } else { + false + } + } + fun test(obj: Table) : Table? { + val o = __offset(20); return if (o != 0) __union(obj, o + bb_pos) else null + } + fun test4(j: Int) : MyGame.Example.Test? = test4(MyGame.Example.Test(), j) + fun test4(obj: MyGame.Example.Test, j: Int) : MyGame.Example.Test? { + val o = __offset(22) + return if (o != 0) { + obj.__assign(__vector(o) + j * 4, bb) + } else { + null + } + } + val test4Length : Int + get() { + val o = __offset(22); return if (o != 0) __vector_len(o) else 0 + } + fun testarrayofstring(j: Int) : String? { + val o = __offset(24) + return if (o != 0) { + __string(__vector(o) + j * 4) + } else { + null + } + } + val testarrayofstringLength : Int + get() { + val o = __offset(24); return if (o != 0) __vector_len(o) else 0 + } + /** + * an example documentation comment: this will end up in the generated code + * multiline too + */ + fun testarrayoftables(j: Int) : MyGame.Example.Monster? = testarrayoftables(MyGame.Example.Monster(), j) + fun testarrayoftables(obj: MyGame.Example.Monster, j: Int) : MyGame.Example.Monster? { + val o = __offset(26) + return if (o != 0) { + obj.__assign(__indirect(__vector(o) + j * 4), bb) + } else { + null + } + } + val testarrayoftablesLength : Int + get() { + val o = __offset(26); return if (o != 0) __vector_len(o) else 0 + } + fun testarrayoftablesByKey(key: String) : MyGame.Example.Monster? { + val o = __offset(26) + return if (o != 0) { + MyGame.Example.Monster.__lookup_by_key(null, __vector(o), key, bb) + } else { + null + } + } + fun testarrayoftablesByKey(obj: MyGame.Example.Monster, key: String) : MyGame.Example.Monster? { + val o = __offset(26) + return if (o != 0) { + MyGame.Example.Monster.__lookup_by_key(obj, __vector(o), key, bb) + } else { + null + } + } + val enemy : MyGame.Example.Monster? get() = enemy(MyGame.Example.Monster()) + fun enemy(obj: MyGame.Example.Monster) : MyGame.Example.Monster? { + val o = __offset(28) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + fun testnestedflatbuffer(j: Int) : UByte { + val o = __offset(30) + return if (o != 0) { + bb.get(__vector(o) + j * 1).toUByte() + } else { + 0u + } + } + val testnestedflatbufferLength : Int + get() { + val o = __offset(30); return if (o != 0) __vector_len(o) else 0 + } + val testnestedflatbufferAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(30, 1) + fun testnestedflatbufferInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 30, 1) + val testnestedflatbufferAsMonster : MyGame.Example.Monster? get() = testnestedflatbufferAsMonster(MyGame.Example.Monster()) + fun testnestedflatbufferAsMonster(obj: MyGame.Example.Monster) : MyGame.Example.Monster? { + val o = __offset(30) + return if (o != 0) { + obj.__assign(__indirect(__vector(o)), bb) + } else { + null + } + } + fun mutateTestnestedflatbuffer(j: Int, testnestedflatbuffer: UByte) : Boolean { + val o = __offset(30) + return if (o != 0) { + bb.put(__vector(o) + j * 1, testnestedflatbuffer.toByte()) + true + } else { + false + } + } + val testempty : MyGame.Example.Stat? get() = testempty(MyGame.Example.Stat()) + fun testempty(obj: MyGame.Example.Stat) : MyGame.Example.Stat? { + val o = __offset(32) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + val testbool : Boolean + get() { + val o = __offset(34) + return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else false + } + fun mutateTestbool(testbool: Boolean) : Boolean { + val o = __offset(34) + return if (o != 0) { + bb.put(o + bb_pos, (if(testbool) 1 else 0).toByte()) + true + } else { + false + } + } + val testhashs32Fnv1 : Int + get() { + val o = __offset(36) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + fun mutateTesthashs32Fnv1(testhashs32Fnv1: Int) : Boolean { + val o = __offset(36) + return if (o != 0) { + bb.putInt(o + bb_pos, testhashs32Fnv1) + true + } else { + false + } + } + val testhashu32Fnv1 : UInt + get() { + val o = __offset(38) + return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 0u + } + fun mutateTesthashu32Fnv1(testhashu32Fnv1: UInt) : Boolean { + val o = __offset(38) + return if (o != 0) { + bb.putInt(o + bb_pos, testhashu32Fnv1.toInt()) + true + } else { + false + } + } + val testhashs64Fnv1 : Long + get() { + val o = __offset(40) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + fun mutateTesthashs64Fnv1(testhashs64Fnv1: Long) : Boolean { + val o = __offset(40) + return if (o != 0) { + bb.putLong(o + bb_pos, testhashs64Fnv1) + true + } else { + false + } + } + val testhashu64Fnv1 : ULong + get() { + val o = __offset(42) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateTesthashu64Fnv1(testhashu64Fnv1: ULong) : Boolean { + val o = __offset(42) + return if (o != 0) { + bb.putLong(o + bb_pos, testhashu64Fnv1.toLong()) + true + } else { + false + } + } + val testhashs32Fnv1a : Int + get() { + val o = __offset(44) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + fun mutateTesthashs32Fnv1a(testhashs32Fnv1a: Int) : Boolean { + val o = __offset(44) + return if (o != 0) { + bb.putInt(o + bb_pos, testhashs32Fnv1a) + true + } else { + false + } + } + val testhashu32Fnv1a : UInt + get() { + val o = __offset(46) + return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 0u + } + fun mutateTesthashu32Fnv1a(testhashu32Fnv1a: UInt) : Boolean { + val o = __offset(46) + return if (o != 0) { + bb.putInt(o + bb_pos, testhashu32Fnv1a.toInt()) + true + } else { + false + } + } + val testhashs64Fnv1a : Long + get() { + val o = __offset(48) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + fun mutateTesthashs64Fnv1a(testhashs64Fnv1a: Long) : Boolean { + val o = __offset(48) + return if (o != 0) { + bb.putLong(o + bb_pos, testhashs64Fnv1a) + true + } else { + false + } + } + val testhashu64Fnv1a : ULong + get() { + val o = __offset(50) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateTesthashu64Fnv1a(testhashu64Fnv1a: ULong) : Boolean { + val o = __offset(50) + return if (o != 0) { + bb.putLong(o + bb_pos, testhashu64Fnv1a.toLong()) + true + } else { + false + } + } + fun testarrayofbools(j: Int) : Boolean { + val o = __offset(52) + return if (o != 0) { + 0.toByte() != bb.get(__vector(o) + j * 1) + } else { + false + } + } + val testarrayofboolsLength : Int + get() { + val o = __offset(52); return if (o != 0) __vector_len(o) else 0 + } + val testarrayofboolsAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(52, 1) + fun testarrayofboolsInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 52, 1) + fun mutateTestarrayofbools(j: Int, testarrayofbools: Boolean) : Boolean { + val o = __offset(52) + return if (o != 0) { + bb.put(__vector(o) + j * 1, (if(testarrayofbools) 1 else 0).toByte()) + true + } else { + false + } + } + val testf : Float + get() { + val o = __offset(54) + return if(o != 0) bb.getFloat(o + bb_pos) else 3.14159f + } + fun mutateTestf(testf: Float) : Boolean { + val o = __offset(54) + return if (o != 0) { + bb.putFloat(o + bb_pos, testf) + true + } else { + false + } + } + val testf2 : Float + get() { + val o = __offset(56) + return if(o != 0) bb.getFloat(o + bb_pos) else 3.0f + } + fun mutateTestf2(testf2: Float) : Boolean { + val o = __offset(56) + return if (o != 0) { + bb.putFloat(o + bb_pos, testf2) + true + } else { + false + } + } + val testf3 : Float + get() { + val o = __offset(58) + return if(o != 0) bb.getFloat(o + bb_pos) else 0.0f + } + fun mutateTestf3(testf3: Float) : Boolean { + val o = __offset(58) + return if (o != 0) { + bb.putFloat(o + bb_pos, testf3) + true + } else { + false + } + } + fun testarrayofstring2(j: Int) : String? { + val o = __offset(60) + return if (o != 0) { + __string(__vector(o) + j * 4) + } else { + null + } + } + val testarrayofstring2Length : Int + get() { + val o = __offset(60); return if (o != 0) __vector_len(o) else 0 + } + fun testarrayofsortedstruct(j: Int) : MyGame.Example.Ability? = testarrayofsortedstruct(MyGame.Example.Ability(), j) + fun testarrayofsortedstruct(obj: MyGame.Example.Ability, j: Int) : MyGame.Example.Ability? { + val o = __offset(62) + return if (o != 0) { + obj.__assign(__vector(o) + j * 8, bb) + } else { + null + } + } + val testarrayofsortedstructLength : Int + get() { + val o = __offset(62); return if (o != 0) __vector_len(o) else 0 + } + fun flex(j: Int) : UByte { + val o = __offset(64) + return if (o != 0) { + bb.get(__vector(o) + j * 1).toUByte() + } else { + 0u + } + } + val flexLength : Int + get() { + val o = __offset(64); return if (o != 0) __vector_len(o) else 0 + } + val flexAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(64, 1) + fun flexInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 64, 1) + fun mutateFlex(j: Int, flex: UByte) : Boolean { + val o = __offset(64) + return if (o != 0) { + bb.put(__vector(o) + j * 1, flex.toByte()) + true + } else { + false + } + } + fun test5(j: Int) : MyGame.Example.Test? = test5(MyGame.Example.Test(), j) + fun test5(obj: MyGame.Example.Test, j: Int) : MyGame.Example.Test? { + val o = __offset(66) + return if (o != 0) { + obj.__assign(__vector(o) + j * 4, bb) + } else { + null + } + } + val test5Length : Int + get() { + val o = __offset(66); return if (o != 0) __vector_len(o) else 0 + } + fun vectorOfLongs(j: Int) : Long { + val o = __offset(68) + return if (o != 0) { + bb.getLong(__vector(o) + j * 8) + } else { + 0 + } + } + val vectorOfLongsLength : Int + get() { + val o = __offset(68); return if (o != 0) __vector_len(o) else 0 + } + val vectorOfLongsAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(68, 8) + fun vectorOfLongsInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 68, 8) + fun mutateVectorOfLongs(j: Int, vectorOfLongs: Long) : Boolean { + val o = __offset(68) + return if (o != 0) { + bb.putLong(__vector(o) + j * 8, vectorOfLongs) + true + } else { + false + } + } + fun vectorOfDoubles(j: Int) : Double { + val o = __offset(70) + return if (o != 0) { + bb.getDouble(__vector(o) + j * 8) + } else { + 0.0 + } + } + val vectorOfDoublesLength : Int + get() { + val o = __offset(70); return if (o != 0) __vector_len(o) else 0 + } + val vectorOfDoublesAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(70, 8) + fun vectorOfDoublesInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 70, 8) + fun mutateVectorOfDoubles(j: Int, vectorOfDoubles: Double) : Boolean { + val o = __offset(70) + return if (o != 0) { + bb.putDouble(__vector(o) + j * 8, vectorOfDoubles) + true + } else { + false + } + } + val parentNamespaceTest : MyGame.InParentNamespace? get() = parentNamespaceTest(MyGame.InParentNamespace()) + fun parentNamespaceTest(obj: MyGame.InParentNamespace) : MyGame.InParentNamespace? { + val o = __offset(72) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + fun vectorOfReferrables(j: Int) : MyGame.Example.Referrable? = vectorOfReferrables(MyGame.Example.Referrable(), j) + fun vectorOfReferrables(obj: MyGame.Example.Referrable, j: Int) : MyGame.Example.Referrable? { + val o = __offset(74) + return if (o != 0) { + obj.__assign(__indirect(__vector(o) + j * 4), bb) + } else { + null + } + } + val vectorOfReferrablesLength : Int + get() { + val o = __offset(74); return if (o != 0) __vector_len(o) else 0 + } + fun vectorOfReferrablesByKey(key: ULong) : MyGame.Example.Referrable? { + val o = __offset(74) + return if (o != 0) { + MyGame.Example.Referrable.__lookup_by_key(null, __vector(o), key, bb) + } else { + null + } + } + fun vectorOfReferrablesByKey(obj: MyGame.Example.Referrable, key: ULong) : MyGame.Example.Referrable? { + val o = __offset(74) + return if (o != 0) { + MyGame.Example.Referrable.__lookup_by_key(obj, __vector(o), key, bb) + } else { + null + } + } + val singleWeakReference : ULong + get() { + val o = __offset(76) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateSingleWeakReference(singleWeakReference: ULong) : Boolean { + val o = __offset(76) + return if (o != 0) { + bb.putLong(o + bb_pos, singleWeakReference.toLong()) + true + } else { + false + } + } + fun vectorOfWeakReferences(j: Int) : ULong { + val o = __offset(78) + return if (o != 0) { + bb.getLong(__vector(o) + j * 8).toULong() + } else { + 0uL + } + } + val vectorOfWeakReferencesLength : Int + get() { + val o = __offset(78); return if (o != 0) __vector_len(o) else 0 + } + val vectorOfWeakReferencesAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(78, 8) + fun vectorOfWeakReferencesInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 78, 8) + fun mutateVectorOfWeakReferences(j: Int, vectorOfWeakReferences: ULong) : Boolean { + val o = __offset(78) + return if (o != 0) { + bb.putLong(__vector(o) + j * 8, vectorOfWeakReferences.toLong()) + true + } else { + false + } + } + fun vectorOfStrongReferrables(j: Int) : MyGame.Example.Referrable? = vectorOfStrongReferrables(MyGame.Example.Referrable(), j) + fun vectorOfStrongReferrables(obj: MyGame.Example.Referrable, j: Int) : MyGame.Example.Referrable? { + val o = __offset(80) + return if (o != 0) { + obj.__assign(__indirect(__vector(o) + j * 4), bb) + } else { + null + } + } + val vectorOfStrongReferrablesLength : Int + get() { + val o = __offset(80); return if (o != 0) __vector_len(o) else 0 + } + fun vectorOfStrongReferrablesByKey(key: ULong) : MyGame.Example.Referrable? { + val o = __offset(80) + return if (o != 0) { + MyGame.Example.Referrable.__lookup_by_key(null, __vector(o), key, bb) + } else { + null + } + } + fun vectorOfStrongReferrablesByKey(obj: MyGame.Example.Referrable, key: ULong) : MyGame.Example.Referrable? { + val o = __offset(80) + return if (o != 0) { + MyGame.Example.Referrable.__lookup_by_key(obj, __vector(o), key, bb) + } else { + null + } + } + val coOwningReference : ULong + get() { + val o = __offset(82) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateCoOwningReference(coOwningReference: ULong) : Boolean { + val o = __offset(82) + return if (o != 0) { + bb.putLong(o + bb_pos, coOwningReference.toLong()) + true + } else { + false + } + } + fun vectorOfCoOwningReferences(j: Int) : ULong { + val o = __offset(84) + return if (o != 0) { + bb.getLong(__vector(o) + j * 8).toULong() + } else { + 0uL + } + } + val vectorOfCoOwningReferencesLength : Int + get() { + val o = __offset(84); return if (o != 0) __vector_len(o) else 0 + } + val vectorOfCoOwningReferencesAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(84, 8) + fun vectorOfCoOwningReferencesInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 84, 8) + fun mutateVectorOfCoOwningReferences(j: Int, vectorOfCoOwningReferences: ULong) : Boolean { + val o = __offset(84) + return if (o != 0) { + bb.putLong(__vector(o) + j * 8, vectorOfCoOwningReferences.toLong()) + true + } else { + false + } + } + val nonOwningReference : ULong + get() { + val o = __offset(86) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateNonOwningReference(nonOwningReference: ULong) : Boolean { + val o = __offset(86) + return if (o != 0) { + bb.putLong(o + bb_pos, nonOwningReference.toLong()) + true + } else { + false + } + } + fun vectorOfNonOwningReferences(j: Int) : ULong { + val o = __offset(88) + return if (o != 0) { + bb.getLong(__vector(o) + j * 8).toULong() + } else { + 0uL + } + } + val vectorOfNonOwningReferencesLength : Int + get() { + val o = __offset(88); return if (o != 0) __vector_len(o) else 0 + } + val vectorOfNonOwningReferencesAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(88, 8) + fun vectorOfNonOwningReferencesInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 88, 8) + fun mutateVectorOfNonOwningReferences(j: Int, vectorOfNonOwningReferences: ULong) : Boolean { + val o = __offset(88) + return if (o != 0) { + bb.putLong(__vector(o) + j * 8, vectorOfNonOwningReferences.toLong()) + true + } else { + false + } + } + val anyUniqueType : UByte + get() { + val o = __offset(90) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + fun mutateAnyUniqueType(anyUniqueType: UByte) : Boolean { + val o = __offset(90) + return if (o != 0) { + bb.put(o + bb_pos, anyUniqueType.toByte()) + true + } else { + false + } + } + fun anyUnique(obj: Table) : Table? { + val o = __offset(92); return if (o != 0) __union(obj, o + bb_pos) else null + } + val anyAmbiguousType : UByte + get() { + val o = __offset(94) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + fun mutateAnyAmbiguousType(anyAmbiguousType: UByte) : Boolean { + val o = __offset(94) + return if (o != 0) { + bb.put(o + bb_pos, anyAmbiguousType.toByte()) + true + } else { + false + } + } + fun anyAmbiguous(obj: Table) : Table? { + val o = __offset(96); return if (o != 0) __union(obj, o + bb_pos) else null + } + fun vectorOfEnums(j: Int) : UByte { + val o = __offset(98) + return if (o != 0) { + bb.get(__vector(o) + j * 1).toUByte() + } else { + 0u + } + } + val vectorOfEnumsLength : Int + get() { + val o = __offset(98); return if (o != 0) __vector_len(o) else 0 + } + val vectorOfEnumsAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(98, 1) + fun vectorOfEnumsInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 98, 1) + fun mutateVectorOfEnums(j: Int, vectorOfEnums: UByte) : Boolean { + val o = __offset(98) + return if (o != 0) { + bb.put(__vector(o) + j * 1, vectorOfEnums.toByte()) + true + } else { + false + } + } + val signedEnum : Byte + get() { + val o = __offset(100) + return if(o != 0) bb.get(o + bb_pos) else -1 + } + fun mutateSignedEnum(signedEnum: Byte) : Boolean { + val o = __offset(100) + return if (o != 0) { + bb.put(o + bb_pos, signedEnum) + true + } else { + false + } + } + fun testrequirednestedflatbuffer(j: Int) : UByte { + val o = __offset(102) + return if (o != 0) { + bb.get(__vector(o) + j * 1).toUByte() + } else { + 0u + } + } + val testrequirednestedflatbufferLength : Int + get() { + val o = __offset(102); return if (o != 0) __vector_len(o) else 0 + } + val testrequirednestedflatbufferAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(102, 1) + fun testrequirednestedflatbufferInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 102, 1) + val testrequirednestedflatbufferAsMonster : MyGame.Example.Monster? get() = testrequirednestedflatbufferAsMonster(MyGame.Example.Monster()) + fun testrequirednestedflatbufferAsMonster(obj: MyGame.Example.Monster) : MyGame.Example.Monster? { + val o = __offset(102) + return if (o != 0) { + obj.__assign(__indirect(__vector(o)), bb) + } else { + null + } + } + fun mutateTestrequirednestedflatbuffer(j: Int, testrequirednestedflatbuffer: UByte) : Boolean { + val o = __offset(102) + return if (o != 0) { + bb.put(__vector(o) + j * 1, testrequirednestedflatbuffer.toByte()) + true + } else { + false + } + } + fun scalarKeySortedTables(j: Int) : MyGame.Example.Stat? = scalarKeySortedTables(MyGame.Example.Stat(), j) + fun scalarKeySortedTables(obj: MyGame.Example.Stat, j: Int) : MyGame.Example.Stat? { + val o = __offset(104) + return if (o != 0) { + obj.__assign(__indirect(__vector(o) + j * 4), bb) + } else { + null + } + } + val scalarKeySortedTablesLength : Int + get() { + val o = __offset(104); return if (o != 0) __vector_len(o) else 0 + } + fun scalarKeySortedTablesByKey(key: UShort) : MyGame.Example.Stat? { + val o = __offset(104) + return if (o != 0) { + MyGame.Example.Stat.__lookup_by_key(null, __vector(o), key, bb) + } else { + null + } + } + fun scalarKeySortedTablesByKey(obj: MyGame.Example.Stat, key: UShort) : MyGame.Example.Stat? { + val o = __offset(104) + return if (o != 0) { + MyGame.Example.Stat.__lookup_by_key(obj, __vector(o), key, bb) + } else { + null + } + } + val nativeInline : MyGame.Example.Test? get() = nativeInline(MyGame.Example.Test()) + fun nativeInline(obj: MyGame.Example.Test) : MyGame.Example.Test? { + val o = __offset(106) + return if (o != 0) { + obj.__assign(o + bb_pos, bb) + } else { + null + } + } + val longEnumNonEnumDefault : ULong + get() { + val o = __offset(108) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateLongEnumNonEnumDefault(longEnumNonEnumDefault: ULong) : Boolean { + val o = __offset(108) + return if (o != 0) { + bb.putLong(o + bb_pos, longEnumNonEnumDefault.toLong()) + true + } else { + false + } + } + val longEnumNormalDefault : ULong + get() { + val o = __offset(110) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 2UL + } + fun mutateLongEnumNormalDefault(longEnumNormalDefault: ULong) : Boolean { + val o = __offset(110) + return if (o != 0) { + bb.putLong(o + bb_pos, longEnumNormalDefault.toLong()) + true + } else { + false + } + } + val nanDefault : Float + get() { + val o = __offset(112) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.NaN + } + fun mutateNanDefault(nanDefault: Float) : Boolean { + val o = __offset(112) + return if (o != 0) { + bb.putFloat(o + bb_pos, nanDefault) + true + } else { + false + } + } + val infDefault : Float + get() { + val o = __offset(114) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.POSITIVE_INFINITY + } + fun mutateInfDefault(infDefault: Float) : Boolean { + val o = __offset(114) + return if (o != 0) { + bb.putFloat(o + bb_pos, infDefault) + true + } else { + false + } + } + val positiveInfDefault : Float + get() { + val o = __offset(116) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.POSITIVE_INFINITY + } + fun mutatePositiveInfDefault(positiveInfDefault: Float) : Boolean { + val o = __offset(116) + return if (o != 0) { + bb.putFloat(o + bb_pos, positiveInfDefault) + true + } else { + false + } + } + val infinityDefault : Float + get() { + val o = __offset(118) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.POSITIVE_INFINITY + } + fun mutateInfinityDefault(infinityDefault: Float) : Boolean { + val o = __offset(118) + return if (o != 0) { + bb.putFloat(o + bb_pos, infinityDefault) + true + } else { + false + } + } + val positiveInfinityDefault : Float + get() { + val o = __offset(120) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.POSITIVE_INFINITY + } + fun mutatePositiveInfinityDefault(positiveInfinityDefault: Float) : Boolean { + val o = __offset(120) + return if (o != 0) { + bb.putFloat(o + bb_pos, positiveInfinityDefault) + true + } else { + false + } + } + val negativeInfDefault : Float + get() { + val o = __offset(122) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.NEGATIVE_INFINITY + } + fun mutateNegativeInfDefault(negativeInfDefault: Float) : Boolean { + val o = __offset(122) + return if (o != 0) { + bb.putFloat(o + bb_pos, negativeInfDefault) + true + } else { + false + } + } + val negativeInfinityDefault : Float + get() { + val o = __offset(124) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.NEGATIVE_INFINITY + } + fun mutateNegativeInfinityDefault(negativeInfinityDefault: Float) : Boolean { + val o = __offset(124) + return if (o != 0) { + bb.putFloat(o + bb_pos, negativeInfinityDefault) + true + } else { + false + } + } + val doubleInfDefault : Double + get() { + val o = __offset(126) + return if(o != 0) bb.getDouble(o + bb_pos) else Double.POSITIVE_INFINITY + } + fun mutateDoubleInfDefault(doubleInfDefault: Double) : Boolean { + val o = __offset(126) + return if (o != 0) { + bb.putDouble(o + bb_pos, doubleInfDefault) + true + } else { + false + } + } + override fun keysCompare(o1: Int, o2: Int, _bb: ByteBuffer) : Int { + return compareStrings(__offset(10, o1, _bb), __offset(10, o2, _bb), _bb) + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsMonster(_bb: ByteBuffer): Monster = getRootAsMonster(_bb, Monster()) + fun getRootAsMonster(_bb: ByteBuffer, obj: Monster): Monster { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun MonsterBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "MONS") + fun startMonster(builder: FlatBufferBuilder) = builder.startTable(62) + fun addPos(builder: FlatBufferBuilder, pos: Int) = builder.addStruct(0, pos, 0) + fun addMana(builder: FlatBufferBuilder, mana: Short) = builder.addShort(1, mana, 150) + fun addHp(builder: FlatBufferBuilder, hp: Short) = builder.addShort(2, hp, 100) + fun addName(builder: FlatBufferBuilder, name: Int) { + builder.addOffset(name) + builder.slot(3) + } + fun addInventory(builder: FlatBufferBuilder, inventory: Int) = builder.addOffset(5, inventory, 0) + @kotlin.ExperimentalUnsignedTypes + fun createInventoryVector(builder: FlatBufferBuilder, data: UByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i].toByte()) + } + return builder.endVector() + } + fun startInventoryVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addColor(builder: FlatBufferBuilder, color: UByte) = builder.addByte(6, color.toByte(), 8) + fun addTestType(builder: FlatBufferBuilder, testType: UByte) = builder.addByte(7, testType.toByte(), 0) + fun addTest(builder: FlatBufferBuilder, test: Int) = builder.addOffset(8, test, 0) + fun addTest4(builder: FlatBufferBuilder, test4: Int) = builder.addOffset(9, test4, 0) + fun startTest4Vector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 2) + fun addTestarrayofstring(builder: FlatBufferBuilder, testarrayofstring: Int) = builder.addOffset(10, testarrayofstring, 0) + fun createTestarrayofstringVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startTestarrayofstringVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun addTestarrayoftables(builder: FlatBufferBuilder, testarrayoftables: Int) = builder.addOffset(11, testarrayoftables, 0) + fun createTestarrayoftablesVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startTestarrayoftablesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun addEnemy(builder: FlatBufferBuilder, enemy: Int) = builder.addOffset(12, enemy, 0) + fun addTestnestedflatbuffer(builder: FlatBufferBuilder, testnestedflatbuffer: Int) = builder.addOffset(13, testnestedflatbuffer, 0) + @kotlin.ExperimentalUnsignedTypes + fun createTestnestedflatbufferVector(builder: FlatBufferBuilder, data: UByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i].toByte()) + } + return builder.endVector() + } + fun startTestnestedflatbufferVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addTestempty(builder: FlatBufferBuilder, testempty: Int) = builder.addOffset(14, testempty, 0) + fun addTestbool(builder: FlatBufferBuilder, testbool: Boolean) = builder.addBoolean(15, testbool, false) + fun addTesthashs32Fnv1(builder: FlatBufferBuilder, testhashs32Fnv1: Int) = builder.addInt(16, testhashs32Fnv1, 0) + fun addTesthashu32Fnv1(builder: FlatBufferBuilder, testhashu32Fnv1: UInt) = builder.addInt(17, testhashu32Fnv1.toInt(), 0) + fun addTesthashs64Fnv1(builder: FlatBufferBuilder, testhashs64Fnv1: Long) = builder.addLong(18, testhashs64Fnv1, 0L) + fun addTesthashu64Fnv1(builder: FlatBufferBuilder, testhashu64Fnv1: ULong) = builder.addLong(19, testhashu64Fnv1.toLong(), 0) + fun addTesthashs32Fnv1a(builder: FlatBufferBuilder, testhashs32Fnv1a: Int) = builder.addInt(20, testhashs32Fnv1a, 0) + fun addTesthashu32Fnv1a(builder: FlatBufferBuilder, testhashu32Fnv1a: UInt) = builder.addInt(21, testhashu32Fnv1a.toInt(), 0) + fun addTesthashs64Fnv1a(builder: FlatBufferBuilder, testhashs64Fnv1a: Long) = builder.addLong(22, testhashs64Fnv1a, 0L) + fun addTesthashu64Fnv1a(builder: FlatBufferBuilder, testhashu64Fnv1a: ULong) = builder.addLong(23, testhashu64Fnv1a.toLong(), 0) + fun addTestarrayofbools(builder: FlatBufferBuilder, testarrayofbools: Int) = builder.addOffset(24, testarrayofbools, 0) + fun createTestarrayofboolsVector(builder: FlatBufferBuilder, data: BooleanArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addBoolean(data[i]) + } + return builder.endVector() + } + fun startTestarrayofboolsVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addTestf(builder: FlatBufferBuilder, testf: Float) = builder.addFloat(25, testf, 3.14159) + fun addTestf2(builder: FlatBufferBuilder, testf2: Float) = builder.addFloat(26, testf2, 3.0) + fun addTestf3(builder: FlatBufferBuilder, testf3: Float) = builder.addFloat(27, testf3, 0.0) + fun addTestarrayofstring2(builder: FlatBufferBuilder, testarrayofstring2: Int) = builder.addOffset(28, testarrayofstring2, 0) + fun createTestarrayofstring2Vector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startTestarrayofstring2Vector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun addTestarrayofsortedstruct(builder: FlatBufferBuilder, testarrayofsortedstruct: Int) = builder.addOffset(29, testarrayofsortedstruct, 0) + fun startTestarrayofsortedstructVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 4) + fun addFlex(builder: FlatBufferBuilder, flex: Int) = builder.addOffset(30, flex, 0) + @kotlin.ExperimentalUnsignedTypes + fun createFlexVector(builder: FlatBufferBuilder, data: UByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i].toByte()) + } + return builder.endVector() + } + fun startFlexVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addTest5(builder: FlatBufferBuilder, test5: Int) = builder.addOffset(31, test5, 0) + fun startTest5Vector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 2) + fun addVectorOfLongs(builder: FlatBufferBuilder, vectorOfLongs: Int) = builder.addOffset(32, vectorOfLongs, 0) + fun createVectorOfLongsVector(builder: FlatBufferBuilder, data: LongArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addLong(data[i]) + } + return builder.endVector() + } + fun startVectorOfLongsVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun addVectorOfDoubles(builder: FlatBufferBuilder, vectorOfDoubles: Int) = builder.addOffset(33, vectorOfDoubles, 0) + fun createVectorOfDoublesVector(builder: FlatBufferBuilder, data: DoubleArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addDouble(data[i]) + } + return builder.endVector() + } + fun startVectorOfDoublesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun addParentNamespaceTest(builder: FlatBufferBuilder, parentNamespaceTest: Int) = builder.addOffset(34, parentNamespaceTest, 0) + fun addVectorOfReferrables(builder: FlatBufferBuilder, vectorOfReferrables: Int) = builder.addOffset(35, vectorOfReferrables, 0) + fun createVectorOfReferrablesVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startVectorOfReferrablesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun addSingleWeakReference(builder: FlatBufferBuilder, singleWeakReference: ULong) = builder.addLong(36, singleWeakReference.toLong(), 0) + fun addVectorOfWeakReferences(builder: FlatBufferBuilder, vectorOfWeakReferences: Int) = builder.addOffset(37, vectorOfWeakReferences, 0) + @kotlin.ExperimentalUnsignedTypes + fun createVectorOfWeakReferencesVector(builder: FlatBufferBuilder, data: ULongArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addLong(data[i].toLong()) + } + return builder.endVector() + } + fun startVectorOfWeakReferencesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun addVectorOfStrongReferrables(builder: FlatBufferBuilder, vectorOfStrongReferrables: Int) = builder.addOffset(38, vectorOfStrongReferrables, 0) + fun createVectorOfStrongReferrablesVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startVectorOfStrongReferrablesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun addCoOwningReference(builder: FlatBufferBuilder, coOwningReference: ULong) = builder.addLong(39, coOwningReference.toLong(), 0) + fun addVectorOfCoOwningReferences(builder: FlatBufferBuilder, vectorOfCoOwningReferences: Int) = builder.addOffset(40, vectorOfCoOwningReferences, 0) + @kotlin.ExperimentalUnsignedTypes + fun createVectorOfCoOwningReferencesVector(builder: FlatBufferBuilder, data: ULongArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addLong(data[i].toLong()) + } + return builder.endVector() + } + fun startVectorOfCoOwningReferencesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun addNonOwningReference(builder: FlatBufferBuilder, nonOwningReference: ULong) = builder.addLong(41, nonOwningReference.toLong(), 0) + fun addVectorOfNonOwningReferences(builder: FlatBufferBuilder, vectorOfNonOwningReferences: Int) = builder.addOffset(42, vectorOfNonOwningReferences, 0) + @kotlin.ExperimentalUnsignedTypes + fun createVectorOfNonOwningReferencesVector(builder: FlatBufferBuilder, data: ULongArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addLong(data[i].toLong()) + } + return builder.endVector() + } + fun startVectorOfNonOwningReferencesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun addAnyUniqueType(builder: FlatBufferBuilder, anyUniqueType: UByte) = builder.addByte(43, anyUniqueType.toByte(), 0) + fun addAnyUnique(builder: FlatBufferBuilder, anyUnique: Int) = builder.addOffset(44, anyUnique, 0) + fun addAnyAmbiguousType(builder: FlatBufferBuilder, anyAmbiguousType: UByte) = builder.addByte(45, anyAmbiguousType.toByte(), 0) + fun addAnyAmbiguous(builder: FlatBufferBuilder, anyAmbiguous: Int) = builder.addOffset(46, anyAmbiguous, 0) + fun addVectorOfEnums(builder: FlatBufferBuilder, vectorOfEnums: Int) = builder.addOffset(47, vectorOfEnums, 0) + @kotlin.ExperimentalUnsignedTypes + fun createVectorOfEnumsVector(builder: FlatBufferBuilder, data: UByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i].toByte()) + } + return builder.endVector() + } + fun startVectorOfEnumsVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addSignedEnum(builder: FlatBufferBuilder, signedEnum: Byte) = builder.addByte(48, signedEnum, -1) + fun addTestrequirednestedflatbuffer(builder: FlatBufferBuilder, testrequirednestedflatbuffer: Int) = builder.addOffset(49, testrequirednestedflatbuffer, 0) + @kotlin.ExperimentalUnsignedTypes + fun createTestrequirednestedflatbufferVector(builder: FlatBufferBuilder, data: UByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i].toByte()) + } + return builder.endVector() + } + fun startTestrequirednestedflatbufferVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addScalarKeySortedTables(builder: FlatBufferBuilder, scalarKeySortedTables: Int) = builder.addOffset(50, scalarKeySortedTables, 0) + fun createScalarKeySortedTablesVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startScalarKeySortedTablesVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun addNativeInline(builder: FlatBufferBuilder, nativeInline: Int) = builder.addStruct(51, nativeInline, 0) + fun addLongEnumNonEnumDefault(builder: FlatBufferBuilder, longEnumNonEnumDefault: ULong) = builder.addLong(52, longEnumNonEnumDefault.toLong(), 0) + fun addLongEnumNormalDefault(builder: FlatBufferBuilder, longEnumNormalDefault: ULong) = builder.addLong(53, longEnumNormalDefault.toLong(), 2) + fun addNanDefault(builder: FlatBufferBuilder, nanDefault: Float) = builder.addFloat(54, nanDefault, Double.NaN) + fun addInfDefault(builder: FlatBufferBuilder, infDefault: Float) = builder.addFloat(55, infDefault, Double.POSITIVE_INFINITY) + fun addPositiveInfDefault(builder: FlatBufferBuilder, positiveInfDefault: Float) = builder.addFloat(56, positiveInfDefault, Double.POSITIVE_INFINITY) + fun addInfinityDefault(builder: FlatBufferBuilder, infinityDefault: Float) = builder.addFloat(57, infinityDefault, Double.POSITIVE_INFINITY) + fun addPositiveInfinityDefault(builder: FlatBufferBuilder, positiveInfinityDefault: Float) = builder.addFloat(58, positiveInfinityDefault, Double.POSITIVE_INFINITY) + fun addNegativeInfDefault(builder: FlatBufferBuilder, negativeInfDefault: Float) = builder.addFloat(59, negativeInfDefault, Double.NEGATIVE_INFINITY) + fun addNegativeInfinityDefault(builder: FlatBufferBuilder, negativeInfinityDefault: Float) = builder.addFloat(60, negativeInfinityDefault, Double.NEGATIVE_INFINITY) + fun addDoubleInfDefault(builder: FlatBufferBuilder, doubleInfDefault: Double) = builder.addDouble(61, doubleInfDefault, Double.POSITIVE_INFINITY) + fun endMonster(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + builder.required(o, 10) + return o + } + fun finishMonsterBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset, "MONS") + fun finishSizePrefixedMonsterBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset, "MONS") + fun __lookup_by_key(obj: Monster?, vectorLocation: Int, key: String, bb: ByteBuffer) : Monster? { + val byteKey = key.toByteArray(java.nio.charset.StandardCharsets.UTF_8) + var span = bb.getInt(vectorLocation - 4) + var start = 0 + while (span != 0) { + var middle = span / 2 + val tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb) + val comp = compareStrings(__offset(10, bb.capacity() - tableOffset, bb), byteKey, bb) + when { + comp > 0 -> span = middle + comp < 0 -> { + middle++ + start += middle + span -= middle + } + else -> { + return (obj ?: Monster()).__assign(tableOffset, bb) + } + } + } + return null + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.lua b/third_party/flatbuffers/tests/MyGame/Example/Monster.lua new file mode 100644 index 00000000000..513f966001e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.lua @@ -0,0 +1,1102 @@ +--[[ MyGame.Example.Monster + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local __MyGame_Example_Ability = require('MyGame.Example.Ability') +local __MyGame_Example_Referrable = require('MyGame.Example.Referrable') +local __MyGame_Example_Stat = require('MyGame.Example.Stat') +local __MyGame_Example_Test = require('MyGame.Example.Test') +local __MyGame_Example_Vec3 = require('MyGame.Example.Vec3') +local __MyGame_InParentNamespace = require('MyGame.InParentNamespace') +local flatbuffers = require('flatbuffers') + +-- an example documentation comment: "monster object" +local Monster = {} +local mt = {} + +function Monster.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function Monster.GetRootAsMonster(buf, offset) + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + + local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) + local o = Monster.New() + o:Init(buf, n + offset) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:Pos() + local o = self.view:Offset(4) + if o ~= 0 then + local x = self.view.pos + o + local obj = __MyGame_Example_Vec3.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:Mana() + local o = self.view:Offset(6) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int16, self.view.pos + o) + end + return 150 +end + +function mt:Hp() + local o = self.view:Offset(8) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int16, self.view.pos + o) + end + return 100 +end + +function mt:Name() + local o = self.view:Offset(10) + if o ~= 0 then + return self.view:String(self.view.pos + o) + end +end + +function mt:Inventory(j) + local o = self.view:Offset(14) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) + end + return 0 +end + +function mt:InventoryAsString(start, stop) + return self.view:VectorAsString(14, start, stop) +end + +function mt:InventoryLength() + local o = self.view:Offset(14) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Color() + local o = self.view:Offset(16) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) + end + return 8 +end + +function mt:TestType() + local o = self.view:Offset(18) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) + end + return 0 +end + +function mt:Test() + local o = self.view:Offset(20) + if o ~= 0 then + local obj = flatbuffers.view.New(flatbuffers.binaryArray.New(0), 0) + self.view:Union(obj, o) + return obj + end +end + +function mt:Test4(j) + local o = self.view:Offset(22) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + local obj = __MyGame_Example_Test.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:Test4Length() + local o = self.view:Offset(22) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Testarrayofstring(j) + local o = self.view:Offset(24) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:String(a + ((j-1) * 4)) + end + return '' +end + +function mt:TestarrayofstringLength() + local o = self.view:Offset(24) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +-- an example documentation comment: this will end up in the generated code +-- multiline too +function mt:Testarrayoftables(j) + local o = self.view:Offset(26) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + x = self.view:Indirect(x) + local obj = Monster.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:TestarrayoftablesLength() + local o = self.view:Offset(26) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Enemy() + local o = self.view:Offset(28) + if o ~= 0 then + local x = self.view:Indirect(self.view.pos + o) + local obj = Monster.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:Testnestedflatbuffer(j) + local o = self.view:Offset(30) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) + end + return 0 +end + +function mt:TestnestedflatbufferAsString(start, stop) + return self.view:VectorAsString(30, start, stop) +end + +function mt:TestnestedflatbufferLength() + local o = self.view:Offset(30) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Testempty() + local o = self.view:Offset(32) + if o ~= 0 then + local x = self.view:Indirect(self.view.pos + o) + local obj = __MyGame_Example_Stat.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:Testbool() + local o = self.view:Offset(34) + if o ~= 0 then + return (self.view:Get(flatbuffers.N.Bool, self.view.pos + o) ~=0) + end + return false +end + +function mt:Testhashs32Fnv1() + local o = self.view:Offset(36) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int32, self.view.pos + o) + end + return 0 +end + +function mt:Testhashu32Fnv1() + local o = self.view:Offset(38) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o) + end + return 0 +end + +function mt:Testhashs64Fnv1() + local o = self.view:Offset(40) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int64, self.view.pos + o) + end + return 0 +end + +function mt:Testhashu64Fnv1() + local o = self.view:Offset(42) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:Testhashs32Fnv1a() + local o = self.view:Offset(44) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int32, self.view.pos + o) + end + return 0 +end + +function mt:Testhashu32Fnv1a() + local o = self.view:Offset(46) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o) + end + return 0 +end + +function mt:Testhashs64Fnv1a() + local o = self.view:Offset(48) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int64, self.view.pos + o) + end + return 0 +end + +function mt:Testhashu64Fnv1a() + local o = self.view:Offset(50) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:Testarrayofbools(j) + local o = self.view:Offset(52) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Bool, a + ((j-1) * 1)) + end + return 0 +end + +function mt:TestarrayofboolsAsString(start, stop) + return self.view:VectorAsString(52, start, stop) +end + +function mt:TestarrayofboolsLength() + local o = self.view:Offset(52) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Testf() + local o = self.view:Offset(54) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return 3.14159 +end + +function mt:Testf2() + local o = self.view:Offset(56) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return 3.0 +end + +function mt:Testf3() + local o = self.view:Offset(58) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return 0.0 +end + +function mt:Testarrayofstring2(j) + local o = self.view:Offset(60) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:String(a + ((j-1) * 4)) + end + return '' +end + +function mt:Testarrayofstring2Length() + local o = self.view:Offset(60) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Testarrayofsortedstruct(j) + local o = self.view:Offset(62) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 8) + local obj = __MyGame_Example_Ability.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:TestarrayofsortedstructLength() + local o = self.view:Offset(62) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Flex(j) + local o = self.view:Offset(64) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) + end + return 0 +end + +function mt:FlexAsString(start, stop) + return self.view:VectorAsString(64, start, stop) +end + +function mt:FlexLength() + local o = self.view:Offset(64) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Test5(j) + local o = self.view:Offset(66) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + local obj = __MyGame_Example_Test.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:Test5Length() + local o = self.view:Offset(66) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:VectorOfLongs(j) + local o = self.view:Offset(68) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Int64, a + ((j-1) * 8)) + end + return 0 +end + +function mt:VectorOfLongsLength() + local o = self.view:Offset(68) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:VectorOfDoubles(j) + local o = self.view:Offset(70) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8)) + end + return 0 +end + +function mt:VectorOfDoublesLength() + local o = self.view:Offset(70) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:ParentNamespaceTest() + local o = self.view:Offset(72) + if o ~= 0 then + local x = self.view:Indirect(self.view.pos + o) + local obj = __MyGame_InParentNamespace.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:VectorOfReferrables(j) + local o = self.view:Offset(74) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + x = self.view:Indirect(x) + local obj = __MyGame_Example_Referrable.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:VectorOfReferrablesLength() + local o = self.view:Offset(74) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:SingleWeakReference() + local o = self.view:Offset(76) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:VectorOfWeakReferences(j) + local o = self.view:Offset(78) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8)) + end + return 0 +end + +function mt:VectorOfWeakReferencesLength() + local o = self.view:Offset(78) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:VectorOfStrongReferrables(j) + local o = self.view:Offset(80) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + x = self.view:Indirect(x) + local obj = __MyGame_Example_Referrable.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:VectorOfStrongReferrablesLength() + local o = self.view:Offset(80) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:CoOwningReference() + local o = self.view:Offset(82) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:VectorOfCoOwningReferences(j) + local o = self.view:Offset(84) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8)) + end + return 0 +end + +function mt:VectorOfCoOwningReferencesLength() + local o = self.view:Offset(84) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:NonOwningReference() + local o = self.view:Offset(86) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:VectorOfNonOwningReferences(j) + local o = self.view:Offset(88) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint64, a + ((j-1) * 8)) + end + return 0 +end + +function mt:VectorOfNonOwningReferencesLength() + local o = self.view:Offset(88) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:AnyUniqueType() + local o = self.view:Offset(90) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) + end + return 0 +end + +function mt:AnyUnique() + local o = self.view:Offset(92) + if o ~= 0 then + local obj = flatbuffers.view.New(flatbuffers.binaryArray.New(0), 0) + self.view:Union(obj, o) + return obj + end +end + +function mt:AnyAmbiguousType() + local o = self.view:Offset(94) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) + end + return 0 +end + +function mt:AnyAmbiguous() + local o = self.view:Offset(96) + if o ~= 0 then + local obj = flatbuffers.view.New(flatbuffers.binaryArray.New(0), 0) + self.view:Union(obj, o) + return obj + end +end + +function mt:VectorOfEnums(j) + local o = self.view:Offset(98) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) + end + return 0 +end + +function mt:VectorOfEnumsAsString(start, stop) + return self.view:VectorAsString(98, start, stop) +end + +function mt:VectorOfEnumsLength() + local o = self.view:Offset(98) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:SignedEnum() + local o = self.view:Offset(100) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int8, self.view.pos + o) + end + return -1 +end + +function mt:Testrequirednestedflatbuffer(j) + local o = self.view:Offset(102) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Uint8, a + ((j-1) * 1)) + end + return 0 +end + +function mt:TestrequirednestedflatbufferAsString(start, stop) + return self.view:VectorAsString(102, start, stop) +end + +function mt:TestrequirednestedflatbufferLength() + local o = self.view:Offset(102) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:ScalarKeySortedTables(j) + local o = self.view:Offset(104) + if o ~= 0 then + local x = self.view:Vector(o) + x = x + ((j-1) * 4) + x = self.view:Indirect(x) + local obj = __MyGame_Example_Stat.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:ScalarKeySortedTablesLength() + local o = self.view:Offset(104) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:NativeInline() + local o = self.view:Offset(106) + if o ~= 0 then + local x = self.view.pos + o + local obj = __MyGame_Example_Test.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function mt:LongEnumNonEnumDefault() + local o = self.view:Offset(108) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:LongEnumNormalDefault() + local o = self.view:Offset(110) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 2 +end + +function mt:NanDefault() + local o = self.view:Offset(112) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return nan +end + +function mt:InfDefault() + local o = self.view:Offset(114) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return inf +end + +function mt:PositiveInfDefault() + local o = self.view:Offset(116) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return inf +end + +function mt:InfinityDefault() + local o = self.view:Offset(118) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return inf +end + +function mt:PositiveInfinityDefault() + local o = self.view:Offset(120) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return inf +end + +function mt:NegativeInfDefault() + local o = self.view:Offset(122) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return -inf +end + +function mt:NegativeInfinityDefault() + local o = self.view:Offset(124) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return -inf +end + +function mt:DoubleInfDefault() + local o = self.view:Offset(126) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float64, self.view.pos + o) + end + return inf +end + +function Monster.Start(builder) + builder:StartObject(62) +end + +function Monster.AddPos(builder, pos) + builder:PrependStructSlot(0, pos, 0) +end + +function Monster.AddMana(builder, mana) + builder:PrependInt16Slot(1, mana, 150) +end + +function Monster.AddHp(builder, hp) + builder:PrependInt16Slot(2, hp, 100) +end + +function Monster.AddName(builder, name) + builder:PrependUOffsetTRelativeSlot(3, name, 0) +end + +function Monster.AddInventory(builder, inventory) + builder:PrependUOffsetTRelativeSlot(5, inventory, 0) +end + +function Monster.StartInventoryVector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function Monster.AddColor(builder, color) + builder:PrependUint8Slot(6, color, 8) +end + +function Monster.AddTestType(builder, testType) + builder:PrependUint8Slot(7, testType, 0) +end + +function Monster.AddTest(builder, test) + builder:PrependUOffsetTRelativeSlot(8, test, 0) +end + +function Monster.AddTest4(builder, test4) + builder:PrependUOffsetTRelativeSlot(9, test4, 0) +end + +function Monster.StartTest4Vector(builder, numElems) + return builder:StartVector(4, numElems, 2) +end + +function Monster.AddTestarrayofstring(builder, testarrayofstring) + builder:PrependUOffsetTRelativeSlot(10, testarrayofstring, 0) +end + +function Monster.StartTestarrayofstringVector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Monster.AddTestarrayoftables(builder, testarrayoftables) + builder:PrependUOffsetTRelativeSlot(11, testarrayoftables, 0) +end + +function Monster.StartTestarrayoftablesVector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Monster.AddEnemy(builder, enemy) + builder:PrependStructSlot(12, enemy, 0) +end + +function Monster.AddTestnestedflatbuffer(builder, testnestedflatbuffer) + builder:PrependUOffsetTRelativeSlot(13, testnestedflatbuffer, 0) +end + +function Monster.StartTestnestedflatbufferVector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function Monster.AddTestempty(builder, testempty) + builder:PrependStructSlot(14, testempty, 0) +end + +function Monster.AddTestbool(builder, testbool) + builder:PrependBoolSlot(15, testbool, false) +end + +function Monster.AddTesthashs32Fnv1(builder, testhashs32Fnv1) + builder:PrependInt32Slot(16, testhashs32Fnv1, 0) +end + +function Monster.AddTesthashu32Fnv1(builder, testhashu32Fnv1) + builder:PrependUint32Slot(17, testhashu32Fnv1, 0) +end + +function Monster.AddTesthashs64Fnv1(builder, testhashs64Fnv1) + builder:PrependInt64Slot(18, testhashs64Fnv1, 0) +end + +function Monster.AddTesthashu64Fnv1(builder, testhashu64Fnv1) + builder:PrependUint64Slot(19, testhashu64Fnv1, 0) +end + +function Monster.AddTesthashs32Fnv1a(builder, testhashs32Fnv1a) + builder:PrependInt32Slot(20, testhashs32Fnv1a, 0) +end + +function Monster.AddTesthashu32Fnv1a(builder, testhashu32Fnv1a) + builder:PrependUint32Slot(21, testhashu32Fnv1a, 0) +end + +function Monster.AddTesthashs64Fnv1a(builder, testhashs64Fnv1a) + builder:PrependInt64Slot(22, testhashs64Fnv1a, 0) +end + +function Monster.AddTesthashu64Fnv1a(builder, testhashu64Fnv1a) + builder:PrependUint64Slot(23, testhashu64Fnv1a, 0) +end + +function Monster.AddTestarrayofbools(builder, testarrayofbools) + builder:PrependUOffsetTRelativeSlot(24, testarrayofbools, 0) +end + +function Monster.StartTestarrayofboolsVector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function Monster.AddTestf(builder, testf) + builder:PrependFloat32Slot(25, testf, 3.14159) +end + +function Monster.AddTestf2(builder, testf2) + builder:PrependFloat32Slot(26, testf2, 3.0) +end + +function Monster.AddTestf3(builder, testf3) + builder:PrependFloat32Slot(27, testf3, 0.0) +end + +function Monster.AddTestarrayofstring2(builder, testarrayofstring2) + builder:PrependUOffsetTRelativeSlot(28, testarrayofstring2, 0) +end + +function Monster.StartTestarrayofstring2Vector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Monster.AddTestarrayofsortedstruct(builder, testarrayofsortedstruct) + builder:PrependUOffsetTRelativeSlot(29, testarrayofsortedstruct, 0) +end + +function Monster.StartTestarrayofsortedstructVector(builder, numElems) + return builder:StartVector(8, numElems, 4) +end + +function Monster.AddFlex(builder, flex) + builder:PrependUOffsetTRelativeSlot(30, flex, 0) +end + +function Monster.StartFlexVector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function Monster.AddTest5(builder, test5) + builder:PrependUOffsetTRelativeSlot(31, test5, 0) +end + +function Monster.StartTest5Vector(builder, numElems) + return builder:StartVector(4, numElems, 2) +end + +function Monster.AddVectorOfLongs(builder, vectorOfLongs) + builder:PrependUOffsetTRelativeSlot(32, vectorOfLongs, 0) +end + +function Monster.StartVectorOfLongsVector(builder, numElems) + return builder:StartVector(8, numElems, 8) +end + +function Monster.AddVectorOfDoubles(builder, vectorOfDoubles) + builder:PrependUOffsetTRelativeSlot(33, vectorOfDoubles, 0) +end + +function Monster.StartVectorOfDoublesVector(builder, numElems) + return builder:StartVector(8, numElems, 8) +end + +function Monster.AddParentNamespaceTest(builder, parentNamespaceTest) + builder:PrependStructSlot(34, parentNamespaceTest, 0) +end + +function Monster.AddVectorOfReferrables(builder, vectorOfReferrables) + builder:PrependUOffsetTRelativeSlot(35, vectorOfReferrables, 0) +end + +function Monster.StartVectorOfReferrablesVector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Monster.AddSingleWeakReference(builder, singleWeakReference) + builder:PrependUint64Slot(36, singleWeakReference, 0) +end + +function Monster.AddVectorOfWeakReferences(builder, vectorOfWeakReferences) + builder:PrependUOffsetTRelativeSlot(37, vectorOfWeakReferences, 0) +end + +function Monster.StartVectorOfWeakReferencesVector(builder, numElems) + return builder:StartVector(8, numElems, 8) +end + +function Monster.AddVectorOfStrongReferrables(builder, vectorOfStrongReferrables) + builder:PrependUOffsetTRelativeSlot(38, vectorOfStrongReferrables, 0) +end + +function Monster.StartVectorOfStrongReferrablesVector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Monster.AddCoOwningReference(builder, coOwningReference) + builder:PrependUint64Slot(39, coOwningReference, 0) +end + +function Monster.AddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences) + builder:PrependUOffsetTRelativeSlot(40, vectorOfCoOwningReferences, 0) +end + +function Monster.StartVectorOfCoOwningReferencesVector(builder, numElems) + return builder:StartVector(8, numElems, 8) +end + +function Monster.AddNonOwningReference(builder, nonOwningReference) + builder:PrependUint64Slot(41, nonOwningReference, 0) +end + +function Monster.AddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences) + builder:PrependUOffsetTRelativeSlot(42, vectorOfNonOwningReferences, 0) +end + +function Monster.StartVectorOfNonOwningReferencesVector(builder, numElems) + return builder:StartVector(8, numElems, 8) +end + +function Monster.AddAnyUniqueType(builder, anyUniqueType) + builder:PrependUint8Slot(43, anyUniqueType, 0) +end + +function Monster.AddAnyUnique(builder, anyUnique) + builder:PrependUOffsetTRelativeSlot(44, anyUnique, 0) +end + +function Monster.AddAnyAmbiguousType(builder, anyAmbiguousType) + builder:PrependUint8Slot(45, anyAmbiguousType, 0) +end + +function Monster.AddAnyAmbiguous(builder, anyAmbiguous) + builder:PrependUOffsetTRelativeSlot(46, anyAmbiguous, 0) +end + +function Monster.AddVectorOfEnums(builder, vectorOfEnums) + builder:PrependUOffsetTRelativeSlot(47, vectorOfEnums, 0) +end + +function Monster.StartVectorOfEnumsVector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function Monster.AddSignedEnum(builder, signedEnum) + builder:PrependInt8Slot(48, signedEnum, -1) +end + +function Monster.AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer) + builder:PrependUOffsetTRelativeSlot(49, testrequirednestedflatbuffer, 0) +end + +function Monster.StartTestrequirednestedflatbufferVector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function Monster.AddScalarKeySortedTables(builder, scalarKeySortedTables) + builder:PrependUOffsetTRelativeSlot(50, scalarKeySortedTables, 0) +end + +function Monster.StartScalarKeySortedTablesVector(builder, numElems) + return builder:StartVector(4, numElems, 4) +end + +function Monster.AddNativeInline(builder, nativeInline) + builder:PrependStructSlot(51, nativeInline, 0) +end + +function Monster.AddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault) + builder:PrependUint64Slot(52, longEnumNonEnumDefault, 0) +end + +function Monster.AddLongEnumNormalDefault(builder, longEnumNormalDefault) + builder:PrependUint64Slot(53, longEnumNormalDefault, 2) +end + +function Monster.AddNanDefault(builder, nanDefault) + builder:PrependFloat32Slot(54, nanDefault, nan) +end + +function Monster.AddInfDefault(builder, infDefault) + builder:PrependFloat32Slot(55, infDefault, inf) +end + +function Monster.AddPositiveInfDefault(builder, positiveInfDefault) + builder:PrependFloat32Slot(56, positiveInfDefault, inf) +end + +function Monster.AddInfinityDefault(builder, infinityDefault) + builder:PrependFloat32Slot(57, infinityDefault, inf) +end + +function Monster.AddPositiveInfinityDefault(builder, positiveInfinityDefault) + builder:PrependFloat32Slot(58, positiveInfinityDefault, inf) +end + +function Monster.AddNegativeInfDefault(builder, negativeInfDefault) + builder:PrependFloat32Slot(59, negativeInfDefault, -inf) +end + +function Monster.AddNegativeInfinityDefault(builder, negativeInfinityDefault) + builder:PrependFloat32Slot(60, negativeInfinityDefault, -inf) +end + +function Monster.AddDoubleInfDefault(builder, doubleInfDefault) + builder:PrependFloat64Slot(61, doubleInfDefault, inf) +end + +function Monster.End(builder) + return builder:EndObject() +end + +return Monster \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.nim b/third_party/flatbuffers/tests/MyGame/Example/Monster.nim new file mode 100644 index 00000000000..30e48e9d0be --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.nim @@ -0,0 +1,734 @@ +#[ MyGame.Example.Monster + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import ../InParentNamespace as MyGame_InParentNamespace +import Ability as MyGame_Example_Ability +import Any as MyGame_Example_Any +import AnyAmbiguousAliases as MyGame_Example_AnyAmbiguousAliases +import AnyUniqueAliases as MyGame_Example_AnyUniqueAliases +import Color as MyGame_Example_Color +import LongEnum as MyGame_Example_LongEnum +import Race as MyGame_Example_Race +import Referrable as MyGame_Example_Referrable +import Stat as MyGame_Example_Stat +import Test as MyGame_Example_Test +import Vec3 as MyGame_Example_Vec3 +import flatbuffers +import std/options + +# an example documentation comment: "monster object" +type Monster* = object of FlatObj +func pos*(self: Monster): Option[MyGame_Example_Vec3.Vec3] = + let o = self.tab.Offset(4) + if o != 0: + return some(MyGame_Example_Vec3.Vec3(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +func mana*(self: Monster): int16 = + let o = self.tab.Offset(6) + if o != 0: + return Get[int16](self.tab, self.tab.Pos + o) + return 150 +func `mana=`*(self: var Monster, n: int16): bool = + return self.tab.MutateSlot(6, n) +func hp*(self: Monster): int16 = + let o = self.tab.Offset(8) + if o != 0: + return Get[int16](self.tab, self.tab.Pos + o) + return 100 +func `hp=`*(self: var Monster, n: int16): bool = + return self.tab.MutateSlot(8, n) +func name*(self: Monster): string = + let o = self.tab.Offset(10) + if o != 0: + return self.tab.String(self.tab.Pos + o) + return "" +func inventoryLength*(self: Monster): int = + let o = self.tab.Offset(14) + if o != 0: + return self.tab.VectorLen(o) +func inventory*(self: Monster, j: int): uint8 = + let o = self.tab.Offset(14) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[uint8](self.tab, x) +func inventory*(self: Monster): seq[uint8] = + let len = self.inventoryLength + for i in countup(0, len - 1): + result.add(self.inventory(i)) +func color*(self: Monster): MyGame_Example_Color.Color = + let o = self.tab.Offset(16) + if o != 0: + return MyGame_Example_Color.Color(Get[uint8](self.tab, self.tab.Pos + o)) + return type(result)(8) +func `color=`*(self: var Monster, n: MyGame_Example_Color.Color): bool = + return self.tab.MutateSlot(16, n) +func testType*(self: Monster): MyGame_Example_Any.Any = + let o = self.tab.Offset(18) + if o != 0: + return MyGame_Example_Any.Any(Get[uint8](self.tab, self.tab.Pos + o)) + return type(result)(0) +func `testType=`*(self: var Monster, n: MyGame_Example_Any.Any): bool = + return self.tab.MutateSlot(18, n) +func test*(self: Monster): Option[Vtable] = + let o = self.tab.Offset(20) + if o != 0: + return some(self.tab.Union(o)) +func test4Length*(self: Monster): int = + let o = self.tab.Offset(22) + if o != 0: + return self.tab.VectorLen(o) +func test4*(self: Monster, j: int): MyGame_Example_Test.Test = + let o = self.tab.Offset(22) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return MyGame_Example_Test.Test(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func test4*(self: Monster): seq[MyGame_Example_Test.Test] = + let len = self.test4Length + for i in countup(0, len - 1): + result.add(self.test4(i)) +func testarrayofstringLength*(self: Monster): int = + let o = self.tab.Offset(24) + if o != 0: + return self.tab.VectorLen(o) +func testarrayofstring*(self: Monster, j: int): string = + let o = self.tab.Offset(24) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return self.tab.String(x) +func testarrayofstring*(self: Monster): seq[string] = + let len = self.testarrayofstringLength + for i in countup(0, len - 1): + result.add(self.testarrayofstring(i)) +func testarrayoftablesLength*(self: Monster): int = + let o = self.tab.Offset(26) + if o != 0: + return self.tab.VectorLen(o) +func testarrayoftables*(self: Monster, j: int): Monster = + let o = self.tab.Offset(26) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return Monster(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func testarrayoftables*(self: Monster): seq[Monster] = + let len = self.testarrayoftablesLength + for i in countup(0, len - 1): + result.add(self.testarrayoftables(i)) +func enemy*(self: Monster): Option[Monster] = + let o = self.tab.Offset(28) + if o != 0: + return some(Monster(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +func testnestedflatbufferLength*(self: Monster): int = + let o = self.tab.Offset(30) + if o != 0: + return self.tab.VectorLen(o) +func testnestedflatbuffer*(self: Monster, j: int): uint8 = + let o = self.tab.Offset(30) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[uint8](self.tab, x) +func testnestedflatbuffer*(self: Monster): seq[uint8] = + let len = self.testnestedflatbufferLength + for i in countup(0, len - 1): + result.add(self.testnestedflatbuffer(i)) +func testempty*(self: Monster): Option[MyGame_Example_Stat.Stat] = + let o = self.tab.Offset(32) + if o != 0: + return some(MyGame_Example_Stat.Stat(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +func testbool*(self: Monster): bool = + let o = self.tab.Offset(34) + if o != 0: + return Get[bool](self.tab, self.tab.Pos + o) + return false +func `testbool=`*(self: var Monster, n: bool): bool = + return self.tab.MutateSlot(34, n) +func testhashs32Fnv1*(self: Monster): int32 = + let o = self.tab.Offset(36) + if o != 0: + return Get[int32](self.tab, self.tab.Pos + o) + return 0 +func `testhashs32Fnv1=`*(self: var Monster, n: int32): bool = + return self.tab.MutateSlot(36, n) +func testhashu32Fnv1*(self: Monster): uint32 = + let o = self.tab.Offset(38) + if o != 0: + return Get[uint32](self.tab, self.tab.Pos + o) + return 0 +func `testhashu32Fnv1=`*(self: var Monster, n: uint32): bool = + return self.tab.MutateSlot(38, n) +func testhashs64Fnv1*(self: Monster): int64 = + let o = self.tab.Offset(40) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 0 +func `testhashs64Fnv1=`*(self: var Monster, n: int64): bool = + return self.tab.MutateSlot(40, n) +func testhashu64Fnv1*(self: Monster): uint64 = + let o = self.tab.Offset(42) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `testhashu64Fnv1=`*(self: var Monster, n: uint64): bool = + return self.tab.MutateSlot(42, n) +func testhashs32Fnv1a*(self: Monster): int32 = + let o = self.tab.Offset(44) + if o != 0: + return Get[int32](self.tab, self.tab.Pos + o) + return 0 +func `testhashs32Fnv1a=`*(self: var Monster, n: int32): bool = + return self.tab.MutateSlot(44, n) +func testhashu32Fnv1a*(self: Monster): uint32 = + let o = self.tab.Offset(46) + if o != 0: + return Get[uint32](self.tab, self.tab.Pos + o) + return 0 +func `testhashu32Fnv1a=`*(self: var Monster, n: uint32): bool = + return self.tab.MutateSlot(46, n) +func testhashs64Fnv1a*(self: Monster): int64 = + let o = self.tab.Offset(48) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 0 +func `testhashs64Fnv1a=`*(self: var Monster, n: int64): bool = + return self.tab.MutateSlot(48, n) +func testhashu64Fnv1a*(self: Monster): uint64 = + let o = self.tab.Offset(50) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `testhashu64Fnv1a=`*(self: var Monster, n: uint64): bool = + return self.tab.MutateSlot(50, n) +func testarrayofboolsLength*(self: Monster): int = + let o = self.tab.Offset(52) + if o != 0: + return self.tab.VectorLen(o) +func testarrayofbools*(self: Monster, j: int): bool = + let o = self.tab.Offset(52) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[bool](self.tab, x) +func testarrayofbools*(self: Monster): seq[bool] = + let len = self.testarrayofboolsLength + for i in countup(0, len - 1): + result.add(self.testarrayofbools(i)) +func testf*(self: Monster): float32 = + let o = self.tab.Offset(54) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return 3.14159 +func `testf=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(54, n) +func testf2*(self: Monster): float32 = + let o = self.tab.Offset(56) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return 3.0 +func `testf2=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(56, n) +func testf3*(self: Monster): float32 = + let o = self.tab.Offset(58) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return 0.0 +func `testf3=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(58, n) +func testarrayofstring2Length*(self: Monster): int = + let o = self.tab.Offset(60) + if o != 0: + return self.tab.VectorLen(o) +func testarrayofstring2*(self: Monster, j: int): string = + let o = self.tab.Offset(60) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return self.tab.String(x) +func testarrayofstring2*(self: Monster): seq[string] = + let len = self.testarrayofstring2Length + for i in countup(0, len - 1): + result.add(self.testarrayofstring2(i)) +func testarrayofsortedstructLength*(self: Monster): int = + let o = self.tab.Offset(62) + if o != 0: + return self.tab.VectorLen(o) +func testarrayofsortedstruct*(self: Monster, j: int): MyGame_Example_Ability.Ability = + let o = self.tab.Offset(62) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return MyGame_Example_Ability.Ability(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func testarrayofsortedstruct*(self: Monster): seq[MyGame_Example_Ability.Ability] = + let len = self.testarrayofsortedstructLength + for i in countup(0, len - 1): + result.add(self.testarrayofsortedstruct(i)) +func flexLength*(self: Monster): int = + let o = self.tab.Offset(64) + if o != 0: + return self.tab.VectorLen(o) +func flex*(self: Monster, j: int): uint8 = + let o = self.tab.Offset(64) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[uint8](self.tab, x) +func flex*(self: Monster): seq[uint8] = + let len = self.flexLength + for i in countup(0, len - 1): + result.add(self.flex(i)) +func test5Length*(self: Monster): int = + let o = self.tab.Offset(66) + if o != 0: + return self.tab.VectorLen(o) +func test5*(self: Monster, j: int): MyGame_Example_Test.Test = + let o = self.tab.Offset(66) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return MyGame_Example_Test.Test(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func test5*(self: Monster): seq[MyGame_Example_Test.Test] = + let len = self.test5Length + for i in countup(0, len - 1): + result.add(self.test5(i)) +func vectorOfLongsLength*(self: Monster): int = + let o = self.tab.Offset(68) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfLongs*(self: Monster, j: int): int64 = + let o = self.tab.Offset(68) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return Get[int64](self.tab, x) +func vectorOfLongs*(self: Monster): seq[int64] = + let len = self.vectorOfLongsLength + for i in countup(0, len - 1): + result.add(self.vectorOfLongs(i)) +func vectorOfDoublesLength*(self: Monster): int = + let o = self.tab.Offset(70) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfDoubles*(self: Monster, j: int): float64 = + let o = self.tab.Offset(70) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return Get[float64](self.tab, x) +func vectorOfDoubles*(self: Monster): seq[float64] = + let len = self.vectorOfDoublesLength + for i in countup(0, len - 1): + result.add(self.vectorOfDoubles(i)) +func parentNamespaceTest*(self: Monster): Option[MyGame_InParentNamespace.InParentNamespace] = + let o = self.tab.Offset(72) + if o != 0: + return some(MyGame_InParentNamespace.InParentNamespace(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +func vectorOfReferrablesLength*(self: Monster): int = + let o = self.tab.Offset(74) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfReferrables*(self: Monster, j: int): MyGame_Example_Referrable.Referrable = + let o = self.tab.Offset(74) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return MyGame_Example_Referrable.Referrable(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func vectorOfReferrables*(self: Monster): seq[MyGame_Example_Referrable.Referrable] = + let len = self.vectorOfReferrablesLength + for i in countup(0, len - 1): + result.add(self.vectorOfReferrables(i)) +func singleWeakReference*(self: Monster): uint64 = + let o = self.tab.Offset(76) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `singleWeakReference=`*(self: var Monster, n: uint64): bool = + return self.tab.MutateSlot(76, n) +func vectorOfWeakReferencesLength*(self: Monster): int = + let o = self.tab.Offset(78) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfWeakReferences*(self: Monster, j: int): uint64 = + let o = self.tab.Offset(78) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return Get[uint64](self.tab, x) +func vectorOfWeakReferences*(self: Monster): seq[uint64] = + let len = self.vectorOfWeakReferencesLength + for i in countup(0, len - 1): + result.add(self.vectorOfWeakReferences(i)) +func vectorOfStrongReferrablesLength*(self: Monster): int = + let o = self.tab.Offset(80) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfStrongReferrables*(self: Monster, j: int): MyGame_Example_Referrable.Referrable = + let o = self.tab.Offset(80) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return MyGame_Example_Referrable.Referrable(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func vectorOfStrongReferrables*(self: Monster): seq[MyGame_Example_Referrable.Referrable] = + let len = self.vectorOfStrongReferrablesLength + for i in countup(0, len - 1): + result.add(self.vectorOfStrongReferrables(i)) +func coOwningReference*(self: Monster): uint64 = + let o = self.tab.Offset(82) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `coOwningReference=`*(self: var Monster, n: uint64): bool = + return self.tab.MutateSlot(82, n) +func vectorOfCoOwningReferencesLength*(self: Monster): int = + let o = self.tab.Offset(84) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfCoOwningReferences*(self: Monster, j: int): uint64 = + let o = self.tab.Offset(84) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return Get[uint64](self.tab, x) +func vectorOfCoOwningReferences*(self: Monster): seq[uint64] = + let len = self.vectorOfCoOwningReferencesLength + for i in countup(0, len - 1): + result.add(self.vectorOfCoOwningReferences(i)) +func nonOwningReference*(self: Monster): uint64 = + let o = self.tab.Offset(86) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `nonOwningReference=`*(self: var Monster, n: uint64): bool = + return self.tab.MutateSlot(86, n) +func vectorOfNonOwningReferencesLength*(self: Monster): int = + let o = self.tab.Offset(88) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfNonOwningReferences*(self: Monster, j: int): uint64 = + let o = self.tab.Offset(88) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return Get[uint64](self.tab, x) +func vectorOfNonOwningReferences*(self: Monster): seq[uint64] = + let len = self.vectorOfNonOwningReferencesLength + for i in countup(0, len - 1): + result.add(self.vectorOfNonOwningReferences(i)) +func anyUniqueType*(self: Monster): MyGame_Example_AnyUniqueAliases.AnyUniqueAliases = + let o = self.tab.Offset(90) + if o != 0: + return MyGame_Example_AnyUniqueAliases.AnyUniqueAliases(Get[uint8](self.tab, self.tab.Pos + o)) + return type(result)(0) +func `anyUniqueType=`*(self: var Monster, n: MyGame_Example_AnyUniqueAliases.AnyUniqueAliases): bool = + return self.tab.MutateSlot(90, n) +func anyUnique*(self: Monster): Option[Vtable] = + let o = self.tab.Offset(92) + if o != 0: + return some(self.tab.Union(o)) +func anyAmbiguousType*(self: Monster): MyGame_Example_AnyAmbiguousAliases.AnyAmbiguousAliases = + let o = self.tab.Offset(94) + if o != 0: + return MyGame_Example_AnyAmbiguousAliases.AnyAmbiguousAliases(Get[uint8](self.tab, self.tab.Pos + o)) + return type(result)(0) +func `anyAmbiguousType=`*(self: var Monster, n: MyGame_Example_AnyAmbiguousAliases.AnyAmbiguousAliases): bool = + return self.tab.MutateSlot(94, n) +func anyAmbiguous*(self: Monster): Option[Vtable] = + let o = self.tab.Offset(96) + if o != 0: + return some(self.tab.Union(o)) +func vectorOfEnumsLength*(self: Monster): int = + let o = self.tab.Offset(98) + if o != 0: + return self.tab.VectorLen(o) +func vectorOfEnums*(self: Monster, j: int): MyGame_Example_Color.Color = + let o = self.tab.Offset(98) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return MyGame_Example_Color.Color(Get[uint8](self.tab, x)) +func vectorOfEnums*(self: Monster): seq[MyGame_Example_Color.Color] = + let len = self.vectorOfEnumsLength + for i in countup(0, len - 1): + result.add(self.vectorOfEnums(i)) +func signedEnum*(self: Monster): MyGame_Example_Race.Race = + let o = self.tab.Offset(100) + if o != 0: + return MyGame_Example_Race.Race(Get[int8](self.tab, self.tab.Pos + o)) + return type(result)(-1) +func `signedEnum=`*(self: var Monster, n: MyGame_Example_Race.Race): bool = + return self.tab.MutateSlot(100, n) +func testrequirednestedflatbufferLength*(self: Monster): int = + let o = self.tab.Offset(102) + if o != 0: + return self.tab.VectorLen(o) +func testrequirednestedflatbuffer*(self: Monster, j: int): uint8 = + let o = self.tab.Offset(102) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[uint8](self.tab, x) +func testrequirednestedflatbuffer*(self: Monster): seq[uint8] = + let len = self.testrequirednestedflatbufferLength + for i in countup(0, len - 1): + result.add(self.testrequirednestedflatbuffer(i)) +func scalarKeySortedTablesLength*(self: Monster): int = + let o = self.tab.Offset(104) + if o != 0: + return self.tab.VectorLen(o) +func scalarKeySortedTables*(self: Monster, j: int): MyGame_Example_Stat.Stat = + let o = self.tab.Offset(104) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 4.uoffset + return MyGame_Example_Stat.Stat(tab: Vtable(Bytes: self.tab.Bytes, Pos: x)) +func scalarKeySortedTables*(self: Monster): seq[MyGame_Example_Stat.Stat] = + let len = self.scalarKeySortedTablesLength + for i in countup(0, len - 1): + result.add(self.scalarKeySortedTables(i)) +func nativeInline*(self: Monster): Option[MyGame_Example_Test.Test] = + let o = self.tab.Offset(106) + if o != 0: + return some(MyGame_Example_Test.Test(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +func longEnumNonEnumDefault*(self: Monster): MyGame_Example_LongEnum.LongEnum = + let o = self.tab.Offset(108) + if o != 0: + return MyGame_Example_LongEnum.LongEnum(Get[uint64](self.tab, self.tab.Pos + o)) + return type(result)(0) +func `longEnumNonEnumDefault=`*(self: var Monster, n: MyGame_Example_LongEnum.LongEnum): bool = + return self.tab.MutateSlot(108, n) +func longEnumNormalDefault*(self: Monster): MyGame_Example_LongEnum.LongEnum = + let o = self.tab.Offset(110) + if o != 0: + return MyGame_Example_LongEnum.LongEnum(Get[uint64](self.tab, self.tab.Pos + o)) + return type(result)(2) +func `longEnumNormalDefault=`*(self: var Monster, n: MyGame_Example_LongEnum.LongEnum): bool = + return self.tab.MutateSlot(110, n) +func nanDefault*(self: Monster): float32 = + let o = self.tab.Offset(112) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return NaN +func `nanDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(112, n) +func infDefault*(self: Monster): float32 = + let o = self.tab.Offset(114) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return Inf +func `infDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(114, n) +func positiveInfDefault*(self: Monster): float32 = + let o = self.tab.Offset(116) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return Inf +func `positiveInfDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(116, n) +func infinityDefault*(self: Monster): float32 = + let o = self.tab.Offset(118) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return Inf +func `infinityDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(118, n) +func positiveInfinityDefault*(self: Monster): float32 = + let o = self.tab.Offset(120) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return Inf +func `positiveInfinityDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(120, n) +func negativeInfDefault*(self: Monster): float32 = + let o = self.tab.Offset(122) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return -Inf +func `negativeInfDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(122, n) +func negativeInfinityDefault*(self: Monster): float32 = + let o = self.tab.Offset(124) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return -Inf +func `negativeInfinityDefault=`*(self: var Monster, n: float32): bool = + return self.tab.MutateSlot(124, n) +func doubleInfDefault*(self: Monster): float64 = + let o = self.tab.Offset(126) + if o != 0: + return Get[float64](self.tab, self.tab.Pos + o) + return Inf +func `doubleInfDefault=`*(self: var Monster, n: float64): bool = + return self.tab.MutateSlot(126, n) +proc MonsterStart*(builder: var Builder) = + builder.StartObject(62) +proc MonsterAddpos*(builder: var Builder, pos: uoffset) = + builder.PrependStructSlot(0, pos, default(uoffset)) +proc MonsterAddmana*(builder: var Builder, mana: int16) = + builder.PrependSlot(1, mana, default(int16)) +proc MonsterAddhp*(builder: var Builder, hp: int16) = + builder.PrependSlot(2, hp, default(int16)) +proc MonsterAddname*(builder: var Builder, name: uoffset) = + builder.PrependSlot(3, name, default(uoffset)) +proc MonsterAddinventory*(builder: var Builder, inventory: uoffset) = + builder.PrependSlot(5, inventory, default(uoffset)) +proc MonsterStartinventoryVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MonsterAddcolor*(builder: var Builder, color: uint8) = + builder.PrependSlot(6, color, default(uint8)) +proc MonsterAddtestType*(builder: var Builder, testType: uint8) = + builder.PrependSlot(7, testType, default(uint8)) +proc MonsterAddtest*(builder: var Builder, test: uoffset) = + builder.PrependSlot(8, test, default(uoffset)) +proc MonsterAddtest4*(builder: var Builder, test4: uoffset) = + builder.PrependSlot(9, test4, default(uoffset)) +proc MonsterStarttest4Vector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 2) +proc MonsterAddtestarrayofstring*(builder: var Builder, testarrayofstring: uoffset) = + builder.PrependSlot(10, testarrayofstring, default(uoffset)) +proc MonsterStarttestarrayofstringVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MonsterAddtestarrayoftables*(builder: var Builder, testarrayoftables: uoffset) = + builder.PrependSlot(11, testarrayoftables, default(uoffset)) +proc MonsterStarttestarrayoftablesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MonsterAddenemy*(builder: var Builder, enemy: uoffset) = + builder.PrependStructSlot(12, enemy, default(uoffset)) +proc MonsterAddtestnestedflatbuffer*(builder: var Builder, testnestedflatbuffer: uoffset) = + builder.PrependSlot(13, testnestedflatbuffer, default(uoffset)) +proc MonsterStarttestnestedflatbufferVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MonsterAddtestempty*(builder: var Builder, testempty: uoffset) = + builder.PrependStructSlot(14, testempty, default(uoffset)) +proc MonsterAddtestbool*(builder: var Builder, testbool: bool) = + builder.PrependSlot(15, testbool, default(bool)) +proc MonsterAddtesthashs32Fnv1*(builder: var Builder, testhashs32Fnv1: int32) = + builder.PrependSlot(16, testhashs32Fnv1, default(int32)) +proc MonsterAddtesthashu32Fnv1*(builder: var Builder, testhashu32Fnv1: uint32) = + builder.PrependSlot(17, testhashu32Fnv1, default(uint32)) +proc MonsterAddtesthashs64Fnv1*(builder: var Builder, testhashs64Fnv1: int64) = + builder.PrependSlot(18, testhashs64Fnv1, default(int64)) +proc MonsterAddtesthashu64Fnv1*(builder: var Builder, testhashu64Fnv1: uint64) = + builder.PrependSlot(19, testhashu64Fnv1, default(uint64)) +proc MonsterAddtesthashs32Fnv1a*(builder: var Builder, testhashs32Fnv1a: int32) = + builder.PrependSlot(20, testhashs32Fnv1a, default(int32)) +proc MonsterAddtesthashu32Fnv1a*(builder: var Builder, testhashu32Fnv1a: uint32) = + builder.PrependSlot(21, testhashu32Fnv1a, default(uint32)) +proc MonsterAddtesthashs64Fnv1a*(builder: var Builder, testhashs64Fnv1a: int64) = + builder.PrependSlot(22, testhashs64Fnv1a, default(int64)) +proc MonsterAddtesthashu64Fnv1a*(builder: var Builder, testhashu64Fnv1a: uint64) = + builder.PrependSlot(23, testhashu64Fnv1a, default(uint64)) +proc MonsterAddtestarrayofbools*(builder: var Builder, testarrayofbools: uoffset) = + builder.PrependSlot(24, testarrayofbools, default(uoffset)) +proc MonsterStarttestarrayofboolsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MonsterAddtestf*(builder: var Builder, testf: float32) = + builder.PrependSlot(25, testf, default(float32)) +proc MonsterAddtestf2*(builder: var Builder, testf2: float32) = + builder.PrependSlot(26, testf2, default(float32)) +proc MonsterAddtestf3*(builder: var Builder, testf3: float32) = + builder.PrependSlot(27, testf3, default(float32)) +proc MonsterAddtestarrayofstring2*(builder: var Builder, testarrayofstring2: uoffset) = + builder.PrependSlot(28, testarrayofstring2, default(uoffset)) +proc MonsterStarttestarrayofstring2Vector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MonsterAddtestarrayofsortedstruct*(builder: var Builder, testarrayofsortedstruct: uoffset) = + builder.PrependSlot(29, testarrayofsortedstruct, default(uoffset)) +proc MonsterStarttestarrayofsortedstructVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 4) +proc MonsterAddflex*(builder: var Builder, flex: uoffset) = + builder.PrependSlot(30, flex, default(uoffset)) +proc MonsterStartflexVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MonsterAddtest5*(builder: var Builder, test5: uoffset) = + builder.PrependSlot(31, test5, default(uoffset)) +proc MonsterStarttest5Vector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 2) +proc MonsterAddvectorOfLongs*(builder: var Builder, vectorOfLongs: uoffset) = + builder.PrependSlot(32, vectorOfLongs, default(uoffset)) +proc MonsterStartvectorOfLongsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 8) +proc MonsterAddvectorOfDoubles*(builder: var Builder, vectorOfDoubles: uoffset) = + builder.PrependSlot(33, vectorOfDoubles, default(uoffset)) +proc MonsterStartvectorOfDoublesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 8) +proc MonsterAddparentNamespaceTest*(builder: var Builder, parentNamespaceTest: uoffset) = + builder.PrependStructSlot(34, parentNamespaceTest, default(uoffset)) +proc MonsterAddvectorOfReferrables*(builder: var Builder, vectorOfReferrables: uoffset) = + builder.PrependSlot(35, vectorOfReferrables, default(uoffset)) +proc MonsterStartvectorOfReferrablesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MonsterAddsingleWeakReference*(builder: var Builder, singleWeakReference: uint64) = + builder.PrependSlot(36, singleWeakReference, default(uint64)) +proc MonsterAddvectorOfWeakReferences*(builder: var Builder, vectorOfWeakReferences: uoffset) = + builder.PrependSlot(37, vectorOfWeakReferences, default(uoffset)) +proc MonsterStartvectorOfWeakReferencesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 8) +proc MonsterAddvectorOfStrongReferrables*(builder: var Builder, vectorOfStrongReferrables: uoffset) = + builder.PrependSlot(38, vectorOfStrongReferrables, default(uoffset)) +proc MonsterStartvectorOfStrongReferrablesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MonsterAddcoOwningReference*(builder: var Builder, coOwningReference: uint64) = + builder.PrependSlot(39, coOwningReference, default(uint64)) +proc MonsterAddvectorOfCoOwningReferences*(builder: var Builder, vectorOfCoOwningReferences: uoffset) = + builder.PrependSlot(40, vectorOfCoOwningReferences, default(uoffset)) +proc MonsterStartvectorOfCoOwningReferencesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 8) +proc MonsterAddnonOwningReference*(builder: var Builder, nonOwningReference: uint64) = + builder.PrependSlot(41, nonOwningReference, default(uint64)) +proc MonsterAddvectorOfNonOwningReferences*(builder: var Builder, vectorOfNonOwningReferences: uoffset) = + builder.PrependSlot(42, vectorOfNonOwningReferences, default(uoffset)) +proc MonsterStartvectorOfNonOwningReferencesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 8) +proc MonsterAddanyUniqueType*(builder: var Builder, anyUniqueType: uint8) = + builder.PrependSlot(43, anyUniqueType, default(uint8)) +proc MonsterAddanyUnique*(builder: var Builder, anyUnique: uoffset) = + builder.PrependSlot(44, anyUnique, default(uoffset)) +proc MonsterAddanyAmbiguousType*(builder: var Builder, anyAmbiguousType: uint8) = + builder.PrependSlot(45, anyAmbiguousType, default(uint8)) +proc MonsterAddanyAmbiguous*(builder: var Builder, anyAmbiguous: uoffset) = + builder.PrependSlot(46, anyAmbiguous, default(uoffset)) +proc MonsterAddvectorOfEnums*(builder: var Builder, vectorOfEnums: uoffset) = + builder.PrependSlot(47, vectorOfEnums, default(uoffset)) +proc MonsterStartvectorOfEnumsVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MonsterAddsignedEnum*(builder: var Builder, signedEnum: int8) = + builder.PrependSlot(48, signedEnum, default(int8)) +proc MonsterAddtestrequirednestedflatbuffer*(builder: var Builder, testrequirednestedflatbuffer: uoffset) = + builder.PrependSlot(49, testrequirednestedflatbuffer, default(uoffset)) +proc MonsterStarttestrequirednestedflatbufferVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc MonsterAddscalarKeySortedTables*(builder: var Builder, scalarKeySortedTables: uoffset) = + builder.PrependSlot(50, scalarKeySortedTables, default(uoffset)) +proc MonsterStartscalarKeySortedTablesVector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(4, numElems, 4) +proc MonsterAddnativeInline*(builder: var Builder, nativeInline: uoffset) = + builder.PrependStructSlot(51, nativeInline, default(uoffset)) +proc MonsterAddlongEnumNonEnumDefault*(builder: var Builder, longEnumNonEnumDefault: uint64) = + builder.PrependSlot(52, longEnumNonEnumDefault, default(uint64)) +proc MonsterAddlongEnumNormalDefault*(builder: var Builder, longEnumNormalDefault: uint64) = + builder.PrependSlot(53, longEnumNormalDefault, default(uint64)) +proc MonsterAddnanDefault*(builder: var Builder, nanDefault: float32) = + builder.PrependSlot(54, nanDefault, default(float32)) +proc MonsterAddinfDefault*(builder: var Builder, infDefault: float32) = + builder.PrependSlot(55, infDefault, default(float32)) +proc MonsterAddpositiveInfDefault*(builder: var Builder, positiveInfDefault: float32) = + builder.PrependSlot(56, positiveInfDefault, default(float32)) +proc MonsterAddinfinityDefault*(builder: var Builder, infinityDefault: float32) = + builder.PrependSlot(57, infinityDefault, default(float32)) +proc MonsterAddpositiveInfinityDefault*(builder: var Builder, positiveInfinityDefault: float32) = + builder.PrependSlot(58, positiveInfinityDefault, default(float32)) +proc MonsterAddnegativeInfDefault*(builder: var Builder, negativeInfDefault: float32) = + builder.PrependSlot(59, negativeInfDefault, default(float32)) +proc MonsterAddnegativeInfinityDefault*(builder: var Builder, negativeInfinityDefault: float32) = + builder.PrependSlot(60, negativeInfinityDefault, default(float32)) +proc MonsterAdddoubleInfDefault*(builder: var Builder, doubleInfDefault: float64) = + builder.PrependSlot(61, doubleInfDefault, default(float64)) +proc MonsterEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.php b/third_party/flatbuffers/tests/MyGame/Example/Monster.php new file mode 100644 index 00000000000..446494030af --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.php @@ -0,0 +1,2001 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function MonsterIdentifier() + { + return "MONS"; + } + + public static function MonsterBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::MonsterIdentifier()); + } + + public static function MonsterExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Monster + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + public function getPos() + { + $obj = new Vec3(); + $o = $this->__offset(4); + return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : 0; + } + + /** + * @return short + */ + public function getMana() + { + $o = $this->__offset(6); + return $o != 0 ? $this->bb->getShort($o + $this->bb_pos) : 150; + } + + /** + * @return short + */ + public function getHp() + { + $o = $this->__offset(8); + return $o != 0 ? $this->bb->getShort($o + $this->bb_pos) : 100; + } + + public function getName() + { + $o = $this->__offset(10); + return $o != 0 ? $this->__string($o + $this->bb_pos) : null; + } + + /** + * @param int offset + * @return byte + */ + public function getInventory($j) + { + $o = $this->__offset(14); + return $o != 0 ? $this->bb->getByte($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getInventoryLength() + { + $o = $this->__offset(14); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return string + */ + public function getInventoryBytes() + { + return $this->__vector_as_bytes(14); + } + + /** + * @return byte + */ + public function getColor() + { + $o = $this->__offset(16); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \MyGame\Example\Color::Blue; + } + + /** + * @return byte + */ + public function getTestType() + { + $o = $this->__offset(18); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \MyGame\Example\Any::NONE; + } + + /** + * @returnint + */ + public function getTest($obj) + { + $o = $this->__offset(20); + return $o != 0 ? $this->__union($obj, $o) : null; + } + + /** + * @returnVectorOffset + */ + public function getTest4($j) + { + $o = $this->__offset(22); + $obj = new Test(); + return $o != 0 ? $obj->init($this->__vector($o) + $j *4, $this->bb) : null; + } + + /** + * @return int + */ + public function getTest4Length() + { + $o = $this->__offset(22); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param int offset + * @return string + */ + public function getTestarrayofstring($j) + { + $o = $this->__offset(24); + return $o != 0 ? $this->__string($this->__vector($o) + $j * 4) : 0; + } + + /** + * @return int + */ + public function getTestarrayofstringLength() + { + $o = $this->__offset(24); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /// an example documentation comment: this will end up in the generated code + /// multiline too + /** + * @returnVectorOffset + */ + public function getTestarrayoftables($j) + { + $o = $this->__offset(26); + $obj = new Monster(); + return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null; + } + + /** + * @return int + */ + public function getTestarrayoftablesLength() + { + $o = $this->__offset(26); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + public function getEnemy() + { + $obj = new Monster(); + $o = $this->__offset(28); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @param int offset + * @return byte + */ + public function getTestnestedflatbuffer($j) + { + $o = $this->__offset(30); + return $o != 0 ? $this->bb->getByte($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getTestnestedflatbufferLength() + { + $o = $this->__offset(30); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return string + */ + public function getTestnestedflatbufferBytes() + { + return $this->__vector_as_bytes(30); + } + + public function getTestempty() + { + $obj = new Stat(); + $o = $this->__offset(32); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @return bool + */ + public function getTestbool() + { + $o = $this->__offset(34); + return $o != 0 ? $this->bb->getBool($o + $this->bb_pos) : false; + } + + /** + * @return int + */ + public function getTesthashs32Fnv1() + { + $o = $this->__offset(36); + return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0; + } + + /** + * @return uint + */ + public function getTesthashu32Fnv1() + { + $o = $this->__offset(38); + return $o != 0 ? $this->bb->getUint($o + $this->bb_pos) : 0; + } + + /** + * @return long + */ + public function getTesthashs64Fnv1() + { + $o = $this->__offset(40); + return $o != 0 ? $this->bb->getLong($o + $this->bb_pos) : 0; + } + + /** + * @return ulong + */ + public function getTesthashu64Fnv1() + { + $o = $this->__offset(42); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @return int + */ + public function getTesthashs32Fnv1a() + { + $o = $this->__offset(44); + return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0; + } + + /** + * @return uint + */ + public function getTesthashu32Fnv1a() + { + $o = $this->__offset(46); + return $o != 0 ? $this->bb->getUint($o + $this->bb_pos) : 0; + } + + /** + * @return long + */ + public function getTesthashs64Fnv1a() + { + $o = $this->__offset(48); + return $o != 0 ? $this->bb->getLong($o + $this->bb_pos) : 0; + } + + /** + * @return ulong + */ + public function getTesthashu64Fnv1a() + { + $o = $this->__offset(50); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @param int offset + * @return bool + */ + public function getTestarrayofbools($j) + { + $o = $this->__offset(52); + return $o != 0 ? $this->bb->getBool($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getTestarrayofboolsLength() + { + $o = $this->__offset(52); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return float + */ + public function getTestf() + { + $o = $this->__offset(54); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : 3.14159; + } + + /** + * @return float + */ + public function getTestf2() + { + $o = $this->__offset(56); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : 3.0; + } + + /** + * @return float + */ + public function getTestf3() + { + $o = $this->__offset(58); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : 0.0; + } + + /** + * @param int offset + * @return string + */ + public function getTestarrayofstring2($j) + { + $o = $this->__offset(60); + return $o != 0 ? $this->__string($this->__vector($o) + $j * 4) : 0; + } + + /** + * @return int + */ + public function getTestarrayofstring2Length() + { + $o = $this->__offset(60); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @returnVectorOffset + */ + public function getTestarrayofsortedstruct($j) + { + $o = $this->__offset(62); + $obj = new Ability(); + return $o != 0 ? $obj->init($this->__vector($o) + $j *8, $this->bb) : null; + } + + /** + * @return int + */ + public function getTestarrayofsortedstructLength() + { + $o = $this->__offset(62); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param int offset + * @return byte + */ + public function getFlex($j) + { + $o = $this->__offset(64); + return $o != 0 ? $this->bb->getByte($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getFlexLength() + { + $o = $this->__offset(64); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return string + */ + public function getFlexBytes() + { + return $this->__vector_as_bytes(64); + } + + /** + * @returnVectorOffset + */ + public function getTest5($j) + { + $o = $this->__offset(66); + $obj = new Test(); + return $o != 0 ? $obj->init($this->__vector($o) + $j *4, $this->bb) : null; + } + + /** + * @return int + */ + public function getTest5Length() + { + $o = $this->__offset(66); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param int offset + * @return long + */ + public function getVectorOfLongs($j) + { + $o = $this->__offset(68); + return $o != 0 ? $this->bb->getLong($this->__vector($o) + $j * 8) : 0; + } + + /** + * @return int + */ + public function getVectorOfLongsLength() + { + $o = $this->__offset(68); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param int offset + * @return double + */ + public function getVectorOfDoubles($j) + { + $o = $this->__offset(70); + return $o != 0 ? $this->bb->getDouble($this->__vector($o) + $j * 8) : 0; + } + + /** + * @return int + */ + public function getVectorOfDoublesLength() + { + $o = $this->__offset(70); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + public function getParentNamespaceTest() + { + $obj = new InParentNamespace(); + $o = $this->__offset(72); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @returnVectorOffset + */ + public function getVectorOfReferrables($j) + { + $o = $this->__offset(74); + $obj = new Referrable(); + return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null; + } + + /** + * @return int + */ + public function getVectorOfReferrablesLength() + { + $o = $this->__offset(74); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return ulong + */ + public function getSingleWeakReference() + { + $o = $this->__offset(76); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @param int offset + * @return ulong + */ + public function getVectorOfWeakReferences($j) + { + $o = $this->__offset(78); + return $o != 0 ? $this->bb->getUlong($this->__vector($o) + $j * 8) : 0; + } + + /** + * @return int + */ + public function getVectorOfWeakReferencesLength() + { + $o = $this->__offset(78); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @returnVectorOffset + */ + public function getVectorOfStrongReferrables($j) + { + $o = $this->__offset(80); + $obj = new Referrable(); + return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null; + } + + /** + * @return int + */ + public function getVectorOfStrongReferrablesLength() + { + $o = $this->__offset(80); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return ulong + */ + public function getCoOwningReference() + { + $o = $this->__offset(82); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @param int offset + * @return ulong + */ + public function getVectorOfCoOwningReferences($j) + { + $o = $this->__offset(84); + return $o != 0 ? $this->bb->getUlong($this->__vector($o) + $j * 8) : 0; + } + + /** + * @return int + */ + public function getVectorOfCoOwningReferencesLength() + { + $o = $this->__offset(84); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return ulong + */ + public function getNonOwningReference() + { + $o = $this->__offset(86); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @param int offset + * @return ulong + */ + public function getVectorOfNonOwningReferences($j) + { + $o = $this->__offset(88); + return $o != 0 ? $this->bb->getUlong($this->__vector($o) + $j * 8) : 0; + } + + /** + * @return int + */ + public function getVectorOfNonOwningReferencesLength() + { + $o = $this->__offset(88); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return byte + */ + public function getAnyUniqueType() + { + $o = $this->__offset(90); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \MyGame\Example\AnyUniqueAliases::NONE; + } + + /** + * @returnint + */ + public function getAnyUnique($obj) + { + $o = $this->__offset(92); + return $o != 0 ? $this->__union($obj, $o) : null; + } + + /** + * @return byte + */ + public function getAnyAmbiguousType() + { + $o = $this->__offset(94); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \MyGame\Example\AnyAmbiguousAliases::NONE; + } + + /** + * @returnint + */ + public function getAnyAmbiguous($obj) + { + $o = $this->__offset(96); + return $o != 0 ? $this->__union($obj, $o) : null; + } + + /** + * @param int offset + * @return byte + */ + public function getVectorOfEnums($j) + { + $o = $this->__offset(98); + return $o != 0 ? $this->bb->getByte($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getVectorOfEnumsLength() + { + $o = $this->__offset(98); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return string + */ + public function getVectorOfEnumsBytes() + { + return $this->__vector_as_bytes(98); + } + + /** + * @return sbyte + */ + public function getSignedEnum() + { + $o = $this->__offset(100); + return $o != 0 ? $this->bb->getSbyte($o + $this->bb_pos) : \MyGame\Example\Race::None; + } + + /** + * @param int offset + * @return byte + */ + public function getTestrequirednestedflatbuffer($j) + { + $o = $this->__offset(102); + return $o != 0 ? $this->bb->getByte($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getTestrequirednestedflatbufferLength() + { + $o = $this->__offset(102); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @return string + */ + public function getTestrequirednestedflatbufferBytes() + { + return $this->__vector_as_bytes(102); + } + + /** + * @returnVectorOffset + */ + public function getScalarKeySortedTables($j) + { + $o = $this->__offset(104); + $obj = new Stat(); + return $o != 0 ? $obj->init($this->__indirect($this->__vector($o) + $j * 4), $this->bb) : null; + } + + /** + * @return int + */ + public function getScalarKeySortedTablesLength() + { + $o = $this->__offset(104); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + public function getNativeInline() + { + $obj = new Test(); + $o = $this->__offset(106); + return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : 0; + } + + /** + * @return ulong + */ + public function getLongEnumNonEnumDefault() + { + $o = $this->__offset(108); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @return ulong + */ + public function getLongEnumNormalDefault() + { + $o = $this->__offset(110); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : \MyGame\Example\LongEnum::LongOne; + } + + /** + * @return float + */ + public function getNanDefault() + { + $o = $this->__offset(112); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : nan; + } + + /** + * @return float + */ + public function getInfDefault() + { + $o = $this->__offset(114); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : inf; + } + + /** + * @return float + */ + public function getPositiveInfDefault() + { + $o = $this->__offset(116); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : +inf; + } + + /** + * @return float + */ + public function getInfinityDefault() + { + $o = $this->__offset(118); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : infinity; + } + + /** + * @return float + */ + public function getPositiveInfinityDefault() + { + $o = $this->__offset(120); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : +infinity; + } + + /** + * @return float + */ + public function getNegativeInfDefault() + { + $o = $this->__offset(122); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : -inf; + } + + /** + * @return float + */ + public function getNegativeInfinityDefault() + { + $o = $this->__offset(124); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : -infinity; + } + + /** + * @return double + */ + public function getDoubleInfDefault() + { + $o = $this->__offset(126); + return $o != 0 ? $this->bb->getDouble($o + $this->bb_pos) : inf; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startMonster(FlatBufferBuilder $builder) + { + $builder->StartObject(62); + } + + /** + * @param FlatBufferBuilder $builder + * @return Monster + */ + public static function createMonster(FlatBufferBuilder $builder, $pos, $mana, $hp, $name, $inventory, $color, $test_type, $test, $test4, $testarrayofstring, $testarrayoftables, $enemy, $testnestedflatbuffer, $testempty, $testbool, $testhashs32_fnv1, $testhashu32_fnv1, $testhashs64_fnv1, $testhashu64_fnv1, $testhashs32_fnv1a, $testhashu32_fnv1a, $testhashs64_fnv1a, $testhashu64_fnv1a, $testarrayofbools, $testf, $testf2, $testf3, $testarrayofstring2, $testarrayofsortedstruct, $flex, $test5, $vector_of_longs, $vector_of_doubles, $parent_namespace_test, $vector_of_referrables, $single_weak_reference, $vector_of_weak_references, $vector_of_strong_referrables, $co_owning_reference, $vector_of_co_owning_references, $non_owning_reference, $vector_of_non_owning_references, $any_unique_type, $any_unique, $any_ambiguous_type, $any_ambiguous, $vector_of_enums, $signed_enum, $testrequirednestedflatbuffer, $scalar_key_sorted_tables, $native_inline, $long_enum_non_enum_default, $long_enum_normal_default, $nan_default, $inf_default, $positive_inf_default, $infinity_default, $positive_infinity_default, $negative_inf_default, $negative_infinity_default, $double_inf_default) + { + $builder->startObject(62); + self::addPos($builder, $pos); + self::addMana($builder, $mana); + self::addHp($builder, $hp); + self::addName($builder, $name); + self::addInventory($builder, $inventory); + self::addColor($builder, $color); + self::addTestType($builder, $test_type); + self::addTest($builder, $test); + self::addTest4($builder, $test4); + self::addTestarrayofstring($builder, $testarrayofstring); + self::addTestarrayoftables($builder, $testarrayoftables); + self::addEnemy($builder, $enemy); + self::addTestnestedflatbuffer($builder, $testnestedflatbuffer); + self::addTestempty($builder, $testempty); + self::addTestbool($builder, $testbool); + self::addTesthashs32Fnv1($builder, $testhashs32_fnv1); + self::addTesthashu32Fnv1($builder, $testhashu32_fnv1); + self::addTesthashs64Fnv1($builder, $testhashs64_fnv1); + self::addTesthashu64Fnv1($builder, $testhashu64_fnv1); + self::addTesthashs32Fnv1a($builder, $testhashs32_fnv1a); + self::addTesthashu32Fnv1a($builder, $testhashu32_fnv1a); + self::addTesthashs64Fnv1a($builder, $testhashs64_fnv1a); + self::addTesthashu64Fnv1a($builder, $testhashu64_fnv1a); + self::addTestarrayofbools($builder, $testarrayofbools); + self::addTestf($builder, $testf); + self::addTestf2($builder, $testf2); + self::addTestf3($builder, $testf3); + self::addTestarrayofstring2($builder, $testarrayofstring2); + self::addTestarrayofsortedstruct($builder, $testarrayofsortedstruct); + self::addFlex($builder, $flex); + self::addTest5($builder, $test5); + self::addVectorOfLongs($builder, $vector_of_longs); + self::addVectorOfDoubles($builder, $vector_of_doubles); + self::addParentNamespaceTest($builder, $parent_namespace_test); + self::addVectorOfReferrables($builder, $vector_of_referrables); + self::addSingleWeakReference($builder, $single_weak_reference); + self::addVectorOfWeakReferences($builder, $vector_of_weak_references); + self::addVectorOfStrongReferrables($builder, $vector_of_strong_referrables); + self::addCoOwningReference($builder, $co_owning_reference); + self::addVectorOfCoOwningReferences($builder, $vector_of_co_owning_references); + self::addNonOwningReference($builder, $non_owning_reference); + self::addVectorOfNonOwningReferences($builder, $vector_of_non_owning_references); + self::addAnyUniqueType($builder, $any_unique_type); + self::addAnyUnique($builder, $any_unique); + self::addAnyAmbiguousType($builder, $any_ambiguous_type); + self::addAnyAmbiguous($builder, $any_ambiguous); + self::addVectorOfEnums($builder, $vector_of_enums); + self::addSignedEnum($builder, $signed_enum); + self::addTestrequirednestedflatbuffer($builder, $testrequirednestedflatbuffer); + self::addScalarKeySortedTables($builder, $scalar_key_sorted_tables); + self::addNativeInline($builder, $native_inline); + self::addLongEnumNonEnumDefault($builder, $long_enum_non_enum_default); + self::addLongEnumNormalDefault($builder, $long_enum_normal_default); + self::addNanDefault($builder, $nan_default); + self::addInfDefault($builder, $inf_default); + self::addPositiveInfDefault($builder, $positive_inf_default); + self::addInfinityDefault($builder, $infinity_default); + self::addPositiveInfinityDefault($builder, $positive_infinity_default); + self::addNegativeInfDefault($builder, $negative_inf_default); + self::addNegativeInfinityDefault($builder, $negative_infinity_default); + self::addDoubleInfDefault($builder, $double_inf_default); + $o = $builder->endObject(); + $builder->required($o, 10); // name + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addPos(FlatBufferBuilder $builder, $pos) + { + $builder->addStructX(0, $pos, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param short + * @return void + */ + public static function addMana(FlatBufferBuilder $builder, $mana) + { + $builder->addShortX(1, $mana, 150); + } + + /** + * @param FlatBufferBuilder $builder + * @param short + * @return void + */ + public static function addHp(FlatBufferBuilder $builder, $hp) + { + $builder->addShortX(2, $hp, 100); + } + + /** + * @param FlatBufferBuilder $builder + * @param StringOffset + * @return void + */ + public static function addName(FlatBufferBuilder $builder, $name) + { + $builder->addOffsetX(3, $name, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addInventory(FlatBufferBuilder $builder, $inventory) + { + $builder->addOffsetX(5, $inventory, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createInventoryVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putByte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startInventoryVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addColor(FlatBufferBuilder $builder, $color) + { + $builder->addByteX(6, $color, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addTestType(FlatBufferBuilder $builder, $testType) + { + $builder->addByteX(7, $testType, 0); + } + + public static function addTest(FlatBufferBuilder $builder, $offset) + { + $builder->addOffsetX(8, $offset, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTest4(FlatBufferBuilder $builder, $test4) + { + $builder->addOffsetX(9, $test4, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTest4Vector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 2); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTest4Vector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 2); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestarrayofstring(FlatBufferBuilder $builder, $testarrayofstring) + { + $builder->addOffsetX(10, $testarrayofstring, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestarrayofstringVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestarrayofstringVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestarrayoftables(FlatBufferBuilder $builder, $testarrayoftables) + { + $builder->addOffsetX(11, $testarrayoftables, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestarrayoftablesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestarrayoftablesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addEnemy(FlatBufferBuilder $builder, $enemy) + { + $builder->addOffsetX(12, $enemy, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestnestedflatbuffer(FlatBufferBuilder $builder, $testnestedflatbuffer) + { + $builder->addOffsetX(13, $testnestedflatbuffer, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestnestedflatbufferVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putByte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestnestedflatbufferVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestempty(FlatBufferBuilder $builder, $testempty) + { + $builder->addOffsetX(14, $testempty, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param bool + * @return void + */ + public static function addTestbool(FlatBufferBuilder $builder, $testbool) + { + $builder->addBoolX(15, $testbool, false); + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addTesthashs32Fnv1(FlatBufferBuilder $builder, $testhashs32Fnv1) + { + $builder->addIntX(16, $testhashs32Fnv1, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param uint + * @return void + */ + public static function addTesthashu32Fnv1(FlatBufferBuilder $builder, $testhashu32Fnv1) + { + $builder->addUintX(17, $testhashu32Fnv1, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param long + * @return void + */ + public static function addTesthashs64Fnv1(FlatBufferBuilder $builder, $testhashs64Fnv1) + { + $builder->addLongX(18, $testhashs64Fnv1, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addTesthashu64Fnv1(FlatBufferBuilder $builder, $testhashu64Fnv1) + { + $builder->addUlongX(19, $testhashu64Fnv1, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addTesthashs32Fnv1a(FlatBufferBuilder $builder, $testhashs32Fnv1a) + { + $builder->addIntX(20, $testhashs32Fnv1a, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param uint + * @return void + */ + public static function addTesthashu32Fnv1a(FlatBufferBuilder $builder, $testhashu32Fnv1a) + { + $builder->addUintX(21, $testhashu32Fnv1a, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param long + * @return void + */ + public static function addTesthashs64Fnv1a(FlatBufferBuilder $builder, $testhashs64Fnv1a) + { + $builder->addLongX(22, $testhashs64Fnv1a, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addTesthashu64Fnv1a(FlatBufferBuilder $builder, $testhashu64Fnv1a) + { + $builder->addUlongX(23, $testhashu64Fnv1a, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestarrayofbools(FlatBufferBuilder $builder, $testarrayofbools) + { + $builder->addOffsetX(24, $testarrayofbools, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestarrayofboolsVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putBool($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestarrayofboolsVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addTestf(FlatBufferBuilder $builder, $testf) + { + $builder->addFloatX(25, $testf, 3.14159); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addTestf2(FlatBufferBuilder $builder, $testf2) + { + $builder->addFloatX(26, $testf2, 3.0); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addTestf3(FlatBufferBuilder $builder, $testf3) + { + $builder->addFloatX(27, $testf3, 0.0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestarrayofstring2(FlatBufferBuilder $builder, $testarrayofstring2) + { + $builder->addOffsetX(28, $testarrayofstring2, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestarrayofstring2Vector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestarrayofstring2Vector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestarrayofsortedstruct(FlatBufferBuilder $builder, $testarrayofsortedstruct) + { + $builder->addOffsetX(29, $testarrayofsortedstruct, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestarrayofsortedstructVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestarrayofsortedstructVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addFlex(FlatBufferBuilder $builder, $flex) + { + $builder->addOffsetX(30, $flex, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createFlexVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putByte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startFlexVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTest5(FlatBufferBuilder $builder, $test5) + { + $builder->addOffsetX(31, $test5, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTest5Vector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 2); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTest5Vector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 2); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfLongs(FlatBufferBuilder $builder, $vectorOfLongs) + { + $builder->addOffsetX(32, $vectorOfLongs, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfLongsVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 8); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putLong($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfLongsVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfDoubles(FlatBufferBuilder $builder, $vectorOfDoubles) + { + $builder->addOffsetX(33, $vectorOfDoubles, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfDoublesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 8); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putDouble($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfDoublesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addParentNamespaceTest(FlatBufferBuilder $builder, $parentNamespaceTest) + { + $builder->addOffsetX(34, $parentNamespaceTest, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfReferrables(FlatBufferBuilder $builder, $vectorOfReferrables) + { + $builder->addOffsetX(35, $vectorOfReferrables, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfReferrablesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfReferrablesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addSingleWeakReference(FlatBufferBuilder $builder, $singleWeakReference) + { + $builder->addUlongX(36, $singleWeakReference, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfWeakReferences(FlatBufferBuilder $builder, $vectorOfWeakReferences) + { + $builder->addOffsetX(37, $vectorOfWeakReferences, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfWeakReferencesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 8); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putUlong($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfWeakReferencesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfStrongReferrables(FlatBufferBuilder $builder, $vectorOfStrongReferrables) + { + $builder->addOffsetX(38, $vectorOfStrongReferrables, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfStrongReferrablesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfStrongReferrablesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addCoOwningReference(FlatBufferBuilder $builder, $coOwningReference) + { + $builder->addUlongX(39, $coOwningReference, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfCoOwningReferences(FlatBufferBuilder $builder, $vectorOfCoOwningReferences) + { + $builder->addOffsetX(40, $vectorOfCoOwningReferences, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfCoOwningReferencesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 8); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putUlong($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfCoOwningReferencesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addNonOwningReference(FlatBufferBuilder $builder, $nonOwningReference) + { + $builder->addUlongX(41, $nonOwningReference, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfNonOwningReferences(FlatBufferBuilder $builder, $vectorOfNonOwningReferences) + { + $builder->addOffsetX(42, $vectorOfNonOwningReferences, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfNonOwningReferencesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 8); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putUlong($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfNonOwningReferencesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addAnyUniqueType(FlatBufferBuilder $builder, $anyUniqueType) + { + $builder->addByteX(43, $anyUniqueType, 0); + } + + public static function addAnyUnique(FlatBufferBuilder $builder, $offset) + { + $builder->addOffsetX(44, $offset, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addAnyAmbiguousType(FlatBufferBuilder $builder, $anyAmbiguousType) + { + $builder->addByteX(45, $anyAmbiguousType, 0); + } + + public static function addAnyAmbiguous(FlatBufferBuilder $builder, $offset) + { + $builder->addOffsetX(46, $offset, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVectorOfEnums(FlatBufferBuilder $builder, $vectorOfEnums) + { + $builder->addOffsetX(47, $vectorOfEnums, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVectorOfEnumsVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putByte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVectorOfEnumsVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param sbyte + * @return void + */ + public static function addSignedEnum(FlatBufferBuilder $builder, $signedEnum) + { + $builder->addSbyteX(48, $signedEnum, -1); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addTestrequirednestedflatbuffer(FlatBufferBuilder $builder, $testrequirednestedflatbuffer) + { + $builder->addOffsetX(49, $testrequirednestedflatbuffer, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createTestrequirednestedflatbufferVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putByte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startTestrequirednestedflatbufferVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addScalarKeySortedTables(FlatBufferBuilder $builder, $scalarKeySortedTables) + { + $builder->addOffsetX(50, $scalarKeySortedTables, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createScalarKeySortedTablesVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startScalarKeySortedTablesVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addNativeInline(FlatBufferBuilder $builder, $nativeInline) + { + $builder->addStructX(51, $nativeInline, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addLongEnumNonEnumDefault(FlatBufferBuilder $builder, $longEnumNonEnumDefault) + { + $builder->addUlongX(52, $longEnumNonEnumDefault, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addLongEnumNormalDefault(FlatBufferBuilder $builder, $longEnumNormalDefault) + { + $builder->addUlongX(53, $longEnumNormalDefault, 2); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addNanDefault(FlatBufferBuilder $builder, $nanDefault) + { + $builder->addFloatX(54, $nanDefault, nan); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addInfDefault(FlatBufferBuilder $builder, $infDefault) + { + $builder->addFloatX(55, $infDefault, inf); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addPositiveInfDefault(FlatBufferBuilder $builder, $positiveInfDefault) + { + $builder->addFloatX(56, $positiveInfDefault, +inf); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addInfinityDefault(FlatBufferBuilder $builder, $infinityDefault) + { + $builder->addFloatX(57, $infinityDefault, infinity); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addPositiveInfinityDefault(FlatBufferBuilder $builder, $positiveInfinityDefault) + { + $builder->addFloatX(58, $positiveInfinityDefault, +infinity); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addNegativeInfDefault(FlatBufferBuilder $builder, $negativeInfDefault) + { + $builder->addFloatX(59, $negativeInfDefault, -inf); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addNegativeInfinityDefault(FlatBufferBuilder $builder, $negativeInfinityDefault) + { + $builder->addFloatX(60, $negativeInfinityDefault, -infinity); + } + + /** + * @param FlatBufferBuilder $builder + * @param double + * @return void + */ + public static function addDoubleInfDefault(FlatBufferBuilder $builder, $doubleInfDefault) + { + $builder->addDoubleX(61, $doubleInfDefault, inf); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endMonster(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + $builder->required($o, 10); // name + return $o; + } + + public static function finishMonsterBuffer(FlatBufferBuilder $builder, $offset) + { + $builder->finish($offset, "MONS"); + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Monster.py b/third_party/flatbuffers/tests/MyGame/Example/Monster.py new file mode 100644 index 00000000000..9fb81446efc --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Monster.py @@ -0,0 +1,1939 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# an example documentation comment: "monster object" +class Monster(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Monster() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMonster(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Monster + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Monster + def Pos(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = o + self._tab.Pos + from MyGame.Example.Vec3 import Vec3 + obj = Vec3() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Mana(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 150 + + # Monster + def Hp(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 100 + + # Monster + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Monster + def Inventory(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def InventoryAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def InventoryLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def InventoryIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + + # Monster + def Color(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 8 + + # Monster + def TestType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Monster + def Test(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Monster + def Test4(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + from MyGame.Example.Test import Test + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Test4Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def Test4IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + + # Monster + def Testarrayofstring(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Monster + def TestarrayofstringLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayofstringIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # an example documentation comment: this will end up in the generated code + # multiline too + # Monster + def Testarrayoftables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from MyGame.Example.Monster import Monster + obj = Monster() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def TestarrayoftablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayoftablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + return o == 0 + + # Monster + def Enemy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from MyGame.Example.Monster import Monster + obj = Monster() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Testnestedflatbuffer(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def TestnestedflatbufferAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def TestnestedflatbufferNestedRoot(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + from MyGame.Example.Monster import Monster + return Monster.GetRootAs(self._tab.Bytes, self._tab.Vector(o)) + return 0 + + # Monster + def TestnestedflatbufferLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestnestedflatbufferIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + return o == 0 + + # Monster + def Testempty(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(32)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from MyGame.Example.Stat import Stat + obj = Stat() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Testbool(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(34)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # Monster + def Testhashs32Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu32Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(38)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashs64Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(40)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu64Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(42)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashs32Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(44)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu32Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(46)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashs64Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(48)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu64Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(50)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testarrayofbools(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.BoolFlags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def TestarrayofboolsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.BoolFlags, o) + return 0 + + # Monster + def TestarrayofboolsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayofboolsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + return o == 0 + + # Monster + def Testf(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(54)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 3.14159 + + # Monster + def Testf2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(56)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 3.0 + + # Monster + def Testf3(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(58)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # Monster + def Testarrayofstring2(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Monster + def Testarrayofstring2Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def Testarrayofstring2IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + return o == 0 + + # Monster + def Testarrayofsortedstruct(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 8 + from MyGame.Example.Ability import Ability + obj = Ability() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def TestarrayofsortedstructLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayofsortedstructIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + return o == 0 + + # Monster + def Flex(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def FlexAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def FlexLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def FlexIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + return o == 0 + + # Monster + def Test5(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + from MyGame.Example.Test import Test + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Test5Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def Test5IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + return o == 0 + + # Monster + def VectorOfLongs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfLongsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # Monster + def VectorOfLongsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfLongsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + return o == 0 + + # Monster + def VectorOfDoubles(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfDoublesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o) + return 0 + + # Monster + def VectorOfDoublesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfDoublesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + return o == 0 + + # Monster + def ParentNamespaceTest(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(72)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from MyGame.InParentNamespace import InParentNamespace + obj = InParentNamespace() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def VectorOfReferrables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from MyGame.Example.Referrable import Referrable + obj = Referrable() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def VectorOfReferrablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfReferrablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + return o == 0 + + # Monster + def SingleWeakReference(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(76)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def VectorOfWeakReferences(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfWeakReferencesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # Monster + def VectorOfWeakReferencesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfWeakReferencesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + return o == 0 + + # Monster + def VectorOfStrongReferrables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from MyGame.Example.Referrable import Referrable + obj = Referrable() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def VectorOfStrongReferrablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfStrongReferrablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80)) + return o == 0 + + # Monster + def CoOwningReference(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(82)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def VectorOfCoOwningReferences(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfCoOwningReferencesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # Monster + def VectorOfCoOwningReferencesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfCoOwningReferencesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + return o == 0 + + # Monster + def NonOwningReference(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(86)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def VectorOfNonOwningReferences(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfNonOwningReferencesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # Monster + def VectorOfNonOwningReferencesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfNonOwningReferencesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + return o == 0 + + # Monster + def AnyUniqueType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(90)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Monster + def AnyUnique(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(92)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Monster + def AnyAmbiguousType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(94)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Monster + def AnyAmbiguous(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(96)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Monster + def VectorOfEnums(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def VectorOfEnumsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def VectorOfEnumsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfEnumsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + return o == 0 + + # Monster + def SignedEnum(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(100)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return -1 + + # Monster + def Testrequirednestedflatbuffer(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def TestrequirednestedflatbufferAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def TestrequirednestedflatbufferNestedRoot(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + from MyGame.Example.Monster import Monster + return Monster.GetRootAs(self._tab.Bytes, self._tab.Vector(o)) + return 0 + + # Monster + def TestrequirednestedflatbufferLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestrequirednestedflatbufferIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + return o == 0 + + # Monster + def ScalarKeySortedTables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + from MyGame.Example.Stat import Stat + obj = Stat() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def ScalarKeySortedTablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def ScalarKeySortedTablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104)) + return o == 0 + + # Monster + def NativeInline(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(106)) + if o != 0: + x = o + self._tab.Pos + from MyGame.Example.Test import Test + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def LongEnumNonEnumDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(108)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def LongEnumNormalDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(110)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 2 + + # Monster + def NanDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(112)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('nan') + + # Monster + def InfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(114)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def PositiveInfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(116)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def InfinityDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(118)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def PositiveInfinityDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(120)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def NegativeInfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(122)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('-inf') + + # Monster + def NegativeInfinityDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(124)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('-inf') + + # Monster + def DoubleInfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(126)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return float('inf') + +def MonsterStart(builder): + builder.StartObject(62) + +def Start(builder): + MonsterStart(builder) + +def MonsterAddPos(builder, pos): + builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(pos), 0) + +def AddPos(builder, pos): + MonsterAddPos(builder, pos) + +def MonsterAddMana(builder, mana): + builder.PrependInt16Slot(1, mana, 150) + +def AddMana(builder, mana): + MonsterAddMana(builder, mana) + +def MonsterAddHp(builder, hp): + builder.PrependInt16Slot(2, hp, 100) + +def AddHp(builder, hp): + MonsterAddHp(builder, hp) + +def MonsterAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder, name): + MonsterAddName(builder, name) + +def MonsterAddInventory(builder, inventory): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(inventory), 0) + +def AddInventory(builder, inventory): + MonsterAddInventory(builder, inventory) + +def MonsterStartInventoryVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartInventoryVector(builder, numElems): + return MonsterStartInventoryVector(builder, numElems) + +def MonsterAddColor(builder, color): + builder.PrependUint8Slot(6, color, 8) + +def AddColor(builder, color): + MonsterAddColor(builder, color) + +def MonsterAddTestType(builder, testType): + builder.PrependUint8Slot(7, testType, 0) + +def AddTestType(builder, testType): + MonsterAddTestType(builder, testType) + +def MonsterAddTest(builder, test): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(test), 0) + +def AddTest(builder, test): + MonsterAddTest(builder, test) + +def MonsterAddTest4(builder, test4): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(test4), 0) + +def AddTest4(builder, test4): + MonsterAddTest4(builder, test4) + +def MonsterStartTest4Vector(builder, numElems): + return builder.StartVector(4, numElems, 2) + +def StartTest4Vector(builder, numElems): + return MonsterStartTest4Vector(builder, numElems) + +def MonsterAddTestarrayofstring(builder, testarrayofstring): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring), 0) + +def AddTestarrayofstring(builder, testarrayofstring): + MonsterAddTestarrayofstring(builder, testarrayofstring) + +def MonsterStartTestarrayofstringVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartTestarrayofstringVector(builder, numElems): + return MonsterStartTestarrayofstringVector(builder, numElems) + +def MonsterAddTestarrayoftables(builder, testarrayoftables): + builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayoftables), 0) + +def AddTestarrayoftables(builder, testarrayoftables): + MonsterAddTestarrayoftables(builder, testarrayoftables) + +def MonsterStartTestarrayoftablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartTestarrayoftablesVector(builder, numElems): + return MonsterStartTestarrayoftablesVector(builder, numElems) + +def MonsterAddEnemy(builder, enemy): + builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(enemy), 0) + +def AddEnemy(builder, enemy): + MonsterAddEnemy(builder, enemy) + +def MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer): + builder.PrependUOffsetTRelativeSlot(13, flatbuffers.number_types.UOffsetTFlags.py_type(testnestedflatbuffer), 0) + +def AddTestnestedflatbuffer(builder, testnestedflatbuffer): + MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer) + +def MonsterStartTestnestedflatbufferVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartTestnestedflatbufferVector(builder, numElems): + return MonsterStartTestnestedflatbufferVector(builder, numElems) + +def MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes): + builder.StartVector(1, len(bytes), 1) + builder.head = builder.head - len(bytes) + builder.Bytes[builder.head : builder.head + len(bytes)] = bytes + return builder.EndVector() +def MakeTestnestedflatbufferVectorFromBytes(builder, bytes): + return MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes) +def MonsterAddTestempty(builder, testempty): + builder.PrependUOffsetTRelativeSlot(14, flatbuffers.number_types.UOffsetTFlags.py_type(testempty), 0) + +def AddTestempty(builder, testempty): + MonsterAddTestempty(builder, testempty) + +def MonsterAddTestbool(builder, testbool): + builder.PrependBoolSlot(15, testbool, 0) + +def AddTestbool(builder, testbool): + MonsterAddTestbool(builder, testbool) + +def MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1): + builder.PrependInt32Slot(16, testhashs32Fnv1, 0) + +def AddTesthashs32Fnv1(builder, testhashs32Fnv1): + MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1) + +def MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1): + builder.PrependUint32Slot(17, testhashu32Fnv1, 0) + +def AddTesthashu32Fnv1(builder, testhashu32Fnv1): + MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1) + +def MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1): + builder.PrependInt64Slot(18, testhashs64Fnv1, 0) + +def AddTesthashs64Fnv1(builder, testhashs64Fnv1): + MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1) + +def MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1): + builder.PrependUint64Slot(19, testhashu64Fnv1, 0) + +def AddTesthashu64Fnv1(builder, testhashu64Fnv1): + MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1) + +def MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a): + builder.PrependInt32Slot(20, testhashs32Fnv1a, 0) + +def AddTesthashs32Fnv1a(builder, testhashs32Fnv1a): + MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a) + +def MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a): + builder.PrependUint32Slot(21, testhashu32Fnv1a, 0) + +def AddTesthashu32Fnv1a(builder, testhashu32Fnv1a): + MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a) + +def MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a): + builder.PrependInt64Slot(22, testhashs64Fnv1a, 0) + +def AddTesthashs64Fnv1a(builder, testhashs64Fnv1a): + MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a) + +def MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a): + builder.PrependUint64Slot(23, testhashu64Fnv1a, 0) + +def AddTesthashu64Fnv1a(builder, testhashu64Fnv1a): + MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a) + +def MonsterAddTestarrayofbools(builder, testarrayofbools): + builder.PrependUOffsetTRelativeSlot(24, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofbools), 0) + +def AddTestarrayofbools(builder, testarrayofbools): + MonsterAddTestarrayofbools(builder, testarrayofbools) + +def MonsterStartTestarrayofboolsVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartTestarrayofboolsVector(builder, numElems): + return MonsterStartTestarrayofboolsVector(builder, numElems) + +def MonsterAddTestf(builder, testf): + builder.PrependFloat32Slot(25, testf, 3.14159) + +def AddTestf(builder, testf): + MonsterAddTestf(builder, testf) + +def MonsterAddTestf2(builder, testf2): + builder.PrependFloat32Slot(26, testf2, 3.0) + +def AddTestf2(builder, testf2): + MonsterAddTestf2(builder, testf2) + +def MonsterAddTestf3(builder, testf3): + builder.PrependFloat32Slot(27, testf3, 0.0) + +def AddTestf3(builder, testf3): + MonsterAddTestf3(builder, testf3) + +def MonsterAddTestarrayofstring2(builder, testarrayofstring2): + builder.PrependUOffsetTRelativeSlot(28, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring2), 0) + +def AddTestarrayofstring2(builder, testarrayofstring2): + MonsterAddTestarrayofstring2(builder, testarrayofstring2) + +def MonsterStartTestarrayofstring2Vector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartTestarrayofstring2Vector(builder, numElems): + return MonsterStartTestarrayofstring2Vector(builder, numElems) + +def MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct): + builder.PrependUOffsetTRelativeSlot(29, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofsortedstruct), 0) + +def AddTestarrayofsortedstruct(builder, testarrayofsortedstruct): + MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct) + +def MonsterStartTestarrayofsortedstructVector(builder, numElems): + return builder.StartVector(8, numElems, 4) + +def StartTestarrayofsortedstructVector(builder, numElems): + return MonsterStartTestarrayofsortedstructVector(builder, numElems) + +def MonsterAddFlex(builder, flex): + builder.PrependUOffsetTRelativeSlot(30, flatbuffers.number_types.UOffsetTFlags.py_type(flex), 0) + +def AddFlex(builder, flex): + MonsterAddFlex(builder, flex) + +def MonsterStartFlexVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartFlexVector(builder, numElems): + return MonsterStartFlexVector(builder, numElems) + +def MonsterAddTest5(builder, test5): + builder.PrependUOffsetTRelativeSlot(31, flatbuffers.number_types.UOffsetTFlags.py_type(test5), 0) + +def AddTest5(builder, test5): + MonsterAddTest5(builder, test5) + +def MonsterStartTest5Vector(builder, numElems): + return builder.StartVector(4, numElems, 2) + +def StartTest5Vector(builder, numElems): + return MonsterStartTest5Vector(builder, numElems) + +def MonsterAddVectorOfLongs(builder, vectorOfLongs): + builder.PrependUOffsetTRelativeSlot(32, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfLongs), 0) + +def AddVectorOfLongs(builder, vectorOfLongs): + MonsterAddVectorOfLongs(builder, vectorOfLongs) + +def MonsterStartVectorOfLongsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartVectorOfLongsVector(builder, numElems): + return MonsterStartVectorOfLongsVector(builder, numElems) + +def MonsterAddVectorOfDoubles(builder, vectorOfDoubles): + builder.PrependUOffsetTRelativeSlot(33, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfDoubles), 0) + +def AddVectorOfDoubles(builder, vectorOfDoubles): + MonsterAddVectorOfDoubles(builder, vectorOfDoubles) + +def MonsterStartVectorOfDoublesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartVectorOfDoublesVector(builder, numElems): + return MonsterStartVectorOfDoublesVector(builder, numElems) + +def MonsterAddParentNamespaceTest(builder, parentNamespaceTest): + builder.PrependUOffsetTRelativeSlot(34, flatbuffers.number_types.UOffsetTFlags.py_type(parentNamespaceTest), 0) + +def AddParentNamespaceTest(builder, parentNamespaceTest): + MonsterAddParentNamespaceTest(builder, parentNamespaceTest) + +def MonsterAddVectorOfReferrables(builder, vectorOfReferrables): + builder.PrependUOffsetTRelativeSlot(35, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfReferrables), 0) + +def AddVectorOfReferrables(builder, vectorOfReferrables): + MonsterAddVectorOfReferrables(builder, vectorOfReferrables) + +def MonsterStartVectorOfReferrablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartVectorOfReferrablesVector(builder, numElems): + return MonsterStartVectorOfReferrablesVector(builder, numElems) + +def MonsterAddSingleWeakReference(builder, singleWeakReference): + builder.PrependUint64Slot(36, singleWeakReference, 0) + +def AddSingleWeakReference(builder, singleWeakReference): + MonsterAddSingleWeakReference(builder, singleWeakReference) + +def MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences): + builder.PrependUOffsetTRelativeSlot(37, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfWeakReferences), 0) + +def AddVectorOfWeakReferences(builder, vectorOfWeakReferences): + MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences) + +def MonsterStartVectorOfWeakReferencesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartVectorOfWeakReferencesVector(builder, numElems): + return MonsterStartVectorOfWeakReferencesVector(builder, numElems) + +def MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): + builder.PrependUOffsetTRelativeSlot(38, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfStrongReferrables), 0) + +def AddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): + MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables) + +def MonsterStartVectorOfStrongReferrablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartVectorOfStrongReferrablesVector(builder, numElems): + return MonsterStartVectorOfStrongReferrablesVector(builder, numElems) + +def MonsterAddCoOwningReference(builder, coOwningReference): + builder.PrependUint64Slot(39, coOwningReference, 0) + +def AddCoOwningReference(builder, coOwningReference): + MonsterAddCoOwningReference(builder, coOwningReference) + +def MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences): + builder.PrependUOffsetTRelativeSlot(40, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfCoOwningReferences), 0) + +def AddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences): + MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences) + +def MonsterStartVectorOfCoOwningReferencesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartVectorOfCoOwningReferencesVector(builder, numElems): + return MonsterStartVectorOfCoOwningReferencesVector(builder, numElems) + +def MonsterAddNonOwningReference(builder, nonOwningReference): + builder.PrependUint64Slot(41, nonOwningReference, 0) + +def AddNonOwningReference(builder, nonOwningReference): + MonsterAddNonOwningReference(builder, nonOwningReference) + +def MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences): + builder.PrependUOffsetTRelativeSlot(42, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfNonOwningReferences), 0) + +def AddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences): + MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences) + +def MonsterStartVectorOfNonOwningReferencesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartVectorOfNonOwningReferencesVector(builder, numElems): + return MonsterStartVectorOfNonOwningReferencesVector(builder, numElems) + +def MonsterAddAnyUniqueType(builder, anyUniqueType): + builder.PrependUint8Slot(43, anyUniqueType, 0) + +def AddAnyUniqueType(builder, anyUniqueType): + MonsterAddAnyUniqueType(builder, anyUniqueType) + +def MonsterAddAnyUnique(builder, anyUnique): + builder.PrependUOffsetTRelativeSlot(44, flatbuffers.number_types.UOffsetTFlags.py_type(anyUnique), 0) + +def AddAnyUnique(builder, anyUnique): + MonsterAddAnyUnique(builder, anyUnique) + +def MonsterAddAnyAmbiguousType(builder, anyAmbiguousType): + builder.PrependUint8Slot(45, anyAmbiguousType, 0) + +def AddAnyAmbiguousType(builder, anyAmbiguousType): + MonsterAddAnyAmbiguousType(builder, anyAmbiguousType) + +def MonsterAddAnyAmbiguous(builder, anyAmbiguous): + builder.PrependUOffsetTRelativeSlot(46, flatbuffers.number_types.UOffsetTFlags.py_type(anyAmbiguous), 0) + +def AddAnyAmbiguous(builder, anyAmbiguous): + MonsterAddAnyAmbiguous(builder, anyAmbiguous) + +def MonsterAddVectorOfEnums(builder, vectorOfEnums): + builder.PrependUOffsetTRelativeSlot(47, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfEnums), 0) + +def AddVectorOfEnums(builder, vectorOfEnums): + MonsterAddVectorOfEnums(builder, vectorOfEnums) + +def MonsterStartVectorOfEnumsVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartVectorOfEnumsVector(builder, numElems): + return MonsterStartVectorOfEnumsVector(builder, numElems) + +def MonsterAddSignedEnum(builder, signedEnum): + builder.PrependInt8Slot(48, signedEnum, -1) + +def AddSignedEnum(builder, signedEnum): + MonsterAddSignedEnum(builder, signedEnum) + +def MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer): + builder.PrependUOffsetTRelativeSlot(49, flatbuffers.number_types.UOffsetTFlags.py_type(testrequirednestedflatbuffer), 0) + +def AddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer): + MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer) + +def MonsterStartTestrequirednestedflatbufferVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartTestrequirednestedflatbufferVector(builder, numElems): + return MonsterStartTestrequirednestedflatbufferVector(builder, numElems) + +def MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes): + builder.StartVector(1, len(bytes), 1) + builder.head = builder.head - len(bytes) + builder.Bytes[builder.head : builder.head + len(bytes)] = bytes + return builder.EndVector() +def MakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes): + return MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes) +def MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables): + builder.PrependUOffsetTRelativeSlot(50, flatbuffers.number_types.UOffsetTFlags.py_type(scalarKeySortedTables), 0) + +def AddScalarKeySortedTables(builder, scalarKeySortedTables): + MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables) + +def MonsterStartScalarKeySortedTablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def StartScalarKeySortedTablesVector(builder, numElems): + return MonsterStartScalarKeySortedTablesVector(builder, numElems) + +def MonsterAddNativeInline(builder, nativeInline): + builder.PrependStructSlot(51, flatbuffers.number_types.UOffsetTFlags.py_type(nativeInline), 0) + +def AddNativeInline(builder, nativeInline): + MonsterAddNativeInline(builder, nativeInline) + +def MonsterAddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault): + builder.PrependUint64Slot(52, longEnumNonEnumDefault, 0) + +def AddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault): + MonsterAddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault) + +def MonsterAddLongEnumNormalDefault(builder, longEnumNormalDefault): + builder.PrependUint64Slot(53, longEnumNormalDefault, 2) + +def AddLongEnumNormalDefault(builder, longEnumNormalDefault): + MonsterAddLongEnumNormalDefault(builder, longEnumNormalDefault) + +def MonsterAddNanDefault(builder, nanDefault): + builder.PrependFloat32Slot(54, nanDefault, float('nan')) + +def AddNanDefault(builder, nanDefault): + MonsterAddNanDefault(builder, nanDefault) + +def MonsterAddInfDefault(builder, infDefault): + builder.PrependFloat32Slot(55, infDefault, float('inf')) + +def AddInfDefault(builder, infDefault): + MonsterAddInfDefault(builder, infDefault) + +def MonsterAddPositiveInfDefault(builder, positiveInfDefault): + builder.PrependFloat32Slot(56, positiveInfDefault, float('inf')) + +def AddPositiveInfDefault(builder, positiveInfDefault): + MonsterAddPositiveInfDefault(builder, positiveInfDefault) + +def MonsterAddInfinityDefault(builder, infinityDefault): + builder.PrependFloat32Slot(57, infinityDefault, float('inf')) + +def AddInfinityDefault(builder, infinityDefault): + MonsterAddInfinityDefault(builder, infinityDefault) + +def MonsterAddPositiveInfinityDefault(builder, positiveInfinityDefault): + builder.PrependFloat32Slot(58, positiveInfinityDefault, float('inf')) + +def AddPositiveInfinityDefault(builder, positiveInfinityDefault): + MonsterAddPositiveInfinityDefault(builder, positiveInfinityDefault) + +def MonsterAddNegativeInfDefault(builder, negativeInfDefault): + builder.PrependFloat32Slot(59, negativeInfDefault, float('-inf')) + +def AddNegativeInfDefault(builder, negativeInfDefault): + MonsterAddNegativeInfDefault(builder, negativeInfDefault) + +def MonsterAddNegativeInfinityDefault(builder, negativeInfinityDefault): + builder.PrependFloat32Slot(60, negativeInfinityDefault, float('-inf')) + +def AddNegativeInfinityDefault(builder, negativeInfinityDefault): + MonsterAddNegativeInfinityDefault(builder, negativeInfinityDefault) + +def MonsterAddDoubleInfDefault(builder, doubleInfDefault): + builder.PrependFloat64Slot(61, doubleInfDefault, float('inf')) + +def AddDoubleInfDefault(builder, doubleInfDefault): + MonsterAddDoubleInfDefault(builder, doubleInfDefault) + +def MonsterEnd(builder): + return builder.EndObject() + +def End(builder): + return MonsterEnd(builder) + +import MyGame.Example.Ability +import MyGame.Example.Any +import MyGame.Example.AnyAmbiguousAliases +import MyGame.Example.AnyUniqueAliases +import MyGame.Example.Referrable +import MyGame.Example.Stat +import MyGame.Example.Test +import MyGame.Example.TestSimpleTableWithEnum +import MyGame.Example.Vec3 +import MyGame.Example2.Monster +import MyGame.InParentNamespace +try: + from typing import List, Optional, Union +except: + pass + +class MonsterT(object): + + # MonsterT + def __init__(self): + self.pos = None # type: Optional[MyGame.Example.Vec3.Vec3T] + self.mana = 150 # type: int + self.hp = 100 # type: int + self.name = None # type: str + self.inventory = None # type: List[int] + self.color = 8 # type: int + self.testType = 0 # type: int + self.test = None # type: Union[None, MyGame.Example.Monster.MonsterT, MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT, MyGame.Example2.Monster.MonsterT] + self.test4 = None # type: List[MyGame.Example.Test.TestT] + self.testarrayofstring = None # type: List[str] + self.testarrayoftables = None # type: List[MyGame.Example.Monster.MonsterT] + self.enemy = None # type: Optional[MyGame.Example.Monster.MonsterT] + self.testnestedflatbuffer = None # type: List[int] + self.testempty = None # type: Optional[MyGame.Example.Stat.StatT] + self.testbool = False # type: bool + self.testhashs32Fnv1 = 0 # type: int + self.testhashu32Fnv1 = 0 # type: int + self.testhashs64Fnv1 = 0 # type: int + self.testhashu64Fnv1 = 0 # type: int + self.testhashs32Fnv1a = 0 # type: int + self.testhashu32Fnv1a = 0 # type: int + self.testhashs64Fnv1a = 0 # type: int + self.testhashu64Fnv1a = 0 # type: int + self.testarrayofbools = None # type: List[bool] + self.testf = 3.14159 # type: float + self.testf2 = 3.0 # type: float + self.testf3 = 0.0 # type: float + self.testarrayofstring2 = None # type: List[str] + self.testarrayofsortedstruct = None # type: List[MyGame.Example.Ability.AbilityT] + self.flex = None # type: List[int] + self.test5 = None # type: List[MyGame.Example.Test.TestT] + self.vectorOfLongs = None # type: List[int] + self.vectorOfDoubles = None # type: List[float] + self.parentNamespaceTest = None # type: Optional[MyGame.InParentNamespace.InParentNamespaceT] + self.vectorOfReferrables = None # type: List[MyGame.Example.Referrable.ReferrableT] + self.singleWeakReference = 0 # type: int + self.vectorOfWeakReferences = None # type: List[int] + self.vectorOfStrongReferrables = None # type: List[MyGame.Example.Referrable.ReferrableT] + self.coOwningReference = 0 # type: int + self.vectorOfCoOwningReferences = None # type: List[int] + self.nonOwningReference = 0 # type: int + self.vectorOfNonOwningReferences = None # type: List[int] + self.anyUniqueType = 0 # type: int + self.anyUnique = None # type: Union[None, MyGame.Example.Monster.MonsterT, MyGame.Example.TestSimpleTableWithEnum.TestSimpleTableWithEnumT, MyGame.Example2.Monster.MonsterT] + self.anyAmbiguousType = 0 # type: int + self.anyAmbiguous = None # type: Union[None, MyGame.Example.Monster.MonsterT, MyGame.Example.Monster.MonsterT, MyGame.Example.Monster.MonsterT] + self.vectorOfEnums = None # type: List[int] + self.signedEnum = -1 # type: int + self.testrequirednestedflatbuffer = None # type: List[int] + self.scalarKeySortedTables = None # type: List[MyGame.Example.Stat.StatT] + self.nativeInline = None # type: Optional[MyGame.Example.Test.TestT] + self.longEnumNonEnumDefault = 0 # type: int + self.longEnumNormalDefault = 2 # type: int + self.nanDefault = float('nan') # type: float + self.infDefault = float('inf') # type: float + self.positiveInfDefault = float('inf') # type: float + self.infinityDefault = float('inf') # type: float + self.positiveInfinityDefault = float('inf') # type: float + self.negativeInfDefault = float('-inf') # type: float + self.negativeInfinityDefault = float('-inf') # type: float + self.doubleInfDefault = float('inf') # type: float + + @classmethod + def InitFromBuf(cls, buf, pos): + monster = Monster() + monster.Init(buf, pos) + return cls.InitFromObj(monster) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, monster): + x = MonsterT() + x._UnPack(monster) + return x + + # MonsterT + def _UnPack(self, monster): + if monster is None: + return + if monster.Pos() is not None: + self.pos = MyGame.Example.Vec3.Vec3T.InitFromObj(monster.Pos()) + self.mana = monster.Mana() + self.hp = monster.Hp() + self.name = monster.Name() + if not monster.InventoryIsNone(): + if np is None: + self.inventory = [] + for i in range(monster.InventoryLength()): + self.inventory.append(monster.Inventory(i)) + else: + self.inventory = monster.InventoryAsNumpy() + self.color = monster.Color() + self.testType = monster.TestType() + self.test = MyGame.Example.Any.AnyCreator(self.testType, monster.Test()) + if not monster.Test4IsNone(): + self.test4 = [] + for i in range(monster.Test4Length()): + if monster.Test4(i) is None: + self.test4.append(None) + else: + test_ = MyGame.Example.Test.TestT.InitFromObj(monster.Test4(i)) + self.test4.append(test_) + if not monster.TestarrayofstringIsNone(): + self.testarrayofstring = [] + for i in range(monster.TestarrayofstringLength()): + self.testarrayofstring.append(monster.Testarrayofstring(i)) + if not monster.TestarrayoftablesIsNone(): + self.testarrayoftables = [] + for i in range(monster.TestarrayoftablesLength()): + if monster.Testarrayoftables(i) is None: + self.testarrayoftables.append(None) + else: + monster_ = MyGame.Example.Monster.MonsterT.InitFromObj(monster.Testarrayoftables(i)) + self.testarrayoftables.append(monster_) + if monster.Enemy() is not None: + self.enemy = MyGame.Example.Monster.MonsterT.InitFromObj(monster.Enemy()) + if not monster.TestnestedflatbufferIsNone(): + if np is None: + self.testnestedflatbuffer = [] + for i in range(monster.TestnestedflatbufferLength()): + self.testnestedflatbuffer.append(monster.Testnestedflatbuffer(i)) + else: + self.testnestedflatbuffer = monster.TestnestedflatbufferAsNumpy() + if monster.Testempty() is not None: + self.testempty = MyGame.Example.Stat.StatT.InitFromObj(monster.Testempty()) + self.testbool = monster.Testbool() + self.testhashs32Fnv1 = monster.Testhashs32Fnv1() + self.testhashu32Fnv1 = monster.Testhashu32Fnv1() + self.testhashs64Fnv1 = monster.Testhashs64Fnv1() + self.testhashu64Fnv1 = monster.Testhashu64Fnv1() + self.testhashs32Fnv1a = monster.Testhashs32Fnv1a() + self.testhashu32Fnv1a = monster.Testhashu32Fnv1a() + self.testhashs64Fnv1a = monster.Testhashs64Fnv1a() + self.testhashu64Fnv1a = monster.Testhashu64Fnv1a() + if not monster.TestarrayofboolsIsNone(): + if np is None: + self.testarrayofbools = [] + for i in range(monster.TestarrayofboolsLength()): + self.testarrayofbools.append(monster.Testarrayofbools(i)) + else: + self.testarrayofbools = monster.TestarrayofboolsAsNumpy() + self.testf = monster.Testf() + self.testf2 = monster.Testf2() + self.testf3 = monster.Testf3() + if not monster.Testarrayofstring2IsNone(): + self.testarrayofstring2 = [] + for i in range(monster.Testarrayofstring2Length()): + self.testarrayofstring2.append(monster.Testarrayofstring2(i)) + if not monster.TestarrayofsortedstructIsNone(): + self.testarrayofsortedstruct = [] + for i in range(monster.TestarrayofsortedstructLength()): + if monster.Testarrayofsortedstruct(i) is None: + self.testarrayofsortedstruct.append(None) + else: + ability_ = MyGame.Example.Ability.AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i)) + self.testarrayofsortedstruct.append(ability_) + if not monster.FlexIsNone(): + if np is None: + self.flex = [] + for i in range(monster.FlexLength()): + self.flex.append(monster.Flex(i)) + else: + self.flex = monster.FlexAsNumpy() + if not monster.Test5IsNone(): + self.test5 = [] + for i in range(monster.Test5Length()): + if monster.Test5(i) is None: + self.test5.append(None) + else: + test_ = MyGame.Example.Test.TestT.InitFromObj(monster.Test5(i)) + self.test5.append(test_) + if not monster.VectorOfLongsIsNone(): + if np is None: + self.vectorOfLongs = [] + for i in range(monster.VectorOfLongsLength()): + self.vectorOfLongs.append(monster.VectorOfLongs(i)) + else: + self.vectorOfLongs = monster.VectorOfLongsAsNumpy() + if not monster.VectorOfDoublesIsNone(): + if np is None: + self.vectorOfDoubles = [] + for i in range(monster.VectorOfDoublesLength()): + self.vectorOfDoubles.append(monster.VectorOfDoubles(i)) + else: + self.vectorOfDoubles = monster.VectorOfDoublesAsNumpy() + if monster.ParentNamespaceTest() is not None: + self.parentNamespaceTest = MyGame.InParentNamespace.InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest()) + if not monster.VectorOfReferrablesIsNone(): + self.vectorOfReferrables = [] + for i in range(monster.VectorOfReferrablesLength()): + if monster.VectorOfReferrables(i) is None: + self.vectorOfReferrables.append(None) + else: + referrable_ = MyGame.Example.Referrable.ReferrableT.InitFromObj(monster.VectorOfReferrables(i)) + self.vectorOfReferrables.append(referrable_) + self.singleWeakReference = monster.SingleWeakReference() + if not monster.VectorOfWeakReferencesIsNone(): + if np is None: + self.vectorOfWeakReferences = [] + for i in range(monster.VectorOfWeakReferencesLength()): + self.vectorOfWeakReferences.append(monster.VectorOfWeakReferences(i)) + else: + self.vectorOfWeakReferences = monster.VectorOfWeakReferencesAsNumpy() + if not monster.VectorOfStrongReferrablesIsNone(): + self.vectorOfStrongReferrables = [] + for i in range(monster.VectorOfStrongReferrablesLength()): + if monster.VectorOfStrongReferrables(i) is None: + self.vectorOfStrongReferrables.append(None) + else: + referrable_ = MyGame.Example.Referrable.ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i)) + self.vectorOfStrongReferrables.append(referrable_) + self.coOwningReference = monster.CoOwningReference() + if not monster.VectorOfCoOwningReferencesIsNone(): + if np is None: + self.vectorOfCoOwningReferences = [] + for i in range(monster.VectorOfCoOwningReferencesLength()): + self.vectorOfCoOwningReferences.append(monster.VectorOfCoOwningReferences(i)) + else: + self.vectorOfCoOwningReferences = monster.VectorOfCoOwningReferencesAsNumpy() + self.nonOwningReference = monster.NonOwningReference() + if not monster.VectorOfNonOwningReferencesIsNone(): + if np is None: + self.vectorOfNonOwningReferences = [] + for i in range(monster.VectorOfNonOwningReferencesLength()): + self.vectorOfNonOwningReferences.append(monster.VectorOfNonOwningReferences(i)) + else: + self.vectorOfNonOwningReferences = monster.VectorOfNonOwningReferencesAsNumpy() + self.anyUniqueType = monster.AnyUniqueType() + self.anyUnique = MyGame.Example.AnyUniqueAliases.AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique()) + self.anyAmbiguousType = monster.AnyAmbiguousType() + self.anyAmbiguous = MyGame.Example.AnyAmbiguousAliases.AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous()) + if not monster.VectorOfEnumsIsNone(): + if np is None: + self.vectorOfEnums = [] + for i in range(monster.VectorOfEnumsLength()): + self.vectorOfEnums.append(monster.VectorOfEnums(i)) + else: + self.vectorOfEnums = monster.VectorOfEnumsAsNumpy() + self.signedEnum = monster.SignedEnum() + if not monster.TestrequirednestedflatbufferIsNone(): + if np is None: + self.testrequirednestedflatbuffer = [] + for i in range(monster.TestrequirednestedflatbufferLength()): + self.testrequirednestedflatbuffer.append(monster.Testrequirednestedflatbuffer(i)) + else: + self.testrequirednestedflatbuffer = monster.TestrequirednestedflatbufferAsNumpy() + if not monster.ScalarKeySortedTablesIsNone(): + self.scalarKeySortedTables = [] + for i in range(monster.ScalarKeySortedTablesLength()): + if monster.ScalarKeySortedTables(i) is None: + self.scalarKeySortedTables.append(None) + else: + stat_ = MyGame.Example.Stat.StatT.InitFromObj(monster.ScalarKeySortedTables(i)) + self.scalarKeySortedTables.append(stat_) + if monster.NativeInline() is not None: + self.nativeInline = MyGame.Example.Test.TestT.InitFromObj(monster.NativeInline()) + self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault() + self.longEnumNormalDefault = monster.LongEnumNormalDefault() + self.nanDefault = monster.NanDefault() + self.infDefault = monster.InfDefault() + self.positiveInfDefault = monster.PositiveInfDefault() + self.infinityDefault = monster.InfinityDefault() + self.positiveInfinityDefault = monster.PositiveInfinityDefault() + self.negativeInfDefault = monster.NegativeInfDefault() + self.negativeInfinityDefault = monster.NegativeInfinityDefault() + self.doubleInfDefault = monster.DoubleInfDefault() + + # MonsterT + def Pack(self, builder): + if self.name is not None: + name = builder.CreateString(self.name) + if self.inventory is not None: + if np is not None and type(self.inventory) is np.ndarray: + inventory = builder.CreateNumpyVector(self.inventory) + else: + MonsterStartInventoryVector(builder, len(self.inventory)) + for i in reversed(range(len(self.inventory))): + builder.PrependUint8(self.inventory[i]) + inventory = builder.EndVector() + if self.test is not None: + test = self.test.Pack(builder) + if self.test4 is not None: + MonsterStartTest4Vector(builder, len(self.test4)) + for i in reversed(range(len(self.test4))): + self.test4[i].Pack(builder) + test4 = builder.EndVector() + if self.testarrayofstring is not None: + testarrayofstringlist = [] + for i in range(len(self.testarrayofstring)): + testarrayofstringlist.append(builder.CreateString(self.testarrayofstring[i])) + MonsterStartTestarrayofstringVector(builder, len(self.testarrayofstring)) + for i in reversed(range(len(self.testarrayofstring))): + builder.PrependUOffsetTRelative(testarrayofstringlist[i]) + testarrayofstring = builder.EndVector() + if self.testarrayoftables is not None: + testarrayoftableslist = [] + for i in range(len(self.testarrayoftables)): + testarrayoftableslist.append(self.testarrayoftables[i].Pack(builder)) + MonsterStartTestarrayoftablesVector(builder, len(self.testarrayoftables)) + for i in reversed(range(len(self.testarrayoftables))): + builder.PrependUOffsetTRelative(testarrayoftableslist[i]) + testarrayoftables = builder.EndVector() + if self.enemy is not None: + enemy = self.enemy.Pack(builder) + if self.testnestedflatbuffer is not None: + if np is not None and type(self.testnestedflatbuffer) is np.ndarray: + testnestedflatbuffer = builder.CreateNumpyVector(self.testnestedflatbuffer) + else: + MonsterStartTestnestedflatbufferVector(builder, len(self.testnestedflatbuffer)) + for i in reversed(range(len(self.testnestedflatbuffer))): + builder.PrependUint8(self.testnestedflatbuffer[i]) + testnestedflatbuffer = builder.EndVector() + if self.testempty is not None: + testempty = self.testempty.Pack(builder) + if self.testarrayofbools is not None: + if np is not None and type(self.testarrayofbools) is np.ndarray: + testarrayofbools = builder.CreateNumpyVector(self.testarrayofbools) + else: + MonsterStartTestarrayofboolsVector(builder, len(self.testarrayofbools)) + for i in reversed(range(len(self.testarrayofbools))): + builder.PrependBool(self.testarrayofbools[i]) + testarrayofbools = builder.EndVector() + if self.testarrayofstring2 is not None: + testarrayofstring2list = [] + for i in range(len(self.testarrayofstring2)): + testarrayofstring2list.append(builder.CreateString(self.testarrayofstring2[i])) + MonsterStartTestarrayofstring2Vector(builder, len(self.testarrayofstring2)) + for i in reversed(range(len(self.testarrayofstring2))): + builder.PrependUOffsetTRelative(testarrayofstring2list[i]) + testarrayofstring2 = builder.EndVector() + if self.testarrayofsortedstruct is not None: + MonsterStartTestarrayofsortedstructVector(builder, len(self.testarrayofsortedstruct)) + for i in reversed(range(len(self.testarrayofsortedstruct))): + self.testarrayofsortedstruct[i].Pack(builder) + testarrayofsortedstruct = builder.EndVector() + if self.flex is not None: + if np is not None and type(self.flex) is np.ndarray: + flex = builder.CreateNumpyVector(self.flex) + else: + MonsterStartFlexVector(builder, len(self.flex)) + for i in reversed(range(len(self.flex))): + builder.PrependUint8(self.flex[i]) + flex = builder.EndVector() + if self.test5 is not None: + MonsterStartTest5Vector(builder, len(self.test5)) + for i in reversed(range(len(self.test5))): + self.test5[i].Pack(builder) + test5 = builder.EndVector() + if self.vectorOfLongs is not None: + if np is not None and type(self.vectorOfLongs) is np.ndarray: + vectorOfLongs = builder.CreateNumpyVector(self.vectorOfLongs) + else: + MonsterStartVectorOfLongsVector(builder, len(self.vectorOfLongs)) + for i in reversed(range(len(self.vectorOfLongs))): + builder.PrependInt64(self.vectorOfLongs[i]) + vectorOfLongs = builder.EndVector() + if self.vectorOfDoubles is not None: + if np is not None and type(self.vectorOfDoubles) is np.ndarray: + vectorOfDoubles = builder.CreateNumpyVector(self.vectorOfDoubles) + else: + MonsterStartVectorOfDoublesVector(builder, len(self.vectorOfDoubles)) + for i in reversed(range(len(self.vectorOfDoubles))): + builder.PrependFloat64(self.vectorOfDoubles[i]) + vectorOfDoubles = builder.EndVector() + if self.parentNamespaceTest is not None: + parentNamespaceTest = self.parentNamespaceTest.Pack(builder) + if self.vectorOfReferrables is not None: + vectorOfReferrableslist = [] + for i in range(len(self.vectorOfReferrables)): + vectorOfReferrableslist.append(self.vectorOfReferrables[i].Pack(builder)) + MonsterStartVectorOfReferrablesVector(builder, len(self.vectorOfReferrables)) + for i in reversed(range(len(self.vectorOfReferrables))): + builder.PrependUOffsetTRelative(vectorOfReferrableslist[i]) + vectorOfReferrables = builder.EndVector() + if self.vectorOfWeakReferences is not None: + if np is not None and type(self.vectorOfWeakReferences) is np.ndarray: + vectorOfWeakReferences = builder.CreateNumpyVector(self.vectorOfWeakReferences) + else: + MonsterStartVectorOfWeakReferencesVector(builder, len(self.vectorOfWeakReferences)) + for i in reversed(range(len(self.vectorOfWeakReferences))): + builder.PrependUint64(self.vectorOfWeakReferences[i]) + vectorOfWeakReferences = builder.EndVector() + if self.vectorOfStrongReferrables is not None: + vectorOfStrongReferrableslist = [] + for i in range(len(self.vectorOfStrongReferrables)): + vectorOfStrongReferrableslist.append(self.vectorOfStrongReferrables[i].Pack(builder)) + MonsterStartVectorOfStrongReferrablesVector(builder, len(self.vectorOfStrongReferrables)) + for i in reversed(range(len(self.vectorOfStrongReferrables))): + builder.PrependUOffsetTRelative(vectorOfStrongReferrableslist[i]) + vectorOfStrongReferrables = builder.EndVector() + if self.vectorOfCoOwningReferences is not None: + if np is not None and type(self.vectorOfCoOwningReferences) is np.ndarray: + vectorOfCoOwningReferences = builder.CreateNumpyVector(self.vectorOfCoOwningReferences) + else: + MonsterStartVectorOfCoOwningReferencesVector(builder, len(self.vectorOfCoOwningReferences)) + for i in reversed(range(len(self.vectorOfCoOwningReferences))): + builder.PrependUint64(self.vectorOfCoOwningReferences[i]) + vectorOfCoOwningReferences = builder.EndVector() + if self.vectorOfNonOwningReferences is not None: + if np is not None and type(self.vectorOfNonOwningReferences) is np.ndarray: + vectorOfNonOwningReferences = builder.CreateNumpyVector(self.vectorOfNonOwningReferences) + else: + MonsterStartVectorOfNonOwningReferencesVector(builder, len(self.vectorOfNonOwningReferences)) + for i in reversed(range(len(self.vectorOfNonOwningReferences))): + builder.PrependUint64(self.vectorOfNonOwningReferences[i]) + vectorOfNonOwningReferences = builder.EndVector() + if self.anyUnique is not None: + anyUnique = self.anyUnique.Pack(builder) + if self.anyAmbiguous is not None: + anyAmbiguous = self.anyAmbiguous.Pack(builder) + if self.vectorOfEnums is not None: + if np is not None and type(self.vectorOfEnums) is np.ndarray: + vectorOfEnums = builder.CreateNumpyVector(self.vectorOfEnums) + else: + MonsterStartVectorOfEnumsVector(builder, len(self.vectorOfEnums)) + for i in reversed(range(len(self.vectorOfEnums))): + builder.PrependUint8(self.vectorOfEnums[i]) + vectorOfEnums = builder.EndVector() + if self.testrequirednestedflatbuffer is not None: + if np is not None and type(self.testrequirednestedflatbuffer) is np.ndarray: + testrequirednestedflatbuffer = builder.CreateNumpyVector(self.testrequirednestedflatbuffer) + else: + MonsterStartTestrequirednestedflatbufferVector(builder, len(self.testrequirednestedflatbuffer)) + for i in reversed(range(len(self.testrequirednestedflatbuffer))): + builder.PrependUint8(self.testrequirednestedflatbuffer[i]) + testrequirednestedflatbuffer = builder.EndVector() + if self.scalarKeySortedTables is not None: + scalarKeySortedTableslist = [] + for i in range(len(self.scalarKeySortedTables)): + scalarKeySortedTableslist.append(self.scalarKeySortedTables[i].Pack(builder)) + MonsterStartScalarKeySortedTablesVector(builder, len(self.scalarKeySortedTables)) + for i in reversed(range(len(self.scalarKeySortedTables))): + builder.PrependUOffsetTRelative(scalarKeySortedTableslist[i]) + scalarKeySortedTables = builder.EndVector() + MonsterStart(builder) + if self.pos is not None: + pos = self.pos.Pack(builder) + MonsterAddPos(builder, pos) + MonsterAddMana(builder, self.mana) + MonsterAddHp(builder, self.hp) + if self.name is not None: + MonsterAddName(builder, name) + if self.inventory is not None: + MonsterAddInventory(builder, inventory) + MonsterAddColor(builder, self.color) + MonsterAddTestType(builder, self.testType) + if self.test is not None: + MonsterAddTest(builder, test) + if self.test4 is not None: + MonsterAddTest4(builder, test4) + if self.testarrayofstring is not None: + MonsterAddTestarrayofstring(builder, testarrayofstring) + if self.testarrayoftables is not None: + MonsterAddTestarrayoftables(builder, testarrayoftables) + if self.enemy is not None: + MonsterAddEnemy(builder, enemy) + if self.testnestedflatbuffer is not None: + MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer) + if self.testempty is not None: + MonsterAddTestempty(builder, testempty) + MonsterAddTestbool(builder, self.testbool) + MonsterAddTesthashs32Fnv1(builder, self.testhashs32Fnv1) + MonsterAddTesthashu32Fnv1(builder, self.testhashu32Fnv1) + MonsterAddTesthashs64Fnv1(builder, self.testhashs64Fnv1) + MonsterAddTesthashu64Fnv1(builder, self.testhashu64Fnv1) + MonsterAddTesthashs32Fnv1a(builder, self.testhashs32Fnv1a) + MonsterAddTesthashu32Fnv1a(builder, self.testhashu32Fnv1a) + MonsterAddTesthashs64Fnv1a(builder, self.testhashs64Fnv1a) + MonsterAddTesthashu64Fnv1a(builder, self.testhashu64Fnv1a) + if self.testarrayofbools is not None: + MonsterAddTestarrayofbools(builder, testarrayofbools) + MonsterAddTestf(builder, self.testf) + MonsterAddTestf2(builder, self.testf2) + MonsterAddTestf3(builder, self.testf3) + if self.testarrayofstring2 is not None: + MonsterAddTestarrayofstring2(builder, testarrayofstring2) + if self.testarrayofsortedstruct is not None: + MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct) + if self.flex is not None: + MonsterAddFlex(builder, flex) + if self.test5 is not None: + MonsterAddTest5(builder, test5) + if self.vectorOfLongs is not None: + MonsterAddVectorOfLongs(builder, vectorOfLongs) + if self.vectorOfDoubles is not None: + MonsterAddVectorOfDoubles(builder, vectorOfDoubles) + if self.parentNamespaceTest is not None: + MonsterAddParentNamespaceTest(builder, parentNamespaceTest) + if self.vectorOfReferrables is not None: + MonsterAddVectorOfReferrables(builder, vectorOfReferrables) + MonsterAddSingleWeakReference(builder, self.singleWeakReference) + if self.vectorOfWeakReferences is not None: + MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences) + if self.vectorOfStrongReferrables is not None: + MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables) + MonsterAddCoOwningReference(builder, self.coOwningReference) + if self.vectorOfCoOwningReferences is not None: + MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences) + MonsterAddNonOwningReference(builder, self.nonOwningReference) + if self.vectorOfNonOwningReferences is not None: + MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences) + MonsterAddAnyUniqueType(builder, self.anyUniqueType) + if self.anyUnique is not None: + MonsterAddAnyUnique(builder, anyUnique) + MonsterAddAnyAmbiguousType(builder, self.anyAmbiguousType) + if self.anyAmbiguous is not None: + MonsterAddAnyAmbiguous(builder, anyAmbiguous) + if self.vectorOfEnums is not None: + MonsterAddVectorOfEnums(builder, vectorOfEnums) + MonsterAddSignedEnum(builder, self.signedEnum) + if self.testrequirednestedflatbuffer is not None: + MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer) + if self.scalarKeySortedTables is not None: + MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables) + if self.nativeInline is not None: + nativeInline = self.nativeInline.Pack(builder) + MonsterAddNativeInline(builder, nativeInline) + MonsterAddLongEnumNonEnumDefault(builder, self.longEnumNonEnumDefault) + MonsterAddLongEnumNormalDefault(builder, self.longEnumNormalDefault) + MonsterAddNanDefault(builder, self.nanDefault) + MonsterAddInfDefault(builder, self.infDefault) + MonsterAddPositiveInfDefault(builder, self.positiveInfDefault) + MonsterAddInfinityDefault(builder, self.infinityDefault) + MonsterAddPositiveInfinityDefault(builder, self.positiveInfinityDefault) + MonsterAddNegativeInfDefault(builder, self.negativeInfDefault) + MonsterAddNegativeInfinityDefault(builder, self.negativeInfinityDefault) + MonsterAddDoubleInfDefault(builder, self.doubleInfDefault) + monster = MonsterEnd(builder) + return monster diff --git a/third_party/flatbuffers/tests/MyGame/Example/MonsterStorageGrpc.java b/third_party/flatbuffers/tests/MyGame/Example/MonsterStorageGrpc.java new file mode 100644 index 00000000000..40103aeb4c3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/MonsterStorageGrpc.java @@ -0,0 +1,470 @@ +//Generated by flatc compiler (version 2.0.0) +//If you make any local changes, they will be lost +//source: monster_test.fbs + +package MyGame.Example; + +import com.google.flatbuffers.grpc.FlatbuffersUtils; + +import java.nio.ByteBuffer; +import static io.grpc.MethodDescriptor.generateFullMethodName; +import static io.grpc.stub.ClientCalls.asyncBidiStreamingCall; +import static io.grpc.stub.ClientCalls.asyncClientStreamingCall; +import static io.grpc.stub.ClientCalls.asyncServerStreamingCall; +import static io.grpc.stub.ClientCalls.asyncUnaryCall; +import static io.grpc.stub.ClientCalls.blockingServerStreamingCall; +import static io.grpc.stub.ClientCalls.blockingUnaryCall; +import static io.grpc.stub.ClientCalls.futureUnaryCall; +import static io.grpc.stub.ServerCalls.asyncBidiStreamingCall; +import static io.grpc.stub.ServerCalls.asyncClientStreamingCall; +import static io.grpc.stub.ServerCalls.asyncServerStreamingCall; +import static io.grpc.stub.ServerCalls.asyncUnaryCall; +import static io.grpc.stub.ServerCalls.asyncUnimplementedStreamingCall; +import static io.grpc.stub.ServerCalls.asyncUnimplementedUnaryCall; + +/** + */ +@javax.annotation.Generated( + value = "by gRPC proto compiler", + comments = "Source: monster_test.fbs") +public final class MonsterStorageGrpc { + + private MonsterStorageGrpc() {} + + public static final String SERVICE_NAME = "MyGame.Example.MonsterStorage"; + + // Static method descriptors that strictly reflect the proto. + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + @java.lang.Deprecated // Use {@link #getStoreMethod()} instead. + public static final io.grpc.MethodDescriptor METHOD_STORE = getStoreMethod(); + + private static volatile io.grpc.MethodDescriptor getStoreMethod; + + private static volatile FlatbuffersUtils.FBExtactor extractorOfMonster; + private static FlatbuffersUtils.FBExtactor getExtractorOfMonster() { + if (extractorOfMonster != null) return extractorOfMonster; + synchronized (MonsterStorageGrpc.class) { + if (extractorOfMonster != null) return extractorOfMonster; + extractorOfMonster = new FlatbuffersUtils.FBExtactor() { + public MyGame.Example.Monster extract (ByteBuffer buffer) { + return MyGame.Example.Monster.getRootAsMonster(buffer); + } + }; + return extractorOfMonster; + } + } + + private static volatile FlatbuffersUtils.FBExtactor extractorOfStat; + private static FlatbuffersUtils.FBExtactor getExtractorOfStat() { + if (extractorOfStat != null) return extractorOfStat; + synchronized (MonsterStorageGrpc.class) { + if (extractorOfStat != null) return extractorOfStat; + extractorOfStat = new FlatbuffersUtils.FBExtactor() { + public MyGame.Example.Stat extract (ByteBuffer buffer) { + return MyGame.Example.Stat.getRootAsStat(buffer); + } + }; + return extractorOfStat; + } + } + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + public static io.grpc.MethodDescriptor getStoreMethod() { + io.grpc.MethodDescriptor getStoreMethod; + if ((getStoreMethod = MonsterStorageGrpc.getStoreMethod) == null) { + synchronized (MonsterStorageGrpc.class) { + if ((getStoreMethod = MonsterStorageGrpc.getStoreMethod) == null) { + MonsterStorageGrpc.getStoreMethod = getStoreMethod = + io.grpc.MethodDescriptor.newBuilder() + .setType(io.grpc.MethodDescriptor.MethodType.UNARY) + .setFullMethodName(generateFullMethodName( + "MyGame.Example.MonsterStorage", "Store")) + .setSampledToLocalTracing(true) + .setRequestMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Monster.class, getExtractorOfMonster())) + .setResponseMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Stat.class, getExtractorOfStat())) + .setSchemaDescriptor(null) + .build(); + } + } + } + return getStoreMethod; + } + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + @java.lang.Deprecated // Use {@link #getRetrieveMethod()} instead. + public static final io.grpc.MethodDescriptor METHOD_RETRIEVE = getRetrieveMethod(); + + private static volatile io.grpc.MethodDescriptor getRetrieveMethod; + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + public static io.grpc.MethodDescriptor getRetrieveMethod() { + io.grpc.MethodDescriptor getRetrieveMethod; + if ((getRetrieveMethod = MonsterStorageGrpc.getRetrieveMethod) == null) { + synchronized (MonsterStorageGrpc.class) { + if ((getRetrieveMethod = MonsterStorageGrpc.getRetrieveMethod) == null) { + MonsterStorageGrpc.getRetrieveMethod = getRetrieveMethod = + io.grpc.MethodDescriptor.newBuilder() + .setType(io.grpc.MethodDescriptor.MethodType.SERVER_STREAMING) + .setFullMethodName(generateFullMethodName( + "MyGame.Example.MonsterStorage", "Retrieve")) + .setSampledToLocalTracing(true) + .setRequestMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Stat.class, getExtractorOfStat())) + .setResponseMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Monster.class, getExtractorOfMonster())) + .setSchemaDescriptor(null) + .build(); + } + } + } + return getRetrieveMethod; + } + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + @java.lang.Deprecated // Use {@link #getGetMaxHitPointMethod()} instead. + public static final io.grpc.MethodDescriptor METHOD_GET_MAX_HIT_POINT = getGetMaxHitPointMethod(); + + private static volatile io.grpc.MethodDescriptor getGetMaxHitPointMethod; + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + public static io.grpc.MethodDescriptor getGetMaxHitPointMethod() { + io.grpc.MethodDescriptor getGetMaxHitPointMethod; + if ((getGetMaxHitPointMethod = MonsterStorageGrpc.getGetMaxHitPointMethod) == null) { + synchronized (MonsterStorageGrpc.class) { + if ((getGetMaxHitPointMethod = MonsterStorageGrpc.getGetMaxHitPointMethod) == null) { + MonsterStorageGrpc.getGetMaxHitPointMethod = getGetMaxHitPointMethod = + io.grpc.MethodDescriptor.newBuilder() + .setType(io.grpc.MethodDescriptor.MethodType.CLIENT_STREAMING) + .setFullMethodName(generateFullMethodName( + "MyGame.Example.MonsterStorage", "GetMaxHitPoint")) + .setSampledToLocalTracing(true) + .setRequestMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Monster.class, getExtractorOfMonster())) + .setResponseMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Stat.class, getExtractorOfStat())) + .setSchemaDescriptor(null) + .build(); + } + } + } + return getGetMaxHitPointMethod; + } + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + @java.lang.Deprecated // Use {@link #getGetMinMaxHitPointsMethod()} instead. + public static final io.grpc.MethodDescriptor METHOD_GET_MIN_MAX_HIT_POINTS = getGetMinMaxHitPointsMethod(); + + private static volatile io.grpc.MethodDescriptor getGetMinMaxHitPointsMethod; + + @io.grpc.ExperimentalApi("https://github.com/grpc/grpc-java/issues/1901") + public static io.grpc.MethodDescriptor getGetMinMaxHitPointsMethod() { + io.grpc.MethodDescriptor getGetMinMaxHitPointsMethod; + if ((getGetMinMaxHitPointsMethod = MonsterStorageGrpc.getGetMinMaxHitPointsMethod) == null) { + synchronized (MonsterStorageGrpc.class) { + if ((getGetMinMaxHitPointsMethod = MonsterStorageGrpc.getGetMinMaxHitPointsMethod) == null) { + MonsterStorageGrpc.getGetMinMaxHitPointsMethod = getGetMinMaxHitPointsMethod = + io.grpc.MethodDescriptor.newBuilder() + .setType(io.grpc.MethodDescriptor.MethodType.BIDI_STREAMING) + .setFullMethodName(generateFullMethodName( + "MyGame.Example.MonsterStorage", "GetMinMaxHitPoints")) + .setSampledToLocalTracing(true) + .setRequestMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Monster.class, getExtractorOfMonster())) + .setResponseMarshaller(FlatbuffersUtils.marshaller( + MyGame.Example.Stat.class, getExtractorOfStat())) + .setSchemaDescriptor(null) + .build(); + } + } + } + return getGetMinMaxHitPointsMethod; + } + + /** + * Creates a new async stub that supports all call types for the service + */ + public static MonsterStorageStub newStub(io.grpc.Channel channel) { + return new MonsterStorageStub(channel); + } + + /** + * Creates a new blocking-style stub that supports unary and streaming output calls on the service + */ + public static MonsterStorageBlockingStub newBlockingStub( + io.grpc.Channel channel) { + return new MonsterStorageBlockingStub(channel); + } + + /** + * Creates a new ListenableFuture-style stub that supports unary calls on the service + */ + public static MonsterStorageFutureStub newFutureStub( + io.grpc.Channel channel) { + return new MonsterStorageFutureStub(channel); + } + + /** + */ + public static abstract class MonsterStorageImplBase implements io.grpc.BindableService { + + /** + */ + public void store(MyGame.Example.Monster request, + io.grpc.stub.StreamObserver responseObserver) { + asyncUnimplementedUnaryCall(getStoreMethod(), responseObserver); + } + + /** + */ + public void retrieve(MyGame.Example.Stat request, + io.grpc.stub.StreamObserver responseObserver) { + asyncUnimplementedUnaryCall(getRetrieveMethod(), responseObserver); + } + + /** + */ + public io.grpc.stub.StreamObserver getMaxHitPoint( + io.grpc.stub.StreamObserver responseObserver) { + return asyncUnimplementedStreamingCall(getGetMaxHitPointMethod(), responseObserver); + } + + /** + */ + public io.grpc.stub.StreamObserver getMinMaxHitPoints( + io.grpc.stub.StreamObserver responseObserver) { + return asyncUnimplementedStreamingCall(getGetMinMaxHitPointsMethod(), responseObserver); + } + + @java.lang.Override public final io.grpc.ServerServiceDefinition bindService() { + return io.grpc.ServerServiceDefinition.builder(getServiceDescriptor()) + .addMethod( + getStoreMethod(), + asyncUnaryCall( + new MethodHandlers< + MyGame.Example.Monster, + MyGame.Example.Stat>( + this, METHODID_STORE))) + .addMethod( + getRetrieveMethod(), + asyncServerStreamingCall( + new MethodHandlers< + MyGame.Example.Stat, + MyGame.Example.Monster>( + this, METHODID_RETRIEVE))) + .addMethod( + getGetMaxHitPointMethod(), + asyncClientStreamingCall( + new MethodHandlers< + MyGame.Example.Monster, + MyGame.Example.Stat>( + this, METHODID_GET_MAX_HIT_POINT))) + .addMethod( + getGetMinMaxHitPointsMethod(), + asyncBidiStreamingCall( + new MethodHandlers< + MyGame.Example.Monster, + MyGame.Example.Stat>( + this, METHODID_GET_MIN_MAX_HIT_POINTS))) + .build(); + } + } + + /** + */ + public static final class MonsterStorageStub extends io.grpc.stub.AbstractStub { + private MonsterStorageStub(io.grpc.Channel channel) { + super(channel); + } + + private MonsterStorageStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected MonsterStorageStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new MonsterStorageStub(channel, callOptions); + } + + /** + */ + public void store(MyGame.Example.Monster request, + io.grpc.stub.StreamObserver responseObserver) { + asyncUnaryCall( + getChannel().newCall(getStoreMethod(), getCallOptions()), request, responseObserver); + } + + /** + */ + public void retrieve(MyGame.Example.Stat request, + io.grpc.stub.StreamObserver responseObserver) { + asyncServerStreamingCall( + getChannel().newCall(getRetrieveMethod(), getCallOptions()), request, responseObserver); + } + + /** + */ + public io.grpc.stub.StreamObserver getMaxHitPoint( + io.grpc.stub.StreamObserver responseObserver) { + return asyncClientStreamingCall( + getChannel().newCall(getGetMaxHitPointMethod(), getCallOptions()), responseObserver); + } + + /** + */ + public io.grpc.stub.StreamObserver getMinMaxHitPoints( + io.grpc.stub.StreamObserver responseObserver) { + return asyncBidiStreamingCall( + getChannel().newCall(getGetMinMaxHitPointsMethod(), getCallOptions()), responseObserver); + } + } + + /** + */ + public static final class MonsterStorageBlockingStub extends io.grpc.stub.AbstractStub { + private MonsterStorageBlockingStub(io.grpc.Channel channel) { + super(channel); + } + + private MonsterStorageBlockingStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected MonsterStorageBlockingStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new MonsterStorageBlockingStub(channel, callOptions); + } + + /** + */ + public MyGame.Example.Stat store(MyGame.Example.Monster request) { + return blockingUnaryCall( + getChannel(), getStoreMethod(), getCallOptions(), request); + } + + /** + */ + public java.util.Iterator retrieve( + MyGame.Example.Stat request) { + return blockingServerStreamingCall( + getChannel(), getRetrieveMethod(), getCallOptions(), request); + } + } + + /** + */ + public static final class MonsterStorageFutureStub extends io.grpc.stub.AbstractStub { + private MonsterStorageFutureStub(io.grpc.Channel channel) { + super(channel); + } + + private MonsterStorageFutureStub(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + super(channel, callOptions); + } + + @java.lang.Override + protected MonsterStorageFutureStub build(io.grpc.Channel channel, + io.grpc.CallOptions callOptions) { + return new MonsterStorageFutureStub(channel, callOptions); + } + + /** + */ + public com.google.common.util.concurrent.ListenableFuture store( + MyGame.Example.Monster request) { + return futureUnaryCall( + getChannel().newCall(getStoreMethod(), getCallOptions()), request); + } + } + + private static final int METHODID_STORE = 0; + private static final int METHODID_RETRIEVE = 1; + private static final int METHODID_GET_MIN_MAX_HIT_POINTS = 2; + private static final int METHODID_GET_MAX_HIT_POINT = 3; + + private static final class MethodHandlers implements + io.grpc.stub.ServerCalls.UnaryMethod, + io.grpc.stub.ServerCalls.ServerStreamingMethod, + io.grpc.stub.ServerCalls.ClientStreamingMethod, + io.grpc.stub.ServerCalls.BidiStreamingMethod { + private final MonsterStorageImplBase serviceImpl; + private final int methodId; + + MethodHandlers(MonsterStorageImplBase serviceImpl, int methodId) { + this.serviceImpl = serviceImpl; + this.methodId = methodId; + } + + @java.lang.Override + @java.lang.SuppressWarnings("unchecked") + public void invoke(Req request, io.grpc.stub.StreamObserver responseObserver) { + switch (methodId) { + case METHODID_STORE: + serviceImpl.store((MyGame.Example.Monster) request, + (io.grpc.stub.StreamObserver) responseObserver); + break; + case METHODID_RETRIEVE: + serviceImpl.retrieve((MyGame.Example.Stat) request, + (io.grpc.stub.StreamObserver) responseObserver); + break; + default: + throw new AssertionError(); + } + } + + @java.lang.Override + @java.lang.SuppressWarnings("unchecked") + public io.grpc.stub.StreamObserver invoke( + io.grpc.stub.StreamObserver responseObserver) { + switch (methodId) { + case METHODID_GET_MAX_HIT_POINT: + return (io.grpc.stub.StreamObserver) serviceImpl.getMaxHitPoint( + (io.grpc.stub.StreamObserver) responseObserver); + case METHODID_GET_MIN_MAX_HIT_POINTS: + return (io.grpc.stub.StreamObserver) serviceImpl.getMinMaxHitPoints( + (io.grpc.stub.StreamObserver) responseObserver); + default: + throw new AssertionError(); + } + } + } + + private static volatile io.grpc.ServiceDescriptor serviceDescriptor; + + public static io.grpc.ServiceDescriptor getServiceDescriptor() { + io.grpc.ServiceDescriptor result = serviceDescriptor; + if (result == null) { + synchronized (MonsterStorageGrpc.class) { + result = serviceDescriptor; + if (result == null) { + serviceDescriptor = result = io.grpc.ServiceDescriptor.newBuilder(SERVICE_NAME) + .setSchemaDescriptor(null) + .addMethod(getStoreMethod()) + .addMethod(getRetrieveMethod()) + .addMethod(getGetMaxHitPointMethod()) + .addMethod(getGetMinMaxHitPointsMethod()) + .build(); + } + } + } + return result; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/MonsterStorage_grpc.go b/third_party/flatbuffers/tests/MyGame/Example/MonsterStorage_grpc.go new file mode 100644 index 00000000000..4d9f104a5b7 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/MonsterStorage_grpc.go @@ -0,0 +1,302 @@ +//Generated by gRPC Go plugin +//If you make any local changes, they will be lost +//source: monster_test + +package Example + +import ( + context "context" + flatbuffers "github.com/google/flatbuffers/go" + grpc "google.golang.org/grpc" + "google.golang.org/grpc/codes" + "google.golang.org/grpc/status" +) + +// Client API for MonsterStorage service +type MonsterStorageClient interface { + Store(ctx context.Context, in *flatbuffers.Builder, + opts ...grpc.CallOption) (*Stat, error) + Retrieve(ctx context.Context, in *flatbuffers.Builder, + opts ...grpc.CallOption) (MonsterStorage_RetrieveClient, error) + GetMaxHitPoint(ctx context.Context, + opts ...grpc.CallOption) (MonsterStorage_GetMaxHitPointClient, error) + GetMinMaxHitPoints(ctx context.Context, + opts ...grpc.CallOption) (MonsterStorage_GetMinMaxHitPointsClient, error) +} + +type monsterStorageClient struct { + cc grpc.ClientConnInterface +} + +func NewMonsterStorageClient(cc grpc.ClientConnInterface) MonsterStorageClient { + return &monsterStorageClient{cc} +} + +func (c *monsterStorageClient) Store(ctx context.Context, in *flatbuffers.Builder, + opts ...grpc.CallOption) (*Stat, error) { + out := new(Stat) + err := c.cc.Invoke(ctx, "/MyGame.Example.MonsterStorage/Store", in, out, opts...) + if err != nil { + return nil, err + } + return out, nil +} + +func (c *monsterStorageClient) Retrieve(ctx context.Context, in *flatbuffers.Builder, + opts ...grpc.CallOption) (MonsterStorage_RetrieveClient, error) { + stream, err := c.cc.NewStream(ctx, &_MonsterStorage_serviceDesc.Streams[0], "/MyGame.Example.MonsterStorage/Retrieve", opts...) + if err != nil { + return nil, err + } + x := &monsterStorageRetrieveClient{stream} + if err := x.ClientStream.SendMsg(in); err != nil { + return nil, err + } + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + return x, nil +} + +type MonsterStorage_RetrieveClient interface { + Recv() (*Monster, error) + grpc.ClientStream +} + +type monsterStorageRetrieveClient struct { + grpc.ClientStream +} + +func (x *monsterStorageRetrieveClient) Recv() (*Monster, error) { + m := new(Monster) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *monsterStorageClient) GetMaxHitPoint(ctx context.Context, + opts ...grpc.CallOption) (MonsterStorage_GetMaxHitPointClient, error) { + stream, err := c.cc.NewStream(ctx, &_MonsterStorage_serviceDesc.Streams[1], "/MyGame.Example.MonsterStorage/GetMaxHitPoint", opts...) + if err != nil { + return nil, err + } + x := &monsterStorageGetMaxHitPointClient{stream} + return x, nil +} + +type MonsterStorage_GetMaxHitPointClient interface { + Send(*flatbuffers.Builder) error + CloseAndRecv() (*Stat, error) + grpc.ClientStream +} + +type monsterStorageGetMaxHitPointClient struct { + grpc.ClientStream +} + +func (x *monsterStorageGetMaxHitPointClient) Send(m *flatbuffers.Builder) error { + return x.ClientStream.SendMsg(m) +} + +func (x *monsterStorageGetMaxHitPointClient) CloseAndRecv() (*Stat, error) { + if err := x.ClientStream.CloseSend(); err != nil { + return nil, err + } + m := new(Stat) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (c *monsterStorageClient) GetMinMaxHitPoints(ctx context.Context, + opts ...grpc.CallOption) (MonsterStorage_GetMinMaxHitPointsClient, error) { + stream, err := c.cc.NewStream(ctx, &_MonsterStorage_serviceDesc.Streams[2], "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", opts...) + if err != nil { + return nil, err + } + x := &monsterStorageGetMinMaxHitPointsClient{stream} + return x, nil +} + +type MonsterStorage_GetMinMaxHitPointsClient interface { + Send(*flatbuffers.Builder) error + Recv() (*Stat, error) + grpc.ClientStream +} + +type monsterStorageGetMinMaxHitPointsClient struct { + grpc.ClientStream +} + +func (x *monsterStorageGetMinMaxHitPointsClient) Send(m *flatbuffers.Builder) error { + return x.ClientStream.SendMsg(m) +} + +func (x *monsterStorageGetMinMaxHitPointsClient) Recv() (*Stat, error) { + m := new(Stat) + if err := x.ClientStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +// Server API for MonsterStorage service +type MonsterStorageServer interface { + Store(context.Context, *Monster) (*flatbuffers.Builder, error) + Retrieve(*Stat, MonsterStorage_RetrieveServer) error + GetMaxHitPoint(MonsterStorage_GetMaxHitPointServer) error + GetMinMaxHitPoints(MonsterStorage_GetMinMaxHitPointsServer) error + mustEmbedUnimplementedMonsterStorageServer() +} + +type UnimplementedMonsterStorageServer struct { +} + +func (UnimplementedMonsterStorageServer) Store(context.Context, *Monster) (*flatbuffers.Builder, error) { + return nil, status.Errorf(codes.Unimplemented, "method Store not implemented") +} + +func (UnimplementedMonsterStorageServer) Retrieve(*Stat, MonsterStorage_RetrieveServer) error { + return status.Errorf(codes.Unimplemented, "method Retrieve not implemented") +} + +func (UnimplementedMonsterStorageServer) GetMaxHitPoint(MonsterStorage_GetMaxHitPointServer) error { + return status.Errorf(codes.Unimplemented, "method GetMaxHitPoint not implemented") +} + +func (UnimplementedMonsterStorageServer) GetMinMaxHitPoints(MonsterStorage_GetMinMaxHitPointsServer) error { + return status.Errorf(codes.Unimplemented, "method GetMinMaxHitPoints not implemented") +} + +func (UnimplementedMonsterStorageServer) mustEmbedUnimplementedMonsterStorageServer() {} + +type UnsafeMonsterStorageServer interface { + mustEmbedUnimplementedMonsterStorageServer() +} + +func RegisterMonsterStorageServer(s grpc.ServiceRegistrar, srv MonsterStorageServer) { + s.RegisterService(&_MonsterStorage_serviceDesc, srv) +} + +func _MonsterStorage_Store_Handler(srv interface{}, ctx context.Context, + dec func(interface{}) error, interceptor grpc.UnaryServerInterceptor) (interface{}, error) { + in := new(Monster) + if err := dec(in); err != nil { + return nil, err + } + if interceptor == nil { + return srv.(MonsterStorageServer).Store(ctx, in) + } + info := &grpc.UnaryServerInfo{ + Server: srv, + FullMethod: "/MyGame.Example.MonsterStorage/Store", + } + + handler := func(ctx context.Context, req interface{}) (interface{}, error) { + return srv.(MonsterStorageServer).Store(ctx, req.(*Monster)) + } + return interceptor(ctx, in, info, handler) +} +func _MonsterStorage_Retrieve_Handler(srv interface{}, stream grpc.ServerStream) error { + m := new(Stat) + if err := stream.RecvMsg(m); err != nil { + return err + } + return srv.(MonsterStorageServer).Retrieve(m, &monsterStorageRetrieveServer{stream}) +} + +type MonsterStorage_RetrieveServer interface { + Send(*flatbuffers.Builder) error + grpc.ServerStream +} + +type monsterStorageRetrieveServer struct { + grpc.ServerStream +} + +func (x *monsterStorageRetrieveServer) Send(m *flatbuffers.Builder) error { + return x.ServerStream.SendMsg(m) +} + +func _MonsterStorage_GetMaxHitPoint_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(MonsterStorageServer).GetMaxHitPoint(&monsterStorageGetMaxHitPointServer{stream}) +} + +type MonsterStorage_GetMaxHitPointServer interface { + Recv() (*Monster, error) + SendAndClose(*flatbuffers.Builder) error + grpc.ServerStream +} + +type monsterStorageGetMaxHitPointServer struct { + grpc.ServerStream +} + +func (x *monsterStorageGetMaxHitPointServer) Recv() (*Monster, error) { + m := new(Monster) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +func (x *monsterStorageGetMaxHitPointServer) SendAndClose(m *flatbuffers.Builder) error { + return x.ServerStream.SendMsg(m) +} + +func _MonsterStorage_GetMinMaxHitPoints_Handler(srv interface{}, stream grpc.ServerStream) error { + return srv.(MonsterStorageServer).GetMinMaxHitPoints(&monsterStorageGetMinMaxHitPointsServer{stream}) +} + +type MonsterStorage_GetMinMaxHitPointsServer interface { + Send(*flatbuffers.Builder) error + Recv() (*Monster, error) + grpc.ServerStream +} + +type monsterStorageGetMinMaxHitPointsServer struct { + grpc.ServerStream +} + +func (x *monsterStorageGetMinMaxHitPointsServer) Send(m *flatbuffers.Builder) error { + return x.ServerStream.SendMsg(m) +} + +func (x *monsterStorageGetMinMaxHitPointsServer) Recv() (*Monster, error) { + m := new(Monster) + if err := x.ServerStream.RecvMsg(m); err != nil { + return nil, err + } + return m, nil +} + +var _MonsterStorage_serviceDesc = grpc.ServiceDesc{ + ServiceName: "MyGame.Example.MonsterStorage", + HandlerType: (*MonsterStorageServer)(nil), + Methods: []grpc.MethodDesc{ + { + MethodName: "Store", + Handler: _MonsterStorage_Store_Handler, + }, + }, + Streams: []grpc.StreamDesc{ + { + StreamName: "Retrieve", + Handler: _MonsterStorage_Retrieve_Handler, + ServerStreams: true, + }, + { + StreamName: "GetMaxHitPoint", + Handler: _MonsterStorage_GetMaxHitPoint_Handler, + ClientStreams: true, + }, + { + StreamName: "GetMinMaxHitPoints", + Handler: _MonsterStorage_GetMinMaxHitPoints_Handler, + ServerStreams: true, + ClientStreams: true, + }, + }, +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/MonsterT.java b/third_party/flatbuffers/tests/MyGame/Example/MonsterT.java new file mode 100644 index 00000000000..622a4fa806b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/MonsterT.java @@ -0,0 +1,384 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class MonsterT { + private MyGame.Example.Vec3T pos; + private short mana; + private short hp; + private String name; + private int[] inventory; + private int color; + private MyGame.Example.AnyUnion test; + private MyGame.Example.TestT[] test4; + private String[] testarrayofstring; + private MyGame.Example.MonsterT[] testarrayoftables; + private MyGame.Example.MonsterT enemy; + private int[] testnestedflatbuffer; + private MyGame.Example.StatT testempty; + private boolean testbool; + private int testhashs32Fnv1; + private long testhashu32Fnv1; + private long testhashs64Fnv1; + private long testhashu64Fnv1; + private int testhashs32Fnv1a; + private long testhashu32Fnv1a; + private long testhashs64Fnv1a; + private long testhashu64Fnv1a; + private boolean[] testarrayofbools; + private float testf; + private float testf2; + private float testf3; + private String[] testarrayofstring2; + private MyGame.Example.AbilityT[] testarrayofsortedstruct; + private int[] flex; + private MyGame.Example.TestT[] test5; + private long[] vectorOfLongs; + private double[] vectorOfDoubles; + private MyGame.InParentNamespaceT parentNamespaceTest; + private MyGame.Example.ReferrableT[] vectorOfReferrables; + private long singleWeakReference; + private long[] vectorOfWeakReferences; + private MyGame.Example.ReferrableT[] vectorOfStrongReferrables; + private long coOwningReference; + private long[] vectorOfCoOwningReferences; + private long nonOwningReference; + private long[] vectorOfNonOwningReferences; + private MyGame.Example.AnyUniqueAliasesUnion anyUnique; + private MyGame.Example.AnyAmbiguousAliasesUnion anyAmbiguous; + private int[] vectorOfEnums; + private byte signedEnum; + private int[] testrequirednestedflatbuffer; + private MyGame.Example.StatT[] scalarKeySortedTables; + private MyGame.Example.TestT nativeInline; + private long longEnumNonEnumDefault; + private long longEnumNormalDefault; + private float nanDefault; + private float infDefault; + private float positiveInfDefault; + private float infinityDefault; + private float positiveInfinityDefault; + private float negativeInfDefault; + private float negativeInfinityDefault; + private double doubleInfDefault; + + public MyGame.Example.Vec3T getPos() { return pos; } + + public void setPos(MyGame.Example.Vec3T pos) { this.pos = pos; } + + public short getMana() { return mana; } + + public void setMana(short mana) { this.mana = mana; } + + public short getHp() { return hp; } + + public void setHp(short hp) { this.hp = hp; } + + public String getName() { return name; } + + public void setName(String name) { this.name = name; } + + public int[] getInventory() { return inventory; } + + public void setInventory(int[] inventory) { this.inventory = inventory; } + + public int getColor() { return color; } + + public void setColor(int color) { this.color = color; } + + public MyGame.Example.AnyUnion getTest() { return test; } + + public void setTest(MyGame.Example.AnyUnion test) { this.test = test; } + + public MyGame.Example.TestT[] getTest4() { return test4; } + + public void setTest4(MyGame.Example.TestT[] test4) { this.test4 = test4; } + + public String[] getTestarrayofstring() { return testarrayofstring; } + + public void setTestarrayofstring(String[] testarrayofstring) { this.testarrayofstring = testarrayofstring; } + + public MyGame.Example.MonsterT[] getTestarrayoftables() { return testarrayoftables; } + + public void setTestarrayoftables(MyGame.Example.MonsterT[] testarrayoftables) { this.testarrayoftables = testarrayoftables; } + + public MyGame.Example.MonsterT getEnemy() { return enemy; } + + public void setEnemy(MyGame.Example.MonsterT enemy) { this.enemy = enemy; } + + public int[] getTestnestedflatbuffer() { return testnestedflatbuffer; } + + public void setTestnestedflatbuffer(int[] testnestedflatbuffer) { this.testnestedflatbuffer = testnestedflatbuffer; } + + public MyGame.Example.StatT getTestempty() { return testempty; } + + public void setTestempty(MyGame.Example.StatT testempty) { this.testempty = testempty; } + + public boolean getTestbool() { return testbool; } + + public void setTestbool(boolean testbool) { this.testbool = testbool; } + + public int getTesthashs32Fnv1() { return testhashs32Fnv1; } + + public void setTesthashs32Fnv1(int testhashs32Fnv1) { this.testhashs32Fnv1 = testhashs32Fnv1; } + + public long getTesthashu32Fnv1() { return testhashu32Fnv1; } + + public void setTesthashu32Fnv1(long testhashu32Fnv1) { this.testhashu32Fnv1 = testhashu32Fnv1; } + + public long getTesthashs64Fnv1() { return testhashs64Fnv1; } + + public void setTesthashs64Fnv1(long testhashs64Fnv1) { this.testhashs64Fnv1 = testhashs64Fnv1; } + + public long getTesthashu64Fnv1() { return testhashu64Fnv1; } + + public void setTesthashu64Fnv1(long testhashu64Fnv1) { this.testhashu64Fnv1 = testhashu64Fnv1; } + + public int getTesthashs32Fnv1a() { return testhashs32Fnv1a; } + + public void setTesthashs32Fnv1a(int testhashs32Fnv1a) { this.testhashs32Fnv1a = testhashs32Fnv1a; } + + public long getTesthashu32Fnv1a() { return testhashu32Fnv1a; } + + public void setTesthashu32Fnv1a(long testhashu32Fnv1a) { this.testhashu32Fnv1a = testhashu32Fnv1a; } + + public long getTesthashs64Fnv1a() { return testhashs64Fnv1a; } + + public void setTesthashs64Fnv1a(long testhashs64Fnv1a) { this.testhashs64Fnv1a = testhashs64Fnv1a; } + + public long getTesthashu64Fnv1a() { return testhashu64Fnv1a; } + + public void setTesthashu64Fnv1a(long testhashu64Fnv1a) { this.testhashu64Fnv1a = testhashu64Fnv1a; } + + public boolean[] getTestarrayofbools() { return testarrayofbools; } + + public void setTestarrayofbools(boolean[] testarrayofbools) { this.testarrayofbools = testarrayofbools; } + + public float getTestf() { return testf; } + + public void setTestf(float testf) { this.testf = testf; } + + public float getTestf2() { return testf2; } + + public void setTestf2(float testf2) { this.testf2 = testf2; } + + public float getTestf3() { return testf3; } + + public void setTestf3(float testf3) { this.testf3 = testf3; } + + public String[] getTestarrayofstring2() { return testarrayofstring2; } + + public void setTestarrayofstring2(String[] testarrayofstring2) { this.testarrayofstring2 = testarrayofstring2; } + + public MyGame.Example.AbilityT[] getTestarrayofsortedstruct() { return testarrayofsortedstruct; } + + public void setTestarrayofsortedstruct(MyGame.Example.AbilityT[] testarrayofsortedstruct) { this.testarrayofsortedstruct = testarrayofsortedstruct; } + + public int[] getFlex() { return flex; } + + public void setFlex(int[] flex) { this.flex = flex; } + + public MyGame.Example.TestT[] getTest5() { return test5; } + + public void setTest5(MyGame.Example.TestT[] test5) { this.test5 = test5; } + + public long[] getVectorOfLongs() { return vectorOfLongs; } + + public void setVectorOfLongs(long[] vectorOfLongs) { this.vectorOfLongs = vectorOfLongs; } + + public double[] getVectorOfDoubles() { return vectorOfDoubles; } + + public void setVectorOfDoubles(double[] vectorOfDoubles) { this.vectorOfDoubles = vectorOfDoubles; } + + public MyGame.InParentNamespaceT getParentNamespaceTest() { return parentNamespaceTest; } + + public void setParentNamespaceTest(MyGame.InParentNamespaceT parentNamespaceTest) { this.parentNamespaceTest = parentNamespaceTest; } + + public MyGame.Example.ReferrableT[] getVectorOfReferrables() { return vectorOfReferrables; } + + public void setVectorOfReferrables(MyGame.Example.ReferrableT[] vectorOfReferrables) { this.vectorOfReferrables = vectorOfReferrables; } + + public long getSingleWeakReference() { return singleWeakReference; } + + public void setSingleWeakReference(long singleWeakReference) { this.singleWeakReference = singleWeakReference; } + + public long[] getVectorOfWeakReferences() { return vectorOfWeakReferences; } + + public void setVectorOfWeakReferences(long[] vectorOfWeakReferences) { this.vectorOfWeakReferences = vectorOfWeakReferences; } + + public MyGame.Example.ReferrableT[] getVectorOfStrongReferrables() { return vectorOfStrongReferrables; } + + public void setVectorOfStrongReferrables(MyGame.Example.ReferrableT[] vectorOfStrongReferrables) { this.vectorOfStrongReferrables = vectorOfStrongReferrables; } + + public long getCoOwningReference() { return coOwningReference; } + + public void setCoOwningReference(long coOwningReference) { this.coOwningReference = coOwningReference; } + + public long[] getVectorOfCoOwningReferences() { return vectorOfCoOwningReferences; } + + public void setVectorOfCoOwningReferences(long[] vectorOfCoOwningReferences) { this.vectorOfCoOwningReferences = vectorOfCoOwningReferences; } + + public long getNonOwningReference() { return nonOwningReference; } + + public void setNonOwningReference(long nonOwningReference) { this.nonOwningReference = nonOwningReference; } + + public long[] getVectorOfNonOwningReferences() { return vectorOfNonOwningReferences; } + + public void setVectorOfNonOwningReferences(long[] vectorOfNonOwningReferences) { this.vectorOfNonOwningReferences = vectorOfNonOwningReferences; } + + public MyGame.Example.AnyUniqueAliasesUnion getAnyUnique() { return anyUnique; } + + public void setAnyUnique(MyGame.Example.AnyUniqueAliasesUnion anyUnique) { this.anyUnique = anyUnique; } + + public MyGame.Example.AnyAmbiguousAliasesUnion getAnyAmbiguous() { return anyAmbiguous; } + + public void setAnyAmbiguous(MyGame.Example.AnyAmbiguousAliasesUnion anyAmbiguous) { this.anyAmbiguous = anyAmbiguous; } + + public int[] getVectorOfEnums() { return vectorOfEnums; } + + public void setVectorOfEnums(int[] vectorOfEnums) { this.vectorOfEnums = vectorOfEnums; } + + public byte getSignedEnum() { return signedEnum; } + + public void setSignedEnum(byte signedEnum) { this.signedEnum = signedEnum; } + + public int[] getTestrequirednestedflatbuffer() { return testrequirednestedflatbuffer; } + + public void setTestrequirednestedflatbuffer(int[] testrequirednestedflatbuffer) { this.testrequirednestedflatbuffer = testrequirednestedflatbuffer; } + + public MyGame.Example.StatT[] getScalarKeySortedTables() { return scalarKeySortedTables; } + + public void setScalarKeySortedTables(MyGame.Example.StatT[] scalarKeySortedTables) { this.scalarKeySortedTables = scalarKeySortedTables; } + + public MyGame.Example.TestT getNativeInline() { return nativeInline; } + + public void setNativeInline(MyGame.Example.TestT nativeInline) { this.nativeInline = nativeInline; } + + public long getLongEnumNonEnumDefault() { return longEnumNonEnumDefault; } + + public void setLongEnumNonEnumDefault(long longEnumNonEnumDefault) { this.longEnumNonEnumDefault = longEnumNonEnumDefault; } + + public long getLongEnumNormalDefault() { return longEnumNormalDefault; } + + public void setLongEnumNormalDefault(long longEnumNormalDefault) { this.longEnumNormalDefault = longEnumNormalDefault; } + + public float getNanDefault() { return nanDefault; } + + public void setNanDefault(float nanDefault) { this.nanDefault = nanDefault; } + + public float getInfDefault() { return infDefault; } + + public void setInfDefault(float infDefault) { this.infDefault = infDefault; } + + public float getPositiveInfDefault() { return positiveInfDefault; } + + public void setPositiveInfDefault(float positiveInfDefault) { this.positiveInfDefault = positiveInfDefault; } + + public float getInfinityDefault() { return infinityDefault; } + + public void setInfinityDefault(float infinityDefault) { this.infinityDefault = infinityDefault; } + + public float getPositiveInfinityDefault() { return positiveInfinityDefault; } + + public void setPositiveInfinityDefault(float positiveInfinityDefault) { this.positiveInfinityDefault = positiveInfinityDefault; } + + public float getNegativeInfDefault() { return negativeInfDefault; } + + public void setNegativeInfDefault(float negativeInfDefault) { this.negativeInfDefault = negativeInfDefault; } + + public float getNegativeInfinityDefault() { return negativeInfinityDefault; } + + public void setNegativeInfinityDefault(float negativeInfinityDefault) { this.negativeInfinityDefault = negativeInfinityDefault; } + + public double getDoubleInfDefault() { return doubleInfDefault; } + + public void setDoubleInfDefault(double doubleInfDefault) { this.doubleInfDefault = doubleInfDefault; } + + + public MonsterT() { + this.pos = new MyGame.Example.Vec3T(); + this.mana = 150; + this.hp = 100; + this.name = null; + this.inventory = null; + this.color = 8; + this.test = null; + this.test4 = null; + this.testarrayofstring = null; + this.testarrayoftables = null; + this.enemy = null; + this.testnestedflatbuffer = null; + this.testempty = null; + this.testbool = false; + this.testhashs32Fnv1 = 0; + this.testhashu32Fnv1 = 0L; + this.testhashs64Fnv1 = 0L; + this.testhashu64Fnv1 = 0L; + this.testhashs32Fnv1a = 0; + this.testhashu32Fnv1a = 0L; + this.testhashs64Fnv1a = 0L; + this.testhashu64Fnv1a = 0L; + this.testarrayofbools = null; + this.testf = 3.14159f; + this.testf2 = 3.0f; + this.testf3 = 0.0f; + this.testarrayofstring2 = null; + this.testarrayofsortedstruct = null; + this.flex = null; + this.test5 = null; + this.vectorOfLongs = null; + this.vectorOfDoubles = null; + this.parentNamespaceTest = null; + this.vectorOfReferrables = null; + this.singleWeakReference = 0L; + this.vectorOfWeakReferences = null; + this.vectorOfStrongReferrables = null; + this.coOwningReference = 0L; + this.vectorOfCoOwningReferences = null; + this.nonOwningReference = 0L; + this.vectorOfNonOwningReferences = null; + this.anyUnique = null; + this.anyAmbiguous = null; + this.vectorOfEnums = null; + this.signedEnum = -1; + this.testrequirednestedflatbuffer = null; + this.scalarKeySortedTables = null; + this.nativeInline = new MyGame.Example.TestT(); + this.longEnumNonEnumDefault = 0L; + this.longEnumNormalDefault = 2L; + this.nanDefault = Float.NaN; + this.infDefault = Float.POSITIVE_INFINITY; + this.positiveInfDefault = Float.POSITIVE_INFINITY; + this.infinityDefault = Float.POSITIVE_INFINITY; + this.positiveInfinityDefault = Float.POSITIVE_INFINITY; + this.negativeInfDefault = Float.NEGATIVE_INFINITY; + this.negativeInfinityDefault = Float.NEGATIVE_INFINITY; + this.doubleInfDefault = Double.POSITIVE_INFINITY; + } + public static MonsterT deserializeFromBinary(byte[] fbBuffer) { + return Monster.getRootAsMonster(ByteBuffer.wrap(fbBuffer)).unpack(); + } + public byte[] serializeToBinary() { + FlatBufferBuilder fbb = new FlatBufferBuilder(); + Monster.finishMonsterBuffer(fbb, Monster.pack(fbb, this)); + return fbb.sizedByteArray(); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.cs b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.cs new file mode 100644 index 00000000000..78173acc613 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.cs @@ -0,0 +1,91 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct NestedStruct : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public NestedStruct __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int A(int j) { return __p.bb.GetInt(__p.bb_pos + 0 + j * 4); } + public void MutateA(int j, int a) { __p.bb.PutInt(__p.bb_pos + 0 + j * 4, a); } + public MyGame.Example.TestEnum B { get { return (MyGame.Example.TestEnum)__p.bb.GetSbyte(__p.bb_pos + 8); } } + public void MutateB(MyGame.Example.TestEnum b) { __p.bb.PutSbyte(__p.bb_pos + 8, (sbyte)b); } + public MyGame.Example.TestEnum C(int j) { return (MyGame.Example.TestEnum)__p.bb.GetSbyte(__p.bb_pos + 9 + j * 1); } + public void MutateC(int j, MyGame.Example.TestEnum c) { __p.bb.PutSbyte(__p.bb_pos + 9 + j * 1, (sbyte)c); } + public long D(int j) { return __p.bb.GetLong(__p.bb_pos + 16 + j * 8); } + public void MutateD(int j, long d) { __p.bb.PutLong(__p.bb_pos + 16 + j * 8, d); } + + public static Offset CreateNestedStruct(FlatBufferBuilder builder, int[] A, MyGame.Example.TestEnum B, MyGame.Example.TestEnum[] C, long[] D) { + builder.Prep(8, 32); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.PutLong(D[_idx0-1]); + } + builder.Pad(5); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.PutSbyte((sbyte)C[_idx0-1]); + } + builder.PutSbyte((sbyte)B); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.PutInt(A[_idx0-1]); + } + return new Offset(builder.Offset); + } + public NestedStructT UnPack() { + var _o = new NestedStructT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(NestedStructT _o) { + _o.A = new int[2]; + for (var _j = 0; _j < 2; ++_j) { _o.A[_j] = this.A(_j); } + _o.B = this.B; + _o.C = new MyGame.Example.TestEnum[2]; + for (var _j = 0; _j < 2; ++_j) { _o.C[_j] = this.C(_j); } + _o.D = new long[2]; + for (var _j = 0; _j < 2; ++_j) { _o.D[_j] = this.D(_j); } + } + public static Offset Pack(FlatBufferBuilder builder, NestedStructT _o) { + if (_o == null) return default(Offset); + var _a = _o.A; + var _c = _o.C; + var _d = _o.D; + return CreateNestedStruct( + builder, + _a, + _o.B, + _c, + _d); + } +} + +public class NestedStructT +{ + [Newtonsoft.Json.JsonProperty("a")] + public int[] A { get; set; } + [Newtonsoft.Json.JsonProperty("b")] + public MyGame.Example.TestEnum B { get; set; } + [Newtonsoft.Json.JsonProperty("c")] + public MyGame.Example.TestEnum[] C { get; set; } + [Newtonsoft.Json.JsonProperty("d")] + public long[] D { get; set; } + + public NestedStructT() { + this.A = new int[2]; + this.B = MyGame.Example.TestEnum.A; + this.C = new MyGame.Example.TestEnum[2]; + this.D = new long[2]; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.java b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.java new file mode 100644 index 00000000000..0d33f71332e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.java @@ -0,0 +1,86 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class NestedStruct extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public NestedStruct __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int a(int j) { return bb.getInt(bb_pos + 0 + j * 4); } + public void mutateA(int j, int a) { bb.putInt(bb_pos + 0 + j * 4, a); } + public byte b() { return bb.get(bb_pos + 8); } + public void mutateB(byte b) { bb.put(bb_pos + 8, b); } + public byte c(int j) { return bb.get(bb_pos + 9 + j * 1); } + public void mutateC(int j, byte c) { bb.put(bb_pos + 9 + j * 1, c); } + public long d(int j) { return bb.getLong(bb_pos + 16 + j * 8); } + public void mutateD(int j, long d) { bb.putLong(bb_pos + 16 + j * 8, d); } + + public static int createNestedStruct(FlatBufferBuilder builder, int[] a, byte b, byte[] c, long[] d) { + builder.prep(8, 32); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.putLong(d[_idx0-1]); + } + builder.pad(5); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.putByte(c[_idx0-1]); + } + builder.putByte(b); + for (int _idx0 = 2; _idx0 > 0; _idx0--) { + builder.putInt(a[_idx0-1]); + } + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public NestedStruct get(int j) { return get(new NestedStruct(), j); } + public NestedStruct get(NestedStruct obj, int j) { return obj.__assign(__element(j), bb); } + } + public NestedStructT unpack() { + NestedStructT _o = new NestedStructT(); + unpackTo(_o); + return _o; + } + public void unpackTo(NestedStructT _o) { + int[] _oA = _o.getA(); + for (int _j = 0; _j < 2; ++_j) { _oA[_j] = a(_j); } + byte _oB = b(); + _o.setB(_oB); + byte[] _oC = _o.getC(); + for (int _j = 0; _j < 2; ++_j) { _oC[_j] = c(_j); } + long[] _oD = _o.getD(); + for (int _j = 0; _j < 2; ++_j) { _oD[_j] = d(_j); } + } + public static int pack(FlatBufferBuilder builder, NestedStructT _o) { + if (_o == null) return 0; + int[] _a = _o.getA(); + byte[] _c = _o.getC(); + long[] _d = _o.getD(); + return createNestedStruct( + builder, + _a, + _o.getB(), + _c, + _d); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.py b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.py new file mode 100644 index 00000000000..d5d672a2eab --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.py @@ -0,0 +1,159 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +np = import_numpy() + +class NestedStruct(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls) -> int: + return 32 + + # NestedStruct + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # NestedStruct + def A(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0 + i * 4)) for i in range(self.ALength())] + elif j >= 0 and j < self.ALength(): + return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0 + j * 4)) + else: + return None + + # NestedStruct + def AAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int32Flags, self._tab.Pos + 0, self.ALength()) + + # NestedStruct + def ALength(self) -> int: + return 2 + + # NestedStruct + def AIsNone(self) -> bool: + return False + + # NestedStruct + def B(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8)) + # NestedStruct + def C(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(9 + i * 1)) for i in range(self.CLength())] + elif j >= 0 and j < self.CLength(): + return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(9 + j * 1)) + else: + return None + + # NestedStruct + def CAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int8Flags, self._tab.Pos + 9, self.CLength()) + + # NestedStruct + def CLength(self) -> int: + return 2 + + # NestedStruct + def CIsNone(self) -> bool: + return False + + # NestedStruct + def D(self, j = None): + if j is None: + return [self._tab.Get(flatbuffers.number_types.Int64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16 + i * 8)) for i in range(self.DLength())] + elif j >= 0 and j < self.DLength(): + return self._tab.Get(flatbuffers.number_types.Int64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16 + j * 8)) + else: + return None + + # NestedStruct + def DAsNumpy(self): + return self._tab.GetArrayAsNumpy(flatbuffers.number_types.Int64Flags, self._tab.Pos + 16, self.DLength()) + + # NestedStruct + def DLength(self) -> int: + return 2 + + # NestedStruct + def DIsNone(self) -> bool: + return False + + +def CreateNestedStruct(builder, a, b, c, d): + builder.Prep(8, 32) + for _idx0 in range(2 , 0, -1): + builder.PrependInt64(d[_idx0-1]) + builder.Pad(5) + for _idx0 in range(2 , 0, -1): + builder.PrependInt8(c[_idx0-1]) + builder.PrependInt8(b) + for _idx0 in range(2 , 0, -1): + builder.PrependInt32(a[_idx0-1]) + return builder.Offset() + +try: + from typing import List +except: + pass + +class NestedStructT(object): + + # NestedStructT + def __init__(self): + self.a = None # type: List[int] + self.b = 0 # type: int + self.c = None # type: List[int] + self.d = None # type: List[int] + + @classmethod + def InitFromBuf(cls, buf, pos): + nestedStruct = NestedStruct() + nestedStruct.Init(buf, pos) + return cls.InitFromObj(nestedStruct) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, nestedStruct): + x = NestedStructT() + x._UnPack(nestedStruct) + return x + + # NestedStructT + def _UnPack(self, nestedStruct): + if nestedStruct is None: + return + if not nestedStruct.AIsNone(): + if np is None: + self.a = [] + for i in range(nestedStruct.ALength()): + self.a.append(nestedStruct.A(i)) + else: + self.a = nestedStruct.AAsNumpy() + self.b = nestedStruct.B() + if not nestedStruct.CIsNone(): + if np is None: + self.c = [] + for i in range(nestedStruct.CLength()): + self.c.append(nestedStruct.C(i)) + else: + self.c = nestedStruct.CAsNumpy() + if not nestedStruct.DIsNone(): + if np is None: + self.d = [] + for i in range(nestedStruct.DLength()): + self.d.append(nestedStruct.D(i)) + else: + self.d = nestedStruct.DAsNumpy() + + # NestedStructT + def Pack(self, builder): + return CreateNestedStruct(builder, self.a, self.b, self.c, self.d) diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.pyi new file mode 100644 index 00000000000..09e6fc68927 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedStruct.pyi @@ -0,0 +1,46 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.NestedStruct import NestedStruct +from MyGame.Example.TestEnum import TestEnum + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class NestedStruct(object): + @classmethod + def SizeOf(cls) -> int: ... + + def Init(self, buf: bytes, pos: int) -> None: ... + def A(self, i: int) -> typing.List[int]: ... + def AAsNumpy(self) -> np.ndarray: ... + def ALength(self) -> int: ... + def AIsNone(self) -> bool: ... + def B(self) -> typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]: ... + def C(self, i: int) -> typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]: ... + def CAsNumpy(self) -> np.ndarray: ... + def CLength(self) -> int: ... + def CIsNone(self) -> bool: ... + def D(self, i: int) -> typing.List[int]: ... + def DAsNumpy(self) -> np.ndarray: ... + def DLength(self) -> int: ... + def DIsNone(self) -> bool: ... +class NestedStructT(object): + a: typing.List[int] + b: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C] + c: typing.List[typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C]] + d: typing.List[int] + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> NestedStructT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> NestedStructT: ... + @classmethod + def InitFromObj(cls, nestedStruct: NestedStruct) -> NestedStructT: ... + def _UnPack(self, nestedStruct: NestedStruct) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... + +def CreateNestedStruct(builder: flatbuffers.Builder, a: int, b: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C], c: typing.Literal[TestEnum.A, TestEnum.B, TestEnum.C], d: int) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedStructT.java b/third_party/flatbuffers/tests/MyGame/Example/NestedStructT.java new file mode 100644 index 00000000000..396522a9146 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedStructT.java @@ -0,0 +1,52 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class NestedStructT { + private int[] a; + private byte b; + private byte[] c; + private long[] d; + + public int[] getA() { return a; } + + public void setA(int[] a) { if (a != null && a.length == 2) this.a = a; } + + public byte getB() { return b; } + + public void setB(byte b) { this.b = b; } + + public byte[] getC() { return c; } + + public void setC(byte[] c) { if (c != null && c.length == 2) this.c = c; } + + public long[] getD() { return d; } + + public void setD(long[] d) { if (d != null && d.length == 2) this.d = d; } + + + public NestedStructT() { + this.a = new int[2]; + this.b = 0; + this.c = new byte[2]; + this.d = new long[2]; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Any.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Any.py new file mode 100644 index 00000000000..caf272720d7 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Any.py @@ -0,0 +1,20 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NestedUnion + +class Any(object): + NONE = 0 + Vec3 = 1 + TestSimpleTableWithEnum = 2 + +def AnyCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == Any.Vec3: + import MyGame.Example.NestedUnion.Vec3 + return MyGame.Example.NestedUnion.Vec3.Vec3T.InitFromBuf(table.Bytes, table.Pos) + if unionType == Any.TestSimpleTableWithEnum: + import MyGame.Example.NestedUnion.TestSimpleTableWithEnum + return MyGame.Example.NestedUnion.TestSimpleTableWithEnum.TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + return None diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Any.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Any.pyi new file mode 100644 index 00000000000..dee0f7f2e38 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Any.pyi @@ -0,0 +1,20 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.NestedUnion.Any import Any +from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnum +from MyGame.Example.NestedUnion.Vec3 import Vec3 +from flatbuffers import table + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class Any(object): + NONE: int + Vec3: int + TestSimpleTableWithEnum: int +def AnyCreator(union_type: typing.Literal[Any.NONE, Any.Vec3, Any.TestSimpleTableWithEnum], table: table.Table) -> typing.Union[None, Vec3, TestSimpleTableWithEnum]: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Color.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Color.py new file mode 100644 index 00000000000..6ba9ca1c633 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Color.py @@ -0,0 +1,12 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NestedUnion + +# Composite components of Monster color. +class Color(object): + Red = 1 + # \brief color Green + # Green is bit_flag with value (1u << 1) + Green = 2 + # \brief color Blue (1u << 3) + Blue = 8 diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Color.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Color.pyi new file mode 100644 index 00000000000..fe8879e2960 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Color.pyi @@ -0,0 +1,15 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class Color(object): + Red: int + Green: int + Blue: int + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/NestedUnionTest.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/NestedUnionTest.py new file mode 100644 index 00000000000..7540b6e8ad6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/NestedUnionTest.py @@ -0,0 +1,153 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NestedUnion + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +from flatbuffers.table import Table +from typing import Optional +np = import_numpy() + +class NestedUnionTest(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = NestedUnionTest() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsNestedUnionTest(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # NestedUnionTest + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # NestedUnionTest + def Name(self) -> Optional[str]: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # NestedUnionTest + def DataType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # NestedUnionTest + def Data(self) -> Optional[flatbuffers.table.Table]: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # NestedUnionTest + def Id(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 0 + +def NestedUnionTestStart(builder: flatbuffers.Builder): + builder.StartObject(4) + +def Start(builder: flatbuffers.Builder): + NestedUnionTestStart(builder) + +def NestedUnionTestAddName(builder: flatbuffers.Builder, name: int): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def AddName(builder: flatbuffers.Builder, name: int): + NestedUnionTestAddName(builder, name) + +def NestedUnionTestAddDataType(builder: flatbuffers.Builder, dataType: int): + builder.PrependUint8Slot(1, dataType, 0) + +def AddDataType(builder: flatbuffers.Builder, dataType: int): + NestedUnionTestAddDataType(builder, dataType) + +def NestedUnionTestAddData(builder: flatbuffers.Builder, data: int): + builder.PrependUOffsetTRelativeSlot(2, flatbuffers.number_types.UOffsetTFlags.py_type(data), 0) + +def AddData(builder: flatbuffers.Builder, data: int): + NestedUnionTestAddData(builder, data) + +def NestedUnionTestAddId(builder: flatbuffers.Builder, id: int): + builder.PrependInt16Slot(3, id, 0) + +def AddId(builder: flatbuffers.Builder, id: int): + NestedUnionTestAddId(builder, id) + +def NestedUnionTestEnd(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + +def End(builder: flatbuffers.Builder) -> int: + return NestedUnionTestEnd(builder) + +import MyGame.Example.NestedUnion.Any +import MyGame.Example.NestedUnion.TestSimpleTableWithEnum +import MyGame.Example.NestedUnion.Vec3 +try: + from typing import Union +except: + pass + +class NestedUnionTestT(object): + + # NestedUnionTestT + def __init__(self): + self.name = None # type: str + self.dataType = 0 # type: int + self.data = None # type: Union[None, MyGame.Example.NestedUnion.Vec3.Vec3T, MyGame.Example.NestedUnion.TestSimpleTableWithEnum.TestSimpleTableWithEnumT] + self.id = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + nestedUnionTest = NestedUnionTest() + nestedUnionTest.Init(buf, pos) + return cls.InitFromObj(nestedUnionTest) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, nestedUnionTest): + x = NestedUnionTestT() + x._UnPack(nestedUnionTest) + return x + + # NestedUnionTestT + def _UnPack(self, nestedUnionTest): + if nestedUnionTest is None: + return + self.name = nestedUnionTest.Name() + self.dataType = nestedUnionTest.DataType() + self.data = MyGame.Example.NestedUnion.Any.AnyCreator(self.dataType, nestedUnionTest.Data()) + self.id = nestedUnionTest.Id() + + # NestedUnionTestT + def Pack(self, builder): + if self.name is not None: + name = builder.CreateString(self.name) + if self.data is not None: + data = self.data.Pack(builder) + NestedUnionTestStart(builder) + if self.name is not None: + NestedUnionTestAddName(builder, name) + NestedUnionTestAddDataType(builder, self.dataType) + if self.data is not None: + NestedUnionTestAddData(builder, data) + NestedUnionTestAddId(builder, self.id) + nestedUnionTest = NestedUnionTestEnd(builder) + return nestedUnionTest diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/NestedUnionTest.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/NestedUnionTest.pyi new file mode 100644 index 00000000000..06a906d4024 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/NestedUnionTest.pyi @@ -0,0 +1,47 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.NestedUnion.Any import Any +from MyGame.Example.NestedUnion.NestedUnionTest import NestedUnionTest +from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnumT +from MyGame.Example.NestedUnion.Vec3 import Vec3T +from flatbuffers import table + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class NestedUnionTest(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> NestedUnionTest: ... + @classmethod + def GetRootAsNestedUnionTest(cls, buf: bytes, offset: int) -> NestedUnionTest: ... + def Init(self, buf: bytes, pos: int) -> None: ... + def Name(self) -> str | None: ... + def DataType(self) -> typing.Literal[Any.NONE, Any.Vec3, Any.TestSimpleTableWithEnum]: ... + def Data(self) -> table.Table | None: ... + def Id(self) -> int: ... +class NestedUnionTestT(object): + name: str | None + dataType: typing.Literal[Any.NONE, Any.Vec3, Any.TestSimpleTableWithEnum] + data: typing.Union[None, Vec3T, TestSimpleTableWithEnumT] + id: int + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> NestedUnionTestT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> NestedUnionTestT: ... + @classmethod + def InitFromObj(cls, nestedUnionTest: NestedUnionTest) -> NestedUnionTestT: ... + def _UnPack(self, nestedUnionTest: NestedUnionTest) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... +def NestedUnionTestStart(builder: flatbuffers.Builder) -> None: ... +def Start(builder: flatbuffers.Builder) -> None: ... +def NestedUnionTestAddName(builder: flatbuffers.Builder, name: uoffset) -> None: ... +def NestedUnionTestAddDataType(builder: flatbuffers.Builder, dataType: typing.Literal[Any.NONE, Any.Vec3, Any.TestSimpleTableWithEnum]) -> None: ... +def NestedUnionTestAddData(builder: flatbuffers.Builder, data: uoffset) -> None: ... +def NestedUnionTestAddId(builder: flatbuffers.Builder, id: int) -> None: ... +def NestedUnionTestEnd(builder: flatbuffers.Builder) -> uoffset: ... +def End(builder: flatbuffers.Builder) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Test.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Test.py new file mode 100644 index 00000000000..e4e90be27f4 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Test.py @@ -0,0 +1,67 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NestedUnion + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +np = import_numpy() + +class Test(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls) -> int: + return 4 + + # Test + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # Test + def A(self): return self._tab.Get(flatbuffers.number_types.Int16Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Test + def B(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(2)) + +def CreateTest(builder, a, b): + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b) + builder.PrependInt16(a) + return builder.Offset() + + +class TestT(object): + + # TestT + def __init__(self): + self.a = 0 # type: int + self.b = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + test = Test() + test.Init(buf, pos) + return cls.InitFromObj(test) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, test): + x = TestT() + x._UnPack(test) + return x + + # TestT + def _UnPack(self, test): + if test is None: + return + self.a = test.A() + self.b = test.B() + + # TestT + def Pack(self, builder): + return CreateTest(builder, self.a, self.b) diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Test.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Test.pyi new file mode 100644 index 00000000000..2fa64aa8202 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Test.pyi @@ -0,0 +1,32 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.NestedUnion.Test import Test + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class Test(object): + @classmethod + def SizeOf(cls) -> int: ... + + def Init(self, buf: bytes, pos: int) -> None: ... + def A(self) -> int: ... + def B(self) -> int: ... +class TestT(object): + a: int + b: int + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> TestT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> TestT: ... + @classmethod + def InitFromObj(cls, test: Test) -> TestT: ... + def _UnPack(self, test: Test) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... + +def CreateTest(builder: flatbuffers.Builder, a: int, b: int) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/TestSimpleTableWithEnum.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/TestSimpleTableWithEnum.py new file mode 100644 index 00000000000..9b7ef28c01f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/TestSimpleTableWithEnum.py @@ -0,0 +1,88 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NestedUnion + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +np = import_numpy() + +class TestSimpleTableWithEnum(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TestSimpleTableWithEnum() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTestSimpleTableWithEnum(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # TestSimpleTableWithEnum + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # TestSimpleTableWithEnum + def Color(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 2 + +def TestSimpleTableWithEnumStart(builder: flatbuffers.Builder): + builder.StartObject(1) + +def Start(builder: flatbuffers.Builder): + TestSimpleTableWithEnumStart(builder) + +def TestSimpleTableWithEnumAddColor(builder: flatbuffers.Builder, color: int): + builder.PrependUint8Slot(0, color, 2) + +def AddColor(builder: flatbuffers.Builder, color: int): + TestSimpleTableWithEnumAddColor(builder, color) + +def TestSimpleTableWithEnumEnd(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + +def End(builder: flatbuffers.Builder) -> int: + return TestSimpleTableWithEnumEnd(builder) + + +class TestSimpleTableWithEnumT(object): + + # TestSimpleTableWithEnumT + def __init__(self): + self.color = 2 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + testSimpleTableWithEnum = TestSimpleTableWithEnum() + testSimpleTableWithEnum.Init(buf, pos) + return cls.InitFromObj(testSimpleTableWithEnum) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, testSimpleTableWithEnum): + x = TestSimpleTableWithEnumT() + x._UnPack(testSimpleTableWithEnum) + return x + + # TestSimpleTableWithEnumT + def _UnPack(self, testSimpleTableWithEnum): + if testSimpleTableWithEnum is None: + return + self.color = testSimpleTableWithEnum.Color() + + # TestSimpleTableWithEnumT + def Pack(self, builder): + TestSimpleTableWithEnumStart(builder) + TestSimpleTableWithEnumAddColor(builder, self.color) + testSimpleTableWithEnum = TestSimpleTableWithEnumEnd(builder) + return testSimpleTableWithEnum diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/TestSimpleTableWithEnum.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/TestSimpleTableWithEnum.pyi new file mode 100644 index 00000000000..117b19d532d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/TestSimpleTableWithEnum.pyi @@ -0,0 +1,35 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.NestedUnion.Color import Color +from MyGame.Example.NestedUnion.TestSimpleTableWithEnum import TestSimpleTableWithEnum + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class TestSimpleTableWithEnum(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> TestSimpleTableWithEnum: ... + @classmethod + def GetRootAsTestSimpleTableWithEnum(cls, buf: bytes, offset: int) -> TestSimpleTableWithEnum: ... + def Init(self, buf: bytes, pos: int) -> None: ... + def Color(self) -> typing.Literal[Color.Red, Color.Green, Color.Blue]: ... +class TestSimpleTableWithEnumT(object): + color: typing.Literal[Color.Red, Color.Green, Color.Blue] + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> TestSimpleTableWithEnumT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> TestSimpleTableWithEnumT: ... + @classmethod + def InitFromObj(cls, testSimpleTableWithEnum: TestSimpleTableWithEnum) -> TestSimpleTableWithEnumT: ... + def _UnPack(self, testSimpleTableWithEnum: TestSimpleTableWithEnum) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... +def TestSimpleTableWithEnumStart(builder: flatbuffers.Builder) -> None: ... +def Start(builder: flatbuffers.Builder) -> None: ... +def TestSimpleTableWithEnumAddColor(builder: flatbuffers.Builder, color: typing.Literal[Color.Red, Color.Green, Color.Blue]) -> None: ... +def TestSimpleTableWithEnumEnd(builder: flatbuffers.Builder) -> uoffset: ... +def End(builder: flatbuffers.Builder) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Vec3.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Vec3.py new file mode 100644 index 00000000000..d0f8676f46e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Vec3.py @@ -0,0 +1,181 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NestedUnion + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +from MyGame.Example.NestedUnion.Test import Test +from typing import Optional +np = import_numpy() + +class Vec3(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Vec3() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsVec3(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # Vec3 + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # Vec3 + def X(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # Vec3 + def Y(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # Vec3 + def Z(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # Vec3 + def Test1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # Vec3 + def Test2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Vec3 + def Test3(self) -> Optional[Test]: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + x = o + self._tab.Pos + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def Vec3Start(builder: flatbuffers.Builder): + builder.StartObject(6) + +def Start(builder: flatbuffers.Builder): + Vec3Start(builder) + +def Vec3AddX(builder: flatbuffers.Builder, x: float): + builder.PrependFloat64Slot(0, x, 0.0) + +def AddX(builder: flatbuffers.Builder, x: float): + Vec3AddX(builder, x) + +def Vec3AddY(builder: flatbuffers.Builder, y: float): + builder.PrependFloat64Slot(1, y, 0.0) + +def AddY(builder: flatbuffers.Builder, y: float): + Vec3AddY(builder, y) + +def Vec3AddZ(builder: flatbuffers.Builder, z: float): + builder.PrependFloat64Slot(2, z, 0.0) + +def AddZ(builder: flatbuffers.Builder, z: float): + Vec3AddZ(builder, z) + +def Vec3AddTest1(builder: flatbuffers.Builder, test1: float): + builder.PrependFloat64Slot(3, test1, 0.0) + +def AddTest1(builder: flatbuffers.Builder, test1: float): + Vec3AddTest1(builder, test1) + +def Vec3AddTest2(builder: flatbuffers.Builder, test2: int): + builder.PrependUint8Slot(4, test2, 0) + +def AddTest2(builder: flatbuffers.Builder, test2: int): + Vec3AddTest2(builder, test2) + +def Vec3AddTest3(builder: flatbuffers.Builder, test3: Any): + builder.PrependStructSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(test3), 0) + +def AddTest3(builder: flatbuffers.Builder, test3: Any): + Vec3AddTest3(builder, test3) + +def Vec3End(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + +def End(builder: flatbuffers.Builder) -> int: + return Vec3End(builder) + +import MyGame.Example.NestedUnion.Test +try: + from typing import Optional +except: + pass + +class Vec3T(object): + + # Vec3T + def __init__(self): + self.x = 0.0 # type: float + self.y = 0.0 # type: float + self.z = 0.0 # type: float + self.test1 = 0.0 # type: float + self.test2 = 0 # type: int + self.test3 = None # type: Optional[MyGame.Example.NestedUnion.Test.TestT] + + @classmethod + def InitFromBuf(cls, buf, pos): + vec3 = Vec3() + vec3.Init(buf, pos) + return cls.InitFromObj(vec3) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, vec3): + x = Vec3T() + x._UnPack(vec3) + return x + + # Vec3T + def _UnPack(self, vec3): + if vec3 is None: + return + self.x = vec3.X() + self.y = vec3.Y() + self.z = vec3.Z() + self.test1 = vec3.Test1() + self.test2 = vec3.Test2() + if vec3.Test3() is not None: + self.test3 = MyGame.Example.NestedUnion.Test.TestT.InitFromObj(vec3.Test3()) + + # Vec3T + def Pack(self, builder): + Vec3Start(builder) + Vec3AddX(builder, self.x) + Vec3AddY(builder, self.y) + Vec3AddZ(builder, self.z) + Vec3AddTest1(builder, self.test1) + Vec3AddTest2(builder, self.test2) + if self.test3 is not None: + test3 = self.test3.Pack(builder) + Vec3AddTest3(builder, test3) + vec3 = Vec3End(builder) + return vec3 diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Vec3.pyi b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Vec3.pyi new file mode 100644 index 00000000000..c570c20b4c1 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/Vec3.pyi @@ -0,0 +1,51 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.Example.NestedUnion.Color import Color +from MyGame.Example.NestedUnion.Test import Test, TestT +from MyGame.Example.NestedUnion.Vec3 import Vec3 + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class Vec3(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> Vec3: ... + @classmethod + def GetRootAsVec3(cls, buf: bytes, offset: int) -> Vec3: ... + def Init(self, buf: bytes, pos: int) -> None: ... + def X(self) -> float: ... + def Y(self) -> float: ... + def Z(self) -> float: ... + def Test1(self) -> float: ... + def Test2(self) -> typing.Literal[Color.Red, Color.Green, Color.Blue]: ... + def Test3(self) -> Test | None: ... +class Vec3T(object): + x: float + y: float + z: float + test1: float + test2: typing.Literal[Color.Red, Color.Green, Color.Blue] + test3: TestT | None + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> Vec3T: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> Vec3T: ... + @classmethod + def InitFromObj(cls, vec3: Vec3) -> Vec3T: ... + def _UnPack(self, vec3: Vec3) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... +def Vec3Start(builder: flatbuffers.Builder) -> None: ... +def Start(builder: flatbuffers.Builder) -> None: ... +def Vec3AddX(builder: flatbuffers.Builder, x: float) -> None: ... +def Vec3AddY(builder: flatbuffers.Builder, y: float) -> None: ... +def Vec3AddZ(builder: flatbuffers.Builder, z: float) -> None: ... +def Vec3AddTest1(builder: flatbuffers.Builder, test1: float) -> None: ... +def Vec3AddTest2(builder: flatbuffers.Builder, test2: typing.Literal[Color.Red, Color.Green, Color.Blue]) -> None: ... +def Vec3AddTest3(builder: flatbuffers.Builder, test3: uoffset) -> None: ... +def Vec3End(builder: flatbuffers.Builder) -> uoffset: ... +def End(builder: flatbuffers.Builder) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/__init__.py b/third_party/flatbuffers/tests/MyGame/Example/NestedUnion/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.cs b/third_party/flatbuffers/tests/MyGame/Example/Race.cs new file mode 100644 index 00000000000..8a1959a8406 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.cs @@ -0,0 +1,18 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Race : sbyte +{ + None = -1, + Human = 0, + Dwarf = 1, + Elf = 2, +}; + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.go b/third_party/flatbuffers/tests/MyGame/Example/Race.go new file mode 100644 index 00000000000..0762bca0959 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.go @@ -0,0 +1,35 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import "strconv" + +type Race int8 + +const ( + RaceNone Race = -1 + RaceHuman Race = 0 + RaceDwarf Race = 1 + RaceElf Race = 2 +) + +var EnumNamesRace = map[Race]string{ + RaceNone: "None", + RaceHuman: "Human", + RaceDwarf: "Dwarf", + RaceElf: "Elf", +} + +var EnumValuesRace = map[string]Race{ + "None": RaceNone, + "Human": RaceHuman, + "Dwarf": RaceDwarf, + "Elf": RaceElf, +} + +func (v Race) String() string { + if s, ok := EnumNamesRace[v]; ok { + return s + } + return "Race(" + strconv.FormatInt(int64(v), 10) + ")" +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.java b/third_party/flatbuffers/tests/MyGame/Example/Race.java new file mode 100644 index 00000000000..9f20e304306 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.java @@ -0,0 +1,17 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +@SuppressWarnings("unused") +public final class Race { + private Race() { } + public static final byte None = -1; + public static final byte Human = 0; + public static final byte Dwarf = 1; + public static final byte Elf = 2; + + public static final String[] names = { "None", "Human", "Dwarf", "Elf", }; + + public static String name(int e) { return names[e - None]; } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.kt b/third_party/flatbuffers/tests/MyGame/Example/Race.kt new file mode 100644 index 00000000000..6f770a3c9a3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.kt @@ -0,0 +1,15 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +@Suppress("unused") +class Race private constructor() { + companion object { + const val None: Byte = -1 + const val Human: Byte = 0 + const val Dwarf: Byte = 1 + const val Elf: Byte = 2 + val names : Array = arrayOf("None", "Human", "Dwarf", "Elf") + fun name(e: Int) : String = names[e - None.toInt()] + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.lua b/third_party/flatbuffers/tests/MyGame/Example/Race.lua new file mode 100644 index 00000000000..8977ca4db9f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.lua @@ -0,0 +1,20 @@ +--[[ MyGame.Example.Race + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local Race = { + None = -1, + Human = 0, + Dwarf = 1, + Elf = 2, +} + +return Race \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.nim b/third_party/flatbuffers/tests/MyGame/Example/Race.nim new file mode 100644 index 00000000000..ca0c565c264 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.nim @@ -0,0 +1,15 @@ +#[ MyGame.Example.Race + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +type Race*{.pure.} = enum + None = -1.int8, + Human = 0.int8, + Dwarf = 1.int8, + Elf = 2.int8, diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.php b/third_party/flatbuffers/tests/MyGame/Example/Race.php new file mode 100644 index 00000000000..3f05c43c05f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.php @@ -0,0 +1,27 @@ +"None", + Race::Human=>"Human", + Race::Dwarf=>"Dwarf", + Race::Elf=>"Elf", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Race.py b/third_party/flatbuffers/tests/MyGame/Example/Race.py new file mode 100644 index 00000000000..30f39601edc --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Race.py @@ -0,0 +1,9 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +class Race(object): + None_ = -1 + Human = 0 + Dwarf = 1 + Elf = 2 diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.cs b/third_party/flatbuffers/tests/MyGame/Example/Referrable.cs new file mode 100644 index 00000000000..d93017877e0 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.cs @@ -0,0 +1,105 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Referrable : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Referrable GetRootAsReferrable(ByteBuffer _bb) { return GetRootAsReferrable(_bb, new Referrable()); } + public static Referrable GetRootAsReferrable(ByteBuffer _bb, Referrable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Referrable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public ulong Id { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateId(ulong id) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, id); return true; } else { return false; } } + + public static Offset CreateReferrable(FlatBufferBuilder builder, + ulong id = 0) { + builder.StartTable(1); + Referrable.AddId(builder, id); + return Referrable.EndReferrable(builder); + } + + public static void StartReferrable(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddId(FlatBufferBuilder builder, ulong id) { builder.AddUlong(0, id, 0); } + public static Offset EndReferrable(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + + public static VectorOffset CreateSortedVectorOfReferrable(FlatBufferBuilder builder, Offset[] offsets) { + Array.Sort(offsets, + (Offset o1, Offset o2) => + new Referrable().__assign(builder.DataBuffer.Length - o1.Value, builder.DataBuffer).Id.CompareTo(new Referrable().__assign(builder.DataBuffer.Length - o2.Value, builder.DataBuffer).Id)); + return builder.CreateVectorOfTables(offsets); + } + + public static Referrable? __lookup_by_key(int vectorLocation, ulong key, ByteBuffer bb) { + Referrable obj_ = new Referrable(); + int span = bb.GetInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = Table.__indirect(vectorLocation + 4 * (start + middle), bb); + obj_.__assign(tableOffset, bb); + int comp = obj_.Id.CompareTo(key); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return obj_; + } + } + return null; + } + public ReferrableT UnPack() { + var _o = new ReferrableT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(ReferrableT _o) { + _o.Id = this.Id; + } + public static Offset Pack(FlatBufferBuilder builder, ReferrableT _o) { + if (_o == null) return default(Offset); + return CreateReferrable( + builder, + _o.Id); + } +} + +public class ReferrableT +{ + [Newtonsoft.Json.JsonProperty("id")] + [Newtonsoft.Json.JsonIgnore()] + public ulong Id { get; set; } + + public ReferrableT() { + this.Id = 0; + } +} + + +static public class ReferrableVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Id*/, 8 /*ulong*/, 8, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.go b/third_party/flatbuffers/tests/MyGame/Example/Referrable.go new file mode 100644 index 00000000000..f6248bb7e32 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.go @@ -0,0 +1,127 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type ReferrableT struct { + Id uint64 `json:"id"` +} + +func (t *ReferrableT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + ReferrableStart(builder) + ReferrableAddId(builder, t.Id) + return ReferrableEnd(builder) +} + +func (rcv *Referrable) UnPackTo(t *ReferrableT) { + t.Id = rcv.Id() +} + +func (rcv *Referrable) UnPack() *ReferrableT { + if rcv == nil { + return nil + } + t := &ReferrableT{} + rcv.UnPackTo(t) + return t +} + +type Referrable struct { + _tab flatbuffers.Table +} + +func GetRootAsReferrable(buf []byte, offset flatbuffers.UOffsetT) *Referrable { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Referrable{} + x.Init(buf, n+offset) + return x +} + +func FinishReferrableBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsReferrable(buf []byte, offset flatbuffers.UOffsetT) *Referrable { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Referrable{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedReferrableBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *Referrable) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Referrable) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Referrable) Id() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Referrable) MutateId(n uint64) bool { + return rcv._tab.MutateUint64Slot(4, n) +} + +func ReferrableKeyCompare(o1, o2 flatbuffers.UOffsetT, buf []byte) bool { + obj1 := &Referrable{} + obj2 := &Referrable{} + obj1.Init(buf, flatbuffers.UOffsetT(len(buf))-o1) + obj2.Init(buf, flatbuffers.UOffsetT(len(buf))-o2) + return obj1.Id() < obj2.Id() +} + +func (rcv *Referrable) LookupByKey(key uint64, vectorLocation flatbuffers.UOffsetT, buf []byte) bool { + span := flatbuffers.GetUOffsetT(buf[vectorLocation-4:]) + start := flatbuffers.UOffsetT(0) + for span != 0 { + middle := span / 2 + tableOffset := flatbuffers.GetIndirectOffset(buf, vectorLocation+4*(start+middle)) + obj := &Referrable{} + obj.Init(buf, tableOffset) + val := obj.Id() + comp := 0 + if val > key { + comp = 1 + } else if val < key { + comp = -1 + } + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + rcv.Init(buf, tableOffset) + return true + } + } + return false +} + +func ReferrableStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func ReferrableAddId(builder *flatbuffers.Builder, id uint64) { + builder.PrependUint64Slot(0, id, 0) +} +func ReferrableEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.java b/third_party/flatbuffers/tests/MyGame/Example/Referrable.java new file mode 100644 index 00000000000..dbc6620748b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.java @@ -0,0 +1,99 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Referrable extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Referrable getRootAsReferrable(ByteBuffer _bb) { return getRootAsReferrable(_bb, new Referrable()); } + public static Referrable getRootAsReferrable(ByteBuffer _bb, Referrable obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Referrable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public long id() { int o = __offset(4); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateId(long id) { int o = __offset(4); if (o != 0) { bb.putLong(o + bb_pos, id); return true; } else { return false; } } + + public static int createReferrable(FlatBufferBuilder builder, + long id) { + builder.startTable(1); + Referrable.addId(builder, id); + return Referrable.endReferrable(builder); + } + + public static void startReferrable(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addId(FlatBufferBuilder builder, long id) { builder.addLong(id); builder.slot(0); } + public static int endReferrable(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { + long val_1 = _bb.getLong(__offset(4, o1, _bb)); + long val_2 = _bb.getLong(__offset(4, o2, _bb)); + return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0; + } + + public static Referrable __lookup_by_key(Referrable obj, int vectorLocation, long key, ByteBuffer bb) { + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + long val = bb.getLong(__offset(4, bb.capacity() - tableOffset, bb)); + int comp = val > key ? 1 : val < key ? -1 : 0; + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Referrable() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Referrable get(int j) { return get(new Referrable(), j); } + public Referrable get(Referrable obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Referrable getByKey(long key) { return __lookup_by_key(null, __vector(), key, bb); } + public Referrable getByKey(Referrable obj, long key) { return __lookup_by_key(obj, __vector(), key, bb); } + } + public ReferrableT unpack() { + ReferrableT _o = new ReferrableT(); + unpackTo(_o); + return _o; + } + public void unpackTo(ReferrableT _o) { + long _oId = id(); + _o.setId(_oId); + } + public static int pack(FlatBufferBuilder builder, ReferrableT _o) { + if (_o == null) return 0; + return createReferrable( + builder, + _o.getId()); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.kt b/third_party/flatbuffers/tests/MyGame/Example/Referrable.kt new file mode 100644 index 00000000000..089329aa73e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.kt @@ -0,0 +1,94 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Referrable : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Referrable { + __init(_i, _bb) + return this + } + val id : ULong + get() { + val o = __offset(4) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateId(id: ULong) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.putLong(o + bb_pos, id.toLong()) + true + } else { + false + } + } + override fun keysCompare(o1: Int, o2: Int, _bb: ByteBuffer) : Int { + val val_1 = _bb.getLong(__offset(4, o1, _bb)) + val val_2 = _bb.getLong(__offset(4, o2, _bb)) + return (val_1 - val_2).sign + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsReferrable(_bb: ByteBuffer): Referrable = getRootAsReferrable(_bb, Referrable()) + fun getRootAsReferrable(_bb: ByteBuffer, obj: Referrable): Referrable { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createReferrable(builder: FlatBufferBuilder, id: ULong) : Int { + builder.startTable(1) + addId(builder, id) + return endReferrable(builder) + } + fun startReferrable(builder: FlatBufferBuilder) = builder.startTable(1) + fun addId(builder: FlatBufferBuilder, id: ULong) { + builder.addLong(id.toLong()) + builder.slot(0) + } + fun endReferrable(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun __lookup_by_key(obj: Referrable?, vectorLocation: Int, key: ULong, bb: ByteBuffer) : Referrable? { + var span = bb.getInt(vectorLocation - 4) + var start = 0 + while (span != 0) { + var middle = span / 2 + val tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb) + val value = bb.getLong(__offset(4, bb.capacity() - tableOffset, bb)).toULong() + val comp = value.compareTo(key) + when { + comp > 0 -> span = middle + comp < 0 -> { + middle++ + start += middle + span -= middle + } + else -> { + return (obj ?: Referrable()).__assign(tableOffset, bb) + } + } + } + return null + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.lua b/third_party/flatbuffers/tests/MyGame/Example/Referrable.lua new file mode 100644 index 00000000000..ec55dcad8d2 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.lua @@ -0,0 +1,48 @@ +--[[ MyGame.Example.Referrable + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Referrable = {} +local mt = {} + +function Referrable.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:Id() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function Referrable.Start(builder) + builder:StartObject(1) +end + +function Referrable.AddId(builder, id) + builder:PrependUint64Slot(0, id, 0) +end + +function Referrable.End(builder) + return builder:EndObject() +end + +return Referrable \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.nim b/third_party/flatbuffers/tests/MyGame/Example/Referrable.nim new file mode 100644 index 00000000000..612749297e3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.nim @@ -0,0 +1,26 @@ +#[ MyGame.Example.Referrable + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers + +type Referrable* = object of FlatObj +func id*(self: Referrable): uint64 = + let o = self.tab.Offset(4) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `id=`*(self: var Referrable, n: uint64): bool = + return self.tab.MutateSlot(4, n) +proc ReferrableStart*(builder: var Builder) = + builder.StartObject(1) +proc ReferrableAddid*(builder: var Builder, id: uint64) = + builder.PrependSlot(0, id, default(uint64)) +proc ReferrableEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.php b/third_party/flatbuffers/tests/MyGame/Example/Referrable.php new file mode 100644 index 00000000000..58440110e0f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.php @@ -0,0 +1,99 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function ReferrableIdentifier() + { + return "MONS"; + } + + public static function ReferrableBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::ReferrableIdentifier()); + } + + public static function ReferrableExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Referrable + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return ulong + */ + public function getId() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startReferrable(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return Referrable + */ + public static function createReferrable(FlatBufferBuilder $builder, $id) + { + $builder->startObject(1); + self::addId($builder, $id); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addId(FlatBufferBuilder $builder, $id) + { + $builder->addUlongX(0, $id, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endReferrable(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Referrable.py b/third_party/flatbuffers/tests/MyGame/Example/Referrable.py new file mode 100644 index 00000000000..9cc5f5724d3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Referrable.py @@ -0,0 +1,91 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Referrable(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Referrable() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReferrable(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReferrableBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Referrable + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Referrable + def Id(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + +def ReferrableStart(builder): + builder.StartObject(1) + +def Start(builder): + ReferrableStart(builder) + +def ReferrableAddId(builder, id): + builder.PrependUint64Slot(0, id, 0) + +def AddId(builder, id): + ReferrableAddId(builder, id) + +def ReferrableEnd(builder): + return builder.EndObject() + +def End(builder): + return ReferrableEnd(builder) + + +class ReferrableT(object): + + # ReferrableT + def __init__(self): + self.id = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + referrable = Referrable() + referrable.Init(buf, pos) + return cls.InitFromObj(referrable) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, referrable): + x = ReferrableT() + x._UnPack(referrable) + return x + + # ReferrableT + def _UnPack(self, referrable): + if referrable is None: + return + self.id = referrable.Id() + + # ReferrableT + def Pack(self, builder): + ReferrableStart(builder) + ReferrableAddId(builder, self.id) + referrable = ReferrableEnd(builder) + return referrable diff --git a/third_party/flatbuffers/tests/MyGame/Example/ReferrableT.java b/third_party/flatbuffers/tests/MyGame/Example/ReferrableT.java new file mode 100644 index 00000000000..5efd363f8c3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/ReferrableT.java @@ -0,0 +1,34 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class ReferrableT { + private long id; + + public long getId() { return id; } + + public void setId(long id) { this.id = id; } + + + public ReferrableT() { + this.id = 0L; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.cs b/third_party/flatbuffers/tests/MyGame/Example/Stat.cs new file mode 100644 index 00000000000..17d26573515 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.cs @@ -0,0 +1,132 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Stat : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Stat GetRootAsStat(ByteBuffer _bb) { return GetRootAsStat(_bb, new Stat()); } + public static Stat GetRootAsStat(ByteBuffer _bb, Stat obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Stat __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public string Id { get { int o = __p.__offset(4); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } } +#if ENABLE_SPAN_T + public Span GetIdBytes() { return __p.__vector_as_span(4, 1); } +#else + public ArraySegment? GetIdBytes() { return __p.__vector_as_arraysegment(4); } +#endif + public byte[] GetIdArray() { return __p.__vector_as_array(4); } + public long Val { get { int o = __p.__offset(6); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } } + public bool MutateVal(long val) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutLong(o + __p.bb_pos, val); return true; } else { return false; } } + public ushort Count { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetUshort(o + __p.bb_pos) : (ushort)0; } } + public bool MutateCount(ushort count) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutUshort(o + __p.bb_pos, count); return true; } else { return false; } } + + public static Offset CreateStat(FlatBufferBuilder builder, + StringOffset idOffset = default(StringOffset), + long val = 0, + ushort count = 0) { + builder.StartTable(3); + Stat.AddVal(builder, val); + Stat.AddId(builder, idOffset); + Stat.AddCount(builder, count); + return Stat.EndStat(builder); + } + + public static void StartStat(FlatBufferBuilder builder) { builder.StartTable(3); } + public static void AddId(FlatBufferBuilder builder, StringOffset idOffset) { builder.AddOffset(0, idOffset.Value, 0); } + public static void AddVal(FlatBufferBuilder builder, long val) { builder.AddLong(1, val, 0); } + public static void AddCount(FlatBufferBuilder builder, ushort count) { builder.AddUshort(2, count, 0); } + public static Offset EndStat(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + + public static VectorOffset CreateSortedVectorOfStat(FlatBufferBuilder builder, Offset[] offsets) { + Array.Sort(offsets, + (Offset o1, Offset o2) => + new Stat().__assign(builder.DataBuffer.Length - o1.Value, builder.DataBuffer).Count.CompareTo(new Stat().__assign(builder.DataBuffer.Length - o2.Value, builder.DataBuffer).Count)); + return builder.CreateVectorOfTables(offsets); + } + + public static Stat? __lookup_by_key(int vectorLocation, ushort key, ByteBuffer bb) { + Stat obj_ = new Stat(); + int span = bb.GetInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = Table.__indirect(vectorLocation + 4 * (start + middle), bb); + obj_.__assign(tableOffset, bb); + int comp = obj_.Count.CompareTo(key); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return obj_; + } + } + return null; + } + public StatT UnPack() { + var _o = new StatT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(StatT _o) { + _o.Id = this.Id; + _o.Val = this.Val; + _o.Count = this.Count; + } + public static Offset Pack(FlatBufferBuilder builder, StatT _o) { + if (_o == null) return default(Offset); + var _id = _o.Id == null ? default(StringOffset) : builder.CreateString(_o.Id); + return CreateStat( + builder, + _id, + _o.Val, + _o.Count); + } +} + +public class StatT +{ + [Newtonsoft.Json.JsonProperty("id")] + public string Id { get; set; } + [Newtonsoft.Json.JsonProperty("val")] + public long Val { get; set; } + [Newtonsoft.Json.JsonProperty("count")] + public ushort Count { get; set; } + + public StatT() { + this.Id = null; + this.Val = 0; + this.Count = 0; + } +} + + +static public class StatVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyString(tablePos, 4 /*Id*/, false) + && verifier.VerifyField(tablePos, 6 /*Val*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 8 /*Count*/, 2 /*ushort*/, 2, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.go b/third_party/flatbuffers/tests/MyGame/Example/Stat.go new file mode 100644 index 00000000000..5855abf1662 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.go @@ -0,0 +1,163 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type StatT struct { + Id string `json:"id"` + Val int64 `json:"val"` + Count uint16 `json:"count"` +} + +func (t *StatT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + idOffset := flatbuffers.UOffsetT(0) + if t.Id != "" { + idOffset = builder.CreateString(t.Id) + } + StatStart(builder) + StatAddId(builder, idOffset) + StatAddVal(builder, t.Val) + StatAddCount(builder, t.Count) + return StatEnd(builder) +} + +func (rcv *Stat) UnPackTo(t *StatT) { + t.Id = string(rcv.Id()) + t.Val = rcv.Val() + t.Count = rcv.Count() +} + +func (rcv *Stat) UnPack() *StatT { + if rcv == nil { + return nil + } + t := &StatT{} + rcv.UnPackTo(t) + return t +} + +type Stat struct { + _tab flatbuffers.Table +} + +func GetRootAsStat(buf []byte, offset flatbuffers.UOffsetT) *Stat { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Stat{} + x.Init(buf, n+offset) + return x +} + +func FinishStatBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsStat(buf []byte, offset flatbuffers.UOffsetT) *Stat { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Stat{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedStatBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *Stat) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Stat) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Stat) Id() []byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.ByteVector(o + rcv._tab.Pos) + } + return nil +} + +func (rcv *Stat) Val() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Stat) MutateVal(n int64) bool { + return rcv._tab.MutateInt64Slot(6, n) +} + +func (rcv *Stat) Count() uint16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) + if o != 0 { + return rcv._tab.GetUint16(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Stat) MutateCount(n uint16) bool { + return rcv._tab.MutateUint16Slot(8, n) +} + +func StatKeyCompare(o1, o2 flatbuffers.UOffsetT, buf []byte) bool { + obj1 := &Stat{} + obj2 := &Stat{} + obj1.Init(buf, flatbuffers.UOffsetT(len(buf))-o1) + obj2.Init(buf, flatbuffers.UOffsetT(len(buf))-o2) + return obj1.Count() < obj2.Count() +} + +func (rcv *Stat) LookupByKey(key uint16, vectorLocation flatbuffers.UOffsetT, buf []byte) bool { + span := flatbuffers.GetUOffsetT(buf[vectorLocation-4:]) + start := flatbuffers.UOffsetT(0) + for span != 0 { + middle := span / 2 + tableOffset := flatbuffers.GetIndirectOffset(buf, vectorLocation+4*(start+middle)) + obj := &Stat{} + obj.Init(buf, tableOffset) + val := obj.Count() + comp := 0 + if val > key { + comp = 1 + } else if val < key { + comp = -1 + } + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + rcv.Init(buf, tableOffset) + return true + } + } + return false +} + +func StatStart(builder *flatbuffers.Builder) { + builder.StartObject(3) +} +func StatAddId(builder *flatbuffers.Builder, id flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(id), 0) +} +func StatAddVal(builder *flatbuffers.Builder, val int64) { + builder.PrependInt64Slot(1, val, 0) +} +func StatAddCount(builder *flatbuffers.Builder, count uint16) { + builder.PrependUint16Slot(2, count, 0) +} +func StatEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.java b/third_party/flatbuffers/tests/MyGame/Example/Stat.java new file mode 100644 index 00000000000..9913ae27b3e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.java @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Stat extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Stat getRootAsStat(ByteBuffer _bb) { return getRootAsStat(_bb, new Stat()); } + public static Stat getRootAsStat(ByteBuffer _bb, Stat obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Stat __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public String id() { int o = __offset(4); return o != 0 ? __string(o + bb_pos) : null; } + public ByteBuffer idAsByteBuffer() { return __vector_as_bytebuffer(4, 1); } + public ByteBuffer idInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 4, 1); } + public long val() { int o = __offset(6); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateVal(long val) { int o = __offset(6); if (o != 0) { bb.putLong(o + bb_pos, val); return true; } else { return false; } } + public int count() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + public boolean mutateCount(int count) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, (short) count); return true; } else { return false; } } + + public static int createStat(FlatBufferBuilder builder, + int idOffset, + long val, + int count) { + builder.startTable(3); + Stat.addVal(builder, val); + Stat.addId(builder, idOffset); + Stat.addCount(builder, count); + return Stat.endStat(builder); + } + + public static void startStat(FlatBufferBuilder builder) { builder.startTable(3); } + public static void addId(FlatBufferBuilder builder, int idOffset) { builder.addOffset(0, idOffset, 0); } + public static void addVal(FlatBufferBuilder builder, long val) { builder.addLong(1, val, 0L); } + public static void addCount(FlatBufferBuilder builder, int count) { builder.addShort((short) count); builder.slot(2); } + public static int endStat(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + @Override + protected int keysCompare(Integer o1, Integer o2, ByteBuffer _bb) { + int val_1 = _bb.getShort(__offset(8, o1, _bb)) & 0xFFFF; + int val_2 = _bb.getShort(__offset(8, o2, _bb)) & 0xFFFF; + return val_1 > val_2 ? 1 : val_1 < val_2 ? -1 : 0; + } + + public static Stat __lookup_by_key(Stat obj, int vectorLocation, int key, ByteBuffer bb) { + int span = bb.getInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb); + int val = bb.getShort(__offset(8, bb.capacity() - tableOffset, bb)) & 0xFFFF; + int comp = val > key ? 1 : val < key ? -1 : 0; + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return (obj == null ? new Stat() : obj).__assign(tableOffset, bb); + } + } + return null; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Stat get(int j) { return get(new Stat(), j); } + public Stat get(Stat obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + public Stat getByKey(int key) { return __lookup_by_key(null, __vector(), key, bb); } + public Stat getByKey(Stat obj, int key) { return __lookup_by_key(obj, __vector(), key, bb); } + } + public StatT unpack() { + StatT _o = new StatT(); + unpackTo(_o); + return _o; + } + public void unpackTo(StatT _o) { + String _oId = id(); + _o.setId(_oId); + long _oVal = val(); + _o.setVal(_oVal); + int _oCount = count(); + _o.setCount(_oCount); + } + public static int pack(FlatBufferBuilder builder, StatT _o) { + if (_o == null) return 0; + int _id = _o.getId() == null ? 0 : builder.createString(_o.getId()); + return createStat( + builder, + _id, + _o.getVal(), + _o.getCount()); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.kt b/third_party/flatbuffers/tests/MyGame/Example/Stat.kt new file mode 100644 index 00000000000..fea80b8c919 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.kt @@ -0,0 +1,123 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Stat : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Stat { + __init(_i, _bb) + return this + } + val id : String? + get() { + val o = __offset(4) + return if (o != 0) { + __string(o + bb_pos) + } else { + null + } + } + val idAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(4, 1) + fun idInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 4, 1) + val val_ : Long + get() { + val o = __offset(6) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + fun mutateVal_(val_: Long) : Boolean { + val o = __offset(6) + return if (o != 0) { + bb.putLong(o + bb_pos, val_) + true + } else { + false + } + } + val count : UShort + get() { + val o = __offset(8) + return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u + } + fun mutateCount(count: UShort) : Boolean { + val o = __offset(8) + return if (o != 0) { + bb.putShort(o + bb_pos, count.toShort()) + true + } else { + false + } + } + override fun keysCompare(o1: Int, o2: Int, _bb: ByteBuffer) : Int { + val val_1 = _bb.getShort(__offset(8, o1, _bb)) + val val_2 = _bb.getShort(__offset(8, o2, _bb)) + return (val_1 - val_2).sign + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsStat(_bb: ByteBuffer): Stat = getRootAsStat(_bb, Stat()) + fun getRootAsStat(_bb: ByteBuffer, obj: Stat): Stat { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createStat(builder: FlatBufferBuilder, idOffset: Int, val_: Long, count: UShort) : Int { + builder.startTable(3) + addVal_(builder, val_) + addId(builder, idOffset) + addCount(builder, count) + return endStat(builder) + } + fun startStat(builder: FlatBufferBuilder) = builder.startTable(3) + fun addId(builder: FlatBufferBuilder, id: Int) = builder.addOffset(0, id, 0) + fun addVal_(builder: FlatBufferBuilder, val_: Long) = builder.addLong(1, val_, 0L) + fun addCount(builder: FlatBufferBuilder, count: UShort) { + builder.addShort(count.toShort()) + builder.slot(2) + } + fun endStat(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun __lookup_by_key(obj: Stat?, vectorLocation: Int, key: UShort, bb: ByteBuffer) : Stat? { + var span = bb.getInt(vectorLocation - 4) + var start = 0 + while (span != 0) { + var middle = span / 2 + val tableOffset = __indirect(vectorLocation + 4 * (start + middle), bb) + val value = bb.getShort(__offset(8, bb.capacity() - tableOffset, bb)).toUShort() + val comp = value.compareTo(key) + when { + comp > 0 -> span = middle + comp < 0 -> { + middle++ + start += middle + span -= middle + } + else -> { + return (obj ?: Stat()).__assign(tableOffset, bb) + } + } + } + return null + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.lua b/third_party/flatbuffers/tests/MyGame/Example/Stat.lua new file mode 100644 index 00000000000..57671a1e345 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.lua @@ -0,0 +1,71 @@ +--[[ MyGame.Example.Stat + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Stat = {} +local mt = {} + +function Stat.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:Id() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:String(self.view.pos + o) + end +end + +function mt:Val() + local o = self.view:Offset(6) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int64, self.view.pos + o) + end + return 0 +end + +function mt:Count() + local o = self.view:Offset(8) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o) + end + return 0 +end + +function Stat.Start(builder) + builder:StartObject(3) +end + +function Stat.AddId(builder, id) + builder:PrependUOffsetTRelativeSlot(0, id, 0) +end + +function Stat.AddVal(builder, val) + builder:PrependInt64Slot(1, val, 0) +end + +function Stat.AddCount(builder, count) + builder:PrependUint16Slot(2, count, 0) +end + +function Stat.End(builder) + return builder:EndObject() +end + +return Stat \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.nim b/third_party/flatbuffers/tests/MyGame/Example/Stat.nim new file mode 100644 index 00000000000..a2d6e184831 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.nim @@ -0,0 +1,42 @@ +#[ MyGame.Example.Stat + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers +import std/options + +type Stat* = object of FlatObj +func id*(self: Stat): Option[string] = + let o = self.tab.Offset(4) + if o != 0: + return some(self.tab.String(self.tab.Pos + o)) +func val*(self: Stat): int64 = + let o = self.tab.Offset(6) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 0 +func `val=`*(self: var Stat, n: int64): bool = + return self.tab.MutateSlot(6, n) +func count*(self: Stat): uint16 = + let o = self.tab.Offset(8) + if o != 0: + return Get[uint16](self.tab, self.tab.Pos + o) + return 0 +func `count=`*(self: var Stat, n: uint16): bool = + return self.tab.MutateSlot(8, n) +proc StatStart*(builder: var Builder) = + builder.StartObject(3) +proc StatAddid*(builder: var Builder, id: uoffset) = + builder.PrependSlot(0, id, default(uoffset)) +proc StatAddval*(builder: var Builder, val: int64) = + builder.PrependSlot(1, val, default(int64)) +proc StatAddcount*(builder: var Builder, count: uint16) = + builder.PrependSlot(2, count, default(uint16)) +proc StatEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.php b/third_party/flatbuffers/tests/MyGame/Example/Stat.php new file mode 100644 index 00000000000..6ef70348dac --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.php @@ -0,0 +1,136 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function StatIdentifier() + { + return "MONS"; + } + + public static function StatBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::StatIdentifier()); + } + + public static function StatExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Stat + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + public function getId() + { + $o = $this->__offset(4); + return $o != 0 ? $this->__string($o + $this->bb_pos) : null; + } + + /** + * @return long + */ + public function getVal() + { + $o = $this->__offset(6); + return $o != 0 ? $this->bb->getLong($o + $this->bb_pos) : 0; + } + + /** + * @return ushort + */ + public function getCount() + { + $o = $this->__offset(8); + return $o != 0 ? $this->bb->getUshort($o + $this->bb_pos) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startStat(FlatBufferBuilder $builder) + { + $builder->StartObject(3); + } + + /** + * @param FlatBufferBuilder $builder + * @return Stat + */ + public static function createStat(FlatBufferBuilder $builder, $id, $val, $count) + { + $builder->startObject(3); + self::addId($builder, $id); + self::addVal($builder, $val); + self::addCount($builder, $count); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param StringOffset + * @return void + */ + public static function addId(FlatBufferBuilder $builder, $id) + { + $builder->addOffsetX(0, $id, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param long + * @return void + */ + public static function addVal(FlatBufferBuilder $builder, $val) + { + $builder->addLongX(1, $val, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ushort + * @return void + */ + public static function addCount(FlatBufferBuilder $builder, $count) + { + $builder->addUshortX(2, $count, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endStat(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Stat.py b/third_party/flatbuffers/tests/MyGame/Example/Stat.py new file mode 100644 index 00000000000..ec6b9d9a227 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Stat.py @@ -0,0 +1,126 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Stat(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Stat() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStat(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StatBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Stat + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Stat + def Id(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Stat + def Val(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Stat + def Count(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return 0 + +def StatStart(builder): + builder.StartObject(3) + +def Start(builder): + StatStart(builder) + +def StatAddId(builder, id): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(id), 0) + +def AddId(builder, id): + StatAddId(builder, id) + +def StatAddVal(builder, val): + builder.PrependInt64Slot(1, val, 0) + +def AddVal(builder, val): + StatAddVal(builder, val) + +def StatAddCount(builder, count): + builder.PrependUint16Slot(2, count, 0) + +def AddCount(builder, count): + StatAddCount(builder, count) + +def StatEnd(builder): + return builder.EndObject() + +def End(builder): + return StatEnd(builder) + + +class StatT(object): + + # StatT + def __init__(self): + self.id = None # type: str + self.val = 0 # type: int + self.count = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stat = Stat() + stat.Init(buf, pos) + return cls.InitFromObj(stat) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stat): + x = StatT() + x._UnPack(stat) + return x + + # StatT + def _UnPack(self, stat): + if stat is None: + return + self.id = stat.Id() + self.val = stat.Val() + self.count = stat.Count() + + # StatT + def Pack(self, builder): + if self.id is not None: + id = builder.CreateString(self.id) + StatStart(builder) + if self.id is not None: + StatAddId(builder, id) + StatAddVal(builder, self.val) + StatAddCount(builder, self.count) + stat = StatEnd(builder) + return stat diff --git a/third_party/flatbuffers/tests/MyGame/Example/StatT.java b/third_party/flatbuffers/tests/MyGame/Example/StatT.java new file mode 100644 index 00000000000..82939a6c658 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StatT.java @@ -0,0 +1,46 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class StatT { + private String id; + private long val; + private int count; + + public String getId() { return id; } + + public void setId(String id) { this.id = id; } + + public long getVal() { return val; } + + public void setVal(long val) { this.val = val; } + + public int getCount() { return count; } + + public void setCount(int count) { this.count = count; } + + + public StatT() { + this.id = null; + this.val = 0L; + this.count = 0; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.cs b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.cs new file mode 100644 index 00000000000..955aeabdeca --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.cs @@ -0,0 +1,83 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct StructOfStructs : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public StructOfStructs __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.Ability A { get { return (new MyGame.Example.Ability()).__assign(__p.bb_pos + 0, __p.bb); } } + public MyGame.Example.Test B { get { return (new MyGame.Example.Test()).__assign(__p.bb_pos + 8, __p.bb); } } + public MyGame.Example.Ability C { get { return (new MyGame.Example.Ability()).__assign(__p.bb_pos + 12, __p.bb); } } + + public static Offset CreateStructOfStructs(FlatBufferBuilder builder, uint a_Id, uint a_Distance, short b_A, sbyte b_B, uint c_Id, uint c_Distance) { + builder.Prep(4, 20); + builder.Prep(4, 8); + builder.PutUint(c_Distance); + builder.PutUint(c_Id); + builder.Prep(2, 4); + builder.Pad(1); + builder.PutSbyte(b_B); + builder.PutShort(b_A); + builder.Prep(4, 8); + builder.PutUint(a_Distance); + builder.PutUint(a_Id); + return new Offset(builder.Offset); + } + public StructOfStructsT UnPack() { + var _o = new StructOfStructsT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(StructOfStructsT _o) { + _o.A = this.A.UnPack(); + _o.B = this.B.UnPack(); + _o.C = this.C.UnPack(); + } + public static Offset Pack(FlatBufferBuilder builder, StructOfStructsT _o) { + if (_o == null) return default(Offset); + var _a_id = _o.A.Id; + var _a_distance = _o.A.Distance; + var _b_a = _o.B.A; + var _b_b = _o.B.B; + var _c_id = _o.C.Id; + var _c_distance = _o.C.Distance; + return CreateStructOfStructs( + builder, + _a_id, + _a_distance, + _b_a, + _b_b, + _c_id, + _c_distance); + } +} + +public class StructOfStructsT +{ + [Newtonsoft.Json.JsonProperty("a")] + public MyGame.Example.AbilityT A { get; set; } + [Newtonsoft.Json.JsonProperty("b")] + public MyGame.Example.TestT B { get; set; } + [Newtonsoft.Json.JsonProperty("c")] + public MyGame.Example.AbilityT C { get; set; } + + public StructOfStructsT() { + this.A = new MyGame.Example.AbilityT(); + this.B = new MyGame.Example.TestT(); + this.C = new MyGame.Example.AbilityT(); + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.go b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.go new file mode 100644 index 00000000000..234c795e380 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.go @@ -0,0 +1,84 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type StructOfStructsT struct { + A *AbilityT `json:"a"` + B *TestT `json:"b"` + C *AbilityT `json:"c"` +} + +func (t *StructOfStructsT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + return CreateStructOfStructs(builder, t.A.Id, t.A.Distance, t.B.A, t.B.B, t.C.Id, t.C.Distance) +} +func (rcv *StructOfStructs) UnPackTo(t *StructOfStructsT) { + t.A = rcv.A(nil).UnPack() + t.B = rcv.B(nil).UnPack() + t.C = rcv.C(nil).UnPack() +} + +func (rcv *StructOfStructs) UnPack() *StructOfStructsT { + if rcv == nil { + return nil + } + t := &StructOfStructsT{} + rcv.UnPackTo(t) + return t +} + +type StructOfStructs struct { + _tab flatbuffers.Struct +} + +func (rcv *StructOfStructs) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *StructOfStructs) Table() flatbuffers.Table { + return rcv._tab.Table +} + +func (rcv *StructOfStructs) A(obj *Ability) *Ability { + if obj == nil { + obj = new(Ability) + } + obj.Init(rcv._tab.Bytes, rcv._tab.Pos+0) + return obj +} +func (rcv *StructOfStructs) B(obj *Test) *Test { + if obj == nil { + obj = new(Test) + } + obj.Init(rcv._tab.Bytes, rcv._tab.Pos+8) + return obj +} +func (rcv *StructOfStructs) C(obj *Ability) *Ability { + if obj == nil { + obj = new(Ability) + } + obj.Init(rcv._tab.Bytes, rcv._tab.Pos+12) + return obj +} + +func CreateStructOfStructs(builder *flatbuffers.Builder, a_id uint32, a_distance uint32, b_a int16, b_b int8, c_id uint32, c_distance uint32) flatbuffers.UOffsetT { + builder.Prep(4, 20) + builder.Prep(4, 8) + builder.PrependUint32(c_distance) + builder.PrependUint32(c_id) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b_b) + builder.PrependInt16(b_a) + builder.Prep(4, 8) + builder.PrependUint32(a_distance) + builder.PrependUint32(a_id) + return builder.Offset() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.java b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.java new file mode 100644 index 00000000000..befd3359050 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.java @@ -0,0 +1,83 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class StructOfStructs extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public StructOfStructs __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.Ability a() { return a(new MyGame.Example.Ability()); } + public MyGame.Example.Ability a(MyGame.Example.Ability obj) { return obj.__assign(bb_pos + 0, bb); } + public MyGame.Example.Test b() { return b(new MyGame.Example.Test()); } + public MyGame.Example.Test b(MyGame.Example.Test obj) { return obj.__assign(bb_pos + 8, bb); } + public MyGame.Example.Ability c() { return c(new MyGame.Example.Ability()); } + public MyGame.Example.Ability c(MyGame.Example.Ability obj) { return obj.__assign(bb_pos + 12, bb); } + + public static int createStructOfStructs(FlatBufferBuilder builder, long a_id, long a_distance, short b_a, byte b_b, long c_id, long c_distance) { + builder.prep(4, 20); + builder.prep(4, 8); + builder.putInt((int) c_distance); + builder.putInt((int) c_id); + builder.prep(2, 4); + builder.pad(1); + builder.putByte(b_b); + builder.putShort(b_a); + builder.prep(4, 8); + builder.putInt((int) a_distance); + builder.putInt((int) a_id); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public StructOfStructs get(int j) { return get(new StructOfStructs(), j); } + public StructOfStructs get(StructOfStructs obj, int j) { return obj.__assign(__element(j), bb); } + } + public StructOfStructsT unpack() { + StructOfStructsT _o = new StructOfStructsT(); + unpackTo(_o); + return _o; + } + public void unpackTo(StructOfStructsT _o) { + a().unpackTo(_o.getA()); + b().unpackTo(_o.getB()); + c().unpackTo(_o.getC()); + } + public static int pack(FlatBufferBuilder builder, StructOfStructsT _o) { + if (_o == null) return 0; + int _a_id = (int) _o.getA().getId(); + int _a_distance = (int) _o.getA().getDistance(); + short _b_a = _o.getB().getA(); + byte _b_b = _o.getB().getB(); + int _c_id = (int) _o.getC().getId(); + int _c_distance = (int) _o.getC().getDistance(); + return createStructOfStructs( + builder, + _a_id, + _a_distance, + _b_a, + _b_b, + _c_id, + _c_distance); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.kt b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.kt new file mode 100644 index 00000000000..e7a27a2315d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.kt @@ -0,0 +1,53 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class StructOfStructs : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : StructOfStructs { + __init(_i, _bb) + return this + } + val a : MyGame.Example.Ability? get() = a(MyGame.Example.Ability()) + fun a(obj: MyGame.Example.Ability) : MyGame.Example.Ability? = obj.__assign(bb_pos + 0, bb) + val b : MyGame.Example.Test? get() = b(MyGame.Example.Test()) + fun b(obj: MyGame.Example.Test) : MyGame.Example.Test? = obj.__assign(bb_pos + 8, bb) + val c : MyGame.Example.Ability? get() = c(MyGame.Example.Ability()) + fun c(obj: MyGame.Example.Ability) : MyGame.Example.Ability? = obj.__assign(bb_pos + 12, bb) + companion object { + fun createStructOfStructs(builder: FlatBufferBuilder, a_id: UInt, a_distance: UInt, b_a: Short, b_b: Byte, c_id: UInt, c_distance: UInt) : Int { + builder.prep(4, 20) + builder.prep(4, 8) + builder.putInt(c_distance.toInt()) + builder.putInt(c_id.toInt()) + builder.prep(2, 4) + builder.pad(1) + builder.putByte(b_b) + builder.putShort(b_a) + builder.prep(4, 8) + builder.putInt(a_distance.toInt()) + builder.putInt(a_id.toInt()) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.lua b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.lua new file mode 100644 index 00000000000..826dcae809e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.lua @@ -0,0 +1,58 @@ +--[[ MyGame.Example.StructOfStructs + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local StructOfStructs = {} +local mt = {} + +function StructOfStructs.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:A(obj) + obj:Init(self.view.bytes, self.view.pos + 0) + return obj +end + +function mt:B(obj) + obj:Init(self.view.bytes, self.view.pos + 8) + return obj +end + +function mt:C(obj) + obj:Init(self.view.bytes, self.view.pos + 12) + return obj +end + +function StructOfStructs.CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance) + builder:Prep(4, 20) + builder:Prep(4, 8) + builder:PrependUint32(c_distance) + builder:PrependUint32(c_id) + builder:Prep(2, 4) + builder:Pad(1) + builder:PrependInt8(b_b) + builder:PrependInt16(b_a) + builder:Prep(4, 8) + builder:PrependUint32(a_distance) + builder:PrependUint32(a_id) + return builder:Offset() +end + +return StructOfStructs \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.nim b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.nim new file mode 100644 index 00000000000..1d9243c5e9f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.nim @@ -0,0 +1,34 @@ +#[ MyGame.Example.StructOfStructs + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import Ability as MyGame_Example_Ability +import Test as MyGame_Example_Test +import flatbuffers + +type StructOfStructs* = object of FlatObj +func a*(self: StructOfStructs): MyGame_Example_Ability.Ability = + return MyGame_Example_Ability.Ability(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + 0)) +func b*(self: StructOfStructs): MyGame_Example_Test.Test = + return MyGame_Example_Test.Test(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + 8)) +func c*(self: StructOfStructs): MyGame_Example_Ability.Ability = + return MyGame_Example_Ability.Ability(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + 12)) +proc StructOfStructsCreate*(self: var Builder, a_id: uint32, a_distance: uint32, b_a: int16, b_b: int8, c_id: uint32, c_distance: uint32): uoffset = + self.Prep(4, 20) + self.Prep(4, 8) + self.Prepend(c_distance) + self.Prepend(c_id) + self.Prep(2, 4) + self.Pad(1) + self.Prepend(b_b) + self.Prepend(b_a) + self.Prep(4, 8) + self.Prepend(a_distance) + self.Prepend(a_id) + return self.Offset() diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.php b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.php new file mode 100644 index 00000000000..fe5fac3ad50 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.php @@ -0,0 +1,74 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return Ability + */ + public function getA() + { + $obj = new Ability(); + $obj->init($this->bb_pos + 0, $this->bb); + return $obj; + } + + /** + * @return Test + */ + public function getB() + { + $obj = new Test(); + $obj->init($this->bb_pos + 8, $this->bb); + return $obj; + } + + /** + * @return Ability + */ + public function getC() + { + $obj = new Ability(); + $obj->init($this->bb_pos + 12, $this->bb); + return $obj; + } + + + /** + * @return int offset + */ + public static function createStructOfStructs(FlatBufferBuilder $builder, $a_id, $a_distance, $b_a, $b_b, $c_id, $c_distance) + { + $builder->prep(4, 20); + $builder->prep(4, 8); + $builder->putUint($c_distance); + $builder->putUint($c_id); + $builder->prep(2, 4); + $builder->pad(1); + $builder->putSbyte($b_b); + $builder->putShort($b_a); + $builder->prep(4, 8); + $builder->putUint($a_distance); + $builder->putUint($a_id); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.py b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.py new file mode 100644 index 00000000000..88c469ed7c4 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructs.py @@ -0,0 +1,95 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class StructOfStructs(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 20 + + # StructOfStructs + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StructOfStructs + def A(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 0) + return obj + + # StructOfStructs + def B(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 8) + return obj + + # StructOfStructs + def C(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 12) + return obj + + +def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance): + builder.Prep(4, 20) + builder.Prep(4, 8) + builder.PrependUint32(c_distance) + builder.PrependUint32(c_id) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b_b) + builder.PrependInt16(b_a) + builder.Prep(4, 8) + builder.PrependUint32(a_distance) + builder.PrependUint32(a_id) + return builder.Offset() + +import MyGame.Example.Ability +import MyGame.Example.Test +try: + from typing import Optional +except: + pass + +class StructOfStructsT(object): + + # StructOfStructsT + def __init__(self): + self.a = None # type: Optional[MyGame.Example.Ability.AbilityT] + self.b = None # type: Optional[MyGame.Example.Test.TestT] + self.c = None # type: Optional[MyGame.Example.Ability.AbilityT] + + @classmethod + def InitFromBuf(cls, buf, pos): + structOfStructs = StructOfStructs() + structOfStructs.Init(buf, pos) + return cls.InitFromObj(structOfStructs) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, structOfStructs): + x = StructOfStructsT() + x._UnPack(structOfStructs) + return x + + # StructOfStructsT + def _UnPack(self, structOfStructs): + if structOfStructs is None: + return + if structOfStructs.A(MyGame.Example.Ability.Ability()) is not None: + self.a = MyGame.Example.Ability.AbilityT.InitFromObj(structOfStructs.A(MyGame.Example.Ability.Ability())) + if structOfStructs.B(MyGame.Example.Test.Test()) is not None: + self.b = MyGame.Example.Test.TestT.InitFromObj(structOfStructs.B(MyGame.Example.Test.Test())) + if structOfStructs.C(MyGame.Example.Ability.Ability()) is not None: + self.c = MyGame.Example.Ability.AbilityT.InitFromObj(structOfStructs.C(MyGame.Example.Ability.Ability())) + + # StructOfStructsT + def Pack(self, builder): + return CreateStructOfStructs(builder, self.a.id, self.a.distance, self.b.a, self.b.b, self.c.id, self.c.distance) diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.cs b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.cs new file mode 100644 index 00000000000..90cfc299aad --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.cs @@ -0,0 +1,74 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct StructOfStructsOfStructs : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public StructOfStructsOfStructs __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.StructOfStructs A { get { return (new MyGame.Example.StructOfStructs()).__assign(__p.bb_pos + 0, __p.bb); } } + + public static Offset CreateStructOfStructsOfStructs(FlatBufferBuilder builder, uint a_a_Id, uint a_a_Distance, short a_b_A, sbyte a_b_B, uint a_c_Id, uint a_c_Distance) { + builder.Prep(4, 20); + builder.Prep(4, 20); + builder.Prep(4, 8); + builder.PutUint(a_c_Distance); + builder.PutUint(a_c_Id); + builder.Prep(2, 4); + builder.Pad(1); + builder.PutSbyte(a_b_B); + builder.PutShort(a_b_A); + builder.Prep(4, 8); + builder.PutUint(a_a_Distance); + builder.PutUint(a_a_Id); + return new Offset(builder.Offset); + } + public StructOfStructsOfStructsT UnPack() { + var _o = new StructOfStructsOfStructsT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(StructOfStructsOfStructsT _o) { + _o.A = this.A.UnPack(); + } + public static Offset Pack(FlatBufferBuilder builder, StructOfStructsOfStructsT _o) { + if (_o == null) return default(Offset); + var _a_a_id = _o.A.A.Id; + var _a_a_distance = _o.A.A.Distance; + var _a_b_a = _o.A.B.A; + var _a_b_b = _o.A.B.B; + var _a_c_id = _o.A.C.Id; + var _a_c_distance = _o.A.C.Distance; + return CreateStructOfStructsOfStructs( + builder, + _a_a_id, + _a_a_distance, + _a_b_a, + _a_b_b, + _a_c_id, + _a_c_distance); + } +} + +public class StructOfStructsOfStructsT +{ + [Newtonsoft.Json.JsonProperty("a")] + public MyGame.Example.StructOfStructsT A { get; set; } + + public StructOfStructsOfStructsT() { + this.A = new MyGame.Example.StructOfStructsT(); + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.go b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.go new file mode 100644 index 00000000000..90094aa9990 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.go @@ -0,0 +1,67 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type StructOfStructsOfStructsT struct { + A *StructOfStructsT `json:"a"` +} + +func (t *StructOfStructsOfStructsT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + return CreateStructOfStructsOfStructs(builder, t.A.A.Id, t.A.A.Distance, t.A.B.A, t.A.B.B, t.A.C.Id, t.A.C.Distance) +} +func (rcv *StructOfStructsOfStructs) UnPackTo(t *StructOfStructsOfStructsT) { + t.A = rcv.A(nil).UnPack() +} + +func (rcv *StructOfStructsOfStructs) UnPack() *StructOfStructsOfStructsT { + if rcv == nil { + return nil + } + t := &StructOfStructsOfStructsT{} + rcv.UnPackTo(t) + return t +} + +type StructOfStructsOfStructs struct { + _tab flatbuffers.Struct +} + +func (rcv *StructOfStructsOfStructs) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *StructOfStructsOfStructs) Table() flatbuffers.Table { + return rcv._tab.Table +} + +func (rcv *StructOfStructsOfStructs) A(obj *StructOfStructs) *StructOfStructs { + if obj == nil { + obj = new(StructOfStructs) + } + obj.Init(rcv._tab.Bytes, rcv._tab.Pos+0) + return obj +} + +func CreateStructOfStructsOfStructs(builder *flatbuffers.Builder, a_a_id uint32, a_a_distance uint32, a_b_a int16, a_b_b int8, a_c_id uint32, a_c_distance uint32) flatbuffers.UOffsetT { + builder.Prep(4, 20) + builder.Prep(4, 20) + builder.Prep(4, 8) + builder.PrependUint32(a_c_distance) + builder.PrependUint32(a_c_id) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(a_b_b) + builder.PrependInt16(a_b_a) + builder.Prep(4, 8) + builder.PrependUint32(a_a_distance) + builder.PrependUint32(a_a_id) + return builder.Offset() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.java b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.java new file mode 100644 index 00000000000..fb14a5a0cf0 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.java @@ -0,0 +1,78 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class StructOfStructsOfStructs extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public StructOfStructsOfStructs __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.StructOfStructs a() { return a(new MyGame.Example.StructOfStructs()); } + public MyGame.Example.StructOfStructs a(MyGame.Example.StructOfStructs obj) { return obj.__assign(bb_pos + 0, bb); } + + public static int createStructOfStructsOfStructs(FlatBufferBuilder builder, long a_a_id, long a_a_distance, short a_b_a, byte a_b_b, long a_c_id, long a_c_distance) { + builder.prep(4, 20); + builder.prep(4, 20); + builder.prep(4, 8); + builder.putInt((int) a_c_distance); + builder.putInt((int) a_c_id); + builder.prep(2, 4); + builder.pad(1); + builder.putByte(a_b_b); + builder.putShort(a_b_a); + builder.prep(4, 8); + builder.putInt((int) a_a_distance); + builder.putInt((int) a_a_id); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public StructOfStructsOfStructs get(int j) { return get(new StructOfStructsOfStructs(), j); } + public StructOfStructsOfStructs get(StructOfStructsOfStructs obj, int j) { return obj.__assign(__element(j), bb); } + } + public StructOfStructsOfStructsT unpack() { + StructOfStructsOfStructsT _o = new StructOfStructsOfStructsT(); + unpackTo(_o); + return _o; + } + public void unpackTo(StructOfStructsOfStructsT _o) { + a().unpackTo(_o.getA()); + } + public static int pack(FlatBufferBuilder builder, StructOfStructsOfStructsT _o) { + if (_o == null) return 0; + int _a_a_id = (int) _o.getA().getA().getId(); + int _a_a_distance = (int) _o.getA().getA().getDistance(); + short _a_b_a = _o.getA().getB().getA(); + byte _a_b_b = _o.getA().getB().getB(); + int _a_c_id = (int) _o.getA().getC().getId(); + int _a_c_distance = (int) _o.getA().getC().getDistance(); + return createStructOfStructsOfStructs( + builder, + _a_a_id, + _a_a_distance, + _a_b_a, + _a_b_b, + _a_c_id, + _a_c_distance); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.kt b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.kt new file mode 100644 index 00000000000..5fb1a1ef552 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.kt @@ -0,0 +1,50 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class StructOfStructsOfStructs : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : StructOfStructsOfStructs { + __init(_i, _bb) + return this + } + val a : MyGame.Example.StructOfStructs? get() = a(MyGame.Example.StructOfStructs()) + fun a(obj: MyGame.Example.StructOfStructs) : MyGame.Example.StructOfStructs? = obj.__assign(bb_pos + 0, bb) + companion object { + fun createStructOfStructsOfStructs(builder: FlatBufferBuilder, a_a_id: UInt, a_a_distance: UInt, a_b_a: Short, a_b_b: Byte, a_c_id: UInt, a_c_distance: UInt) : Int { + builder.prep(4, 20) + builder.prep(4, 20) + builder.prep(4, 8) + builder.putInt(a_c_distance.toInt()) + builder.putInt(a_c_id.toInt()) + builder.prep(2, 4) + builder.pad(1) + builder.putByte(a_b_b) + builder.putShort(a_b_a) + builder.prep(4, 8) + builder.putInt(a_a_distance.toInt()) + builder.putInt(a_a_id.toInt()) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.lua b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.lua new file mode 100644 index 00000000000..366c0984d35 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.lua @@ -0,0 +1,49 @@ +--[[ MyGame.Example.StructOfStructsOfStructs + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local StructOfStructsOfStructs = {} +local mt = {} + +function StructOfStructsOfStructs.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:A(obj) + obj:Init(self.view.bytes, self.view.pos + 0) + return obj +end + +function StructOfStructsOfStructs.CreateStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, a_c_id, a_c_distance) + builder:Prep(4, 20) + builder:Prep(4, 20) + builder:Prep(4, 8) + builder:PrependUint32(a_c_distance) + builder:PrependUint32(a_c_id) + builder:Prep(2, 4) + builder:Pad(1) + builder:PrependInt8(a_b_b) + builder:PrependInt16(a_b_a) + builder:Prep(4, 8) + builder:PrependUint32(a_a_distance) + builder:PrependUint32(a_a_id) + return builder:Offset() +end + +return StructOfStructsOfStructs \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.nim b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.nim new file mode 100644 index 00000000000..5a72f77a54f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.nim @@ -0,0 +1,30 @@ +#[ MyGame.Example.StructOfStructsOfStructs + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import StructOfStructs as MyGame_Example_StructOfStructs +import flatbuffers + +type StructOfStructsOfStructs* = object of FlatObj +func a*(self: StructOfStructsOfStructs): MyGame_Example_StructOfStructs.StructOfStructs = + return MyGame_Example_StructOfStructs.StructOfStructs(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + 0)) +proc StructOfStructsOfStructsCreate*(self: var Builder, a_a_id: uint32, a_a_distance: uint32, a_b_a: int16, a_b_b: int8, a_c_id: uint32, a_c_distance: uint32): uoffset = + self.Prep(4, 20) + self.Prep(4, 20) + self.Prep(4, 8) + self.Prepend(a_c_distance) + self.Prepend(a_c_id) + self.Prep(2, 4) + self.Pad(1) + self.Prepend(a_b_b) + self.Prepend(a_b_a) + self.Prep(4, 8) + self.Prepend(a_a_distance) + self.Prepend(a_a_id) + return self.Offset() diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.php b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.php new file mode 100644 index 00000000000..bcdcca079e2 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.php @@ -0,0 +1,55 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return StructOfStructs + */ + public function getA() + { + $obj = new StructOfStructs(); + $obj->init($this->bb_pos + 0, $this->bb); + return $obj; + } + + + /** + * @return int offset + */ + public static function createStructOfStructsOfStructs(FlatBufferBuilder $builder, $a_a_id, $a_a_distance, $a_b_a, $a_b_b, $a_c_id, $a_c_distance) + { + $builder->prep(4, 20); + $builder->prep(4, 20); + $builder->prep(4, 8); + $builder->putUint($a_c_distance); + $builder->putUint($a_c_id); + $builder->prep(2, 4); + $builder->pad(1); + $builder->putSbyte($a_b_b); + $builder->putShort($a_b_a); + $builder->prep(4, 8); + $builder->putUint($a_a_distance); + $builder->putUint($a_a_id); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.py b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.py new file mode 100644 index 00000000000..0243f71c4d4 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructs.py @@ -0,0 +1,79 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class StructOfStructsOfStructs(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 20 + + # StructOfStructsOfStructs + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StructOfStructsOfStructs + def A(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 0) + return obj + + +def CreateStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, a_c_id, a_c_distance): + builder.Prep(4, 20) + builder.Prep(4, 20) + builder.Prep(4, 8) + builder.PrependUint32(a_c_distance) + builder.PrependUint32(a_c_id) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(a_b_b) + builder.PrependInt16(a_b_a) + builder.Prep(4, 8) + builder.PrependUint32(a_a_distance) + builder.PrependUint32(a_a_id) + return builder.Offset() + +import MyGame.Example.StructOfStructs +try: + from typing import Optional +except: + pass + +class StructOfStructsOfStructsT(object): + + # StructOfStructsOfStructsT + def __init__(self): + self.a = None # type: Optional[MyGame.Example.StructOfStructs.StructOfStructsT] + + @classmethod + def InitFromBuf(cls, buf, pos): + structOfStructsOfStructs = StructOfStructsOfStructs() + structOfStructsOfStructs.Init(buf, pos) + return cls.InitFromObj(structOfStructsOfStructs) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, structOfStructsOfStructs): + x = StructOfStructsOfStructsT() + x._UnPack(structOfStructsOfStructs) + return x + + # StructOfStructsOfStructsT + def _UnPack(self, structOfStructsOfStructs): + if structOfStructsOfStructs is None: + return + if structOfStructsOfStructs.A(MyGame.Example.StructOfStructs.StructOfStructs()) is not None: + self.a = MyGame.Example.StructOfStructs.StructOfStructsT.InitFromObj(structOfStructsOfStructs.A(MyGame.Example.StructOfStructs.StructOfStructs())) + + # StructOfStructsOfStructsT + def Pack(self, builder): + return CreateStructOfStructsOfStructs(builder, self.a.a.id, self.a.a.distance, self.a.b.a, self.a.b.b, self.a.c.id, self.a.c.distance) diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructsT.java b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructsT.java new file mode 100644 index 00000000000..60afd7384b7 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsOfStructsT.java @@ -0,0 +1,34 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class StructOfStructsOfStructsT { + private MyGame.Example.StructOfStructsT a; + + public MyGame.Example.StructOfStructsT getA() { return a; } + + public void setA(MyGame.Example.StructOfStructsT a) { this.a = a; } + + + public StructOfStructsOfStructsT() { + this.a = new MyGame.Example.StructOfStructsT(); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsT.java b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsT.java new file mode 100644 index 00000000000..8d5034af542 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/StructOfStructsT.java @@ -0,0 +1,46 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class StructOfStructsT { + private MyGame.Example.AbilityT a; + private MyGame.Example.TestT b; + private MyGame.Example.AbilityT c; + + public MyGame.Example.AbilityT getA() { return a; } + + public void setA(MyGame.Example.AbilityT a) { this.a = a; } + + public MyGame.Example.TestT getB() { return b; } + + public void setB(MyGame.Example.TestT b) { this.b = b; } + + public MyGame.Example.AbilityT getC() { return c; } + + public void setC(MyGame.Example.AbilityT c) { this.c = c; } + + + public StructOfStructsT() { + this.a = new MyGame.Example.AbilityT(); + this.b = new MyGame.Example.TestT(); + this.c = new MyGame.Example.AbilityT(); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.cs b/third_party/flatbuffers/tests/MyGame/Example/Test.cs new file mode 100644 index 00000000000..68f3354486f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.cs @@ -0,0 +1,63 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Test : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public Test __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public short A { get { return __p.bb.GetShort(__p.bb_pos + 0); } } + public void MutateA(short a) { __p.bb.PutShort(__p.bb_pos + 0, a); } + public sbyte B { get { return __p.bb.GetSbyte(__p.bb_pos + 2); } } + public void MutateB(sbyte b) { __p.bb.PutSbyte(__p.bb_pos + 2, b); } + + public static Offset CreateTest(FlatBufferBuilder builder, short A, sbyte B) { + builder.Prep(2, 4); + builder.Pad(1); + builder.PutSbyte(B); + builder.PutShort(A); + return new Offset(builder.Offset); + } + public TestT UnPack() { + var _o = new TestT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(TestT _o) { + _o.A = this.A; + _o.B = this.B; + } + public static Offset Pack(FlatBufferBuilder builder, TestT _o) { + if (_o == null) return default(Offset); + return CreateTest( + builder, + _o.A, + _o.B); + } +} + +public class TestT +{ + [Newtonsoft.Json.JsonProperty("a")] + public short A { get; set; } + [Newtonsoft.Json.JsonProperty("b")] + public sbyte B { get; set; } + + public TestT() { + this.A = 0; + this.B = 0; + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.go b/third_party/flatbuffers/tests/MyGame/Example/Test.go new file mode 100644 index 00000000000..d7efcf4f7a6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.go @@ -0,0 +1,67 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type TestT struct { + A int16 `json:"a"` + B int8 `json:"b"` +} + +func (t *TestT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + return CreateTest(builder, t.A, t.B) +} +func (rcv *Test) UnPackTo(t *TestT) { + t.A = rcv.A() + t.B = rcv.B() +} + +func (rcv *Test) UnPack() *TestT { + if rcv == nil { + return nil + } + t := &TestT{} + rcv.UnPackTo(t) + return t +} + +type Test struct { + _tab flatbuffers.Struct +} + +func (rcv *Test) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Test) Table() flatbuffers.Table { + return rcv._tab.Table +} + +func (rcv *Test) A() int16 { + return rcv._tab.GetInt16(rcv._tab.Pos + flatbuffers.UOffsetT(0)) +} +func (rcv *Test) MutateA(n int16) bool { + return rcv._tab.MutateInt16(rcv._tab.Pos+flatbuffers.UOffsetT(0), n) +} + +func (rcv *Test) B() int8 { + return rcv._tab.GetInt8(rcv._tab.Pos + flatbuffers.UOffsetT(2)) +} +func (rcv *Test) MutateB(n int8) bool { + return rcv._tab.MutateInt8(rcv._tab.Pos+flatbuffers.UOffsetT(2), n) +} + +func CreateTest(builder *flatbuffers.Builder, a int16, b int8) flatbuffers.UOffsetT { + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b) + builder.PrependInt16(a) + return builder.Offset() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.java b/third_party/flatbuffers/tests/MyGame/Example/Test.java new file mode 100644 index 00000000000..cff5a6503dc --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.java @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Test extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Test __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public short a() { return bb.getShort(bb_pos + 0); } + public void mutateA(short a) { bb.putShort(bb_pos + 0, a); } + public byte b() { return bb.get(bb_pos + 2); } + public void mutateB(byte b) { bb.put(bb_pos + 2, b); } + + public static int createTest(FlatBufferBuilder builder, short a, byte b) { + builder.prep(2, 4); + builder.pad(1); + builder.putByte(b); + builder.putShort(a); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Test get(int j) { return get(new Test(), j); } + public Test get(Test obj, int j) { return obj.__assign(__element(j), bb); } + } + public TestT unpack() { + TestT _o = new TestT(); + unpackTo(_o); + return _o; + } + public void unpackTo(TestT _o) { + short _oA = a(); + _o.setA(_oA); + byte _oB = b(); + _o.setB(_oB); + } + public static int pack(FlatBufferBuilder builder, TestT _o) { + if (_o == null) return 0; + return createTest( + builder, + _o.getA(), + _o.getB()); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.kt b/third_party/flatbuffers/tests/MyGame/Example/Test.kt new file mode 100644 index 00000000000..c2ce96e9b4d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.kt @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Test : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Test { + __init(_i, _bb) + return this + } + val a : Short get() = bb.getShort(bb_pos + 0) + fun mutateA(a: Short) : ByteBuffer = bb.putShort(bb_pos + 0, a) + val b : Byte get() = bb.get(bb_pos + 2) + fun mutateB(b: Byte) : ByteBuffer = bb.put(bb_pos + 2, b) + companion object { + fun createTest(builder: FlatBufferBuilder, a: Short, b: Byte) : Int { + builder.prep(2, 4) + builder.pad(1) + builder.putByte(b) + builder.putShort(a) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.lua b/third_party/flatbuffers/tests/MyGame/Example/Test.lua new file mode 100644 index 00000000000..a3b2fbd9602 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.lua @@ -0,0 +1,44 @@ +--[[ MyGame.Example.Test + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Test = {} +local mt = {} + +function Test.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:A() + return self.view:Get(flatbuffers.N.Int16, self.view.pos + 0) +end + +function mt:B() + return self.view:Get(flatbuffers.N.Int8, self.view.pos + 2) +end + +function Test.CreateTest(builder, a, b) + builder:Prep(2, 4) + builder:Pad(1) + builder:PrependInt8(b) + builder:PrependInt16(a) + return builder:Offset() +end + +return Test \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.nim b/third_party/flatbuffers/tests/MyGame/Example/Test.nim new file mode 100644 index 00000000000..0c5834a840d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.nim @@ -0,0 +1,27 @@ +#[ MyGame.Example.Test + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers + +type Test* = object of FlatObj +func a*(self: Test): int16 = + return Get[int16](self.tab, self.tab.Pos + 0) +func `a=`*(self: var Test, n: int16): bool = + return self.tab.Mutate(self.tab.Pos + 0, n) +func b*(self: Test): int8 = + return Get[int8](self.tab, self.tab.Pos + 2) +func `b=`*(self: var Test, n: int8): bool = + return self.tab.Mutate(self.tab.Pos + 2, n) +proc TestCreate*(self: var Builder, a: int16, b: int8): uoffset = + self.Prep(2, 4) + self.Pad(1) + self.Prepend(b) + self.Prepend(a) + return self.Offset() diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.php b/third_party/flatbuffers/tests/MyGame/Example/Test.php new file mode 100644 index 00000000000..13cced00151 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.php @@ -0,0 +1,53 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return short + */ + public function GetA() + { + return $this->bb->getShort($this->bb_pos + 0); + } + + /** + * @return sbyte + */ + public function GetB() + { + return $this->bb->getSbyte($this->bb_pos + 2); + } + + + /** + * @return int offset + */ + public static function createTest(FlatBufferBuilder $builder, $a, $b) + { + $builder->prep(2, 4); + $builder->pad(1); + $builder->putSbyte($b); + $builder->putShort($a); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Test.py b/third_party/flatbuffers/tests/MyGame/Example/Test.py new file mode 100644 index 00000000000..f095d33451a --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Test.py @@ -0,0 +1,66 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Test(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 4 + + # Test + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Test + def A(self): return self._tab.Get(flatbuffers.number_types.Int16Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Test + def B(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(2)) + +def CreateTest(builder, a, b): + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b) + builder.PrependInt16(a) + return builder.Offset() + + +class TestT(object): + + # TestT + def __init__(self): + self.a = 0 # type: int + self.b = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + test = Test() + test.Init(buf, pos) + return cls.InitFromObj(test) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, test): + x = TestT() + x._UnPack(test) + return x + + # TestT + def _UnPack(self, test): + if test is None: + return + self.a = test.A() + self.b = test.B() + + # TestT + def Pack(self, builder): + return CreateTest(builder, self.a, self.b) diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestEnum.cs b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.cs new file mode 100644 index 00000000000..6dfd6b546cd --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.cs @@ -0,0 +1,17 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum TestEnum : sbyte +{ + A = 0, + B = 1, + C = 2, +}; + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestEnum.java b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.java new file mode 100644 index 00000000000..6330cf61362 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.java @@ -0,0 +1,16 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +@SuppressWarnings("unused") +public final class TestEnum { + private TestEnum() { } + public static final byte A = 0; + public static final byte B = 1; + public static final byte C = 2; + + public static final String[] names = { "A", "B", "C", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestEnum.kt b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.kt new file mode 100644 index 00000000000..ca4d7f879c9 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.kt @@ -0,0 +1,14 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +@Suppress("unused") +class TestEnum private constructor() { + companion object { + const val A: Byte = 0 + const val B: Byte = 1 + const val C: Byte = 2 + val names : Array = arrayOf("A", "B", "C") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestEnum.py b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.py new file mode 100644 index 00000000000..4f5f60800b9 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.py @@ -0,0 +1,8 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +class TestEnum(object): + A = 0 + B = 1 + C = 2 diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestEnum.pyi b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.pyi new file mode 100644 index 00000000000..f2f9042783b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestEnum.pyi @@ -0,0 +1,15 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class TestEnum(object): + A: int + B: int + C: int + diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.cs b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.cs new file mode 100644 index 00000000000..d4b2628b457 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.cs @@ -0,0 +1,75 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +internal partial struct TestSimpleTableWithEnum : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static TestSimpleTableWithEnum GetRootAsTestSimpleTableWithEnum(ByteBuffer _bb) { return GetRootAsTestSimpleTableWithEnum(_bb, new TestSimpleTableWithEnum()); } + public static TestSimpleTableWithEnum GetRootAsTestSimpleTableWithEnum(ByteBuffer _bb, TestSimpleTableWithEnum obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public TestSimpleTableWithEnum __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public MyGame.Example.Color Color { get { int o = __p.__offset(4); return o != 0 ? (MyGame.Example.Color)__p.bb.Get(o + __p.bb_pos) : MyGame.Example.Color.Green; } } + public bool MutateColor(MyGame.Example.Color color) { int o = __p.__offset(4); if (o != 0) { __p.bb.Put(o + __p.bb_pos, (byte)color); return true; } else { return false; } } + + public static Offset CreateTestSimpleTableWithEnum(FlatBufferBuilder builder, + MyGame.Example.Color color = MyGame.Example.Color.Green) { + builder.StartTable(1); + TestSimpleTableWithEnum.AddColor(builder, color); + return TestSimpleTableWithEnum.EndTestSimpleTableWithEnum(builder); + } + + public static void StartTestSimpleTableWithEnum(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddColor(FlatBufferBuilder builder, MyGame.Example.Color color) { builder.AddByte(0, (byte)color, 2); } + public static Offset EndTestSimpleTableWithEnum(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public TestSimpleTableWithEnumT UnPack() { + var _o = new TestSimpleTableWithEnumT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(TestSimpleTableWithEnumT _o) { + _o.Color = this.Color; + } + public static Offset Pack(FlatBufferBuilder builder, TestSimpleTableWithEnumT _o) { + if (_o == null) return default(Offset); + return CreateTestSimpleTableWithEnum( + builder, + _o.Color); + } +} + +internal partial class TestSimpleTableWithEnumT +{ + [Newtonsoft.Json.JsonProperty("color")] + public MyGame.Example.Color Color { get; set; } + + public TestSimpleTableWithEnumT() { + this.Color = MyGame.Example.Color.Green; + } +} + + +static public class TestSimpleTableWithEnumVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Color*/, 1 /*MyGame.Example.Color*/, 1, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.go b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.go new file mode 100644 index 00000000000..f491ccd8669 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.go @@ -0,0 +1,90 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type TestSimpleTableWithEnumT struct { + Color Color `json:"color"` +} + +func (t *TestSimpleTableWithEnumT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + TestSimpleTableWithEnumStart(builder) + TestSimpleTableWithEnumAddColor(builder, t.Color) + return TestSimpleTableWithEnumEnd(builder) +} + +func (rcv *TestSimpleTableWithEnum) UnPackTo(t *TestSimpleTableWithEnumT) { + t.Color = rcv.Color() +} + +func (rcv *TestSimpleTableWithEnum) UnPack() *TestSimpleTableWithEnumT { + if rcv == nil { + return nil + } + t := &TestSimpleTableWithEnumT{} + rcv.UnPackTo(t) + return t +} + +type TestSimpleTableWithEnum struct { + _tab flatbuffers.Table +} + +func GetRootAsTestSimpleTableWithEnum(buf []byte, offset flatbuffers.UOffsetT) *TestSimpleTableWithEnum { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &TestSimpleTableWithEnum{} + x.Init(buf, n+offset) + return x +} + +func FinishTestSimpleTableWithEnumBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsTestSimpleTableWithEnum(buf []byte, offset flatbuffers.UOffsetT) *TestSimpleTableWithEnum { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &TestSimpleTableWithEnum{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedTestSimpleTableWithEnumBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *TestSimpleTableWithEnum) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *TestSimpleTableWithEnum) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *TestSimpleTableWithEnum) Color() Color { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return Color(rcv._tab.GetByte(o + rcv._tab.Pos)) + } + return 2 +} + +func (rcv *TestSimpleTableWithEnum) MutateColor(n Color) bool { + return rcv._tab.MutateByteSlot(4, byte(n)) +} + +func TestSimpleTableWithEnumStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func TestSimpleTableWithEnumAddColor(builder *flatbuffers.Builder, color Color) { + builder.PrependByteSlot(0, byte(color), 2) +} +func TestSimpleTableWithEnumEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.java b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.java new file mode 100644 index 00000000000..1eccca14403 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.java @@ -0,0 +1,69 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +final class TestSimpleTableWithEnum extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static TestSimpleTableWithEnum getRootAsTestSimpleTableWithEnum(ByteBuffer _bb) { return getRootAsTestSimpleTableWithEnum(_bb, new TestSimpleTableWithEnum()); } + public static TestSimpleTableWithEnum getRootAsTestSimpleTableWithEnum(ByteBuffer _bb, TestSimpleTableWithEnum obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public TestSimpleTableWithEnum __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int color() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 2; } + public boolean mutateColor(int color) { int o = __offset(4); if (o != 0) { bb.put(o + bb_pos, (byte) color); return true; } else { return false; } } + + public static int createTestSimpleTableWithEnum(FlatBufferBuilder builder, + int color) { + builder.startTable(1); + TestSimpleTableWithEnum.addColor(builder, color); + return TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder); + } + + public static void startTestSimpleTableWithEnum(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addColor(FlatBufferBuilder builder, int color) { builder.addByte(0, (byte) color, (byte) 2); } + public static int endTestSimpleTableWithEnum(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public TestSimpleTableWithEnum get(int j) { return get(new TestSimpleTableWithEnum(), j); } + public TestSimpleTableWithEnum get(TestSimpleTableWithEnum obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public TestSimpleTableWithEnumT unpack() { + TestSimpleTableWithEnumT _o = new TestSimpleTableWithEnumT(); + unpackTo(_o); + return _o; + } + public void unpackTo(TestSimpleTableWithEnumT _o) { + int _oColor = color(); + _o.setColor(_oColor); + } + public static int pack(FlatBufferBuilder builder, TestSimpleTableWithEnumT _o) { + if (_o == null) return 0; + return createTestSimpleTableWithEnum( + builder, + _o.getColor()); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.kt b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.kt new file mode 100644 index 00000000000..c6380ae073b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.kt @@ -0,0 +1,64 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class TestSimpleTableWithEnum : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : TestSimpleTableWithEnum { + __init(_i, _bb) + return this + } + val color : UByte + get() { + val o = __offset(4) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 2u + } + fun mutateColor(color: UByte) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.put(o + bb_pos, color.toByte()) + true + } else { + false + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsTestSimpleTableWithEnum(_bb: ByteBuffer): TestSimpleTableWithEnum = getRootAsTestSimpleTableWithEnum(_bb, TestSimpleTableWithEnum()) + fun getRootAsTestSimpleTableWithEnum(_bb: ByteBuffer, obj: TestSimpleTableWithEnum): TestSimpleTableWithEnum { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createTestSimpleTableWithEnum(builder: FlatBufferBuilder, color: UByte) : Int { + builder.startTable(1) + addColor(builder, color) + return endTestSimpleTableWithEnum(builder) + } + fun startTestSimpleTableWithEnum(builder: FlatBufferBuilder) = builder.startTable(1) + fun addColor(builder: FlatBufferBuilder, color: UByte) = builder.addByte(0, color.toByte(), 2) + fun endTestSimpleTableWithEnum(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.lua b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.lua new file mode 100644 index 00000000000..f4510693395 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.lua @@ -0,0 +1,48 @@ +--[[ MyGame.Example.TestSimpleTableWithEnum + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local TestSimpleTableWithEnum = {} +local mt = {} + +function TestSimpleTableWithEnum.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:Color() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) + end + return 2 +end + +function TestSimpleTableWithEnum.Start(builder) + builder:StartObject(1) +end + +function TestSimpleTableWithEnum.AddColor(builder, color) + builder:PrependUint8Slot(0, color, 2) +end + +function TestSimpleTableWithEnum.End(builder) + return builder:EndObject() +end + +return TestSimpleTableWithEnum \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.nim b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.nim new file mode 100644 index 00000000000..43f8ebff246 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.nim @@ -0,0 +1,27 @@ +#[ MyGame.Example.TestSimpleTableWithEnum + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import Color as MyGame_Example_Color +import flatbuffers + +type TestSimpleTableWithEnum* = object of FlatObj +func color*(self: TestSimpleTableWithEnum): MyGame_Example_Color.Color = + let o = self.tab.Offset(4) + if o != 0: + return MyGame_Example_Color.Color(Get[uint8](self.tab, self.tab.Pos + o)) + return type(result)(2) +func `color=`*(self: var TestSimpleTableWithEnum, n: MyGame_Example_Color.Color): bool = + return self.tab.MutateSlot(4, n) +proc TestSimpleTableWithEnumStart*(builder: var Builder) = + builder.StartObject(1) +proc TestSimpleTableWithEnumAddcolor*(builder: var Builder, color: uint8) = + builder.PrependSlot(0, color, default(uint8)) +proc TestSimpleTableWithEnumEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.php b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.php new file mode 100644 index 00000000000..6429f8d8e3d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.php @@ -0,0 +1,99 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function TestSimpleTableWithEnumIdentifier() + { + return "MONS"; + } + + public static function TestSimpleTableWithEnumBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::TestSimpleTableWithEnumIdentifier()); + } + + public static function TestSimpleTableWithEnumExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return TestSimpleTableWithEnum + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return byte + */ + public function getColor() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \MyGame\Example\Color::Green; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startTestSimpleTableWithEnum(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return TestSimpleTableWithEnum + */ + public static function createTestSimpleTableWithEnum(FlatBufferBuilder $builder, $color) + { + $builder->startObject(1); + self::addColor($builder, $color); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addColor(FlatBufferBuilder $builder, $color) + { + $builder->addByteX(0, $color, 2); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endTestSimpleTableWithEnum(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.py b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.py new file mode 100644 index 00000000000..520d257fd7f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnum.py @@ -0,0 +1,91 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TestSimpleTableWithEnum(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TestSimpleTableWithEnum() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTestSimpleTableWithEnum(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TestSimpleTableWithEnumBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # TestSimpleTableWithEnum + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TestSimpleTableWithEnum + def Color(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 2 + +def TestSimpleTableWithEnumStart(builder): + builder.StartObject(1) + +def Start(builder): + TestSimpleTableWithEnumStart(builder) + +def TestSimpleTableWithEnumAddColor(builder, color): + builder.PrependUint8Slot(0, color, 2) + +def AddColor(builder, color): + TestSimpleTableWithEnumAddColor(builder, color) + +def TestSimpleTableWithEnumEnd(builder): + return builder.EndObject() + +def End(builder): + return TestSimpleTableWithEnumEnd(builder) + + +class TestSimpleTableWithEnumT(object): + + # TestSimpleTableWithEnumT + def __init__(self): + self.color = 2 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + testSimpleTableWithEnum = TestSimpleTableWithEnum() + testSimpleTableWithEnum.Init(buf, pos) + return cls.InitFromObj(testSimpleTableWithEnum) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, testSimpleTableWithEnum): + x = TestSimpleTableWithEnumT() + x._UnPack(testSimpleTableWithEnum) + return x + + # TestSimpleTableWithEnumT + def _UnPack(self, testSimpleTableWithEnum): + if testSimpleTableWithEnum is None: + return + self.color = testSimpleTableWithEnum.Color() + + # TestSimpleTableWithEnumT + def Pack(self, builder): + TestSimpleTableWithEnumStart(builder) + TestSimpleTableWithEnumAddColor(builder, self.color) + testSimpleTableWithEnum = TestSimpleTableWithEnumEnd(builder) + return testSimpleTableWithEnum diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnumT.java b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnumT.java new file mode 100644 index 00000000000..7641550c411 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestSimpleTableWithEnumT.java @@ -0,0 +1,34 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +class TestSimpleTableWithEnumT { + private int color; + + public int getColor() { return color; } + + public void setColor(int color) { this.color = color; } + + + public TestSimpleTableWithEnumT() { + this.color = 2; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/TestT.java b/third_party/flatbuffers/tests/MyGame/Example/TestT.java new file mode 100644 index 00000000000..38103172b79 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TestT.java @@ -0,0 +1,40 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class TestT { + private short a; + private byte b; + + public short getA() { return a; } + + public void setA(short a) { this.a = a; } + + public byte getB() { return b; } + + public void setB(byte b) { this.b = b; } + + + public TestT() { + this.a = 0; + this.b = 0; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.cs b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.cs new file mode 100644 index 00000000000..1ba2964aab9 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.cs @@ -0,0 +1,232 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct TypeAliases : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static TypeAliases GetRootAsTypeAliases(ByteBuffer _bb) { return GetRootAsTypeAliases(_bb, new TypeAliases()); } + public static TypeAliases GetRootAsTypeAliases(ByteBuffer _bb, TypeAliases obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public TypeAliases __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public sbyte I8 { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetSbyte(o + __p.bb_pos) : (sbyte)0; } } + public bool MutateI8(sbyte i8) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutSbyte(o + __p.bb_pos, i8); return true; } else { return false; } } + public byte U8 { get { int o = __p.__offset(6); return o != 0 ? __p.bb.Get(o + __p.bb_pos) : (byte)0; } } + public bool MutateU8(byte u8) { int o = __p.__offset(6); if (o != 0) { __p.bb.Put(o + __p.bb_pos, u8); return true; } else { return false; } } + public short I16 { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetShort(o + __p.bb_pos) : (short)0; } } + public bool MutateI16(short i16) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutShort(o + __p.bb_pos, i16); return true; } else { return false; } } + public ushort U16 { get { int o = __p.__offset(10); return o != 0 ? __p.bb.GetUshort(o + __p.bb_pos) : (ushort)0; } } + public bool MutateU16(ushort u16) { int o = __p.__offset(10); if (o != 0) { __p.bb.PutUshort(o + __p.bb_pos, u16); return true; } else { return false; } } + public int I32 { get { int o = __p.__offset(12); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateI32(int i32) { int o = __p.__offset(12); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, i32); return true; } else { return false; } } + public uint U32 { get { int o = __p.__offset(14); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)0; } } + public bool MutateU32(uint u32) { int o = __p.__offset(14); if (o != 0) { __p.bb.PutUint(o + __p.bb_pos, u32); return true; } else { return false; } } + public long I64 { get { int o = __p.__offset(16); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } } + public bool MutateI64(long i64) { int o = __p.__offset(16); if (o != 0) { __p.bb.PutLong(o + __p.bb_pos, i64); return true; } else { return false; } } + public ulong U64 { get { int o = __p.__offset(18); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public bool MutateU64(ulong u64) { int o = __p.__offset(18); if (o != 0) { __p.bb.PutUlong(o + __p.bb_pos, u64); return true; } else { return false; } } + public float F32 { get { int o = __p.__offset(20); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)0.0f; } } + public bool MutateF32(float f32) { int o = __p.__offset(20); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, f32); return true; } else { return false; } } + public double F64 { get { int o = __p.__offset(22); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)0.0; } } + public bool MutateF64(double f64) { int o = __p.__offset(22); if (o != 0) { __p.bb.PutDouble(o + __p.bb_pos, f64); return true; } else { return false; } } + public sbyte V8(int j) { int o = __p.__offset(24); return o != 0 ? __p.bb.GetSbyte(__p.__vector(o) + j * 1) : (sbyte)0; } + public int V8Length { get { int o = __p.__offset(24); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetV8Bytes() { return __p.__vector_as_span(24, 1); } +#else + public ArraySegment? GetV8Bytes() { return __p.__vector_as_arraysegment(24); } +#endif + public sbyte[] GetV8Array() { return __p.__vector_as_array(24); } + public bool MutateV8(int j, sbyte v8) { int o = __p.__offset(24); if (o != 0) { __p.bb.PutSbyte(__p.__vector(o) + j * 1, v8); return true; } else { return false; } } + public double Vf64(int j) { int o = __p.__offset(26); return o != 0 ? __p.bb.GetDouble(__p.__vector(o) + j * 8) : (double)0; } + public int Vf64Length { get { int o = __p.__offset(26); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetVf64Bytes() { return __p.__vector_as_span(26, 8); } +#else + public ArraySegment? GetVf64Bytes() { return __p.__vector_as_arraysegment(26); } +#endif + public double[] GetVf64Array() { return __p.__vector_as_array(26); } + public bool MutateVf64(int j, double vf64) { int o = __p.__offset(26); if (o != 0) { __p.bb.PutDouble(__p.__vector(o) + j * 8, vf64); return true; } else { return false; } } + + public static Offset CreateTypeAliases(FlatBufferBuilder builder, + sbyte i8 = 0, + byte u8 = 0, + short i16 = 0, + ushort u16 = 0, + int i32 = 0, + uint u32 = 0, + long i64 = 0, + ulong u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + VectorOffset v8Offset = default(VectorOffset), + VectorOffset vf64Offset = default(VectorOffset)) { + builder.StartTable(12); + TypeAliases.AddF64(builder, f64); + TypeAliases.AddU64(builder, u64); + TypeAliases.AddI64(builder, i64); + TypeAliases.AddVf64(builder, vf64Offset); + TypeAliases.AddV8(builder, v8Offset); + TypeAliases.AddF32(builder, f32); + TypeAliases.AddU32(builder, u32); + TypeAliases.AddI32(builder, i32); + TypeAliases.AddU16(builder, u16); + TypeAliases.AddI16(builder, i16); + TypeAliases.AddU8(builder, u8); + TypeAliases.AddI8(builder, i8); + return TypeAliases.EndTypeAliases(builder); + } + + public static void StartTypeAliases(FlatBufferBuilder builder) { builder.StartTable(12); } + public static void AddI8(FlatBufferBuilder builder, sbyte i8) { builder.AddSbyte(0, i8, 0); } + public static void AddU8(FlatBufferBuilder builder, byte u8) { builder.AddByte(1, u8, 0); } + public static void AddI16(FlatBufferBuilder builder, short i16) { builder.AddShort(2, i16, 0); } + public static void AddU16(FlatBufferBuilder builder, ushort u16) { builder.AddUshort(3, u16, 0); } + public static void AddI32(FlatBufferBuilder builder, int i32) { builder.AddInt(4, i32, 0); } + public static void AddU32(FlatBufferBuilder builder, uint u32) { builder.AddUint(5, u32, 0); } + public static void AddI64(FlatBufferBuilder builder, long i64) { builder.AddLong(6, i64, 0); } + public static void AddU64(FlatBufferBuilder builder, ulong u64) { builder.AddUlong(7, u64, 0); } + public static void AddF32(FlatBufferBuilder builder, float f32) { builder.AddFloat(8, f32, 0.0f); } + public static void AddF64(FlatBufferBuilder builder, double f64) { builder.AddDouble(9, f64, 0.0); } + public static void AddV8(FlatBufferBuilder builder, VectorOffset v8Offset) { builder.AddOffset(10, v8Offset.Value, 0); } + public static VectorOffset CreateV8Vector(FlatBufferBuilder builder, sbyte[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddSbyte(data[i]); return builder.EndVector(); } + public static VectorOffset CreateV8VectorBlock(FlatBufferBuilder builder, sbyte[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateV8VectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateV8VectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartV8Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddVf64(FlatBufferBuilder builder, VectorOffset vf64Offset) { builder.AddOffset(11, vf64Offset.Value, 0); } + public static VectorOffset CreateVf64Vector(FlatBufferBuilder builder, double[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddDouble(data[i]); return builder.EndVector(); } + public static VectorOffset CreateVf64VectorBlock(FlatBufferBuilder builder, double[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVf64VectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateVf64VectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartVf64Vector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static Offset EndTypeAliases(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public TypeAliasesT UnPack() { + var _o = new TypeAliasesT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(TypeAliasesT _o) { + _o.I8 = this.I8; + _o.U8 = this.U8; + _o.I16 = this.I16; + _o.U16 = this.U16; + _o.I32 = this.I32; + _o.U32 = this.U32; + _o.I64 = this.I64; + _o.U64 = this.U64; + _o.F32 = this.F32; + _o.F64 = this.F64; + _o.V8 = new List(); + for (var _j = 0; _j < this.V8Length; ++_j) {_o.V8.Add(this.V8(_j));} + _o.Vf64 = new List(); + for (var _j = 0; _j < this.Vf64Length; ++_j) {_o.Vf64.Add(this.Vf64(_j));} + } + public static Offset Pack(FlatBufferBuilder builder, TypeAliasesT _o) { + if (_o == null) return default(Offset); + var _v8 = default(VectorOffset); + if (_o.V8 != null) { + var __v8 = _o.V8.ToArray(); + _v8 = CreateV8Vector(builder, __v8); + } + var _vf64 = default(VectorOffset); + if (_o.Vf64 != null) { + var __vf64 = _o.Vf64.ToArray(); + _vf64 = CreateVf64Vector(builder, __vf64); + } + return CreateTypeAliases( + builder, + _o.I8, + _o.U8, + _o.I16, + _o.U16, + _o.I32, + _o.U32, + _o.I64, + _o.U64, + _o.F32, + _o.F64, + _v8, + _vf64); + } +} + +public class TypeAliasesT +{ + [Newtonsoft.Json.JsonProperty("i8")] + public sbyte I8 { get; set; } + [Newtonsoft.Json.JsonProperty("u8")] + public byte U8 { get; set; } + [Newtonsoft.Json.JsonProperty("i16")] + public short I16 { get; set; } + [Newtonsoft.Json.JsonProperty("u16")] + public ushort U16 { get; set; } + [Newtonsoft.Json.JsonProperty("i32")] + public int I32 { get; set; } + [Newtonsoft.Json.JsonProperty("u32")] + public uint U32 { get; set; } + [Newtonsoft.Json.JsonProperty("i64")] + public long I64 { get; set; } + [Newtonsoft.Json.JsonProperty("u64")] + public ulong U64 { get; set; } + [Newtonsoft.Json.JsonProperty("f32")] + public float F32 { get; set; } + [Newtonsoft.Json.JsonProperty("f64")] + public double F64 { get; set; } + [Newtonsoft.Json.JsonProperty("v8")] + public List V8 { get; set; } + [Newtonsoft.Json.JsonProperty("vf64")] + public List Vf64 { get; set; } + + public TypeAliasesT() { + this.I8 = 0; + this.U8 = 0; + this.I16 = 0; + this.U16 = 0; + this.I32 = 0; + this.U32 = 0; + this.I64 = 0; + this.U64 = 0; + this.F32 = 0.0f; + this.F64 = 0.0; + this.V8 = null; + this.Vf64 = null; + } +} + + +static public class TypeAliasesVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*I8*/, 1 /*sbyte*/, 1, false) + && verifier.VerifyField(tablePos, 6 /*U8*/, 1 /*byte*/, 1, false) + && verifier.VerifyField(tablePos, 8 /*I16*/, 2 /*short*/, 2, false) + && verifier.VerifyField(tablePos, 10 /*U16*/, 2 /*ushort*/, 2, false) + && verifier.VerifyField(tablePos, 12 /*I32*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 14 /*U32*/, 4 /*uint*/, 4, false) + && verifier.VerifyField(tablePos, 16 /*I64*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 18 /*U64*/, 8 /*ulong*/, 8, false) + && verifier.VerifyField(tablePos, 20 /*F32*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 22 /*F64*/, 8 /*double*/, 8, false) + && verifier.VerifyVectorOfData(tablePos, 24 /*V8*/, 1 /*sbyte*/, false) + && verifier.VerifyVectorOfData(tablePos, 26 /*Vf64*/, 8 /*double*/, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.go b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.go new file mode 100644 index 00000000000..e13311ee343 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.go @@ -0,0 +1,348 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type TypeAliasesT struct { + I8 int8 `json:"i8"` + U8 byte `json:"u8"` + I16 int16 `json:"i16"` + U16 uint16 `json:"u16"` + I32 int32 `json:"i32"` + U32 uint32 `json:"u32"` + I64 int64 `json:"i64"` + U64 uint64 `json:"u64"` + F32 float32 `json:"f32"` + F64 float64 `json:"f64"` + V8 []int8 `json:"v8"` + Vf64 []float64 `json:"vf64"` +} + +func (t *TypeAliasesT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + v8Offset := flatbuffers.UOffsetT(0) + if t.V8 != nil { + v8Length := len(t.V8) + TypeAliasesStartV8Vector(builder, v8Length) + for j := v8Length - 1; j >= 0; j-- { + builder.PrependInt8(t.V8[j]) + } + v8Offset = builder.EndVector(v8Length) + } + vf64Offset := flatbuffers.UOffsetT(0) + if t.Vf64 != nil { + vf64Length := len(t.Vf64) + TypeAliasesStartVf64Vector(builder, vf64Length) + for j := vf64Length - 1; j >= 0; j-- { + builder.PrependFloat64(t.Vf64[j]) + } + vf64Offset = builder.EndVector(vf64Length) + } + TypeAliasesStart(builder) + TypeAliasesAddI8(builder, t.I8) + TypeAliasesAddU8(builder, t.U8) + TypeAliasesAddI16(builder, t.I16) + TypeAliasesAddU16(builder, t.U16) + TypeAliasesAddI32(builder, t.I32) + TypeAliasesAddU32(builder, t.U32) + TypeAliasesAddI64(builder, t.I64) + TypeAliasesAddU64(builder, t.U64) + TypeAliasesAddF32(builder, t.F32) + TypeAliasesAddF64(builder, t.F64) + TypeAliasesAddV8(builder, v8Offset) + TypeAliasesAddVf64(builder, vf64Offset) + return TypeAliasesEnd(builder) +} + +func (rcv *TypeAliases) UnPackTo(t *TypeAliasesT) { + t.I8 = rcv.I8() + t.U8 = rcv.U8() + t.I16 = rcv.I16() + t.U16 = rcv.U16() + t.I32 = rcv.I32() + t.U32 = rcv.U32() + t.I64 = rcv.I64() + t.U64 = rcv.U64() + t.F32 = rcv.F32() + t.F64 = rcv.F64() + v8Length := rcv.V8Length() + t.V8 = make([]int8, v8Length) + for j := 0; j < v8Length; j++ { + t.V8[j] = rcv.V8(j) + } + vf64Length := rcv.Vf64Length() + t.Vf64 = make([]float64, vf64Length) + for j := 0; j < vf64Length; j++ { + t.Vf64[j] = rcv.Vf64(j) + } +} + +func (rcv *TypeAliases) UnPack() *TypeAliasesT { + if rcv == nil { + return nil + } + t := &TypeAliasesT{} + rcv.UnPackTo(t) + return t +} + +type TypeAliases struct { + _tab flatbuffers.Table +} + +func GetRootAsTypeAliases(buf []byte, offset flatbuffers.UOffsetT) *TypeAliases { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &TypeAliases{} + x.Init(buf, n+offset) + return x +} + +func FinishTypeAliasesBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsTypeAliases(buf []byte, offset flatbuffers.UOffsetT) *TypeAliases { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &TypeAliases{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedTypeAliasesBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *TypeAliases) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *TypeAliases) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *TypeAliases) I8() int8 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetInt8(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateI8(n int8) bool { + return rcv._tab.MutateInt8Slot(4, n) +} + +func (rcv *TypeAliases) U8() byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + return rcv._tab.GetByte(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateU8(n byte) bool { + return rcv._tab.MutateByteSlot(6, n) +} + +func (rcv *TypeAliases) I16() int16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) + if o != 0 { + return rcv._tab.GetInt16(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateI16(n int16) bool { + return rcv._tab.MutateInt16Slot(8, n) +} + +func (rcv *TypeAliases) U16() uint16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(10)) + if o != 0 { + return rcv._tab.GetUint16(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateU16(n uint16) bool { + return rcv._tab.MutateUint16Slot(10, n) +} + +func (rcv *TypeAliases) I32() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(12)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateI32(n int32) bool { + return rcv._tab.MutateInt32Slot(12, n) +} + +func (rcv *TypeAliases) U32() uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) + if o != 0 { + return rcv._tab.GetUint32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateU32(n uint32) bool { + return rcv._tab.MutateUint32Slot(14, n) +} + +func (rcv *TypeAliases) I64() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(16)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateI64(n int64) bool { + return rcv._tab.MutateInt64Slot(16, n) +} + +func (rcv *TypeAliases) U64() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(18)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TypeAliases) MutateU64(n uint64) bool { + return rcv._tab.MutateUint64Slot(18, n) +} + +func (rcv *TypeAliases) F32() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(20)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return 0.0 +} + +func (rcv *TypeAliases) MutateF32(n float32) bool { + return rcv._tab.MutateFloat32Slot(20, n) +} + +func (rcv *TypeAliases) F64() float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(22)) + if o != 0 { + return rcv._tab.GetFloat64(o + rcv._tab.Pos) + } + return 0.0 +} + +func (rcv *TypeAliases) MutateF64(n float64) bool { + return rcv._tab.MutateFloat64Slot(22, n) +} + +func (rcv *TypeAliases) V8(j int) int8 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetInt8(a + flatbuffers.UOffsetT(j*1)) + } + return 0 +} + +func (rcv *TypeAliases) V8Length() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *TypeAliases) MutateV8(j int, n int8) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateInt8(a+flatbuffers.UOffsetT(j*1), n) + } + return false +} + +func (rcv *TypeAliases) Vf64(j int) float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.GetFloat64(a + flatbuffers.UOffsetT(j*8)) + } + return 0 +} + +func (rcv *TypeAliases) Vf64Length() int { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + return rcv._tab.VectorLen(o) + } + return 0 +} + +func (rcv *TypeAliases) MutateVf64(j int, n float64) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + a := rcv._tab.Vector(o) + return rcv._tab.MutateFloat64(a+flatbuffers.UOffsetT(j*8), n) + } + return false +} + +func TypeAliasesStart(builder *flatbuffers.Builder) { + builder.StartObject(12) +} +func TypeAliasesAddI8(builder *flatbuffers.Builder, i8 int8) { + builder.PrependInt8Slot(0, i8, 0) +} +func TypeAliasesAddU8(builder *flatbuffers.Builder, u8 byte) { + builder.PrependByteSlot(1, u8, 0) +} +func TypeAliasesAddI16(builder *flatbuffers.Builder, i16 int16) { + builder.PrependInt16Slot(2, i16, 0) +} +func TypeAliasesAddU16(builder *flatbuffers.Builder, u16 uint16) { + builder.PrependUint16Slot(3, u16, 0) +} +func TypeAliasesAddI32(builder *flatbuffers.Builder, i32 int32) { + builder.PrependInt32Slot(4, i32, 0) +} +func TypeAliasesAddU32(builder *flatbuffers.Builder, u32 uint32) { + builder.PrependUint32Slot(5, u32, 0) +} +func TypeAliasesAddI64(builder *flatbuffers.Builder, i64 int64) { + builder.PrependInt64Slot(6, i64, 0) +} +func TypeAliasesAddU64(builder *flatbuffers.Builder, u64 uint64) { + builder.PrependUint64Slot(7, u64, 0) +} +func TypeAliasesAddF32(builder *flatbuffers.Builder, f32 float32) { + builder.PrependFloat32Slot(8, f32, 0.0) +} +func TypeAliasesAddF64(builder *flatbuffers.Builder, f64 float64) { + builder.PrependFloat64Slot(9, f64, 0.0) +} +func TypeAliasesAddV8(builder *flatbuffers.Builder, v8 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(10, flatbuffers.UOffsetT(v8), 0) +} +func TypeAliasesStartV8Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(1, numElems, 1) +} +func TypeAliasesAddVf64(builder *flatbuffers.Builder, vf64 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(11, flatbuffers.UOffsetT(vf64), 0) +} +func TypeAliasesStartVf64Vector(builder *flatbuffers.Builder, numElems int) flatbuffers.UOffsetT { + return builder.StartVector(8, numElems, 8) +} +func TypeAliasesEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.java b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.java new file mode 100644 index 00000000000..8a0f54420ac --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.java @@ -0,0 +1,182 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class TypeAliases extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static TypeAliases getRootAsTypeAliases(ByteBuffer _bb) { return getRootAsTypeAliases(_bb, new TypeAliases()); } + public static TypeAliases getRootAsTypeAliases(ByteBuffer _bb, TypeAliases obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public TypeAliases __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public byte i8() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; } + public boolean mutateI8(byte i8) { int o = __offset(4); if (o != 0) { bb.put(o + bb_pos, i8); return true; } else { return false; } } + public int u8() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 0; } + public boolean mutateU8(int u8) { int o = __offset(6); if (o != 0) { bb.put(o + bb_pos, (byte) u8); return true; } else { return false; } } + public short i16() { int o = __offset(8); return o != 0 ? bb.getShort(o + bb_pos) : 0; } + public boolean mutateI16(short i16) { int o = __offset(8); if (o != 0) { bb.putShort(o + bb_pos, i16); return true; } else { return false; } } + public int u16() { int o = __offset(10); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + public boolean mutateU16(int u16) { int o = __offset(10); if (o != 0) { bb.putShort(o + bb_pos, (short) u16); return true; } else { return false; } } + public int i32() { int o = __offset(12); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean mutateI32(int i32) { int o = __offset(12); if (o != 0) { bb.putInt(o + bb_pos, i32); return true; } else { return false; } } + public long u32() { int o = __offset(14); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; } + public boolean mutateU32(long u32) { int o = __offset(14); if (o != 0) { bb.putInt(o + bb_pos, (int) u32); return true; } else { return false; } } + public long i64() { int o = __offset(16); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateI64(long i64) { int o = __offset(16); if (o != 0) { bb.putLong(o + bb_pos, i64); return true; } else { return false; } } + public long u64() { int o = __offset(18); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean mutateU64(long u64) { int o = __offset(18); if (o != 0) { bb.putLong(o + bb_pos, u64); return true; } else { return false; } } + public float f32() { int o = __offset(20); return o != 0 ? bb.getFloat(o + bb_pos) : 0.0f; } + public boolean mutateF32(float f32) { int o = __offset(20); if (o != 0) { bb.putFloat(o + bb_pos, f32); return true; } else { return false; } } + public double f64() { int o = __offset(22); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; } + public boolean mutateF64(double f64) { int o = __offset(22); if (o != 0) { bb.putDouble(o + bb_pos, f64); return true; } else { return false; } } + public byte v8(int j) { int o = __offset(24); return o != 0 ? bb.get(__vector(o) + j * 1) : 0; } + public int v8Length() { int o = __offset(24); return o != 0 ? __vector_len(o) : 0; } + public ByteVector v8Vector() { return v8Vector(new ByteVector()); } + public ByteVector v8Vector(ByteVector obj) { int o = __offset(24); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer v8AsByteBuffer() { return __vector_as_bytebuffer(24, 1); } + public ByteBuffer v8InByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 24, 1); } + public boolean mutateV8(int j, byte v8) { int o = __offset(24); if (o != 0) { bb.put(__vector(o) + j * 1, v8); return true; } else { return false; } } + public double vf64(int j) { int o = __offset(26); return o != 0 ? bb.getDouble(__vector(o) + j * 8) : 0; } + public int vf64Length() { int o = __offset(26); return o != 0 ? __vector_len(o) : 0; } + public DoubleVector vf64Vector() { return vf64Vector(new DoubleVector()); } + public DoubleVector vf64Vector(DoubleVector obj) { int o = __offset(26); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer vf64AsByteBuffer() { return __vector_as_bytebuffer(26, 8); } + public ByteBuffer vf64InByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 26, 8); } + public boolean mutateVf64(int j, double vf64) { int o = __offset(26); if (o != 0) { bb.putDouble(__vector(o) + j * 8, vf64); return true; } else { return false; } } + + public static int createTypeAliases(FlatBufferBuilder builder, + byte i8, + int u8, + short i16, + int u16, + int i32, + long u32, + long i64, + long u64, + float f32, + double f64, + int v8Offset, + int vf64Offset) { + builder.startTable(12); + TypeAliases.addF64(builder, f64); + TypeAliases.addU64(builder, u64); + TypeAliases.addI64(builder, i64); + TypeAliases.addVf64(builder, vf64Offset); + TypeAliases.addV8(builder, v8Offset); + TypeAliases.addF32(builder, f32); + TypeAliases.addU32(builder, u32); + TypeAliases.addI32(builder, i32); + TypeAliases.addU16(builder, u16); + TypeAliases.addI16(builder, i16); + TypeAliases.addU8(builder, u8); + TypeAliases.addI8(builder, i8); + return TypeAliases.endTypeAliases(builder); + } + + public static void startTypeAliases(FlatBufferBuilder builder) { builder.startTable(12); } + public static void addI8(FlatBufferBuilder builder, byte i8) { builder.addByte(0, i8, 0); } + public static void addU8(FlatBufferBuilder builder, int u8) { builder.addByte(1, (byte) u8, (byte) 0); } + public static void addI16(FlatBufferBuilder builder, short i16) { builder.addShort(2, i16, 0); } + public static void addU16(FlatBufferBuilder builder, int u16) { builder.addShort(3, (short) u16, (short) 0); } + public static void addI32(FlatBufferBuilder builder, int i32) { builder.addInt(4, i32, 0); } + public static void addU32(FlatBufferBuilder builder, long u32) { builder.addInt(5, (int) u32, (int) 0L); } + public static void addI64(FlatBufferBuilder builder, long i64) { builder.addLong(6, i64, 0L); } + public static void addU64(FlatBufferBuilder builder, long u64) { builder.addLong(7, u64, 0L); } + public static void addF32(FlatBufferBuilder builder, float f32) { builder.addFloat(8, f32, 0.0f); } + public static void addF64(FlatBufferBuilder builder, double f64) { builder.addDouble(9, f64, 0.0); } + public static void addV8(FlatBufferBuilder builder, int v8Offset) { builder.addOffset(10, v8Offset, 0); } + public static int createV8Vector(FlatBufferBuilder builder, byte[] data) { return builder.createByteVector(data); } + public static int createV8Vector(FlatBufferBuilder builder, ByteBuffer data) { return builder.createByteVector(data); } + public static void startV8Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addVf64(FlatBufferBuilder builder, int vf64Offset) { builder.addOffset(11, vf64Offset, 0); } + public static int createVf64Vector(FlatBufferBuilder builder, double[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addDouble(data[i]); return builder.endVector(); } + public static void startVf64Vector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static int endTypeAliases(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public TypeAliases get(int j) { return get(new TypeAliases(), j); } + public TypeAliases get(TypeAliases obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public TypeAliasesT unpack() { + TypeAliasesT _o = new TypeAliasesT(); + unpackTo(_o); + return _o; + } + public void unpackTo(TypeAliasesT _o) { + byte _oI8 = i8(); + _o.setI8(_oI8); + int _oU8 = u8(); + _o.setU8(_oU8); + short _oI16 = i16(); + _o.setI16(_oI16); + int _oU16 = u16(); + _o.setU16(_oU16); + int _oI32 = i32(); + _o.setI32(_oI32); + long _oU32 = u32(); + _o.setU32(_oU32); + long _oI64 = i64(); + _o.setI64(_oI64); + long _oU64 = u64(); + _o.setU64(_oU64); + float _oF32 = f32(); + _o.setF32(_oF32); + double _oF64 = f64(); + _o.setF64(_oF64); + byte[] _oV8 = new byte[v8Length()]; + for (int _j = 0; _j < v8Length(); ++_j) {_oV8[_j] = v8(_j);} + _o.setV8(_oV8); + double[] _oVf64 = new double[vf64Length()]; + for (int _j = 0; _j < vf64Length(); ++_j) {_oVf64[_j] = vf64(_j);} + _o.setVf64(_oVf64); + } + public static int pack(FlatBufferBuilder builder, TypeAliasesT _o) { + if (_o == null) return 0; + int _v8 = 0; + if (_o.getV8() != null) { + _v8 = createV8Vector(builder, _o.getV8()); + } + int _vf64 = 0; + if (_o.getVf64() != null) { + _vf64 = createVf64Vector(builder, _o.getVf64()); + } + return createTypeAliases( + builder, + _o.getI8(), + _o.getU8(), + _o.getI16(), + _o.getU16(), + _o.getI32(), + _o.getU32(), + _o.getI64(), + _o.getU64(), + _o.getF32(), + _o.getF64(), + _v8, + _vf64); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.kt b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.kt new file mode 100644 index 00000000000..546da79f5e6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.kt @@ -0,0 +1,274 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class TypeAliases : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : TypeAliases { + __init(_i, _bb) + return this + } + val i8 : Byte + get() { + val o = __offset(4) + return if(o != 0) bb.get(o + bb_pos) else 0 + } + fun mutateI8(i8: Byte) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.put(o + bb_pos, i8) + true + } else { + false + } + } + val u8 : UByte + get() { + val o = __offset(6) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + fun mutateU8(u8: UByte) : Boolean { + val o = __offset(6) + return if (o != 0) { + bb.put(o + bb_pos, u8.toByte()) + true + } else { + false + } + } + val i16 : Short + get() { + val o = __offset(8) + return if(o != 0) bb.getShort(o + bb_pos) else 0 + } + fun mutateI16(i16: Short) : Boolean { + val o = __offset(8) + return if (o != 0) { + bb.putShort(o + bb_pos, i16) + true + } else { + false + } + } + val u16 : UShort + get() { + val o = __offset(10) + return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u + } + fun mutateU16(u16: UShort) : Boolean { + val o = __offset(10) + return if (o != 0) { + bb.putShort(o + bb_pos, u16.toShort()) + true + } else { + false + } + } + val i32 : Int + get() { + val o = __offset(12) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + fun mutateI32(i32: Int) : Boolean { + val o = __offset(12) + return if (o != 0) { + bb.putInt(o + bb_pos, i32) + true + } else { + false + } + } + val u32 : UInt + get() { + val o = __offset(14) + return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 0u + } + fun mutateU32(u32: UInt) : Boolean { + val o = __offset(14) + return if (o != 0) { + bb.putInt(o + bb_pos, u32.toInt()) + true + } else { + false + } + } + val i64 : Long + get() { + val o = __offset(16) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + fun mutateI64(i64: Long) : Boolean { + val o = __offset(16) + return if (o != 0) { + bb.putLong(o + bb_pos, i64) + true + } else { + false + } + } + val u64 : ULong + get() { + val o = __offset(18) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + fun mutateU64(u64: ULong) : Boolean { + val o = __offset(18) + return if (o != 0) { + bb.putLong(o + bb_pos, u64.toLong()) + true + } else { + false + } + } + val f32 : Float + get() { + val o = __offset(20) + return if(o != 0) bb.getFloat(o + bb_pos) else 0.0f + } + fun mutateF32(f32: Float) : Boolean { + val o = __offset(20) + return if (o != 0) { + bb.putFloat(o + bb_pos, f32) + true + } else { + false + } + } + val f64 : Double + get() { + val o = __offset(22) + return if(o != 0) bb.getDouble(o + bb_pos) else 0.0 + } + fun mutateF64(f64: Double) : Boolean { + val o = __offset(22) + return if (o != 0) { + bb.putDouble(o + bb_pos, f64) + true + } else { + false + } + } + fun v8(j: Int) : Byte { + val o = __offset(24) + return if (o != 0) { + bb.get(__vector(o) + j * 1) + } else { + 0 + } + } + val v8Length : Int + get() { + val o = __offset(24); return if (o != 0) __vector_len(o) else 0 + } + val v8AsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(24, 1) + fun v8InByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 24, 1) + fun mutateV8(j: Int, v8: Byte) : Boolean { + val o = __offset(24) + return if (o != 0) { + bb.put(__vector(o) + j * 1, v8) + true + } else { + false + } + } + fun vf64(j: Int) : Double { + val o = __offset(26) + return if (o != 0) { + bb.getDouble(__vector(o) + j * 8) + } else { + 0.0 + } + } + val vf64Length : Int + get() { + val o = __offset(26); return if (o != 0) __vector_len(o) else 0 + } + val vf64AsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(26, 8) + fun vf64InByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 26, 8) + fun mutateVf64(j: Int, vf64: Double) : Boolean { + val o = __offset(26) + return if (o != 0) { + bb.putDouble(__vector(o) + j * 8, vf64) + true + } else { + false + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsTypeAliases(_bb: ByteBuffer): TypeAliases = getRootAsTypeAliases(_bb, TypeAliases()) + fun getRootAsTypeAliases(_bb: ByteBuffer, obj: TypeAliases): TypeAliases { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createTypeAliases(builder: FlatBufferBuilder, i8: Byte, u8: UByte, i16: Short, u16: UShort, i32: Int, u32: UInt, i64: Long, u64: ULong, f32: Float, f64: Double, v8Offset: Int, vf64Offset: Int) : Int { + builder.startTable(12) + addF64(builder, f64) + addU64(builder, u64) + addI64(builder, i64) + addVf64(builder, vf64Offset) + addV8(builder, v8Offset) + addF32(builder, f32) + addU32(builder, u32) + addI32(builder, i32) + addU16(builder, u16) + addI16(builder, i16) + addU8(builder, u8) + addI8(builder, i8) + return endTypeAliases(builder) + } + fun startTypeAliases(builder: FlatBufferBuilder) = builder.startTable(12) + fun addI8(builder: FlatBufferBuilder, i8: Byte) = builder.addByte(0, i8, 0) + fun addU8(builder: FlatBufferBuilder, u8: UByte) = builder.addByte(1, u8.toByte(), 0) + fun addI16(builder: FlatBufferBuilder, i16: Short) = builder.addShort(2, i16, 0) + fun addU16(builder: FlatBufferBuilder, u16: UShort) = builder.addShort(3, u16.toShort(), 0) + fun addI32(builder: FlatBufferBuilder, i32: Int) = builder.addInt(4, i32, 0) + fun addU32(builder: FlatBufferBuilder, u32: UInt) = builder.addInt(5, u32.toInt(), 0) + fun addI64(builder: FlatBufferBuilder, i64: Long) = builder.addLong(6, i64, 0L) + fun addU64(builder: FlatBufferBuilder, u64: ULong) = builder.addLong(7, u64.toLong(), 0) + fun addF32(builder: FlatBufferBuilder, f32: Float) = builder.addFloat(8, f32, 0.0) + fun addF64(builder: FlatBufferBuilder, f64: Double) = builder.addDouble(9, f64, 0.0) + fun addV8(builder: FlatBufferBuilder, v8: Int) = builder.addOffset(10, v8, 0) + fun createV8Vector(builder: FlatBufferBuilder, data: ByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i]) + } + return builder.endVector() + } + fun startV8Vector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addVf64(builder: FlatBufferBuilder, vf64: Int) = builder.addOffset(11, vf64, 0) + fun createVf64Vector(builder: FlatBufferBuilder, data: DoubleArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addDouble(data[i]) + } + return builder.endVector() + } + fun startVf64Vector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun endTypeAliases(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.lua b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.lua new file mode 100644 index 00000000000..01a1205433e --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.lua @@ -0,0 +1,210 @@ +--[[ MyGame.Example.TypeAliases + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local TypeAliases = {} +local mt = {} + +function TypeAliases.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:I8() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int8, self.view.pos + o) + end + return 0 +end + +function mt:U8() + local o = self.view:Offset(6) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + o) + end + return 0 +end + +function mt:I16() + local o = self.view:Offset(8) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int16, self.view.pos + o) + end + return 0 +end + +function mt:U16() + local o = self.view:Offset(10) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint16, self.view.pos + o) + end + return 0 +end + +function mt:I32() + local o = self.view:Offset(12) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int32, self.view.pos + o) + end + return 0 +end + +function mt:U32() + local o = self.view:Offset(14) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint32, self.view.pos + o) + end + return 0 +end + +function mt:I64() + local o = self.view:Offset(16) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int64, self.view.pos + o) + end + return 0 +end + +function mt:U64() + local o = self.view:Offset(18) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint64, self.view.pos + o) + end + return 0 +end + +function mt:F32() + local o = self.view:Offset(20) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float32, self.view.pos + o) + end + return 0.0 +end + +function mt:F64() + local o = self.view:Offset(22) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Float64, self.view.pos + o) + end + return 0.0 +end + +function mt:V8(j) + local o = self.view:Offset(24) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Int8, a + ((j-1) * 1)) + end + return 0 +end + +function mt:V8AsString(start, stop) + return self.view:VectorAsString(24, start, stop) +end + +function mt:V8Length() + local o = self.view:Offset(24) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function mt:Vf64(j) + local o = self.view:Offset(26) + if o ~= 0 then + local a = self.view:Vector(o) + return self.view:Get(flatbuffers.N.Float64, a + ((j-1) * 8)) + end + return 0 +end + +function mt:Vf64Length() + local o = self.view:Offset(26) + if o ~= 0 then + return self.view:VectorLen(o) + end + return 0 +end + +function TypeAliases.Start(builder) + builder:StartObject(12) +end + +function TypeAliases.AddI8(builder, i8) + builder:PrependInt8Slot(0, i8, 0) +end + +function TypeAliases.AddU8(builder, u8) + builder:PrependUint8Slot(1, u8, 0) +end + +function TypeAliases.AddI16(builder, i16) + builder:PrependInt16Slot(2, i16, 0) +end + +function TypeAliases.AddU16(builder, u16) + builder:PrependUint16Slot(3, u16, 0) +end + +function TypeAliases.AddI32(builder, i32) + builder:PrependInt32Slot(4, i32, 0) +end + +function TypeAliases.AddU32(builder, u32) + builder:PrependUint32Slot(5, u32, 0) +end + +function TypeAliases.AddI64(builder, i64) + builder:PrependInt64Slot(6, i64, 0) +end + +function TypeAliases.AddU64(builder, u64) + builder:PrependUint64Slot(7, u64, 0) +end + +function TypeAliases.AddF32(builder, f32) + builder:PrependFloat32Slot(8, f32, 0.0) +end + +function TypeAliases.AddF64(builder, f64) + builder:PrependFloat64Slot(9, f64, 0.0) +end + +function TypeAliases.AddV8(builder, v8) + builder:PrependUOffsetTRelativeSlot(10, v8, 0) +end + +function TypeAliases.StartV8Vector(builder, numElems) + return builder:StartVector(1, numElems, 1) +end + +function TypeAliases.AddVf64(builder, vf64) + builder:PrependUOffsetTRelativeSlot(11, vf64, 0) +end + +function TypeAliases.StartVf64Vector(builder, numElems) + return builder:StartVector(8, numElems, 8) +end + +function TypeAliases.End(builder) + return builder:EndObject() +end + +return TypeAliases \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.nim b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.nim new file mode 100644 index 00000000000..d5db7ae12ce --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.nim @@ -0,0 +1,144 @@ +#[ MyGame.Example.TypeAliases + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers +import std/options + +type TypeAliases* = object of FlatObj +func i8*(self: TypeAliases): int8 = + let o = self.tab.Offset(4) + if o != 0: + return Get[int8](self.tab, self.tab.Pos + o) + return 0 +func `i8=`*(self: var TypeAliases, n: int8): bool = + return self.tab.MutateSlot(4, n) +func u8*(self: TypeAliases): uint8 = + let o = self.tab.Offset(6) + if o != 0: + return Get[uint8](self.tab, self.tab.Pos + o) + return 0 +func `u8=`*(self: var TypeAliases, n: uint8): bool = + return self.tab.MutateSlot(6, n) +func i16*(self: TypeAliases): int16 = + let o = self.tab.Offset(8) + if o != 0: + return Get[int16](self.tab, self.tab.Pos + o) + return 0 +func `i16=`*(self: var TypeAliases, n: int16): bool = + return self.tab.MutateSlot(8, n) +func u16*(self: TypeAliases): uint16 = + let o = self.tab.Offset(10) + if o != 0: + return Get[uint16](self.tab, self.tab.Pos + o) + return 0 +func `u16=`*(self: var TypeAliases, n: uint16): bool = + return self.tab.MutateSlot(10, n) +func i32*(self: TypeAliases): int32 = + let o = self.tab.Offset(12) + if o != 0: + return Get[int32](self.tab, self.tab.Pos + o) + return 0 +func `i32=`*(self: var TypeAliases, n: int32): bool = + return self.tab.MutateSlot(12, n) +func u32*(self: TypeAliases): uint32 = + let o = self.tab.Offset(14) + if o != 0: + return Get[uint32](self.tab, self.tab.Pos + o) + return 0 +func `u32=`*(self: var TypeAliases, n: uint32): bool = + return self.tab.MutateSlot(14, n) +func i64*(self: TypeAliases): int64 = + let o = self.tab.Offset(16) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 0 +func `i64=`*(self: var TypeAliases, n: int64): bool = + return self.tab.MutateSlot(16, n) +func u64*(self: TypeAliases): uint64 = + let o = self.tab.Offset(18) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `u64=`*(self: var TypeAliases, n: uint64): bool = + return self.tab.MutateSlot(18, n) +func f32*(self: TypeAliases): float32 = + let o = self.tab.Offset(20) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return 0.0 +func `f32=`*(self: var TypeAliases, n: float32): bool = + return self.tab.MutateSlot(20, n) +func f64*(self: TypeAliases): float64 = + let o = self.tab.Offset(22) + if o != 0: + return Get[float64](self.tab, self.tab.Pos + o) + return 0.0 +func `f64=`*(self: var TypeAliases, n: float64): bool = + return self.tab.MutateSlot(22, n) +func v8Length*(self: TypeAliases): int = + let o = self.tab.Offset(24) + if o != 0: + return self.tab.VectorLen(o) +func v8*(self: TypeAliases, j: int): int8 = + let o = self.tab.Offset(24) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 1.uoffset + return Get[int8](self.tab, x) +func v8*(self: TypeAliases): seq[int8] = + let len = self.v8Length + for i in countup(0, len - 1): + result.add(self.v8(i)) +func vf64Length*(self: TypeAliases): int = + let o = self.tab.Offset(26) + if o != 0: + return self.tab.VectorLen(o) +func vf64*(self: TypeAliases, j: int): float64 = + let o = self.tab.Offset(26) + if o != 0: + var x = self.tab.Vector(o) + x += j.uoffset * 8.uoffset + return Get[float64](self.tab, x) +func vf64*(self: TypeAliases): seq[float64] = + let len = self.vf64Length + for i in countup(0, len - 1): + result.add(self.vf64(i)) +proc TypeAliasesStart*(builder: var Builder) = + builder.StartObject(12) +proc TypeAliasesAddi8*(builder: var Builder, i8: int8) = + builder.PrependSlot(0, i8, default(int8)) +proc TypeAliasesAddu8*(builder: var Builder, u8: uint8) = + builder.PrependSlot(1, u8, default(uint8)) +proc TypeAliasesAddi16*(builder: var Builder, i16: int16) = + builder.PrependSlot(2, i16, default(int16)) +proc TypeAliasesAddu16*(builder: var Builder, u16: uint16) = + builder.PrependSlot(3, u16, default(uint16)) +proc TypeAliasesAddi32*(builder: var Builder, i32: int32) = + builder.PrependSlot(4, i32, default(int32)) +proc TypeAliasesAddu32*(builder: var Builder, u32: uint32) = + builder.PrependSlot(5, u32, default(uint32)) +proc TypeAliasesAddi64*(builder: var Builder, i64: int64) = + builder.PrependSlot(6, i64, default(int64)) +proc TypeAliasesAddu64*(builder: var Builder, u64: uint64) = + builder.PrependSlot(7, u64, default(uint64)) +proc TypeAliasesAddf32*(builder: var Builder, f32: float32) = + builder.PrependSlot(8, f32, default(float32)) +proc TypeAliasesAddf64*(builder: var Builder, f64: float64) = + builder.PrependSlot(9, f64, default(float64)) +proc TypeAliasesAddv8*(builder: var Builder, v8: uoffset) = + builder.PrependSlot(10, v8, default(uoffset)) +proc TypeAliasesStartv8Vector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(1, numElems, 1) +proc TypeAliasesAddvf64*(builder: var Builder, vf64: uoffset) = + builder.PrependSlot(11, vf64, default(uoffset)) +proc TypeAliasesStartvf64Vector*(builder: var Builder, numElems: uoffset) = + builder.StartVector(8, numElems, 8) +proc TypeAliasesEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.php b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.php new file mode 100644 index 00000000000..7629897fca2 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.php @@ -0,0 +1,387 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function TypeAliasesIdentifier() + { + return "MONS"; + } + + public static function TypeAliasesBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::TypeAliasesIdentifier()); + } + + public static function TypeAliasesExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return TypeAliases + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return sbyte + */ + public function getI8() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getSbyte($o + $this->bb_pos) : 0; + } + + /** + * @return byte + */ + public function getU8() + { + $o = $this->__offset(6); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : 0; + } + + /** + * @return short + */ + public function getI16() + { + $o = $this->__offset(8); + return $o != 0 ? $this->bb->getShort($o + $this->bb_pos) : 0; + } + + /** + * @return ushort + */ + public function getU16() + { + $o = $this->__offset(10); + return $o != 0 ? $this->bb->getUshort($o + $this->bb_pos) : 0; + } + + /** + * @return int + */ + public function getI32() + { + $o = $this->__offset(12); + return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0; + } + + /** + * @return uint + */ + public function getU32() + { + $o = $this->__offset(14); + return $o != 0 ? $this->bb->getUint($o + $this->bb_pos) : 0; + } + + /** + * @return long + */ + public function getI64() + { + $o = $this->__offset(16); + return $o != 0 ? $this->bb->getLong($o + $this->bb_pos) : 0; + } + + /** + * @return ulong + */ + public function getU64() + { + $o = $this->__offset(18); + return $o != 0 ? $this->bb->getUlong($o + $this->bb_pos) : 0; + } + + /** + * @return float + */ + public function getF32() + { + $o = $this->__offset(20); + return $o != 0 ? $this->bb->getFloat($o + $this->bb_pos) : 0.0; + } + + /** + * @return double + */ + public function getF64() + { + $o = $this->__offset(22); + return $o != 0 ? $this->bb->getDouble($o + $this->bb_pos) : 0.0; + } + + /** + * @param int offset + * @return sbyte + */ + public function getV8($j) + { + $o = $this->__offset(24); + return $o != 0 ? $this->bb->getSbyte($this->__vector($o) + $j * 1) : 0; + } + + /** + * @return int + */ + public function getV8Length() + { + $o = $this->__offset(24); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param int offset + * @return double + */ + public function getVf64($j) + { + $o = $this->__offset(26); + return $o != 0 ? $this->bb->getDouble($this->__vector($o) + $j * 8) : 0; + } + + /** + * @return int + */ + public function getVf64Length() + { + $o = $this->__offset(26); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startTypeAliases(FlatBufferBuilder $builder) + { + $builder->StartObject(12); + } + + /** + * @param FlatBufferBuilder $builder + * @return TypeAliases + */ + public static function createTypeAliases(FlatBufferBuilder $builder, $i8, $u8, $i16, $u16, $i32, $u32, $i64, $u64, $f32, $f64, $v8, $vf64) + { + $builder->startObject(12); + self::addI8($builder, $i8); + self::addU8($builder, $u8); + self::addI16($builder, $i16); + self::addU16($builder, $u16); + self::addI32($builder, $i32); + self::addU32($builder, $u32); + self::addI64($builder, $i64); + self::addU64($builder, $u64); + self::addF32($builder, $f32); + self::addF64($builder, $f64); + self::addV8($builder, $v8); + self::addVf64($builder, $vf64); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param sbyte + * @return void + */ + public static function addI8(FlatBufferBuilder $builder, $i8) + { + $builder->addSbyteX(0, $i8, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addU8(FlatBufferBuilder $builder, $u8) + { + $builder->addByteX(1, $u8, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param short + * @return void + */ + public static function addI16(FlatBufferBuilder $builder, $i16) + { + $builder->addShortX(2, $i16, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ushort + * @return void + */ + public static function addU16(FlatBufferBuilder $builder, $u16) + { + $builder->addUshortX(3, $u16, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addI32(FlatBufferBuilder $builder, $i32) + { + $builder->addIntX(4, $i32, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param uint + * @return void + */ + public static function addU32(FlatBufferBuilder $builder, $u32) + { + $builder->addUintX(5, $u32, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param long + * @return void + */ + public static function addI64(FlatBufferBuilder $builder, $i64) + { + $builder->addLongX(6, $i64, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param ulong + * @return void + */ + public static function addU64(FlatBufferBuilder $builder, $u64) + { + $builder->addUlongX(7, $u64, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param float + * @return void + */ + public static function addF32(FlatBufferBuilder $builder, $f32) + { + $builder->addFloatX(8, $f32, 0.0); + } + + /** + * @param FlatBufferBuilder $builder + * @param double + * @return void + */ + public static function addF64(FlatBufferBuilder $builder, $f64) + { + $builder->addDoubleX(9, $f64, 0.0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addV8(FlatBufferBuilder $builder, $v8) + { + $builder->addOffsetX(10, $v8, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createV8Vector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putSbyte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startV8Vector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addVf64(FlatBufferBuilder $builder, $vf64) + { + $builder->addOffsetX(11, $vf64, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createVf64Vector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(8, count($data), 8); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putDouble($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startVf64Vector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(8, $numElems, 8); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endTypeAliases(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.py b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.py new file mode 100644 index 00000000000..b9cf4552ec9 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliases.py @@ -0,0 +1,353 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TypeAliases(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TypeAliases() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTypeAliases(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TypeAliasesBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # TypeAliases + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TypeAliases + def I8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def I16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def I32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def I64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def F32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # TypeAliases + def F64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # TypeAliases + def V8(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # TypeAliases + def V8AsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int8Flags, o) + return 0 + + # TypeAliases + def V8Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # TypeAliases + def V8IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # TypeAliases + def Vf64(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # TypeAliases + def Vf64AsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o) + return 0 + + # TypeAliases + def Vf64Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # TypeAliases + def Vf64IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + return o == 0 + +def TypeAliasesStart(builder): + builder.StartObject(12) + +def Start(builder): + TypeAliasesStart(builder) + +def TypeAliasesAddI8(builder, i8): + builder.PrependInt8Slot(0, i8, 0) + +def AddI8(builder, i8): + TypeAliasesAddI8(builder, i8) + +def TypeAliasesAddU8(builder, u8): + builder.PrependUint8Slot(1, u8, 0) + +def AddU8(builder, u8): + TypeAliasesAddU8(builder, u8) + +def TypeAliasesAddI16(builder, i16): + builder.PrependInt16Slot(2, i16, 0) + +def AddI16(builder, i16): + TypeAliasesAddI16(builder, i16) + +def TypeAliasesAddU16(builder, u16): + builder.PrependUint16Slot(3, u16, 0) + +def AddU16(builder, u16): + TypeAliasesAddU16(builder, u16) + +def TypeAliasesAddI32(builder, i32): + builder.PrependInt32Slot(4, i32, 0) + +def AddI32(builder, i32): + TypeAliasesAddI32(builder, i32) + +def TypeAliasesAddU32(builder, u32): + builder.PrependUint32Slot(5, u32, 0) + +def AddU32(builder, u32): + TypeAliasesAddU32(builder, u32) + +def TypeAliasesAddI64(builder, i64): + builder.PrependInt64Slot(6, i64, 0) + +def AddI64(builder, i64): + TypeAliasesAddI64(builder, i64) + +def TypeAliasesAddU64(builder, u64): + builder.PrependUint64Slot(7, u64, 0) + +def AddU64(builder, u64): + TypeAliasesAddU64(builder, u64) + +def TypeAliasesAddF32(builder, f32): + builder.PrependFloat32Slot(8, f32, 0.0) + +def AddF32(builder, f32): + TypeAliasesAddF32(builder, f32) + +def TypeAliasesAddF64(builder, f64): + builder.PrependFloat64Slot(9, f64, 0.0) + +def AddF64(builder, f64): + TypeAliasesAddF64(builder, f64) + +def TypeAliasesAddV8(builder, v8): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(v8), 0) + +def AddV8(builder, v8): + TypeAliasesAddV8(builder, v8) + +def TypeAliasesStartV8Vector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def StartV8Vector(builder, numElems): + return TypeAliasesStartV8Vector(builder, numElems) + +def TypeAliasesAddVf64(builder, vf64): + builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(vf64), 0) + +def AddVf64(builder, vf64): + TypeAliasesAddVf64(builder, vf64) + +def TypeAliasesStartVf64Vector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def StartVf64Vector(builder, numElems): + return TypeAliasesStartVf64Vector(builder, numElems) + +def TypeAliasesEnd(builder): + return builder.EndObject() + +def End(builder): + return TypeAliasesEnd(builder) + +try: + from typing import List +except: + pass + +class TypeAliasesT(object): + + # TypeAliasesT + def __init__(self): + self.i8 = 0 # type: int + self.u8 = 0 # type: int + self.i16 = 0 # type: int + self.u16 = 0 # type: int + self.i32 = 0 # type: int + self.u32 = 0 # type: int + self.i64 = 0 # type: int + self.u64 = 0 # type: int + self.f32 = 0.0 # type: float + self.f64 = 0.0 # type: float + self.v8 = None # type: List[int] + self.vf64 = None # type: List[float] + + @classmethod + def InitFromBuf(cls, buf, pos): + typeAliases = TypeAliases() + typeAliases.Init(buf, pos) + return cls.InitFromObj(typeAliases) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, typeAliases): + x = TypeAliasesT() + x._UnPack(typeAliases) + return x + + # TypeAliasesT + def _UnPack(self, typeAliases): + if typeAliases is None: + return + self.i8 = typeAliases.I8() + self.u8 = typeAliases.U8() + self.i16 = typeAliases.I16() + self.u16 = typeAliases.U16() + self.i32 = typeAliases.I32() + self.u32 = typeAliases.U32() + self.i64 = typeAliases.I64() + self.u64 = typeAliases.U64() + self.f32 = typeAliases.F32() + self.f64 = typeAliases.F64() + if not typeAliases.V8IsNone(): + if np is None: + self.v8 = [] + for i in range(typeAliases.V8Length()): + self.v8.append(typeAliases.V8(i)) + else: + self.v8 = typeAliases.V8AsNumpy() + if not typeAliases.Vf64IsNone(): + if np is None: + self.vf64 = [] + for i in range(typeAliases.Vf64Length()): + self.vf64.append(typeAliases.Vf64(i)) + else: + self.vf64 = typeAliases.Vf64AsNumpy() + + # TypeAliasesT + def Pack(self, builder): + if self.v8 is not None: + if np is not None and type(self.v8) is np.ndarray: + v8 = builder.CreateNumpyVector(self.v8) + else: + TypeAliasesStartV8Vector(builder, len(self.v8)) + for i in reversed(range(len(self.v8))): + builder.PrependByte(self.v8[i]) + v8 = builder.EndVector() + if self.vf64 is not None: + if np is not None and type(self.vf64) is np.ndarray: + vf64 = builder.CreateNumpyVector(self.vf64) + else: + TypeAliasesStartVf64Vector(builder, len(self.vf64)) + for i in reversed(range(len(self.vf64))): + builder.PrependFloat64(self.vf64[i]) + vf64 = builder.EndVector() + TypeAliasesStart(builder) + TypeAliasesAddI8(builder, self.i8) + TypeAliasesAddU8(builder, self.u8) + TypeAliasesAddI16(builder, self.i16) + TypeAliasesAddU16(builder, self.u16) + TypeAliasesAddI32(builder, self.i32) + TypeAliasesAddU32(builder, self.u32) + TypeAliasesAddI64(builder, self.i64) + TypeAliasesAddU64(builder, self.u64) + TypeAliasesAddF32(builder, self.f32) + TypeAliasesAddF64(builder, self.f64) + if self.v8 is not None: + TypeAliasesAddV8(builder, v8) + if self.vf64 is not None: + TypeAliasesAddVf64(builder, vf64) + typeAliases = TypeAliasesEnd(builder) + return typeAliases diff --git a/third_party/flatbuffers/tests/MyGame/Example/TypeAliasesT.java b/third_party/flatbuffers/tests/MyGame/Example/TypeAliasesT.java new file mode 100644 index 00000000000..2e056843ce2 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/TypeAliasesT.java @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class TypeAliasesT { + private byte i8; + private int u8; + private short i16; + private int u16; + private int i32; + private long u32; + private long i64; + private long u64; + private float f32; + private double f64; + private byte[] v8; + private double[] vf64; + + public byte getI8() { return i8; } + + public void setI8(byte i8) { this.i8 = i8; } + + public int getU8() { return u8; } + + public void setU8(int u8) { this.u8 = u8; } + + public short getI16() { return i16; } + + public void setI16(short i16) { this.i16 = i16; } + + public int getU16() { return u16; } + + public void setU16(int u16) { this.u16 = u16; } + + public int getI32() { return i32; } + + public void setI32(int i32) { this.i32 = i32; } + + public long getU32() { return u32; } + + public void setU32(long u32) { this.u32 = u32; } + + public long getI64() { return i64; } + + public void setI64(long i64) { this.i64 = i64; } + + public long getU64() { return u64; } + + public void setU64(long u64) { this.u64 = u64; } + + public float getF32() { return f32; } + + public void setF32(float f32) { this.f32 = f32; } + + public double getF64() { return f64; } + + public void setF64(double f64) { this.f64 = f64; } + + public byte[] getV8() { return v8; } + + public void setV8(byte[] v8) { this.v8 = v8; } + + public double[] getVf64() { return vf64; } + + public void setVf64(double[] vf64) { this.vf64 = vf64; } + + + public TypeAliasesT() { + this.i8 = 0; + this.u8 = 0; + this.i16 = 0; + this.u16 = 0; + this.i32 = 0; + this.u32 = 0L; + this.i64 = 0L; + this.u64 = 0L; + this.f32 = 0.0f; + this.f64 = 0.0; + this.v8 = null; + this.vf64 = null; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.cs b/third_party/flatbuffers/tests/MyGame/Example/Vec3.cs new file mode 100644 index 00000000000..a4861faf661 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.cs @@ -0,0 +1,102 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Vec3 : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public Vec3 __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public float X { get { return __p.bb.GetFloat(__p.bb_pos + 0); } } + public void MutateX(float x) { __p.bb.PutFloat(__p.bb_pos + 0, x); } + public float Y { get { return __p.bb.GetFloat(__p.bb_pos + 4); } } + public void MutateY(float y) { __p.bb.PutFloat(__p.bb_pos + 4, y); } + public float Z { get { return __p.bb.GetFloat(__p.bb_pos + 8); } } + public void MutateZ(float z) { __p.bb.PutFloat(__p.bb_pos + 8, z); } + public double Test1 { get { return __p.bb.GetDouble(__p.bb_pos + 16); } } + public void MutateTest1(double test1) { __p.bb.PutDouble(__p.bb_pos + 16, test1); } + public MyGame.Example.Color Test2 { get { return (MyGame.Example.Color)__p.bb.Get(__p.bb_pos + 24); } } + public void MutateTest2(MyGame.Example.Color test2) { __p.bb.Put(__p.bb_pos + 24, (byte)test2); } + public MyGame.Example.Test Test3 { get { return (new MyGame.Example.Test()).__assign(__p.bb_pos + 26, __p.bb); } } + + public static Offset CreateVec3(FlatBufferBuilder builder, float X, float Y, float Z, double Test1, MyGame.Example.Color Test2, short test3_A, sbyte test3_B) { + builder.Prep(8, 32); + builder.Pad(2); + builder.Prep(2, 4); + builder.Pad(1); + builder.PutSbyte(test3_B); + builder.PutShort(test3_A); + builder.Pad(1); + builder.PutByte((byte)Test2); + builder.PutDouble(Test1); + builder.Pad(4); + builder.PutFloat(Z); + builder.PutFloat(Y); + builder.PutFloat(X); + return new Offset(builder.Offset); + } + public Vec3T UnPack() { + var _o = new Vec3T(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(Vec3T _o) { + _o.X = this.X; + _o.Y = this.Y; + _o.Z = this.Z; + _o.Test1 = this.Test1; + _o.Test2 = this.Test2; + _o.Test3 = this.Test3.UnPack(); + } + public static Offset Pack(FlatBufferBuilder builder, Vec3T _o) { + if (_o == null) return default(Offset); + var _test3_a = _o.Test3.A; + var _test3_b = _o.Test3.B; + return CreateVec3( + builder, + _o.X, + _o.Y, + _o.Z, + _o.Test1, + _o.Test2, + _test3_a, + _test3_b); + } +} + +public class Vec3T +{ + [Newtonsoft.Json.JsonProperty("x")] + public float X { get; set; } + [Newtonsoft.Json.JsonProperty("y")] + public float Y { get; set; } + [Newtonsoft.Json.JsonProperty("z")] + public float Z { get; set; } + [Newtonsoft.Json.JsonProperty("test1")] + public double Test1 { get; set; } + [Newtonsoft.Json.JsonProperty("test2")] + public MyGame.Example.Color Test2 { get; set; } + [Newtonsoft.Json.JsonProperty("test3")] + public MyGame.Example.TestT Test3 { get; set; } + + public Vec3T() { + this.X = 0.0f; + this.Y = 0.0f; + this.Z = 0.0f; + this.Test1 = 0.0; + this.Test2 = 0; + this.Test3 = new MyGame.Example.TestT(); + } +} + + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.go b/third_party/flatbuffers/tests/MyGame/Example/Vec3.go new file mode 100644 index 00000000000..ae0cb1e76c7 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.go @@ -0,0 +1,113 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type Vec3T struct { + X float32 `json:"x"` + Y float32 `json:"y"` + Z float32 `json:"z"` + Test1 float64 `json:"test1"` + Test2 Color `json:"test2"` + Test3 *TestT `json:"test3"` +} + +func (t *Vec3T) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + return CreateVec3(builder, t.X, t.Y, t.Z, t.Test1, t.Test2, t.Test3.A, t.Test3.B) +} +func (rcv *Vec3) UnPackTo(t *Vec3T) { + t.X = rcv.X() + t.Y = rcv.Y() + t.Z = rcv.Z() + t.Test1 = rcv.Test1() + t.Test2 = rcv.Test2() + t.Test3 = rcv.Test3(nil).UnPack() +} + +func (rcv *Vec3) UnPack() *Vec3T { + if rcv == nil { + return nil + } + t := &Vec3T{} + rcv.UnPackTo(t) + return t +} + +type Vec3 struct { + _tab flatbuffers.Struct +} + +func (rcv *Vec3) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Vec3) Table() flatbuffers.Table { + return rcv._tab.Table +} + +func (rcv *Vec3) X() float32 { + return rcv._tab.GetFloat32(rcv._tab.Pos + flatbuffers.UOffsetT(0)) +} +func (rcv *Vec3) MutateX(n float32) bool { + return rcv._tab.MutateFloat32(rcv._tab.Pos+flatbuffers.UOffsetT(0), n) +} + +func (rcv *Vec3) Y() float32 { + return rcv._tab.GetFloat32(rcv._tab.Pos + flatbuffers.UOffsetT(4)) +} +func (rcv *Vec3) MutateY(n float32) bool { + return rcv._tab.MutateFloat32(rcv._tab.Pos+flatbuffers.UOffsetT(4), n) +} + +func (rcv *Vec3) Z() float32 { + return rcv._tab.GetFloat32(rcv._tab.Pos + flatbuffers.UOffsetT(8)) +} +func (rcv *Vec3) MutateZ(n float32) bool { + return rcv._tab.MutateFloat32(rcv._tab.Pos+flatbuffers.UOffsetT(8), n) +} + +func (rcv *Vec3) Test1() float64 { + return rcv._tab.GetFloat64(rcv._tab.Pos + flatbuffers.UOffsetT(16)) +} +func (rcv *Vec3) MutateTest1(n float64) bool { + return rcv._tab.MutateFloat64(rcv._tab.Pos+flatbuffers.UOffsetT(16), n) +} + +func (rcv *Vec3) Test2() Color { + return Color(rcv._tab.GetByte(rcv._tab.Pos + flatbuffers.UOffsetT(24))) +} +func (rcv *Vec3) MutateTest2(n Color) bool { + return rcv._tab.MutateByte(rcv._tab.Pos+flatbuffers.UOffsetT(24), byte(n)) +} + +func (rcv *Vec3) Test3(obj *Test) *Test { + if obj == nil { + obj = new(Test) + } + obj.Init(rcv._tab.Bytes, rcv._tab.Pos+26) + return obj +} + +func CreateVec3(builder *flatbuffers.Builder, x float32, y float32, z float32, test1 float64, test2 Color, test3_a int16, test3_b int8) flatbuffers.UOffsetT { + builder.Prep(8, 32) + builder.Pad(2) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(test3_b) + builder.PrependInt16(test3_a) + builder.Pad(1) + builder.PrependByte(byte(test2)) + builder.PrependFloat64(test1) + builder.Pad(4) + builder.PrependFloat32(z) + builder.PrependFloat32(y) + builder.PrependFloat32(x) + return builder.Offset() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.java b/third_party/flatbuffers/tests/MyGame/Example/Vec3.java new file mode 100644 index 00000000000..c1f2ce63c07 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.java @@ -0,0 +1,96 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Vec3 extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Vec3 __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public float x() { return bb.getFloat(bb_pos + 0); } + public void mutateX(float x) { bb.putFloat(bb_pos + 0, x); } + public float y() { return bb.getFloat(bb_pos + 4); } + public void mutateY(float y) { bb.putFloat(bb_pos + 4, y); } + public float z() { return bb.getFloat(bb_pos + 8); } + public void mutateZ(float z) { bb.putFloat(bb_pos + 8, z); } + public double test1() { return bb.getDouble(bb_pos + 16); } + public void mutateTest1(double test1) { bb.putDouble(bb_pos + 16, test1); } + public int test2() { return bb.get(bb_pos + 24) & 0xFF; } + public void mutateTest2(int test2) { bb.put(bb_pos + 24, (byte) test2); } + public MyGame.Example.Test test3() { return test3(new MyGame.Example.Test()); } + public MyGame.Example.Test test3(MyGame.Example.Test obj) { return obj.__assign(bb_pos + 26, bb); } + + public static int createVec3(FlatBufferBuilder builder, float x, float y, float z, double test1, int test2, short test3_a, byte test3_b) { + builder.prep(8, 32); + builder.pad(2); + builder.prep(2, 4); + builder.pad(1); + builder.putByte(test3_b); + builder.putShort(test3_a); + builder.pad(1); + builder.putByte((byte) test2); + builder.putDouble(test1); + builder.pad(4); + builder.putFloat(z); + builder.putFloat(y); + builder.putFloat(x); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Vec3 get(int j) { return get(new Vec3(), j); } + public Vec3 get(Vec3 obj, int j) { return obj.__assign(__element(j), bb); } + } + public Vec3T unpack() { + Vec3T _o = new Vec3T(); + unpackTo(_o); + return _o; + } + public void unpackTo(Vec3T _o) { + float _oX = x(); + _o.setX(_oX); + float _oY = y(); + _o.setY(_oY); + float _oZ = z(); + _o.setZ(_oZ); + double _oTest1 = test1(); + _o.setTest1(_oTest1); + int _oTest2 = test2(); + _o.setTest2(_oTest2); + test3().unpackTo(_o.getTest3()); + } + public static int pack(FlatBufferBuilder builder, Vec3T _o) { + if (_o == null) return 0; + short _test3_a = _o.getTest3().getA(); + byte _test3_b = _o.getTest3().getB(); + return createVec3( + builder, + _o.getX(), + _o.getY(), + _o.getZ(), + _o.getTest1(), + _o.getTest2(), + _test3_a, + _test3_b); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.kt b/third_party/flatbuffers/tests/MyGame/Example/Vec3.kt new file mode 100644 index 00000000000..9e1f89ed887 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.kt @@ -0,0 +1,61 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Vec3 : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Vec3 { + __init(_i, _bb) + return this + } + val x : Float get() = bb.getFloat(bb_pos + 0) + fun mutateX(x: Float) : ByteBuffer = bb.putFloat(bb_pos + 0, x) + val y : Float get() = bb.getFloat(bb_pos + 4) + fun mutateY(y: Float) : ByteBuffer = bb.putFloat(bb_pos + 4, y) + val z : Float get() = bb.getFloat(bb_pos + 8) + fun mutateZ(z: Float) : ByteBuffer = bb.putFloat(bb_pos + 8, z) + val test1 : Double get() = bb.getDouble(bb_pos + 16) + fun mutateTest1(test1: Double) : ByteBuffer = bb.putDouble(bb_pos + 16, test1) + val test2 : UByte get() = bb.get(bb_pos + 24).toUByte() + fun mutateTest2(test2: UByte) : ByteBuffer = bb.put(bb_pos + 24, test2.toByte()) + val test3 : MyGame.Example.Test? get() = test3(MyGame.Example.Test()) + fun test3(obj: MyGame.Example.Test) : MyGame.Example.Test? = obj.__assign(bb_pos + 26, bb) + companion object { + fun createVec3(builder: FlatBufferBuilder, x: Float, y: Float, z: Float, test1: Double, test2: UByte, test3_a: Short, test3_b: Byte) : Int { + builder.prep(8, 32) + builder.pad(2) + builder.prep(2, 4) + builder.pad(1) + builder.putByte(test3_b) + builder.putShort(test3_a) + builder.pad(1) + builder.putByte(test2.toByte()) + builder.putDouble(test1) + builder.pad(4) + builder.putFloat(z) + builder.putFloat(y) + builder.putFloat(x) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.lua b/third_party/flatbuffers/tests/MyGame/Example/Vec3.lua new file mode 100644 index 00000000000..7d46e916a72 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.lua @@ -0,0 +1,70 @@ +--[[ MyGame.Example.Vec3 + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Vec3 = {} +local mt = {} + +function Vec3.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:X() + return self.view:Get(flatbuffers.N.Float32, self.view.pos + 0) +end + +function mt:Y() + return self.view:Get(flatbuffers.N.Float32, self.view.pos + 4) +end + +function mt:Z() + return self.view:Get(flatbuffers.N.Float32, self.view.pos + 8) +end + +function mt:Test1() + return self.view:Get(flatbuffers.N.Float64, self.view.pos + 16) +end + +function mt:Test2() + return self.view:Get(flatbuffers.N.Uint8, self.view.pos + 24) +end + +function mt:Test3(obj) + obj:Init(self.view.bytes, self.view.pos + 26) + return obj +end + +function Vec3.CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b) + builder:Prep(8, 32) + builder:Pad(2) + builder:Prep(2, 4) + builder:Pad(1) + builder:PrependInt8(test3_b) + builder:PrependInt16(test3_a) + builder:Pad(1) + builder:PrependUint8(test2) + builder:PrependFloat64(test1) + builder:Pad(4) + builder:PrependFloat32(z) + builder:PrependFloat32(y) + builder:PrependFloat32(x) + return builder:Offset() +end + +return Vec3 \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.nim b/third_party/flatbuffers/tests/MyGame/Example/Vec3.nim new file mode 100644 index 00000000000..9ff2c56d8da --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.nim @@ -0,0 +1,52 @@ +#[ MyGame.Example.Vec3 + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import Color as MyGame_Example_Color +import Test as MyGame_Example_Test +import flatbuffers + +type Vec3* = object of FlatObj +func x*(self: Vec3): float32 = + return Get[float32](self.tab, self.tab.Pos + 0) +func `x=`*(self: var Vec3, n: float32): bool = + return self.tab.Mutate(self.tab.Pos + 0, n) +func y*(self: Vec3): float32 = + return Get[float32](self.tab, self.tab.Pos + 4) +func `y=`*(self: var Vec3, n: float32): bool = + return self.tab.Mutate(self.tab.Pos + 4, n) +func z*(self: Vec3): float32 = + return Get[float32](self.tab, self.tab.Pos + 8) +func `z=`*(self: var Vec3, n: float32): bool = + return self.tab.Mutate(self.tab.Pos + 8, n) +func test1*(self: Vec3): float64 = + return Get[float64](self.tab, self.tab.Pos + 16) +func `test1=`*(self: var Vec3, n: float64): bool = + return self.tab.Mutate(self.tab.Pos + 16, n) +func test2*(self: Vec3): MyGame_Example_Color.Color = + return MyGame_Example_Color.Color(Get[uint8](self.tab, self.tab.Pos + 24)) +func `test2=`*(self: var Vec3, n: MyGame_Example_Color.Color): bool = + return self.tab.Mutate(self.tab.Pos + 24, n) +func test3*(self: Vec3): MyGame_Example_Test.Test = + return MyGame_Example_Test.Test(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + 26)) +proc Vec3Create*(self: var Builder, x: float32, y: float32, z: float32, test1: float64, test2: MyGame_Example_Color.Color, test3_a: int16, test3_b: int8): uoffset = + self.Prep(8, 32) + self.Pad(2) + self.Prep(2, 4) + self.Pad(1) + self.Prepend(test3_b) + self.Prepend(test3_a) + self.Pad(1) + self.Prepend(test2) + self.Prepend(test1) + self.Pad(4) + self.Prepend(z) + self.Prepend(y) + self.Prepend(x) + return self.Offset() diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.php b/third_party/flatbuffers/tests/MyGame/Example/Vec3.php new file mode 100644 index 00000000000..4d149e6f542 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.php @@ -0,0 +1,96 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return float + */ + public function GetX() + { + return $this->bb->getFloat($this->bb_pos + 0); + } + + /** + * @return float + */ + public function GetY() + { + return $this->bb->getFloat($this->bb_pos + 4); + } + + /** + * @return float + */ + public function GetZ() + { + return $this->bb->getFloat($this->bb_pos + 8); + } + + /** + * @return double + */ + public function GetTest1() + { + return $this->bb->getDouble($this->bb_pos + 16); + } + + /** + * @return byte + */ + public function GetTest2() + { + return $this->bb->getByte($this->bb_pos + 24); + } + + /** + * @return Test + */ + public function getTest3() + { + $obj = new Test(); + $obj->init($this->bb_pos + 26, $this->bb); + return $obj; + } + + + /** + * @return int offset + */ + public static function createVec3(FlatBufferBuilder $builder, $x, $y, $z, $test1, $test2, $test3_a, $test3_b) + { + $builder->prep(8, 32); + $builder->pad(2); + $builder->prep(2, 4); + $builder->pad(1); + $builder->putSbyte($test3_b); + $builder->putShort($test3_a); + $builder->pad(1); + $builder->putByte($test2); + $builder->putDouble($test1); + $builder->pad(4); + $builder->putFloat($z); + $builder->putFloat($y); + $builder->putFloat($x); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3.py b/third_party/flatbuffers/tests/MyGame/Example/Vec3.py new file mode 100644 index 00000000000..3a394a269ce --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3.py @@ -0,0 +1,100 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Vec3(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 32 + + # Vec3 + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Vec3 + def X(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Vec3 + def Y(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4)) + # Vec3 + def Z(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8)) + # Vec3 + def Test1(self): return self._tab.Get(flatbuffers.number_types.Float64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16)) + # Vec3 + def Test2(self): return self._tab.Get(flatbuffers.number_types.Uint8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(24)) + # Vec3 + def Test3(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 26) + return obj + + +def CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b): + builder.Prep(8, 32) + builder.Pad(2) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(test3_b) + builder.PrependInt16(test3_a) + builder.Pad(1) + builder.PrependUint8(test2) + builder.PrependFloat64(test1) + builder.Pad(4) + builder.PrependFloat32(z) + builder.PrependFloat32(y) + builder.PrependFloat32(x) + return builder.Offset() + +import MyGame.Example.Test +try: + from typing import Optional +except: + pass + +class Vec3T(object): + + # Vec3T + def __init__(self): + self.x = 0.0 # type: float + self.y = 0.0 # type: float + self.z = 0.0 # type: float + self.test1 = 0.0 # type: float + self.test2 = 0 # type: int + self.test3 = None # type: Optional[MyGame.Example.Test.TestT] + + @classmethod + def InitFromBuf(cls, buf, pos): + vec3 = Vec3() + vec3.Init(buf, pos) + return cls.InitFromObj(vec3) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, vec3): + x = Vec3T() + x._UnPack(vec3) + return x + + # Vec3T + def _UnPack(self, vec3): + if vec3 is None: + return + self.x = vec3.X() + self.y = vec3.Y() + self.z = vec3.Z() + self.test1 = vec3.Test1() + self.test2 = vec3.Test2() + if vec3.Test3(MyGame.Example.Test.Test()) is not None: + self.test3 = MyGame.Example.Test.TestT.InitFromObj(vec3.Test3(MyGame.Example.Test.Test())) + + # Vec3T + def Pack(self, builder): + return CreateVec3(builder, self.x, self.y, self.z, self.test1, self.test2, self.test3.a, self.test3.b) diff --git a/third_party/flatbuffers/tests/MyGame/Example/Vec3T.java b/third_party/flatbuffers/tests/MyGame/Example/Vec3T.java new file mode 100644 index 00000000000..78fb1dd775d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/Vec3T.java @@ -0,0 +1,64 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class Vec3T { + private float x; + private float y; + private float z; + private double test1; + private int test2; + private MyGame.Example.TestT test3; + + public float getX() { return x; } + + public void setX(float x) { this.x = x; } + + public float getY() { return y; } + + public void setY(float y) { this.y = y; } + + public float getZ() { return z; } + + public void setZ(float z) { this.z = z; } + + public double getTest1() { return test1; } + + public void setTest1(double test1) { this.test1 = test1; } + + public int getTest2() { return test2; } + + public void setTest2(int test2) { this.test2 = test2; } + + public MyGame.Example.TestT getTest3() { return test3; } + + public void setTest3(MyGame.Example.TestT test3) { this.test3 = test3; } + + + public Vec3T() { + this.x = 0.0f; + this.y = 0.0f; + this.z = 0.0f; + this.test1 = 0.0; + this.test2 = 0; + this.test3 = new MyGame.Example.TestT(); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example/__init__.py b/third_party/flatbuffers/tests/MyGame/Example/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/MyGame/Example/monster_test_grpc_fb.py b/third_party/flatbuffers/tests/MyGame/Example/monster_test_grpc_fb.py new file mode 100644 index 00000000000..8375c982414 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example/monster_test_grpc_fb.py @@ -0,0 +1,241 @@ +# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT! +import grpc + + +class MonsterStorageStub(object): + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Store = channel.unary_unary( + '/MyGame.Example.MonsterStorage/Store', + + + ) + self.Retrieve = channel.unary_stream( + '/MyGame.Example.MonsterStorage/Retrieve', + + + ) + self.GetMaxHitPoint = channel.stream_unary( + '/MyGame.Example.MonsterStorage/GetMaxHitPoint', + + + ) + self.GetMinMaxHitPoints = channel.unary_unary( + '/MyGame.Example.MonsterStorage/GetMinMaxHitPoints', + + + ) + + +class MonsterStorageServicer(object): + + def Store(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Retrieve(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetMaxHitPoint(self, request_iterator, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetMinMaxHitPoints(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_MonsterStorageServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Store': grpc.unary_unary_rpc_method_handler( + servicer.Store, + + + ), + 'Retrieve': grpc.unary_stream_rpc_method_handler( + servicer.Retrieve, + + + ), + 'GetMaxHitPoint': grpc.stream_unary_rpc_method_handler( + servicer.GetMaxHitPoint, + + + ), + 'GetMinMaxHitPoints': grpc.unary_unary_rpc_method_handler( + servicer.GetMinMaxHitPoints, + + + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'MyGame.Example.MonsterStorage', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) +try: + # THESE ELEMENTS WILL BE DEPRECATED. + # Please use the generated *_pb2_grpc.py files instead. + import grpc + from grpc.beta import implementations as beta_implementations + from grpc.beta import interfaces as beta_interfaces + from grpc.framework.common import cardinality + from grpc.framework.interfaces.face import utilities as face_utilities + + + class MonsterStorageStub(object): + + def __init__(self, channel): + """Constructor. + + Args: + channel: A grpc.Channel. + """ + self.Store = channel.unary_unary( + '/MyGame.Example.MonsterStorage/Store', + + + ) + self.Retrieve = channel.unary_stream( + '/MyGame.Example.MonsterStorage/Retrieve', + + + ) + self.GetMaxHitPoint = channel.stream_unary( + '/MyGame.Example.MonsterStorage/GetMaxHitPoint', + + + ) + self.GetMinMaxHitPoints = channel.unary_unary( + '/MyGame.Example.MonsterStorage/GetMinMaxHitPoints', + + + ) + + + class MonsterStorageServicer(object): + + def Store(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Retrieve(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetMaxHitPoint(self, request_iterator, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def GetMinMaxHitPoints(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + + def add_MonsterStorageServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Store': grpc.unary_unary_rpc_method_handler( + servicer.Store, + + + ), + 'Retrieve': grpc.unary_stream_rpc_method_handler( + servicer.Retrieve, + + + ), + 'GetMaxHitPoint': grpc.stream_unary_rpc_method_handler( + servicer.GetMaxHitPoint, + + + ), + 'GetMinMaxHitPoints': grpc.unary_unary_rpc_method_handler( + servicer.GetMinMaxHitPoints, + + + ), + } + generic_handler = grpc.method_handlers_generic_handler( + 'MyGame.Example.MonsterStorage', rpc_method_handlers) + server.add_generic_rpc_handlers((generic_handler,)) + + + class BetaMonsterStorageServicer(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + def Store(self, request, context): + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def Retrieve(self, request, context): + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetMaxHitPoint(self, request_iterator, context): + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + def GetMinMaxHitPoints(self, request, context): + context.code(beta_interfaces.StatusCode.UNIMPLEMENTED) + + + class BetaMonsterStorageStub(object): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This class was generated + only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0.""" + def Store(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + raise NotImplementedError() + Store.future = None + def Retrieve(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + raise NotImplementedError() + def GetMaxHitPoint(self, request_iterator, timeout, metadata=None, with_call=False, protocol_options=None): + raise NotImplementedError() + GetMaxHitPoint.future = None + def GetMinMaxHitPoints(self, request, timeout, metadata=None, with_call=False, protocol_options=None): + raise NotImplementedError() + GetMinMaxHitPoints.future = None + + + def beta_create_MonsterStorage_server(servicer, pool=None, pool_size=None, default_timeout=None, maximum_timeout=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + method_implementations = { + ('MyGame.Example.MonsterStorage', 'GetMaxHitPoint'): face_utilities.stream_unary_inline(servicer.GetMaxHitPoint), + ('MyGame.Example.MonsterStorage', 'GetMinMaxHitPoints'): face_utilities.unary_unary_inline(servicer.GetMinMaxHitPoints), + ('MyGame.Example.MonsterStorage', 'Retrieve'): face_utilities.unary_stream_inline(servicer.Retrieve), + ('MyGame.Example.MonsterStorage', 'Store'): face_utilities.unary_unary_inline(servicer.Store), + } + server_options = beta_implementations.server_options(thread_pool=pool, thread_pool_size=pool_size, default_timeout=default_timeout, maximum_timeout=maximum_timeout) + return beta_implementations.server(method_implementations, options=server_options) + + + def beta_create_MonsterStorage_stub(channel, host=None, metadata_transformer=None, pool=None, pool_size=None): + """The Beta API is deprecated for 0.15.0 and later. + + It is recommended to use the GA API (classes and functions in this + file not marked beta) for all further purposes. This function was + generated only to ease transition from grpcio<0.15.0 to grpcio>=0.15.0""" + cardinalities = { + 'GetMaxHitPoint': cardinality.Cardinality.STREAM_UNARY, + 'GetMinMaxHitPoints': cardinality.Cardinality.UNARY_UNARY, + 'Retrieve': cardinality.Cardinality.UNARY_STREAM, + 'Store': cardinality.Cardinality.UNARY_UNARY, + } + stub_options = beta_implementations.stub_options(host=host, metadata_transformer=metadata_transformer, thread_pool=pool, thread_pool_size=pool_size) + return beta_implementations.dynamic_stub(channel, 'MyGame.Example.MonsterStorage', cardinalities, options=stub_options) +except ImportError: + pass \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.cs b/third_party/flatbuffers/tests/MyGame/Example2/Monster.cs new file mode 100644 index 00000000000..0ab6a6865ff --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.cs @@ -0,0 +1,59 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame.Example2 +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Monster : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Monster GetRootAsMonster(ByteBuffer _bb) { return GetRootAsMonster(_bb, new Monster()); } + public static Monster GetRootAsMonster(ByteBuffer _bb, Monster obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Monster __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + + public static void StartMonster(FlatBufferBuilder builder) { builder.StartTable(0); } + public static Offset EndMonster(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public MonsterT UnPack() { + var _o = new MonsterT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(MonsterT _o) { + } + public static Offset Pack(FlatBufferBuilder builder, MonsterT _o) { + if (_o == null) return default(Offset); + StartMonster(builder); + return EndMonster(builder); + } +} + +public class MonsterT +{ + + public MonsterT() { + } +} + + +static public class MonsterVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.go b/third_party/flatbuffers/tests/MyGame/Example2/Monster.go new file mode 100644 index 00000000000..4062f7c2e0d --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.go @@ -0,0 +1,72 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Example2 + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type MonsterT struct { +} + +func (t *MonsterT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + MonsterStart(builder) + return MonsterEnd(builder) +} + +func (rcv *Monster) UnPackTo(t *MonsterT) { +} + +func (rcv *Monster) UnPack() *MonsterT { + if rcv == nil { + return nil + } + t := &MonsterT{} + rcv.UnPackTo(t) + return t +} + +type Monster struct { + _tab flatbuffers.Table +} + +func GetRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Monster{} + x.Init(buf, n+offset) + return x +} + +func FinishMonsterBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsMonster(buf []byte, offset flatbuffers.UOffsetT) *Monster { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Monster{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedMonsterBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *Monster) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Monster) Table() flatbuffers.Table { + return rcv._tab +} + +func MonsterStart(builder *flatbuffers.Builder) { + builder.StartObject(0) +} +func MonsterEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.java b/third_party/flatbuffers/tests/MyGame/Example2/Monster.java new file mode 100644 index 00000000000..adf01cacb69 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.java @@ -0,0 +1,56 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example2; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Monster extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Monster getRootAsMonster(ByteBuffer _bb) { return getRootAsMonster(_bb, new Monster()); } + public static Monster getRootAsMonster(ByteBuffer _bb, Monster obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Monster __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + + public static void startMonster(FlatBufferBuilder builder) { builder.startTable(0); } + public static int endMonster(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Monster get(int j) { return get(new Monster(), j); } + public Monster get(Monster obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public MonsterT unpack() { + MonsterT _o = new MonsterT(); + unpackTo(_o); + return _o; + } + public void unpackTo(MonsterT _o) { + } + public static int pack(FlatBufferBuilder builder, MonsterT _o) { + if (_o == null) return 0; + startMonster(builder); + return endMonster(builder); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.kt b/third_party/flatbuffers/tests/MyGame/Example2/Monster.kt new file mode 100644 index 00000000000..bac8005d4e6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.kt @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example2 + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Monster : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Monster { + __init(_i, _bb) + return this + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsMonster(_bb: ByteBuffer): Monster = getRootAsMonster(_bb, Monster()) + fun getRootAsMonster(_bb: ByteBuffer, obj: Monster): Monster { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun startMonster(builder: FlatBufferBuilder) = builder.startTable(0) + fun endMonster(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.lua b/third_party/flatbuffers/tests/MyGame/Example2/Monster.lua new file mode 100644 index 00000000000..371f145402b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.lua @@ -0,0 +1,36 @@ +--[[ MyGame.Example2.Monster + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Monster = {} +local mt = {} + +function Monster.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function Monster.Start(builder) + builder:StartObject(0) +end + +function Monster.End(builder) + return builder:EndObject() +end + +return Monster \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.nim b/third_party/flatbuffers/tests/MyGame/Example2/Monster.nim new file mode 100644 index 00000000000..39e738a7788 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.nim @@ -0,0 +1,17 @@ +#[ MyGame.Example2.Monster + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers + +type Monster* = object of FlatObj +proc MonsterStart*(builder: var Builder) = + builder.StartObject(0) +proc MonsterEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.php b/third_party/flatbuffers/tests/MyGame/Example2/Monster.php new file mode 100644 index 00000000000..b00f150e56c --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.php @@ -0,0 +1,79 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function MonsterIdentifier() + { + return "MONS"; + } + + public static function MonsterBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::MonsterIdentifier()); + } + + public static function MonsterExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Monster + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startMonster(FlatBufferBuilder $builder) + { + $builder->StartObject(0); + } + + /** + * @param FlatBufferBuilder $builder + * @return Monster + */ + public static function createMonster(FlatBufferBuilder $builder, ) + { + $builder->startObject(0); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endMonster(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/Example2/Monster.py b/third_party/flatbuffers/tests/MyGame/Example2/Monster.py new file mode 100644 index 00000000000..41c43e9ea2f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/Monster.py @@ -0,0 +1,76 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example2 + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class Monster(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Monster() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMonster(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Monster + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def MonsterStart(builder): + builder.StartObject(0) + +def Start(builder): + MonsterStart(builder) + +def MonsterEnd(builder): + return builder.EndObject() + +def End(builder): + return MonsterEnd(builder) + + +class MonsterT(object): + + # MonsterT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + monster = Monster() + monster.Init(buf, pos) + return cls.InitFromObj(monster) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, monster): + x = MonsterT() + x._UnPack(monster) + return x + + # MonsterT + def _UnPack(self, monster): + if monster is None: + return + + # MonsterT + def Pack(self, builder): + MonsterStart(builder) + monster = MonsterEnd(builder) + return monster diff --git a/third_party/flatbuffers/tests/MyGame/Example2/MonsterT.java b/third_party/flatbuffers/tests/MyGame/Example2/MonsterT.java new file mode 100644 index 00000000000..699d6c6daaa --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/Example2/MonsterT.java @@ -0,0 +1,28 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.Example2; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class MonsterT { + + + public MonsterT() { + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/Example2/__init__.py b/third_party/flatbuffers/tests/MyGame/Example2/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.cs b/third_party/flatbuffers/tests/MyGame/InParentNamespace.cs new file mode 100644 index 00000000000..99ccf670fa3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.cs @@ -0,0 +1,59 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct InParentNamespace : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static InParentNamespace GetRootAsInParentNamespace(ByteBuffer _bb) { return GetRootAsInParentNamespace(_bb, new InParentNamespace()); } + public static InParentNamespace GetRootAsInParentNamespace(ByteBuffer _bb, InParentNamespace obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public InParentNamespace __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + + public static void StartInParentNamespace(FlatBufferBuilder builder) { builder.StartTable(0); } + public static Offset EndInParentNamespace(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public InParentNamespaceT UnPack() { + var _o = new InParentNamespaceT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(InParentNamespaceT _o) { + } + public static Offset Pack(FlatBufferBuilder builder, InParentNamespaceT _o) { + if (_o == null) return default(Offset); + StartInParentNamespace(builder); + return EndInParentNamespace(builder); + } +} + +public class InParentNamespaceT +{ + + public InParentNamespaceT() { + } +} + + +static public class InParentNamespaceVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.go b/third_party/flatbuffers/tests/MyGame/InParentNamespace.go new file mode 100644 index 00000000000..37c44c18091 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.go @@ -0,0 +1,72 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package MyGame + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type InParentNamespaceT struct { +} + +func (t *InParentNamespaceT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + InParentNamespaceStart(builder) + return InParentNamespaceEnd(builder) +} + +func (rcv *InParentNamespace) UnPackTo(t *InParentNamespaceT) { +} + +func (rcv *InParentNamespace) UnPack() *InParentNamespaceT { + if rcv == nil { + return nil + } + t := &InParentNamespaceT{} + rcv.UnPackTo(t) + return t +} + +type InParentNamespace struct { + _tab flatbuffers.Table +} + +func GetRootAsInParentNamespace(buf []byte, offset flatbuffers.UOffsetT) *InParentNamespace { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &InParentNamespace{} + x.Init(buf, n+offset) + return x +} + +func FinishInParentNamespaceBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.Finish(offset) +} + +func GetSizePrefixedRootAsInParentNamespace(buf []byte, offset flatbuffers.UOffsetT) *InParentNamespace { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &InParentNamespace{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func FinishSizePrefixedInParentNamespaceBuffer(builder *flatbuffers.Builder, offset flatbuffers.UOffsetT) { + builder.FinishSizePrefixed(offset) +} + +func (rcv *InParentNamespace) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *InParentNamespace) Table() flatbuffers.Table { + return rcv._tab +} + +func InParentNamespaceStart(builder *flatbuffers.Builder) { + builder.StartObject(0) +} +func InParentNamespaceEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.java b/third_party/flatbuffers/tests/MyGame/InParentNamespace.java new file mode 100644 index 00000000000..60437466d61 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.java @@ -0,0 +1,56 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class InParentNamespace extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static InParentNamespace getRootAsInParentNamespace(ByteBuffer _bb) { return getRootAsInParentNamespace(_bb, new InParentNamespace()); } + public static InParentNamespace getRootAsInParentNamespace(ByteBuffer _bb, InParentNamespace obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public InParentNamespace __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + + public static void startInParentNamespace(FlatBufferBuilder builder) { builder.startTable(0); } + public static int endInParentNamespace(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public InParentNamespace get(int j) { return get(new InParentNamespace(), j); } + public InParentNamespace get(InParentNamespace obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public InParentNamespaceT unpack() { + InParentNamespaceT _o = new InParentNamespaceT(); + unpackTo(_o); + return _o; + } + public void unpackTo(InParentNamespaceT _o) { + } + public static int pack(FlatBufferBuilder builder, InParentNamespaceT _o) { + if (_o == null) return 0; + startInParentNamespace(builder); + return endInParentNamespace(builder); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.kt b/third_party/flatbuffers/tests/MyGame/InParentNamespace.kt new file mode 100644 index 00000000000..084372ad777 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.kt @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class InParentNamespace : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : InParentNamespace { + __init(_i, _bb) + return this + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsInParentNamespace(_bb: ByteBuffer): InParentNamespace = getRootAsInParentNamespace(_bb, InParentNamespace()) + fun getRootAsInParentNamespace(_bb: ByteBuffer, obj: InParentNamespace): InParentNamespace { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun startInParentNamespace(builder: FlatBufferBuilder) = builder.startTable(0) + fun endInParentNamespace(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.lua b/third_party/flatbuffers/tests/MyGame/InParentNamespace.lua new file mode 100644 index 00000000000..e065aa9f721 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.lua @@ -0,0 +1,36 @@ +--[[ MyGame.InParentNamespace + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //monster_test.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local InParentNamespace = {} +local mt = {} + +function InParentNamespace.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function InParentNamespace.Start(builder) + builder:StartObject(0) +end + +function InParentNamespace.End(builder) + return builder:EndObject() +end + +return InParentNamespace \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.nim b/third_party/flatbuffers/tests/MyGame/InParentNamespace.nim new file mode 100644 index 00000000000..1dc7f5979b5 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.nim @@ -0,0 +1,17 @@ +#[ MyGame.InParentNamespace + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers + +type InParentNamespace* = object of FlatObj +proc InParentNamespaceStart*(builder: var Builder) = + builder.StartObject(0) +proc InParentNamespaceEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.php b/third_party/flatbuffers/tests/MyGame/InParentNamespace.php new file mode 100644 index 00000000000..e13a4f356ec --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.php @@ -0,0 +1,79 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function InParentNamespaceIdentifier() + { + return "MONS"; + } + + public static function InParentNamespaceBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::InParentNamespaceIdentifier()); + } + + public static function InParentNamespaceExtension() + { + return "mon"; + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return InParentNamespace + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startInParentNamespace(FlatBufferBuilder $builder) + { + $builder->StartObject(0); + } + + /** + * @param FlatBufferBuilder $builder + * @return InParentNamespace + */ + public static function createInParentNamespace(FlatBufferBuilder $builder, ) + { + $builder->startObject(0); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endInParentNamespace(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespace.py b/third_party/flatbuffers/tests/MyGame/InParentNamespace.py new file mode 100644 index 00000000000..adbce9172ba --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespace.py @@ -0,0 +1,76 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: MyGame + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class InParentNamespace(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = InParentNamespace() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsInParentNamespace(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def InParentNamespaceBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # InParentNamespace + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def InParentNamespaceStart(builder): + builder.StartObject(0) + +def Start(builder): + InParentNamespaceStart(builder) + +def InParentNamespaceEnd(builder): + return builder.EndObject() + +def End(builder): + return InParentNamespaceEnd(builder) + + +class InParentNamespaceT(object): + + # InParentNamespaceT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + inParentNamespace = InParentNamespace() + inParentNamespace.Init(buf, pos) + return cls.InitFromObj(inParentNamespace) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, inParentNamespace): + x = InParentNamespaceT() + x._UnPack(inParentNamespace) + return x + + # InParentNamespaceT + def _UnPack(self, inParentNamespace): + if inParentNamespace is None: + return + + # InParentNamespaceT + def Pack(self, builder): + InParentNamespaceStart(builder) + inParentNamespace = InParentNamespaceEnd(builder) + return inParentNamespace diff --git a/third_party/flatbuffers/tests/MyGame/InParentNamespaceT.java b/third_party/flatbuffers/tests/MyGame/InParentNamespaceT.java new file mode 100644 index 00000000000..9180ce19ac2 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/InParentNamespaceT.java @@ -0,0 +1,28 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class InParentNamespaceT { + + + public InParentNamespaceT() { + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/MonsterExtra.cs b/third_party/flatbuffers/tests/MyGame/MonsterExtra.cs new file mode 100644 index 00000000000..cb3df13b6d7 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/MonsterExtra.cs @@ -0,0 +1,229 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace MyGame +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct MonsterExtra : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static MonsterExtra GetRootAsMonsterExtra(ByteBuffer _bb) { return GetRootAsMonsterExtra(_bb, new MonsterExtra()); } + public static MonsterExtra GetRootAsMonsterExtra(ByteBuffer _bb, MonsterExtra obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool MonsterExtraBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "MONE"); } + public static bool VerifyMonsterExtra(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("MONE", false, MonsterExtraVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public MonsterExtra __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public double D0 { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)Double.NaN; } } + public bool MutateD0(double d0) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutDouble(o + __p.bb_pos, d0); return true; } else { return false; } } + public double D1 { get { int o = __p.__offset(6); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)Double.NaN; } } + public bool MutateD1(double d1) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutDouble(o + __p.bb_pos, d1); return true; } else { return false; } } + public double D2 { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)Double.PositiveInfinity; } } + public bool MutateD2(double d2) { int o = __p.__offset(8); if (o != 0) { __p.bb.PutDouble(o + __p.bb_pos, d2); return true; } else { return false; } } + public double D3 { get { int o = __p.__offset(10); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)Double.NegativeInfinity; } } + public bool MutateD3(double d3) { int o = __p.__offset(10); if (o != 0) { __p.bb.PutDouble(o + __p.bb_pos, d3); return true; } else { return false; } } + public float F0 { get { int o = __p.__offset(12); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.NaN; } } + public bool MutateF0(float f0) { int o = __p.__offset(12); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, f0); return true; } else { return false; } } + public float F1 { get { int o = __p.__offset(14); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.NaN; } } + public bool MutateF1(float f1) { int o = __p.__offset(14); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, f1); return true; } else { return false; } } + public float F2 { get { int o = __p.__offset(16); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.PositiveInfinity; } } + public bool MutateF2(float f2) { int o = __p.__offset(16); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, f2); return true; } else { return false; } } + public float F3 { get { int o = __p.__offset(18); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)Single.NegativeInfinity; } } + public bool MutateF3(float f3) { int o = __p.__offset(18); if (o != 0) { __p.bb.PutFloat(o + __p.bb_pos, f3); return true; } else { return false; } } + public double Dvec(int j) { int o = __p.__offset(20); return o != 0 ? __p.bb.GetDouble(__p.__vector(o) + j * 8) : (double)0; } + public int DvecLength { get { int o = __p.__offset(20); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetDvecBytes() { return __p.__vector_as_span(20, 8); } +#else + public ArraySegment? GetDvecBytes() { return __p.__vector_as_arraysegment(20); } +#endif + public double[] GetDvecArray() { return __p.__vector_as_array(20); } + public bool MutateDvec(int j, double dvec) { int o = __p.__offset(20); if (o != 0) { __p.bb.PutDouble(__p.__vector(o) + j * 8, dvec); return true; } else { return false; } } + public float Fvec(int j) { int o = __p.__offset(22); return o != 0 ? __p.bb.GetFloat(__p.__vector(o) + j * 4) : (float)0; } + public int FvecLength { get { int o = __p.__offset(22); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetFvecBytes() { return __p.__vector_as_span(22, 4); } +#else + public ArraySegment? GetFvecBytes() { return __p.__vector_as_arraysegment(22); } +#endif + public float[] GetFvecArray() { return __p.__vector_as_array(22); } + public bool MutateFvec(int j, float fvec) { int o = __p.__offset(22); if (o != 0) { __p.bb.PutFloat(__p.__vector(o) + j * 4, fvec); return true; } else { return false; } } + + public static Offset CreateMonsterExtra(FlatBufferBuilder builder, + double d0 = Double.NaN, + double d1 = Double.NaN, + double d2 = Double.PositiveInfinity, + double d3 = Double.NegativeInfinity, + float f0 = Single.NaN, + float f1 = Single.NaN, + float f2 = Single.PositiveInfinity, + float f3 = Single.NegativeInfinity, + VectorOffset dvecOffset = default(VectorOffset), + VectorOffset fvecOffset = default(VectorOffset)) { + builder.StartTable(11); + MonsterExtra.AddD3(builder, d3); + MonsterExtra.AddD2(builder, d2); + MonsterExtra.AddD1(builder, d1); + MonsterExtra.AddD0(builder, d0); + MonsterExtra.AddFvec(builder, fvecOffset); + MonsterExtra.AddDvec(builder, dvecOffset); + MonsterExtra.AddF3(builder, f3); + MonsterExtra.AddF2(builder, f2); + MonsterExtra.AddF1(builder, f1); + MonsterExtra.AddF0(builder, f0); + return MonsterExtra.EndMonsterExtra(builder); + } + + public static void StartMonsterExtra(FlatBufferBuilder builder) { builder.StartTable(11); } + public static void AddD0(FlatBufferBuilder builder, double d0) { builder.AddDouble(0, d0, Double.NaN); } + public static void AddD1(FlatBufferBuilder builder, double d1) { builder.AddDouble(1, d1, Double.NaN); } + public static void AddD2(FlatBufferBuilder builder, double d2) { builder.AddDouble(2, d2, Double.PositiveInfinity); } + public static void AddD3(FlatBufferBuilder builder, double d3) { builder.AddDouble(3, d3, Double.NegativeInfinity); } + public static void AddF0(FlatBufferBuilder builder, float f0) { builder.AddFloat(4, f0, Single.NaN); } + public static void AddF1(FlatBufferBuilder builder, float f1) { builder.AddFloat(5, f1, Single.NaN); } + public static void AddF2(FlatBufferBuilder builder, float f2) { builder.AddFloat(6, f2, Single.PositiveInfinity); } + public static void AddF3(FlatBufferBuilder builder, float f3) { builder.AddFloat(7, f3, Single.NegativeInfinity); } + public static void AddDvec(FlatBufferBuilder builder, VectorOffset dvecOffset) { builder.AddOffset(8, dvecOffset.Value, 0); } + public static VectorOffset CreateDvecVector(FlatBufferBuilder builder, double[] data) { builder.StartVector(8, data.Length, 8); for (int i = data.Length - 1; i >= 0; i--) builder.AddDouble(data[i]); return builder.EndVector(); } + public static VectorOffset CreateDvecVectorBlock(FlatBufferBuilder builder, double[] data) { builder.StartVector(8, data.Length, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateDvecVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(8, data.Count, 8); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateDvecVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartDvecVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(8, numElems, 8); } + public static void AddFvec(FlatBufferBuilder builder, VectorOffset fvecOffset) { builder.AddOffset(9, fvecOffset.Value, 0); } + public static VectorOffset CreateFvecVector(FlatBufferBuilder builder, float[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddFloat(data[i]); return builder.EndVector(); } + public static VectorOffset CreateFvecVectorBlock(FlatBufferBuilder builder, float[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateFvecVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateFvecVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartFvecVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static Offset EndMonsterExtra(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishMonsterExtraBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value, "MONE"); } + public static void FinishSizePrefixedMonsterExtraBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value, "MONE"); } + public MonsterExtraT UnPack() { + var _o = new MonsterExtraT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(MonsterExtraT _o) { + _o.D0 = this.D0; + _o.D1 = this.D1; + _o.D2 = this.D2; + _o.D3 = this.D3; + _o.F0 = this.F0; + _o.F1 = this.F1; + _o.F2 = this.F2; + _o.F3 = this.F3; + _o.Dvec = new List(); + for (var _j = 0; _j < this.DvecLength; ++_j) {_o.Dvec.Add(this.Dvec(_j));} + _o.Fvec = new List(); + for (var _j = 0; _j < this.FvecLength; ++_j) {_o.Fvec.Add(this.Fvec(_j));} + } + public static Offset Pack(FlatBufferBuilder builder, MonsterExtraT _o) { + if (_o == null) return default(Offset); + var _dvec = default(VectorOffset); + if (_o.Dvec != null) { + var __dvec = _o.Dvec.ToArray(); + _dvec = CreateDvecVector(builder, __dvec); + } + var _fvec = default(VectorOffset); + if (_o.Fvec != null) { + var __fvec = _o.Fvec.ToArray(); + _fvec = CreateFvecVector(builder, __fvec); + } + return CreateMonsterExtra( + builder, + _o.D0, + _o.D1, + _o.D2, + _o.D3, + _o.F0, + _o.F1, + _o.F2, + _o.F3, + _dvec, + _fvec); + } +} + +public class MonsterExtraT +{ + [Newtonsoft.Json.JsonProperty("d0")] + public double D0 { get; set; } + [Newtonsoft.Json.JsonProperty("d1")] + public double D1 { get; set; } + [Newtonsoft.Json.JsonProperty("d2")] + public double D2 { get; set; } + [Newtonsoft.Json.JsonProperty("d3")] + public double D3 { get; set; } + [Newtonsoft.Json.JsonProperty("f0")] + public float F0 { get; set; } + [Newtonsoft.Json.JsonProperty("f1")] + public float F1 { get; set; } + [Newtonsoft.Json.JsonProperty("f2")] + public float F2 { get; set; } + [Newtonsoft.Json.JsonProperty("f3")] + public float F3 { get; set; } + [Newtonsoft.Json.JsonProperty("dvec")] + public List Dvec { get; set; } + [Newtonsoft.Json.JsonProperty("fvec")] + public List Fvec { get; set; } + + public MonsterExtraT() { + this.D0 = Double.NaN; + this.D1 = Double.NaN; + this.D2 = Double.PositiveInfinity; + this.D3 = Double.NegativeInfinity; + this.F0 = Single.NaN; + this.F1 = Single.NaN; + this.F2 = Single.PositiveInfinity; + this.F3 = Single.NegativeInfinity; + this.Dvec = null; + this.Fvec = null; + } + + public static MonsterExtraT DeserializeFromJson(string jsonText) { + return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText); + } + public string SerializeToJson() { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + public static MonsterExtraT DeserializeFromBinary(byte[] fbBuffer) { + return MonsterExtra.GetRootAsMonsterExtra(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + MonsterExtra.FinishMonsterExtraBuffer(fbb, MonsterExtra.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class MonsterExtraVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*D0*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 6 /*D1*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 8 /*D2*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 10 /*D3*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 12 /*F0*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 14 /*F1*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 16 /*F2*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 18 /*F3*/, 4 /*float*/, 4, false) + && verifier.VerifyVectorOfData(tablePos, 20 /*Dvec*/, 8 /*double*/, false) + && verifier.VerifyVectorOfData(tablePos, 22 /*Fvec*/, 4 /*float*/, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/MyGame/MonsterExtra.java b/third_party/flatbuffers/tests/MyGame/MonsterExtra.java new file mode 100644 index 00000000000..039f36db780 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/MonsterExtra.java @@ -0,0 +1,168 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class MonsterExtra extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static MonsterExtra getRootAsMonsterExtra(ByteBuffer _bb) { return getRootAsMonsterExtra(_bb, new MonsterExtra()); } + public static MonsterExtra getRootAsMonsterExtra(ByteBuffer _bb, MonsterExtra obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public static boolean MonsterExtraBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MONE"); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public MonsterExtra __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public double d0() { int o = __offset(4); return o != 0 ? bb.getDouble(o + bb_pos) : Double.NaN; } + public boolean mutateD0(double d0) { int o = __offset(4); if (o != 0) { bb.putDouble(o + bb_pos, d0); return true; } else { return false; } } + public double d1() { int o = __offset(6); return o != 0 ? bb.getDouble(o + bb_pos) : Double.NaN; } + public boolean mutateD1(double d1) { int o = __offset(6); if (o != 0) { bb.putDouble(o + bb_pos, d1); return true; } else { return false; } } + public double d2() { int o = __offset(8); return o != 0 ? bb.getDouble(o + bb_pos) : Double.POSITIVE_INFINITY; } + public boolean mutateD2(double d2) { int o = __offset(8); if (o != 0) { bb.putDouble(o + bb_pos, d2); return true; } else { return false; } } + public double d3() { int o = __offset(10); return o != 0 ? bb.getDouble(o + bb_pos) : Double.NEGATIVE_INFINITY; } + public boolean mutateD3(double d3) { int o = __offset(10); if (o != 0) { bb.putDouble(o + bb_pos, d3); return true; } else { return false; } } + public float f0() { int o = __offset(12); return o != 0 ? bb.getFloat(o + bb_pos) : Float.NaN; } + public boolean mutateF0(float f0) { int o = __offset(12); if (o != 0) { bb.putFloat(o + bb_pos, f0); return true; } else { return false; } } + public float f1() { int o = __offset(14); return o != 0 ? bb.getFloat(o + bb_pos) : Float.NaN; } + public boolean mutateF1(float f1) { int o = __offset(14); if (o != 0) { bb.putFloat(o + bb_pos, f1); return true; } else { return false; } } + public float f2() { int o = __offset(16); return o != 0 ? bb.getFloat(o + bb_pos) : Float.POSITIVE_INFINITY; } + public boolean mutateF2(float f2) { int o = __offset(16); if (o != 0) { bb.putFloat(o + bb_pos, f2); return true; } else { return false; } } + public float f3() { int o = __offset(18); return o != 0 ? bb.getFloat(o + bb_pos) : Float.NEGATIVE_INFINITY; } + public boolean mutateF3(float f3) { int o = __offset(18); if (o != 0) { bb.putFloat(o + bb_pos, f3); return true; } else { return false; } } + public double dvec(int j) { int o = __offset(20); return o != 0 ? bb.getDouble(__vector(o) + j * 8) : 0; } + public int dvecLength() { int o = __offset(20); return o != 0 ? __vector_len(o) : 0; } + public DoubleVector dvecVector() { return dvecVector(new DoubleVector()); } + public DoubleVector dvecVector(DoubleVector obj) { int o = __offset(20); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer dvecAsByteBuffer() { return __vector_as_bytebuffer(20, 8); } + public ByteBuffer dvecInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 20, 8); } + public boolean mutateDvec(int j, double dvec) { int o = __offset(20); if (o != 0) { bb.putDouble(__vector(o) + j * 8, dvec); return true; } else { return false; } } + public float fvec(int j) { int o = __offset(22); return o != 0 ? bb.getFloat(__vector(o) + j * 4) : 0; } + public int fvecLength() { int o = __offset(22); return o != 0 ? __vector_len(o) : 0; } + public FloatVector fvecVector() { return fvecVector(new FloatVector()); } + public FloatVector fvecVector(FloatVector obj) { int o = __offset(22); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer fvecAsByteBuffer() { return __vector_as_bytebuffer(22, 4); } + public ByteBuffer fvecInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 22, 4); } + public boolean mutateFvec(int j, float fvec) { int o = __offset(22); if (o != 0) { bb.putFloat(__vector(o) + j * 4, fvec); return true; } else { return false; } } + + public static int createMonsterExtra(FlatBufferBuilder builder, + double d0, + double d1, + double d2, + double d3, + float f0, + float f1, + float f2, + float f3, + int dvecOffset, + int fvecOffset) { + builder.startTable(11); + MonsterExtra.addD3(builder, d3); + MonsterExtra.addD2(builder, d2); + MonsterExtra.addD1(builder, d1); + MonsterExtra.addD0(builder, d0); + MonsterExtra.addFvec(builder, fvecOffset); + MonsterExtra.addDvec(builder, dvecOffset); + MonsterExtra.addF3(builder, f3); + MonsterExtra.addF2(builder, f2); + MonsterExtra.addF1(builder, f1); + MonsterExtra.addF0(builder, f0); + return MonsterExtra.endMonsterExtra(builder); + } + + public static void startMonsterExtra(FlatBufferBuilder builder) { builder.startTable(11); } + public static void addD0(FlatBufferBuilder builder, double d0) { builder.addDouble(0, d0, Double.NaN); } + public static void addD1(FlatBufferBuilder builder, double d1) { builder.addDouble(1, d1, Double.NaN); } + public static void addD2(FlatBufferBuilder builder, double d2) { builder.addDouble(2, d2, Double.POSITIVE_INFINITY); } + public static void addD3(FlatBufferBuilder builder, double d3) { builder.addDouble(3, d3, Double.NEGATIVE_INFINITY); } + public static void addF0(FlatBufferBuilder builder, float f0) { builder.addFloat(4, f0, Float.NaN); } + public static void addF1(FlatBufferBuilder builder, float f1) { builder.addFloat(5, f1, Float.NaN); } + public static void addF2(FlatBufferBuilder builder, float f2) { builder.addFloat(6, f2, Float.POSITIVE_INFINITY); } + public static void addF3(FlatBufferBuilder builder, float f3) { builder.addFloat(7, f3, Float.NEGATIVE_INFINITY); } + public static void addDvec(FlatBufferBuilder builder, int dvecOffset) { builder.addOffset(8, dvecOffset, 0); } + public static int createDvecVector(FlatBufferBuilder builder, double[] data) { builder.startVector(8, data.length, 8); for (int i = data.length - 1; i >= 0; i--) builder.addDouble(data[i]); return builder.endVector(); } + public static void startDvecVector(FlatBufferBuilder builder, int numElems) { builder.startVector(8, numElems, 8); } + public static void addFvec(FlatBufferBuilder builder, int fvecOffset) { builder.addOffset(9, fvecOffset, 0); } + public static int createFvecVector(FlatBufferBuilder builder, float[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addFloat(data[i]); return builder.endVector(); } + public static void startFvecVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endMonsterExtra(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + public static void finishMonsterExtraBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "MONE"); } + public static void finishSizePrefixedMonsterExtraBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "MONE"); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public MonsterExtra get(int j) { return get(new MonsterExtra(), j); } + public MonsterExtra get(MonsterExtra obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public MonsterExtraT unpack() { + MonsterExtraT _o = new MonsterExtraT(); + unpackTo(_o); + return _o; + } + public void unpackTo(MonsterExtraT _o) { + double _oD0 = d0(); + _o.setD0(_oD0); + double _oD1 = d1(); + _o.setD1(_oD1); + double _oD2 = d2(); + _o.setD2(_oD2); + double _oD3 = d3(); + _o.setD3(_oD3); + float _oF0 = f0(); + _o.setF0(_oF0); + float _oF1 = f1(); + _o.setF1(_oF1); + float _oF2 = f2(); + _o.setF2(_oF2); + float _oF3 = f3(); + _o.setF3(_oF3); + double[] _oDvec = new double[dvecLength()]; + for (int _j = 0; _j < dvecLength(); ++_j) {_oDvec[_j] = dvec(_j);} + _o.setDvec(_oDvec); + float[] _oFvec = new float[fvecLength()]; + for (int _j = 0; _j < fvecLength(); ++_j) {_oFvec[_j] = fvec(_j);} + _o.setFvec(_oFvec); + } + public static int pack(FlatBufferBuilder builder, MonsterExtraT _o) { + if (_o == null) return 0; + int _dvec = 0; + if (_o.getDvec() != null) { + _dvec = createDvecVector(builder, _o.getDvec()); + } + int _fvec = 0; + if (_o.getFvec() != null) { + _fvec = createFvecVector(builder, _o.getFvec()); + } + return createMonsterExtra( + builder, + _o.getD0(), + _o.getD1(), + _o.getD2(), + _o.getD3(), + _o.getF0(), + _o.getF1(), + _o.getF2(), + _o.getF3(), + _dvec, + _fvec); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/MonsterExtra.kt b/third_party/flatbuffers/tests/MyGame/MonsterExtra.kt new file mode 100644 index 00000000000..04ea7d4498f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/MonsterExtra.kt @@ -0,0 +1,245 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class MonsterExtra : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : MonsterExtra { + __init(_i, _bb) + return this + } + val d0 : Double + get() { + val o = __offset(4) + return if(o != 0) bb.getDouble(o + bb_pos) else Double.NaN + } + fun mutateD0(d0: Double) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.putDouble(o + bb_pos, d0) + true + } else { + false + } + } + val d1 : Double + get() { + val o = __offset(6) + return if(o != 0) bb.getDouble(o + bb_pos) else Double.NaN + } + fun mutateD1(d1: Double) : Boolean { + val o = __offset(6) + return if (o != 0) { + bb.putDouble(o + bb_pos, d1) + true + } else { + false + } + } + val d2 : Double + get() { + val o = __offset(8) + return if(o != 0) bb.getDouble(o + bb_pos) else Double.POSITIVE_INFINITY + } + fun mutateD2(d2: Double) : Boolean { + val o = __offset(8) + return if (o != 0) { + bb.putDouble(o + bb_pos, d2) + true + } else { + false + } + } + val d3 : Double + get() { + val o = __offset(10) + return if(o != 0) bb.getDouble(o + bb_pos) else Double.NEGATIVE_INFINITY + } + fun mutateD3(d3: Double) : Boolean { + val o = __offset(10) + return if (o != 0) { + bb.putDouble(o + bb_pos, d3) + true + } else { + false + } + } + val f0 : Float + get() { + val o = __offset(12) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.NaN + } + fun mutateF0(f0: Float) : Boolean { + val o = __offset(12) + return if (o != 0) { + bb.putFloat(o + bb_pos, f0) + true + } else { + false + } + } + val f1 : Float + get() { + val o = __offset(14) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.NaN + } + fun mutateF1(f1: Float) : Boolean { + val o = __offset(14) + return if (o != 0) { + bb.putFloat(o + bb_pos, f1) + true + } else { + false + } + } + val f2 : Float + get() { + val o = __offset(16) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.POSITIVE_INFINITY + } + fun mutateF2(f2: Float) : Boolean { + val o = __offset(16) + return if (o != 0) { + bb.putFloat(o + bb_pos, f2) + true + } else { + false + } + } + val f3 : Float + get() { + val o = __offset(18) + return if(o != 0) bb.getFloat(o + bb_pos) else Float.NEGATIVE_INFINITY + } + fun mutateF3(f3: Float) : Boolean { + val o = __offset(18) + return if (o != 0) { + bb.putFloat(o + bb_pos, f3) + true + } else { + false + } + } + fun dvec(j: Int) : Double { + val o = __offset(20) + return if (o != 0) { + bb.getDouble(__vector(o) + j * 8) + } else { + 0.0 + } + } + val dvecLength : Int + get() { + val o = __offset(20); return if (o != 0) __vector_len(o) else 0 + } + val dvecAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(20, 8) + fun dvecInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 20, 8) + fun mutateDvec(j: Int, dvec: Double) : Boolean { + val o = __offset(20) + return if (o != 0) { + bb.putDouble(__vector(o) + j * 8, dvec) + true + } else { + false + } + } + fun fvec(j: Int) : Float { + val o = __offset(22) + return if (o != 0) { + bb.getFloat(__vector(o) + j * 4) + } else { + 0.0f + } + } + val fvecLength : Int + get() { + val o = __offset(22); return if (o != 0) __vector_len(o) else 0 + } + val fvecAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(22, 4) + fun fvecInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 22, 4) + fun mutateFvec(j: Int, fvec: Float) : Boolean { + val o = __offset(22) + return if (o != 0) { + bb.putFloat(__vector(o) + j * 4, fvec) + true + } else { + false + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsMonsterExtra(_bb: ByteBuffer): MonsterExtra = getRootAsMonsterExtra(_bb, MonsterExtra()) + fun getRootAsMonsterExtra(_bb: ByteBuffer, obj: MonsterExtra): MonsterExtra { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun MonsterExtraBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "MONE") + fun createMonsterExtra(builder: FlatBufferBuilder, d0: Double, d1: Double, d2: Double, d3: Double, f0: Float, f1: Float, f2: Float, f3: Float, dvecOffset: Int, fvecOffset: Int) : Int { + builder.startTable(11) + addD3(builder, d3) + addD2(builder, d2) + addD1(builder, d1) + addD0(builder, d0) + addFvec(builder, fvecOffset) + addDvec(builder, dvecOffset) + addF3(builder, f3) + addF2(builder, f2) + addF1(builder, f1) + addF0(builder, f0) + return endMonsterExtra(builder) + } + fun startMonsterExtra(builder: FlatBufferBuilder) = builder.startTable(11) + fun addD0(builder: FlatBufferBuilder, d0: Double) = builder.addDouble(0, d0, Double.NaN) + fun addD1(builder: FlatBufferBuilder, d1: Double) = builder.addDouble(1, d1, Double.NaN) + fun addD2(builder: FlatBufferBuilder, d2: Double) = builder.addDouble(2, d2, Double.POSITIVE_INFINITY) + fun addD3(builder: FlatBufferBuilder, d3: Double) = builder.addDouble(3, d3, Double.NEGATIVE_INFINITY) + fun addF0(builder: FlatBufferBuilder, f0: Float) = builder.addFloat(4, f0, Double.NaN) + fun addF1(builder: FlatBufferBuilder, f1: Float) = builder.addFloat(5, f1, Double.NaN) + fun addF2(builder: FlatBufferBuilder, f2: Float) = builder.addFloat(6, f2, Double.POSITIVE_INFINITY) + fun addF3(builder: FlatBufferBuilder, f3: Float) = builder.addFloat(7, f3, Double.NEGATIVE_INFINITY) + fun addDvec(builder: FlatBufferBuilder, dvec: Int) = builder.addOffset(8, dvec, 0) + fun createDvecVector(builder: FlatBufferBuilder, data: DoubleArray) : Int { + builder.startVector(8, data.size, 8) + for (i in data.size - 1 downTo 0) { + builder.addDouble(data[i]) + } + return builder.endVector() + } + fun startDvecVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(8, numElems, 8) + fun addFvec(builder: FlatBufferBuilder, fvec: Int) = builder.addOffset(9, fvec, 0) + fun createFvecVector(builder: FlatBufferBuilder, data: FloatArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addFloat(data[i]) + } + return builder.endVector() + } + fun startFvecVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun endMonsterExtra(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun finishMonsterExtraBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset, "MONE") + fun finishSizePrefixedMonsterExtraBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset, "MONE") + } +} diff --git a/third_party/flatbuffers/tests/MyGame/MonsterExtra.py b/third_party/flatbuffers/tests/MyGame/MonsterExtra.py new file mode 100644 index 00000000000..d9e183617c3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/MonsterExtra.py @@ -0,0 +1,335 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: MyGame + +import flatbuffers +from flatbuffers.compat import import_numpy +from typing import Any +np = import_numpy() + +class MonsterExtra(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = MonsterExtra() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMonsterExtra(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MonsterExtraBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x45", size_prefixed=size_prefixed) + + # MonsterExtra + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + + # MonsterExtra + def D0(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return float('nan') + + # MonsterExtra + def D1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return float('nan') + + # MonsterExtra + def D2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return float('inf') + + # MonsterExtra + def D3(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return float('-inf') + + # MonsterExtra + def F0(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('nan') + + # MonsterExtra + def F1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('nan') + + # MonsterExtra + def F2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # MonsterExtra + def F3(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('-inf') + + # MonsterExtra + def Dvec(self, j: int): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # MonsterExtra + def DvecAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o) + return 0 + + # MonsterExtra + def DvecLength(self) -> int: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # MonsterExtra + def DvecIsNone(self) -> bool: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + return o == 0 + + # MonsterExtra + def Fvec(self, j: int): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float32Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return 0 + + # MonsterExtra + def FvecAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float32Flags, o) + return 0 + + # MonsterExtra + def FvecLength(self) -> int: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # MonsterExtra + def FvecIsNone(self) -> bool: + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + +def MonsterExtraStart(builder: flatbuffers.Builder): + builder.StartObject(11) + +def Start(builder: flatbuffers.Builder): + MonsterExtraStart(builder) + +def MonsterExtraAddD0(builder: flatbuffers.Builder, d0: float): + builder.PrependFloat64Slot(0, d0, float('nan')) + +def AddD0(builder: flatbuffers.Builder, d0: float): + MonsterExtraAddD0(builder, d0) + +def MonsterExtraAddD1(builder: flatbuffers.Builder, d1: float): + builder.PrependFloat64Slot(1, d1, float('nan')) + +def AddD1(builder: flatbuffers.Builder, d1: float): + MonsterExtraAddD1(builder, d1) + +def MonsterExtraAddD2(builder: flatbuffers.Builder, d2: float): + builder.PrependFloat64Slot(2, d2, float('inf')) + +def AddD2(builder: flatbuffers.Builder, d2: float): + MonsterExtraAddD2(builder, d2) + +def MonsterExtraAddD3(builder: flatbuffers.Builder, d3: float): + builder.PrependFloat64Slot(3, d3, float('-inf')) + +def AddD3(builder: flatbuffers.Builder, d3: float): + MonsterExtraAddD3(builder, d3) + +def MonsterExtraAddF0(builder: flatbuffers.Builder, f0: float): + builder.PrependFloat32Slot(4, f0, float('nan')) + +def AddF0(builder: flatbuffers.Builder, f0: float): + MonsterExtraAddF0(builder, f0) + +def MonsterExtraAddF1(builder: flatbuffers.Builder, f1: float): + builder.PrependFloat32Slot(5, f1, float('nan')) + +def AddF1(builder: flatbuffers.Builder, f1: float): + MonsterExtraAddF1(builder, f1) + +def MonsterExtraAddF2(builder: flatbuffers.Builder, f2: float): + builder.PrependFloat32Slot(6, f2, float('inf')) + +def AddF2(builder: flatbuffers.Builder, f2: float): + MonsterExtraAddF2(builder, f2) + +def MonsterExtraAddF3(builder: flatbuffers.Builder, f3: float): + builder.PrependFloat32Slot(7, f3, float('-inf')) + +def AddF3(builder: flatbuffers.Builder, f3: float): + MonsterExtraAddF3(builder, f3) + +def MonsterExtraAddDvec(builder: flatbuffers.Builder, dvec: int): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(dvec), 0) + +def AddDvec(builder: flatbuffers.Builder, dvec: int): + MonsterExtraAddDvec(builder, dvec) + +def MonsterExtraStartDvecVector(builder, numElems: int) -> int: + return builder.StartVector(8, numElems, 8) + +def StartDvecVector(builder, numElems: int) -> int: + return MonsterExtraStartDvecVector(builder, numElems) + +def MonsterExtraAddFvec(builder: flatbuffers.Builder, fvec: int): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(fvec), 0) + +def AddFvec(builder: flatbuffers.Builder, fvec: int): + MonsterExtraAddFvec(builder, fvec) + +def MonsterExtraStartFvecVector(builder, numElems: int) -> int: + return builder.StartVector(4, numElems, 4) + +def StartFvecVector(builder, numElems: int) -> int: + return MonsterExtraStartFvecVector(builder, numElems) + +def MonsterExtraEnd(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + +def End(builder: flatbuffers.Builder) -> int: + return MonsterExtraEnd(builder) + +try: + from typing import List +except: + pass + +class MonsterExtraT(object): + + # MonsterExtraT + def __init__(self): + self.d0 = float('nan') # type: float + self.d1 = float('nan') # type: float + self.d2 = float('inf') # type: float + self.d3 = float('-inf') # type: float + self.f0 = float('nan') # type: float + self.f1 = float('nan') # type: float + self.f2 = float('inf') # type: float + self.f3 = float('-inf') # type: float + self.dvec = None # type: List[float] + self.fvec = None # type: List[float] + + @classmethod + def InitFromBuf(cls, buf, pos): + monsterExtra = MonsterExtra() + monsterExtra.Init(buf, pos) + return cls.InitFromObj(monsterExtra) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, monsterExtra): + x = MonsterExtraT() + x._UnPack(monsterExtra) + return x + + def __eq__(self, other): + return type(self) == type(other) and \ + self.d0 == other.d0 and \ + self.d1 == other.d1 and \ + self.d2 == other.d2 and \ + self.d3 == other.d3 and \ + self.f0 == other.f0 and \ + self.f1 == other.f1 and \ + self.f2 == other.f2 and \ + self.f3 == other.f3 and \ + self.dvec == other.dvec and \ + self.fvec == other.fvec + + # MonsterExtraT + def _UnPack(self, monsterExtra): + if monsterExtra is None: + return + self.d0 = monsterExtra.D0() + self.d1 = monsterExtra.D1() + self.d2 = monsterExtra.D2() + self.d3 = monsterExtra.D3() + self.f0 = monsterExtra.F0() + self.f1 = monsterExtra.F1() + self.f2 = monsterExtra.F2() + self.f3 = monsterExtra.F3() + if not monsterExtra.DvecIsNone(): + if np is None: + self.dvec = [] + for i in range(monsterExtra.DvecLength()): + self.dvec.append(monsterExtra.Dvec(i)) + else: + self.dvec = monsterExtra.DvecAsNumpy() + if not monsterExtra.FvecIsNone(): + if np is None: + self.fvec = [] + for i in range(monsterExtra.FvecLength()): + self.fvec.append(monsterExtra.Fvec(i)) + else: + self.fvec = monsterExtra.FvecAsNumpy() + + # MonsterExtraT + def Pack(self, builder): + if self.dvec is not None: + if np is not None and type(self.dvec) is np.ndarray: + dvec = builder.CreateNumpyVector(self.dvec) + else: + MonsterExtraStartDvecVector(builder, len(self.dvec)) + for i in reversed(range(len(self.dvec))): + builder.PrependFloat64(self.dvec[i]) + dvec = builder.EndVector() + if self.fvec is not None: + if np is not None and type(self.fvec) is np.ndarray: + fvec = builder.CreateNumpyVector(self.fvec) + else: + MonsterExtraStartFvecVector(builder, len(self.fvec)) + for i in reversed(range(len(self.fvec))): + builder.PrependFloat32(self.fvec[i]) + fvec = builder.EndVector() + MonsterExtraStart(builder) + MonsterExtraAddD0(builder, self.d0) + MonsterExtraAddD1(builder, self.d1) + MonsterExtraAddD2(builder, self.d2) + MonsterExtraAddD3(builder, self.d3) + MonsterExtraAddF0(builder, self.f0) + MonsterExtraAddF1(builder, self.f1) + MonsterExtraAddF2(builder, self.f2) + MonsterExtraAddF3(builder, self.f3) + if self.dvec is not None: + MonsterExtraAddDvec(builder, dvec) + if self.fvec is not None: + MonsterExtraAddFvec(builder, fvec) + monsterExtra = MonsterExtraEnd(builder) + return monsterExtra diff --git a/third_party/flatbuffers/tests/MyGame/MonsterExtra.pyi b/third_party/flatbuffers/tests/MyGame/MonsterExtra.pyi new file mode 100644 index 00000000000..693cc512673 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/MonsterExtra.pyi @@ -0,0 +1,74 @@ +from __future__ import annotations + +import flatbuffers +import numpy as np + +import flatbuffers +import typing +from MyGame.MonsterExtra import MonsterExtra + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class MonsterExtra(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> MonsterExtra: ... + @classmethod + def GetRootAsMonsterExtra(cls, buf: bytes, offset: int) -> MonsterExtra: ... + @classmethod + def MonsterExtraBufferHasIdentifier(cls, buf: bytes, offset: int, size_prefixed: bool) -> bool: ... + def Init(self, buf: bytes, pos: int) -> None: ... + def D0(self) -> float: ... + def D1(self) -> float: ... + def D2(self) -> float: ... + def D3(self) -> float: ... + def F0(self) -> float: ... + def F1(self) -> float: ... + def F2(self) -> float: ... + def F3(self) -> float: ... + def Dvec(self, i: int) -> typing.List[float]: ... + def DvecAsNumpy(self) -> np.ndarray: ... + def DvecLength(self) -> int: ... + def DvecIsNone(self) -> bool: ... + def Fvec(self, i: int) -> typing.List[float]: ... + def FvecAsNumpy(self) -> np.ndarray: ... + def FvecLength(self) -> int: ... + def FvecIsNone(self) -> bool: ... +class MonsterExtraT(object): + d0: float + d1: float + d2: float + d3: float + f0: float + f1: float + f2: float + f3: float + dvec: typing.List[float] + fvec: typing.List[float] + @classmethod + def InitFromBuf(cls, buf: bytes, pos: int) -> MonsterExtraT: ... + @classmethod + def InitFromPackedBuf(cls, buf: bytes, pos: int = 0) -> MonsterExtraT: ... + @classmethod + def InitFromObj(cls, monsterExtra: MonsterExtra) -> MonsterExtraT: ... + def _UnPack(self, monsterExtra: MonsterExtra) -> None: ... + def Pack(self, builder: flatbuffers.Builder) -> None: ... + def __eq__(self, other: MonsterExtraT) -> bool: ... +def MonsterExtraStart(builder: flatbuffers.Builder) -> None: ... +def Start(builder: flatbuffers.Builder) -> None: ... +def MonsterExtraAddD0(builder: flatbuffers.Builder, d0: float) -> None: ... +def MonsterExtraAddD1(builder: flatbuffers.Builder, d1: float) -> None: ... +def MonsterExtraAddD2(builder: flatbuffers.Builder, d2: float) -> None: ... +def MonsterExtraAddD3(builder: flatbuffers.Builder, d3: float) -> None: ... +def MonsterExtraAddF0(builder: flatbuffers.Builder, f0: float) -> None: ... +def MonsterExtraAddF1(builder: flatbuffers.Builder, f1: float) -> None: ... +def MonsterExtraAddF2(builder: flatbuffers.Builder, f2: float) -> None: ... +def MonsterExtraAddF3(builder: flatbuffers.Builder, f3: float) -> None: ... +def MonsterExtraAddDvec(builder: flatbuffers.Builder, dvec: uoffset) -> None: ... +def MonsterExtraStartDvecVector(builder: flatbuffers.Builder, num_elems: int) -> uoffset: ... +def StartDvecVector(builder: flatbuffers.Builder, num_elems: int) -> uoffset: ... +def MonsterExtraAddFvec(builder: flatbuffers.Builder, fvec: uoffset) -> None: ... +def MonsterExtraStartFvecVector(builder: flatbuffers.Builder, num_elems: int) -> uoffset: ... +def StartFvecVector(builder: flatbuffers.Builder, num_elems: int) -> uoffset: ... +def MonsterExtraEnd(builder: flatbuffers.Builder) -> uoffset: ... +def End(builder: flatbuffers.Builder) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/MyGame/MonsterExtraT.java b/third_party/flatbuffers/tests/MyGame/MonsterExtraT.java new file mode 100644 index 00000000000..8872c1ce2d6 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/MonsterExtraT.java @@ -0,0 +1,96 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class MonsterExtraT { + private double d0; + private double d1; + private double d2; + private double d3; + private float f0; + private float f1; + private float f2; + private float f3; + private double[] dvec; + private float[] fvec; + + public double getD0() { return d0; } + + public void setD0(double d0) { this.d0 = d0; } + + public double getD1() { return d1; } + + public void setD1(double d1) { this.d1 = d1; } + + public double getD2() { return d2; } + + public void setD2(double d2) { this.d2 = d2; } + + public double getD3() { return d3; } + + public void setD3(double d3) { this.d3 = d3; } + + public float getF0() { return f0; } + + public void setF0(float f0) { this.f0 = f0; } + + public float getF1() { return f1; } + + public void setF1(float f1) { this.f1 = f1; } + + public float getF2() { return f2; } + + public void setF2(float f2) { this.f2 = f2; } + + public float getF3() { return f3; } + + public void setF3(float f3) { this.f3 = f3; } + + public double[] getDvec() { return dvec; } + + public void setDvec(double[] dvec) { this.dvec = dvec; } + + public float[] getFvec() { return fvec; } + + public void setFvec(float[] fvec) { this.fvec = fvec; } + + + public MonsterExtraT() { + this.d0 = Double.NaN; + this.d1 = Double.NaN; + this.d2 = Double.POSITIVE_INFINITY; + this.d3 = Double.NEGATIVE_INFINITY; + this.f0 = Float.NaN; + this.f1 = Float.NaN; + this.f2 = Float.POSITIVE_INFINITY; + this.f3 = Float.NEGATIVE_INFINITY; + this.dvec = null; + this.fvec = null; + } + public static MonsterExtraT deserializeFromBinary(byte[] fbBuffer) { + return MonsterExtra.getRootAsMonsterExtra(ByteBuffer.wrap(fbBuffer)).unpack(); + } + public byte[] serializeToBinary() { + FlatBufferBuilder fbb = new FlatBufferBuilder(); + MonsterExtra.finishMonsterExtraBuffer(fbb, MonsterExtra.pack(fbb, this)); + return fbb.sizedByteArray(); + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.lua b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.lua new file mode 100644 index 00000000000..3174ecd2874 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.lua @@ -0,0 +1,17 @@ +--[[ MyGame.OtherNameSpace.FromInclude + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //include_test/sub/include_test2.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local FromInclude = { + IncludeVal = 0, +} + +return FromInclude \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.nim b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.nim new file mode 100644 index 00000000000..22c01f731c4 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.nim @@ -0,0 +1,12 @@ +#[ MyGame.OtherNameSpace.FromInclude + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +type FromInclude*{.pure.} = enum + IncludeVal = 0.int64, diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.py b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.py new file mode 100644 index 00000000000..dbfcbffe797 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/FromInclude.py @@ -0,0 +1,5 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: OtherNameSpace + +# NOTE FromInclude.py does not declare any structs or enums diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.lua b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.lua new file mode 100644 index 00000000000..e629f63c0ff --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.lua @@ -0,0 +1,51 @@ +--[[ MyGame.OtherNameSpace.TableB + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //include_test/sub/include_test2.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local __TableA = require('TableA') +local flatbuffers = require('flatbuffers') + +local TableB = {} +local mt = {} + +function TableB.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:A() + local o = self.view:Offset(4) + if o ~= 0 then + local x = self.view:Indirect(self.view.pos + o) + local obj = __TableA.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function TableB.Start(builder) + builder:StartObject(1) +end + +function TableB.AddA(builder, a) + builder:PrependStructSlot(0, a, 0) +end + +function TableB.End(builder) + return builder:EndObject() +end + +return TableB \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.nim b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.nim new file mode 100644 index 00000000000..4dd23f1bf90 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.nim @@ -0,0 +1,25 @@ +#[ MyGame.OtherNameSpace.TableB + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import ../../TableA as TableA +import flatbuffers +import std/options + +type TableB* = object of FlatObj +func a*(self: TableB): Option[TableA.TableA] = + let o = self.tab.Offset(4) + if o != 0: + return some(TableA.TableA(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +proc TableBstart*(builder: var Builder) = + builder.StartObject(1) +proc TableBadda*(builder: var Builder, a: uoffset) = + builder.PrependStructSlot(0, a, default(uoffset)) +proc TableBend*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.py b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.py new file mode 100644 index 00000000000..1a30369384f --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableB.py @@ -0,0 +1,5 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: OtherNameSpace + +# NOTE TableB.py does not declare any structs or enums diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableBT.java b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableBT.java new file mode 100644 index 00000000000..d38d9ce118b --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/TableBT.java @@ -0,0 +1,22 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.OtherNameSpace; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class TableBT { + private TableAT a; + + public TableAT getA() { return a; } + + public void setA(TableAT a) { this.a = a; } + + + public TableBT() { + this.a = null; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.lua b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.lua new file mode 100644 index 00000000000..597b6fcfb56 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.lua @@ -0,0 +1,38 @@ +--[[ MyGame.OtherNameSpace.Unused + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //include_test/sub/include_test2.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local flatbuffers = require('flatbuffers') + +local Unused = {} +local mt = {} + +function Unused.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:A() + return self.view:Get(flatbuffers.N.Int32, self.view.pos + 0) +end + +function Unused.CreateUnused(builder, a) + builder:Prep(4, 4) + builder:PrependInt32(a) + return builder:Offset() +end + +return Unused \ No newline at end of file diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.nim b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.nim new file mode 100644 index 00000000000..1dc5c54ebca --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.nim @@ -0,0 +1,21 @@ +#[ MyGame.OtherNameSpace.Unused + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import flatbuffers + +type Unused* = object of FlatObj +func a*(self: Unused): int32 = + return Get[int32](self.tab, self.tab.Pos + 0) +func `a=`*(self: var Unused, n: int32): bool = + return self.tab.Mutate(self.tab.Pos + 0, n) +proc UnusedCreate*(self: var Builder, a: int32): uoffset = + self.Prep(4, 4) + self.Prepend(a) + return self.Offset() diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.py b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.py new file mode 100644 index 00000000000..bde02a74739 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/Unused.py @@ -0,0 +1,5 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: OtherNameSpace + +# NOTE Unused.py does not declare any structs or enums diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/UnusedT.java b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/UnusedT.java new file mode 100644 index 00000000000..b525a1ce8f3 --- /dev/null +++ b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/UnusedT.java @@ -0,0 +1,22 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package MyGame.OtherNameSpace; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class UnusedT { + private int a; + + public int getA() { return a; } + + public void setA(int a) { this.a = a; } + + + public UnusedT() { + this.a = 0; + } +} + diff --git a/third_party/flatbuffers/tests/MyGame/OtherNameSpace/__init__.py b/third_party/flatbuffers/tests/MyGame/OtherNameSpace/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/MyGame/__init__.py b/third_party/flatbuffers/tests/MyGame/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/Pizza.go b/third_party/flatbuffers/tests/Pizza.go new file mode 100644 index 00000000000..08df9e16b1c --- /dev/null +++ b/third_party/flatbuffers/tests/Pizza.go @@ -0,0 +1,78 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package Pizza + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type PizzaT struct { + Size int32 `json:"size"` +} + +func (t *PizzaT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + PizzaStart(builder) + PizzaAddSize(builder, t.Size) + return PizzaEnd(builder) +} + +func (rcv *Pizza) UnPackTo(t *PizzaT) { + t.Size = rcv.Size() +} + +func (rcv *Pizza) UnPack() *PizzaT { + if rcv == nil { return nil } + t := &PizzaT{} + rcv.UnPackTo(t) + return t +} + +type Pizza struct { + _tab flatbuffers.Table +} + +func GetRootAsPizza(buf []byte, offset flatbuffers.UOffsetT) *Pizza { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Pizza{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsPizza(buf []byte, offset flatbuffers.UOffsetT) *Pizza { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Pizza{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *Pizza) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Pizza) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Pizza) Size() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *Pizza) MutateSize(n int32) bool { + return rcv._tab.MutateInt32Slot(4, n) +} + +func PizzaStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func PizzaAddSize(builder *flatbuffers.Builder, size int32) { + builder.PrependInt32Slot(0, size, 0) +} +func PizzaEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/Property.nim b/third_party/flatbuffers/tests/Property.nim new file mode 100644 index 00000000000..dda7b927b1f --- /dev/null +++ b/third_party/flatbuffers/tests/Property.nim @@ -0,0 +1,20 @@ +#[ Property + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : +]# + +import flatbuffers + +type Property* = object of FlatObj +func property*(self: Property): bool = + return Get[bool](self.tab, self.tab.Pos + 0) +func `property=`*(self: var Property, n: bool): bool = + return self.tab.Mutate(self.tab.Pos + 0, n) +proc PropertyCreate*(self: var Builder, property: bool): uoffset = + self.Prep(1, 1) + self.Prepend(property) + return self.Offset() diff --git a/third_party/flatbuffers/tests/PythonTest.sh b/third_party/flatbuffers/tests/PythonTest.sh new file mode 100755 index 00000000000..647f3daf158 --- /dev/null +++ b/third_party/flatbuffers/tests/PythonTest.sh @@ -0,0 +1,93 @@ +#!/bin/bash +# +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +set -eu + +pushd "$(dirname $0)" >/dev/null +test_dir="$(pwd)" +gen_code_path=${test_dir} +runtime_library_dir=${test_dir}/../python + +# Emit Python code for the example schema in the test dir: +${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_test.fbs --gen-object-api +${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_test.fbs --gen-object-api --gen-onefile +${test_dir}/../flatc -p -o ${gen_code_path} -I include_test monster_extra.fbs --gen-object-api --python-typing --gen-compare +${test_dir}/../flatc -p -o ${gen_code_path} -I include_test arrays_test.fbs --gen-object-api --python-typing +${test_dir}/../flatc -p -o ${gen_code_path} -I include_test nested_union_test.fbs --gen-object-api --python-typing +${test_dir}/../flatc -p -o ${gen_code_path} -I include_test service_test.fbs --grpc --grpc-python-typed-handlers --python-typing --no-python-gen-numpy --gen-onefile + +# Syntax: run_tests +# +interpreters_tested=() +function run_tests() { + if $(which ${1} >/dev/null); then + echo "Testing with interpreter: ${1}" + PYTHONDONTWRITEBYTECODE=1 \ + JYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=${runtime_library_dir}:${gen_code_path} \ + JYTHONPATH=${runtime_library_dir}:${gen_code_path} \ + COMPARE_GENERATED_TO_GO=0 \ + COMPARE_GENERATED_TO_JAVA=0 \ + $1 py_test.py $2 $3 $4 $5 $6 + if [ $1 = python3 ]; then + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=${runtime_library_dir}:${gen_code_path} \ + $1 py_flexbuffers_test.py + fi + interpreters_tested+=(${1}) + echo + fi +} + +# Run test suite with these interpreters. The arguments are benchmark counts. +run_tests python2.6 100 100 100 100 false +run_tests python2.7 100 100 100 100 false +run_tests python2.7 100 100 100 100 true +run_tests python3 100 100 100 100 false +run_tests python3 100 100 100 100 true +run_tests pypy 100 100 100 100 false + +# NOTE: We'd like to support python2.5 in the future. + +# NOTE: Jython 2.7.0 fails due to a bug in the stdlib `struct` library: +# http://bugs.jython.org/issue2188 + +if [ ${#interpreters_tested[@]} -eq 0 ]; then + echo "No Python interpeters found on this system, could not run tests." + exit 1 +fi + +# Run test suite with default python intereter. +# (If the Python program `coverage` is available, it will be run, too. +# Install `coverage` with `pip install coverage`.) +if $(which coverage >/dev/null); then + echo 'Found coverage utility, running coverage with default Python:' + + PYTHONDONTWRITEBYTECODE=1 \ + PYTHONPATH=${runtime_library_dir}:${gen_code_path} \ + coverage run --source=flatbuffers,MyGame py_test.py 0 0 0 0 false > /dev/null + + echo + cov_result=`coverage report --omit="*flatbuffers/vendor*,*py_test*" \ + | tail -n 1 | awk ' { print $4 } '` + echo "Code coverage: ${cov_result}" +else + echo -n "Did not find coverage utility for default Python, skipping. " + echo "Install with 'pip install coverage'." +fi + +echo +echo "OK: all tests passed for ${#interpreters_tested[@]} interpreters: ${interpreters_tested[@]}." diff --git a/third_party/flatbuffers/tests/RustTest.bat b/third_party/flatbuffers/tests/RustTest.bat new file mode 100644 index 00000000000..56f43f2d033 --- /dev/null +++ b/third_party/flatbuffers/tests/RustTest.bat @@ -0,0 +1,33 @@ +@echo off +rem Copyright 2018 Google Inc. All rights reserved. +rem +rem Licensed under the Apache License, Version 2.0 (the "License"); +rem you may not use this file except in compliance with the License. +rem You may obtain a copy of the License at +rem +rem http://www.apache.org/licenses/LICENSE-2.0 +rem +rem Unless required by applicable law or agreed to in writing, software +rem distributed under the License is distributed on an "AS IS" BASIS, +rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +rem See the License for the specific language governing permissions and +rem limitations under the License. + +rem Compile then run the Rust test. + +cd rust_serialize_test +cargo run -- --quiet || exit /b 1 + +cd ../rust_no_std_compilation_test +rustup install nightly +rustup component add rust-src --toolchain nightly +rustup target add thumbv7m-none-eabi +cargo +nightly build || exit /b 1 + +cd ../rust_usage_test +cargo test -- --quiet || exit /b 1 +cargo run --bin=flatbuffers_alloc_check || exit /b 1 +cargo run --bin=flexbuffers_alloc_check || exit /b 1 +cargo run --bin=monster_example || exit /b 1 +cd .. + diff --git a/third_party/flatbuffers/tests/RustTest.sh b/third_party/flatbuffers/tests/RustTest.sh new file mode 100755 index 00000000000..1e7d0eed9d4 --- /dev/null +++ b/third_party/flatbuffers/tests/RustTest.sh @@ -0,0 +1,76 @@ +#!/bin/bash +set -e +# +# Copyright 2018 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +if [[ "$1" == "mips-unknown-linux-gnu" ]]; then + TARGET_FLAG="--target mips-unknown-linux-gnu" + export CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_LINKER=mips-linux-gnu-gcc + export CARGO_TARGET_MIPS_UNKNOWN_LINUX_GNU_RUNNER="qemu-mips -L /usr/mips-linux-gnu" +fi + + +function check_test_result() { + if [[ $? == 0 ]]; then + echo OK: $1 passed. + else + echo KO: $1 failed. + exit 1 + fi +} + +cd ./rust_serialize_test +cargo run $TARGET_FLAG -- --quiet +check_test_result "Rust serde tests" + +cd ../rust_no_std_compilation_test +rustup install nightly +rustup component add rust-src --toolchain nightly +rustup target add thumbv7m-none-eabi +cargo +nightly build +check_test_result "Rust flatbuffers test no_std compilation" + +cd ../rust_usage_test +cargo test $TARGET_FLAG -- --quiet +check_test_result "Rust tests" + +cargo test $TARGET_FLAG --no-default-features -- --quiet +check_test_result "Rust tests (no_std)" + +cargo run $TARGET_FLAG --bin=flatbuffers_alloc_check +check_test_result "Rust flatbuffers heap alloc test" + +cargo run $TARGET_FLAG --bin=flexbuffers_alloc_check +check_test_result "Rust flexbuffers heap alloc test" + +rustup component add clippy +cargo clippy $TARGET_FLAG +check_test_result "No Cargo clippy lints test" + +cargo bench $TARGET_FLAG + +# This test is dependent on flatc. +if [[ -f ../../flatc ]]; then + cd outdir + cargo test + check_test_result "Rust generated file in \$OUT_DIR" + cd .. +fi + +# RUST_NIGHTLY environment variable set in dockerfile. +if [[ $RUST_NIGHTLY == 1 ]]; then + rustup +nightly component add miri + MIRIFLAGS="-Zmiri-disable-isolation" cargo +nightly miri test +fi diff --git a/third_party/flatbuffers/tests/TableA.lua b/third_party/flatbuffers/tests/TableA.lua new file mode 100644 index 00000000000..d2eb497be25 --- /dev/null +++ b/third_party/flatbuffers/tests/TableA.lua @@ -0,0 +1,51 @@ +--[[ TableA + + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : //include_test/include_test1.fbs + Rooting type : MyGame.Example.Monster (//monster_test.fbs) + +--]] + +local __MyGame_OtherNameSpace_TableB = require('MyGame.OtherNameSpace.TableB') +local flatbuffers = require('flatbuffers') + +local TableA = {} +local mt = {} + +function TableA.New() + local o = {} + setmetatable(o, {__index = mt}) + return o +end + +function mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end + +function mt:B() + local o = self.view:Offset(4) + if o ~= 0 then + local x = self.view:Indirect(self.view.pos + o) + local obj = __MyGame_OtherNameSpace_TableB.New() + obj:Init(self.view.bytes, x) + return obj + end +end + +function TableA.Start(builder) + builder:StartObject(1) +end + +function TableA.AddB(builder, b) + builder:PrependStructSlot(0, b, 0) +end + +function TableA.End(builder) + return builder:EndObject() +end + +return TableA \ No newline at end of file diff --git a/third_party/flatbuffers/tests/TableA.nim b/third_party/flatbuffers/tests/TableA.nim new file mode 100644 index 00000000000..6740395fe97 --- /dev/null +++ b/third_party/flatbuffers/tests/TableA.nim @@ -0,0 +1,25 @@ +#[ TableA + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : MyGame.Example.Monster () +]# + +import MyGame/OtherNameSpace/TableB as MyGame_OtherNameSpace_TableB +import flatbuffers +import std/options + +type TableA* = object of FlatObj +func b*(self: TableA): Option[MyGame_OtherNameSpace_TableB.TableB] = + let o = self.tab.Offset(4) + if o != 0: + return some(MyGame_OtherNameSpace_TableB.TableB(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +proc TableAstart*(builder: var Builder) = + builder.StartObject(1) +proc TableAaddb*(builder: var Builder, b: uoffset) = + builder.PrependStructSlot(0, b, default(uoffset)) +proc TableAend*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/TableA.py b/third_party/flatbuffers/tests/TableA.py new file mode 100644 index 00000000000..ea081ffdc12 --- /dev/null +++ b/third_party/flatbuffers/tests/TableA.py @@ -0,0 +1,5 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: + +# NOTE TableA.py does not declare any structs or enums diff --git a/third_party/flatbuffers/tests/TableAT.java b/third_party/flatbuffers/tests/TableAT.java new file mode 100644 index 00000000000..a81b39b06ed --- /dev/null +++ b/third_party/flatbuffers/tests/TableAT.java @@ -0,0 +1,20 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class TableAT { + private MyGame.OtherNameSpace.TableBT b; + + public MyGame.OtherNameSpace.TableBT getB() { return b; } + + public void setB(MyGame.OtherNameSpace.TableBT b) { this.b = b; } + + + public TableAT() { + this.b = null; + } +} + diff --git a/third_party/flatbuffers/tests/TestAll.sh b/third_party/flatbuffers/tests/TestAll.sh new file mode 100755 index 00000000000..a7741b951a4 --- /dev/null +++ b/third_party/flatbuffers/tests/TestAll.sh @@ -0,0 +1,59 @@ +echo "************************ Java:" + +sh JavaTest.sh + +echo "************************ Kotlin:" + +sh KotlinTest.sh + +echo "************************ Go:" + +sh GoTest.sh + +echo "************************ Python:" + +sh PythonTest.sh + +echo "************************ TypeScript:" + +python3 ts/TypeScriptTest.py + +echo "************************ C++:" + +cd .. +./flattests +cd tests + +echo "************************ C#:" + +cd FlatBuffers.Test +sh NetTest.sh +cd .. + +echo "************************ PHP:" + +php phpTest.php +sh phpUnionVectorTest.sh + +echo "************************ Dart:" + +sh DartTest.sh + +echo "************************ Rust:" + +sh RustTest.sh + +echo "************************ Lobster:" + +# TODO: test if available. +# lobster lobstertest.lobster + +echo "************************ C:" + +echo "(in a different repo)" + +echo "************************ Swift:" + +cd FlatBuffers.Test.Swift +sh SwiftTest.sh +cd .. diff --git a/third_party/flatbuffers/tests/TestMutatingBool.nim b/third_party/flatbuffers/tests/TestMutatingBool.nim new file mode 100644 index 00000000000..5513177da09 --- /dev/null +++ b/third_party/flatbuffers/tests/TestMutatingBool.nim @@ -0,0 +1,24 @@ +#[ TestMutatingBool + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : +]# + +import Property as Property +import flatbuffers +import std/options + +type TestMutatingBool* = object of FlatObj +func b*(self: TestMutatingBool): Option[Property.Property] = + let o = self.tab.Offset(4) + if o != 0: + return some(Property.Property(tab: Vtable(Bytes: self.tab.Bytes, Pos: self.tab.Pos + o))) +proc TestMutatingBoolStart*(builder: var Builder) = + builder.StartObject(1) +proc TestMutatingBoolAddb*(builder: var Builder, b: uoffset) = + builder.PrependStructSlot(0, b, default(uoffset)) +proc TestMutatingBoolEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/__init__.py b/third_party/flatbuffers/tests/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/alignment_test.cpp b/third_party/flatbuffers/tests/alignment_test.cpp new file mode 100644 index 00000000000..2641a3180d8 --- /dev/null +++ b/third_party/flatbuffers/tests/alignment_test.cpp @@ -0,0 +1,83 @@ +#include "alignment_test.h" + +#include "tests/alignment_test_generated.h" +#include "flatbuffers/flatbuffer_builder.h" +#include "flatbuffers/util.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +void AlignmentTest() { + FlatBufferBuilder builder; + + BadAlignmentLarge large; + Offset outer_large = CreateOuterLarge(builder, &large); + + BadAlignmentSmall *small; + Offset> small_offset = + builder.CreateUninitializedVectorOfStructs(9, &small); + (void)small; // We do not have to write data to trigger the test failure + + Offset root = + CreateBadAlignmentRoot(builder, outer_large, small_offset); + + builder.Finish(root); + + Verifier verifier(builder.GetBufferPointer(), builder.GetSize()); + TEST_ASSERT(verifier.VerifyBuffer(nullptr)); + + + // ============= Test Small Structs Vector misalignment ======== + + builder.Clear(); + + // creating 5 structs with 2 bytes each + // 10 bytes in total for Vector data is needed + std::vector even_vector = { { 2, 1 }, { 3, 1 }, { 4, 1 } }; + std::vector odd_vector = { { 6, 5, 4 }, + { 9, 8, 7 }, + { 1, 2, 3 } }; + // CreateVectorOfStructs is used in the generated CreateSmallStructsDirect() + // method, but we test it directly + Offset> even_structs_offset = + builder.CreateVectorOfStructs(even_vector); + Offset> odd_structs_offset = + builder.CreateVectorOfStructs(odd_vector); + Offset small_structs_root = + CreateSmallStructs(builder, even_structs_offset, odd_structs_offset); + + builder.Finish(small_structs_root); + + // Save the binary that we later can annotate with `flatc --annotate` command + // NOTE: the conversion of the JSON data to --binary via `flatc --binary` + // command is not changed with that fix and was always producing the + // correct binary data. + // SaveFile("alignment_test_{before,after}_fix.bin", + // reinterpret_cast(builder.GetBufferPointer()), + // builder.GetSize(), true); + + Verifier verifier_small_structs(builder.GetBufferPointer(), + builder.GetSize()); + TEST_ASSERT(verifier_small_structs.VerifyBuffer(nullptr)); + + // Reading SmallStructs vector values back and compare with original + auto root_msg = + flatbuffers::GetRoot(builder.GetBufferPointer()); + + TEST_EQ(root_msg->even_structs()->size(), even_vector.size()); + for (flatbuffers::uoffset_t i = 0; i < root_msg->even_structs()->size(); + ++i) { + TEST_EQ(even_vector[i].var_0(), root_msg->even_structs()->Get(i)->var_0()); + TEST_EQ(even_vector[i].var_1(), root_msg->even_structs()->Get(i)->var_1()); + } + + TEST_EQ(root_msg->odd_structs()->size(), even_vector.size()); + for (flatbuffers::uoffset_t i = 0; i < root_msg->odd_structs()->size(); ++i) { + TEST_EQ(odd_vector[i].var_0(), root_msg->odd_structs()->Get(i)->var_0()); + TEST_EQ(odd_vector[i].var_1(), root_msg->odd_structs()->Get(i)->var_1()); + } +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/alignment_test.fbs b/third_party/flatbuffers/tests/alignment_test.fbs new file mode 100644 index 00000000000..cf32e0d4532 --- /dev/null +++ b/third_party/flatbuffers/tests/alignment_test.fbs @@ -0,0 +1,44 @@ +// sizeof(BadAlignmentSmall) == 12 +// alignof(BadAlignmentSmall) == 4 +struct BadAlignmentSmall { + var_0: uint; + var_1: uint; + var_2: uint; +} + +// sizeof(BadAlignmentLarge) == 8 +// alignof(BadAlignmentLarge) == 8 +struct BadAlignmentLarge { + var_0: ulong; +} + +table OuterLarge { + large: BadAlignmentLarge; +} + +table BadAlignmentRoot { + large: OuterLarge; + small: [BadAlignmentSmall]; +} + +// sizeof(EvenSmallStruct) == 2 +// alignof(EvenSmallStruct) == 1 +struct EvenSmallStruct { + var_0: uint8; + var_1: uint8; +} + +// sizeof(OddSmallStruct) == 3 +// alignof(OddSmallStruct) == 1 +struct OddSmallStruct { + var_0: uint8; + var_1: uint8; + var_2: uint8; +} + +table SmallStructs { + even_structs: [EvenSmallStruct]; + odd_structs: [OddSmallStruct]; +} + +root_type SmallStructs; diff --git a/third_party/flatbuffers/tests/alignment_test.h b/third_party/flatbuffers/tests/alignment_test.h new file mode 100644 index 00000000000..68cdf0bd82e --- /dev/null +++ b/third_party/flatbuffers/tests/alignment_test.h @@ -0,0 +1,12 @@ +#ifndef TESTS_ALIGNMENT_TEST_H +#define TESTS_ALIGNMENT_TEST_H + +namespace flatbuffers { +namespace tests { + +void AlignmentTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/alignment_test.json b/third_party/flatbuffers/tests/alignment_test.json new file mode 100644 index 00000000000..7831d15e854 --- /dev/null +++ b/third_party/flatbuffers/tests/alignment_test.json @@ -0,0 +1,16 @@ +{ + "small_structs": [ + { + "var_0": 2, + "var_1": 1 + }, + { + "var_0": 3, + "var_1": 1 + }, + { + "var_0": 4, + "var_1": 1 + } + ] +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/alignment_test_after_fix.afb b/third_party/flatbuffers/tests/alignment_test_after_fix.afb new file mode 100644 index 00000000000..b8312e0ed43 --- /dev/null +++ b/third_party/flatbuffers/tests/alignment_test_after_fix.afb @@ -0,0 +1,31 @@ +// Annotated Flatbuffer Binary +// +// Schema file: alignment_test.fbs +// Binary file: alignment_test_after_fix.bin + +header: + +0x00 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0C | offset to root table `SmallStructs` + +padding: + +0x04 | 00 00 | uint8_t[2] | .. | padding + +vtable (SmallStructs): + +0x06 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x08 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0A | 04 00 | VOffset16 | 0x0004 (4) | offset to field `small_structs` (id: 0) + +root_table (SmallStructs): + +0x0C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x06 | offset to vtable + +0x10 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x14 | offset to field `small_structs` (vector) + +vector (SmallStructs.small_structs): + +0x14 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x18 | 02 | uint8_t | 0x02 (2) | struct field `[0].var_0` of 'JustSmallStruct' (UByte) + +0x19 | 01 | uint8_t | 0x01 (1) | struct field `[0].var_1` of 'JustSmallStruct' (UByte) + +0x1A | 03 | uint8_t | 0x03 (3) | struct field `[1].var_0` of 'JustSmallStruct' (UByte) + +0x1B | 01 | uint8_t | 0x01 (1) | struct field `[1].var_1` of 'JustSmallStruct' (UByte) + +0x1C | 04 | uint8_t | 0x04 (4) | struct field `[2].var_0` of 'JustSmallStruct' (UByte) + +0x1D | 01 | uint8_t | 0x01 (1) | struct field `[2].var_1` of 'JustSmallStruct' (UByte) + +padding: + +0x1E | 00 00 | uint8_t[2] | .. | padding diff --git a/third_party/flatbuffers/tests/alignment_test_after_fix.bin b/third_party/flatbuffers/tests/alignment_test_after_fix.bin new file mode 100644 index 00000000000..e9c1ffd0892 Binary files /dev/null and b/third_party/flatbuffers/tests/alignment_test_after_fix.bin differ diff --git a/third_party/flatbuffers/tests/alignment_test_before_fix.afb b/third_party/flatbuffers/tests/alignment_test_before_fix.afb new file mode 100644 index 00000000000..c2665310ae1 --- /dev/null +++ b/third_party/flatbuffers/tests/alignment_test_before_fix.afb @@ -0,0 +1,31 @@ +// Annotated Flatbuffer Binary +// +// Schema file: alignment_test.fbs +// Binary file: alignment_test_before_fix.bin + +header: + +0x00 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0C | offset to root table `SmallStructs` + +padding: + +0x04 | 00 00 | uint8_t[2] | .. | padding + +vtable (SmallStructs): + +0x06 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x08 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0A | 04 00 | VOffset16 | 0x0004 (4) | offset to field `small_structs` (id: 0) + +root_table (SmallStructs): + +0x0C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x06 | offset to vtable + +0x10 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x14 | offset to field `small_structs` (vector) + +vector (SmallStructs.small_structs): + +0x14 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x18 | 00 | uint8_t | 0x00 (0) | struct field `[0].var_0` of 'JustSmallStruct' (UByte) + +0x19 | 00 | uint8_t | 0x00 (0) | struct field `[0].var_1` of 'JustSmallStruct' (UByte) + +0x1A | 02 | uint8_t | 0x02 (2) | struct field `[1].var_0` of 'JustSmallStruct' (UByte) + +0x1B | 01 | uint8_t | 0x01 (1) | struct field `[1].var_1` of 'JustSmallStruct' (UByte) + +0x1C | 03 | uint8_t | 0x03 (3) | struct field `[2].var_0` of 'JustSmallStruct' (UByte) + +0x1D | 01 | uint8_t | 0x01 (1) | struct field `[2].var_1` of 'JustSmallStruct' (UByte) + +unknown (no known references): + +0x1E | 04 01 | ?uint8_t[2] | .. | WARN: could be corrupted padding region. diff --git a/third_party/flatbuffers/tests/alignment_test_before_fix.bin b/third_party/flatbuffers/tests/alignment_test_before_fix.bin new file mode 100644 index 00000000000..d914f1880df Binary files /dev/null and b/third_party/flatbuffers/tests/alignment_test_before_fix.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/README.md b/third_party/flatbuffers/tests/annotated_binary/README.md new file mode 100644 index 00000000000..0cb046114cf --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/README.md @@ -0,0 +1,101 @@ +# Annotated Flatbuffer Binary + +This directory demonstrates the ability of flatc to annotate binary flatbuffers +with helpful annotations. The resulting annotated flatbuffer binary (afb) +contains all the binary data with line-by-line annotations. + +## Usage + +Given a `schema` in either plain-text (.fbs) or already compiled to a binary +schema (.bfbs) and `binary` file(s) that was created by the `schema`. + +```sh +flatc --annotate {schema_file} -- {binary_file}... +``` + +### Example + +The following command should produce `annotated_binary.afb` in this directory: + +```sh +cd tests\annotated_binary +..\..\flatc --annotate annotated_binary.fbs -- annotated_binary.bin +``` + +The `annotated_binary.bin` is the flatbufer binary of the data contained within + `annotated_binary.json`, which was made by the following command: + +```sh +..\..\flatc -b annotated_binary.fbs annotated_binary.json +``` + +## Text Format + +Currently there is a built-in text-based format for outputting the annotations. +The `annotated_binary.afb` is an example of the text format of a binary +`annotated_binary.bin` and the `annotated_binary.fbs` (or +`annotated_binary.bfbs`) schema. + +The file is ordered in increasing the offsets from the beginning of the binary. +The offset is the 1st column, expressed in hexadecimal format (e.g. `+0x003c`). + +### Binary Sections + +Binary sections are comprised of contigious [binary regions](#binary-regions) +that are logically grouped together. For example, a binary section may be a +single instance of a flatbuffer `Table` or its `vtable`. The sections may be +labelled with the name of the associated type, as defined in the input schema. + +Example of a `vtable` Binary Section that is associated with the user-defined +`AnnotateBinary.Bar` table. + +``` +vtable (AnnotatedBinary.Bar): + +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00A2 | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00A4 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00A6 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) +``` + +### Binary Regions + +Binary regions are contigious bytes regions that are grouped together to form +some sort of value, e.g. a `scalar` or an array of scalars. A binary region may +be split up over multiple text lines, if the size of the region is large. + +Looking at an example binary region: + +``` +vtable (AnnotatedBinary.Bar): + +0x00A0 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable +``` + +The first column (`+0x00A0`) is the offset to this region from the beginning of +the buffer. + +The second column are the raw bytes (hexadecimal) that make up this +region. These are expressed in the little-endian format that flatbuffers uses +for the wire format. + +The third column is the type to interpret the bytes as. Some types are special +to flatbuffer internals (e.g. `SOffet32`, `Offset32`, and `VOffset16`) which are +used by flatbuffers to point to various offsetes. The other types are specified +as C++-like types which are the standard fix-width scalars. For the above +example, the type is `uint16_t` which is a 16-bit unsigned integer type. + +The fourth column shows the raw bytes as a compacted, big-endian value. The raw +bytes are duplicated in this fashion since it is more intutive to read the data +in the big-endian format (e.g., `0x0008`). This value is followed by the decimal +representation of the value (e.g., `(8)`). (For strings, the raw string value +is shown instead). + +The fifth column is a textual comment on what the value is. As much metadata as +known is provided. + +#### Offsets + +If the type in the 3rd column is of an absolute offset (`SOffet32` or +`Offset32`), the fourth column also shows an `Loc: +0x025A` value which shows +where in the binary this region is pointing to. These values are absolute from +the beginning of the file, their calculation from the raw value in the 4th +column depends on the context. diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary.afb b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.afb new file mode 100644 index 00000000000..15e10a99ce0 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.afb @@ -0,0 +1,297 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: annotated_binary.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | offset to field `bar` (table) + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0298 | offset to field `c` (table) + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123457) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary.bfbs b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.bfbs new file mode 100644 index 00000000000..b4cf41966a7 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.bfbs differ diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary.bin b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.bin new file mode 100644 index 00000000000..2557aaf533e Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary.fbs b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.fbs new file mode 100644 index 00000000000..60e320ff31b --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.fbs @@ -0,0 +1,92 @@ +namespace AnnotatedBinary; + +enum Food : byte { + None = 0, + Apple = 1, + Banana = 2, + Kiwi = 3, +} + +table Baz { + meal:Food = Banana; +} + +table Bar { + a:double = 3.14; + b:float = 1.68; + c:Baz; +} + +union BarBaz { + Bar, Baz +} + +union Measurement { + Tolerance, Dimension +} + +struct Tolerance { + width:uint8; +} + +union Any { + Bar, Tolerance +} + +struct Dimension { + values:[int:3]; + tolerances:[Tolerance:3]; +} + +struct Building { + floors:int; + doors:int; + windows:int; + dimensions:Dimension; +} + +struct Location { + latitude:double; + longitude:double; +} + +table Foo { + counter:int; + healthy:bool; + level:long = 99; + meal:Food = Apple; + bar:Bar; + home:Building; + name:string; + // Vector of tables + bars:[Bar]; + // Union of tables + bar_baz:BarBaz; + // Vector of Scalars + accounts:[uint16]; + bob:string; + alice:string; + // Optional Scalars + maybe_i32: int32 = null; + default_i32: int32 = 42; + just_i32: int32; + // Vector of strings + names:[string]; + // Vector of structs + points_of_interest:[Location]; + // Vector of unions + foobars:[BarBaz]; + // Union of structs + measurement:Measurement; + // Union of struct/table + anything:Any; + // Default floating point + temperature:float=98.6; + // Not present object + teetotaler:Bar; + charlie:string; +} + +file_identifier "ANNO"; + +root_type Foo; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary.json b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.json new file mode 100644 index 00000000000..744e274093b --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/annotated_binary.json @@ -0,0 +1,124 @@ +{ + "counter": 1234, + "healthy": true, + "meal": "Banana", + "bar": { + "a": 123456.789, + "b": 987654.321, + "c": { + "meal": "Apple" + } + }, + "home": { + "floors": 1, + "doors": 2, + "windows": 12, + "dimensions": { + "values": [ + 10, + 12, + 20 + ], + "tolerances": [ + { + "width": 1 + }, + { + "width": 2 + }, + { + "width": 3 + } + ] + } + }, + "name": "This is a long string to show how it breaks up.", + "bars": [ + { + "a": 123, + "b": 456, + "c": { + "meal": "Apple" + } + }, + { + "a": 987, + "b": 654, + "c": { + "meal": "Kiwi" + } + } + ], + "bar_baz_type": "Baz", + "bar_baz": { + "meal": "Kiwi" + }, + "accounts": [ + 9, + 8, + 7, + 1, + 2, + 3, + 6, + 5, + 4, + ], + // Use the same string to show shared string support + "bob": "charlie", + "alice": "charlie", + "just_i32": 13, + "names": [ + "alice", + "bob", + "charlie" + ], + "points_of_interest": [ + { + "latitude": 43.275, + "longitude": -78.114990 + }, + { + "latitude": 37.422001, + "longitude": -122.084061 + }, + { + "latitude": -54.420792, + "longitude": 3.346450 + } + ], + "foobars_type": [ + "Bar", + "Baz", + "Bar" + ], + "foobars" : [ + { + "a": 123, + "b": 456, + "c": { + "meal": "Apple" + } + }, + { + "meal": "Banana" + }, + { + "a": 987, + "b": 654, + "c": { + "meal": "Kiwi" + } + } + ], + "measurement_type": "Tolerance", + "measurement": { + "width": 5 + }, + "anything_type": "Bar", + "anything": { + "a": 321, + "b": 654 + }, + "charlie": "alice" +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary_old.afb b/third_party/flatbuffers/tests/annotated_binary/annotated_binary_old.afb new file mode 100644 index 00000000000..9a0e5b0226f --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/annotated_binary_old.afb @@ -0,0 +1,293 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary_old.fbs +// Binary file: annotated_binary.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: +0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to unknown field (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: +0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | uint8_t | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | uint8_t | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | uint8_t | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: +0x027C | offset to field `bar` + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `AnnotatedBinary.Building.floors` (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `AnnotatedBinary.Building.doors` (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `AnnotatedBinary.Building.windows` (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `AnnotatedBinary.Dimension.values[0]` (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `AnnotatedBinary.Dimension.values[1]` (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `AnnotatedBinary.Dimension.values[2]` (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `AnnotatedBinary.Tolerance.width` (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `AnnotatedBinary.Tolerance.width` (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `AnnotatedBinary.Tolerance.width` (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: +0x023C | offset to field `name` + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: +0x01D4 | offset to field `bars` + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: +0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: +0x01B4 | offset to field `accounts` + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: +0x01A8 | offset to field `bob` + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: +0x019C | offset to field `alice` + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: +0x016C | offset to field `names` + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: +0x0134 | offset to field `points_of_interest` + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: +0x012C | offset to field `foobars_type` + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: +0x00D4 | offset to field `foobars` + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: +0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: +0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | ?uint8_t[4] | .... | Unknown field + +unknown (no known references): + +0x00AC | 05 00 00 00 61 6C 69 63 | ?uint8_t[12] | ....alic | WARN: nothing refers to this. Check if any `Unkown Field`s point to this. + +0x00B4 | 65 00 00 00 | | e... + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: +0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654.000000) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321.000000) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `AnnotatedBinary.Tolerance.width` (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: +0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: +0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: +0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: +0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654.000000) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: +0x00FC | offset to field `c` + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987.000000) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: +0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: +0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: +0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456.000000) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: +0x0124 | offset to field `c` + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123.000000) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: +0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | uint8_t | 0x01 (1) | value[0] + +0x0131 | 02 | uint8_t | 0x02 (2) | value[1] + +0x0132 | 01 | uint8_t | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275000) | struct field `AnnotatedBinary.Location.latitude` (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.114990) | struct field `AnnotatedBinary.Location.longitude` (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422001) | struct field `AnnotatedBinary.Location.latitude` (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084061) | struct field `AnnotatedBinary.Location.longitude` (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.420792) | struct field `AnnotatedBinary.Location.latitude` (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.346450) | struct field `AnnotatedBinary.Location.longitude` (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: +0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: +0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: +0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: +0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: +0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: +0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: +0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654.000000) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: +0x020C | offset to field `c` + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987.000000) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: +0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: +0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456.000000) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: +0x0234 | offset to field `c` + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123.000000) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: +0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: +0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654.312500) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: +0x0298 | offset to field `c` + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123456.789000) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: +0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/annotated_binary_old.fbs b/third_party/flatbuffers/tests/annotated_binary/annotated_binary_old.fbs new file mode 100644 index 00000000000..c22d6d2f38f --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/annotated_binary_old.fbs @@ -0,0 +1,94 @@ +namespace AnnotatedBinary; + +enum Food : byte { + None = 0, + Apple = 1, + Banana = 2, + Kiwi = 3, +} + +table Baz { + meal:Food = Banana; +} + +table Bar { + a:double = 3.14; + b:float = 1.68; + c:Baz; +} + +union BarBaz { + Bar, Baz +} + +union Measurement { + Tolerance, Dimension +} + +struct Tolerance { + width:uint8; +} + +union Any { + Bar, Tolerance +} + +struct Dimension { + values:[int:3]; + tolerances:[Tolerance:3]; +} + +struct Building { + floors:int; + doors:int; + windows:int; + dimensions:Dimension; +} + +struct Location { + latitude:double; + longitude:double; +} + +table Foo { + counter:int; + healthy:bool; + level:long = 99; + meal:Food = Apple; + bar:Bar; + home:Building; + name:string; + // Vector of tables + bars:[Bar]; + // Union of tables + bar_baz:BarBaz; + // Vector of Scalars + accounts:[uint16]; + bob:string; + alice:string; + // Optional Scalars + maybe_i32: int32 = null; + default_i32: int32 = 42; + just_i32: int32; + // Vector of strings + names:[string]; + // Vector of structs + points_of_interest:[Location]; + // Vector of unions + foobars:[BarBaz]; + // Union of structs + measurement:Measurement; + // Union of struct/table + anything:Any; + // Default floating point + temperature:float=98.6; + // Not present object + teetotaler:Bar; + + // NOTE THIS IS A PURPOSELY OLD VERSION OF annotated_binary.fbs TO TEST + // PROCESSING OF NEWER BINARIES THAN THE SCHEMA. DO NOT ADD TO THIS. +} + +file_identifier "ANNO"; + +root_type Foo; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/annotated_binary/generate_annotations.py b/third_party/flatbuffers/tests/annotated_binary/generate_annotations.py new file mode 100755 index 00000000000..bd5de2b28bc --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/generate_annotations.py @@ -0,0 +1,76 @@ +#!/usr/bin/env python3 +# +# Copyright 2021 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import platform +import subprocess +from pathlib import Path + +# Get the path where this script is located so we can invoke the script from +# any directory and have the paths work correctly. +script_path = Path(__file__).parent.resolve() + +# Get the root path as an absolute path, so all derived paths are absolute. +root_path = script_path.parent.parent.absolute() + +# Get the location of the flatc executable, reading from the first command line +# argument or defaulting to default names. +flatc_exe = Path( + ("flatc" if not platform.system() == "Windows" else "flatc.exe") +) + +# Find and assert flatc compiler is present. +if root_path in flatc_exe.parents: + flatc_exe = flatc_exe.relative_to(root_path) +flatc_path = Path(root_path, flatc_exe) +assert flatc_path.exists(), "Cannot find the flatc compiler " + str(flatc_path) + +# Specify the other paths that will be referenced +tests_path = Path(script_path, "tests") + + +def flatc_annotate(schema, file, cwd=script_path): + cmd = [str(flatc_path), "--annotate", schema, file] + result = subprocess.run(cmd, cwd=str(cwd), check=True) + + +test_files = [ + "annotated_binary.bin", + "tests/invalid_root_offset.bin", + "tests/invalid_root_table_too_short.bin", + "tests/invalid_root_table_vtable_offset.bin", + "tests/invalid_string_length.bin", + "tests/invalid_string_length_cut_short.bin", + "tests/invalid_struct_array_field_cut_short.bin", + "tests/invalid_struct_field_cut_short.bin", + "tests/invalid_table_field_size.bin", + "tests/invalid_table_field_offset.bin", + "tests/invalid_union_type_value.bin", + "tests/invalid_vector_length_cut_short.bin", + "tests/invalid_vector_scalars_cut_short.bin", + "tests/invalid_vector_strings_cut_short.bin", + "tests/invalid_vector_structs_cut_short.bin", + "tests/invalid_vector_tables_cut_short.bin", + "tests/invalid_vector_unions_cut_short.bin", + "tests/invalid_vector_union_type_value.bin", + "tests/invalid_vtable_ref_table_size_short.bin", + "tests/invalid_vtable_ref_table_size.bin", + "tests/invalid_vtable_size_short.bin", + "tests/invalid_vtable_size.bin", + "tests/invalid_vtable_field_offset.bin", +] + +for test_file in test_files: + flatc_annotate("annotated_binary.fbs", test_file) diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/README.md b/third_party/flatbuffers/tests/annotated_binary/tests/README.md new file mode 100644 index 00000000000..c0d73f49914 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/README.md @@ -0,0 +1,125 @@ +# Tests for Annotated Binaries + +## Invalid Binary Tests + +The following is a collection of manually corrupted binaries based off of +`..\annotated_binary.bin`. Each file changes some offset or length/size entry to +point so an invalid spot, and the generated annotated binaries demonstrate that +those corruptions can be spotted. + +Each of these files were ran with the following command: + +```sh +cd .tests/annotated_binary +../../flatc -annotate annotated_binary.fbs tests/{binary_file}... +``` + +### `invalid_root_offset.bin` + +Changed first two bytes from `4400` to `FFFF` which produces an offset larger +than the binary. + +### `invalid_root_table_vtable_offset.bin` + +Changed two bytes at 0x0044 from `3A00` to `FFFF` which points to an offset +outside the binary. + +### `invalid_root_table_too_short.bin` + +Truncated the file to 0x46 bytes, as that cuts into the vtable offset field of +the root table. + +```sh +truncate annotated_binary.bin --size=70 >> invalid_root_table_too_short.bin +``` + +### `invalid_vtable_size.bin` + +Changed two bytes at 0x000A from `3A00` to `FFFF` which size is larger than the +binary. + +### `invalid_vtable_size_short.bin` + +Changed two bytes at 0x000A from `3A00` to `0100` which size is smaller than the +minimum size of 4 bytes. + +### `invalid_vtable_ref_table_size.bin` + +Changed two bytes at 0x000C from `6800` to `FFFF` which size is larger than the +binary. + +### `invalid_vtable_ref_table_size_short.bin` + +Changed two bytes at 0x000C from `6800` to `0100` which size is smaller than +the minimum size of 4 bytes. + +### `invalid_vtable_field_offset.bin` + +Changed two bytes at 0x0016 from `1000` to `FFFF` which points to a field larger +than the binary. + +### `invalid_table_field_size.bin` + +Truncated the file to 0x52 bytes, as that cuts a Uint32t value in half. + +### `invalid_table_field_offset.bin` + +Truncated the file to 0x96 bytes, as that cuts a UOffset32 value in half. Also, +changed two bytes at 0x90 from `DC00` to `FFFF` which points to a section larger +than the binary. + +### `invalid_string_length_cut_short.bin` + +Truncated the file to 0xAD bytes, as that cuts string length Uint32t value in +half. + +### `invalid_string_length.bin` + +Changed two bytes at 0x00AC from `0500` to `FFFF` which is a string length +larger than the binary. + +### `invalid_vector_length_cut_short.bin` + +Truncated the file to 0x0136 bytes, as that cuts vector length Uint32t value in +half. + +### `invalid_struct_field_cut_short.bin` + +Truncated the file to 0x5d bytes, as that cuts struct field value in half. + +### `invalid_struct_array_field_cut_short.bin` + +Truncated the file to 0x6A bytes, as that cuts struct array field value in half. + +### `invalid_vector_structs_cut_short.bin` + +Truncated the file to 0x0154 bytes, as that cuts into a vector of structs. + +### `invalid_vector_tables_cut_short.bin` + +Truncated the file to 0x01DE bytes, as that cuts into a vector of table offsets. + +### `invalid_vector_strings_cut_short.bin` + +Truncated the file to 0x0176 bytes, as that cuts into a vector of string +offsets. + +### `invalid_vector_scalars_cut_short.bin` + +Truncated the file to 0x01C1 bytes, as that cuts into a vector of scalars +values. + +### `invalid_vector_unions_cut_short.bin` + +Truncated the file to 0x01DE bytes, as that cuts into a vector of union offset +values. + +### `invalid_union_type_value.bin` + +Changed one byte at 0x004D from `02` to `FF` which is a union type value that is +larger than the enum. + +### `invalid_vector_union_type_value.bin` + +Changed one byte at 0x0131 from `02` to `FF` which is a vector union type value +that is larger than the enum. \ No newline at end of file diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_offset.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_offset.afb new file mode 100644 index 00000000000..e100feacfe0 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_offset.afb @@ -0,0 +1,93 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_root_offset.bin + +header: + +0x0000 | FF FF 00 00 | UOffset32 | 0x0000FFFF (65535) Loc: 0xFFFF | ERROR: offset to root table `AnnotatedBinary.Foo`. Invalid offset, points outside the binary. + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +unknown (no known references): + +0x0008 | 00 00 3A 00 68 00 0C 00 | ?uint8_t[664] | ..:.h... | WARN: nothing refers to this section. + +0x0010 | 07 00 00 00 08 00 10 00 | | ........ + +0x0018 | 14 00 30 00 34 00 09 00 | | ..0.4... + +0x0020 | 38 00 3C 00 40 00 44 00 | | 8.<.@.D. + +0x0028 | 00 00 00 00 48 00 4C 00 | | ....H.L. + +0x0030 | 50 00 54 00 58 00 0A 00 | | P.T.X... + +0x0038 | 5C 00 0B 00 60 00 00 00 | | \...`... + +0x0040 | 00 00 64 00 3A 00 00 00 | | ..d.:... + +0x0048 | 00 00 00 01 02 02 01 01 | | ........ + +0x0050 | D2 04 00 00 28 02 00 00 | | ....(... + +0x0058 | 01 00 00 00 02 00 00 00 | | ........ + +0x0060 | 0C 00 00 00 0A 00 00 00 | | ........ + +0x0068 | 0C 00 00 00 14 00 00 00 | | ........ + +0x0070 | 01 02 03 00 C8 01 00 00 | | ........ + +0x0078 | 5C 01 00 00 50 01 00 00 | | \...P... + +0x0080 | 34 01 00 00 24 01 00 00 | | 4...$... + +0x0088 | 14 01 00 00 0D 00 00 00 | | ........ + +0x0090 | DC 00 00 00 A0 00 00 00 | | ........ + +0x0098 | 94 00 00 00 38 00 00 00 | | ....8... + +0x00A0 | 33 00 00 00 1C 00 00 00 | | 3....... + +0x00A8 | 04 00 00 00 05 00 00 00 | | ........ + +0x00B0 | 61 6C 69 63 65 00 00 00 | | alice... + +0x00B8 | 08 00 13 00 08 00 04 00 | | ........ + +0x00C0 | 08 00 00 00 00 80 23 44 | | ......#D + +0x00C8 | 00 00 00 00 00 10 74 40 | | ......t@ + +0x00D0 | 00 00 00 05 03 00 00 00 | | ........ + +0x00D8 | 34 00 00 00 2C 00 00 00 | | 4...,... + +0x00E0 | 04 00 00 00 D2 FE FF FF | | ........ + +0x00E8 | 00 80 23 44 10 00 00 00 | | ..#D.... + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 04 00 04 00 | | ........ + +0x0108 | 04 00 00 00 FA FE FF FF | | ........ + +0x0110 | 00 00 E4 43 10 00 00 00 | | ...C.... + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 03 00 00 00 | | ........ + +0x0130 | 01 02 01 00 03 00 00 00 | | ........ + +0x0138 | 33 33 33 33 33 A3 45 40 | | 33333.E@ + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | | ~W..[.S. + +0x0148 | 8D F0 F6 20 04 B6 42 40 | | ... ..B@ + +0x0150 | 9F 77 63 41 61 85 5E C0 | | .wcAa.^. + +0x0158 | 8F 35 23 83 DC 35 4B C0 | | .5#..5K. + +0x0160 | F6 97 DD 93 87 C5 0A 40 | | .......@ + +0x0168 | 00 00 00 00 03 00 00 00 | | ........ + +0x0170 | 20 00 00 00 14 00 00 00 | | ....... + +0x0178 | 04 00 00 00 07 00 00 00 | | ........ + +0x0180 | 63 68 61 72 6C 69 65 00 | | charlie. + +0x0188 | 03 00 00 00 62 6F 62 00 | | ....bob. + +0x0190 | 05 00 00 00 61 6C 69 63 | | ....alic + +0x0198 | 65 00 00 00 07 00 00 00 | | e....... + +0x01A0 | 63 68 61 72 6C 69 65 00 | | charlie. + +0x01A8 | 07 00 00 00 63 68 61 72 | | ....char + +0x01B0 | 6C 69 65 00 09 00 00 00 | | lie..... + +0x01B8 | 09 00 08 00 07 00 01 00 | | ........ + +0x01C0 | 02 00 03 00 06 00 05 00 | | ........ + +0x01C8 | 04 00 00 00 3A FF FF FF | | ....:... + +0x01D0 | 00 00 00 03 02 00 00 00 | | ........ + +0x01D8 | 44 00 00 00 10 00 00 00 | | D....... + +0x01E0 | 00 00 0A 00 1A 00 0C 00 | | ........ + +0x01E8 | 04 00 08 00 0A 00 00 00 | | ........ + +0x01F0 | 00 80 23 44 18 00 00 00 | | ..#D.... + +0x01F8 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x0200 | 00 00 00 00 00 00 06 00 | | ........ + +0x0208 | 06 00 05 00 06 00 00 00 | | ........ + +0x0210 | 00 03 0A 00 18 00 0C 00 | | ........ + +0x0218 | 04 00 08 00 0A 00 00 00 | | ........ + +0x0220 | 00 00 E4 43 10 00 00 00 | | ...C.... + +0x0228 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0230 | 00 00 00 00 A2 FF FF FF | | ........ + +0x0238 | 00 00 00 01 2F 00 00 00 | | ..../... + +0x0240 | 54 68 69 73 20 69 73 20 | | This is + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E 00 | | aks up.. + +0x0270 | 00 00 0A 00 16 00 0C 00 | | ........ + +0x0278 | 04 00 08 00 0A 00 00 00 | | ........ + +0x0280 | 65 20 71 49 14 00 00 00 | | e qI.... + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | | .v...$.@ + +0x0290 | 00 00 06 00 08 00 07 00 | | ........ + +0x0298 | 06 00 00 00 00 00 00 01 | | ........ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_offset.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_offset.bin new file mode 100644 index 00000000000..c539a01be45 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_offset.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_too_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_too_short.afb new file mode 100644 index 00000000000..2b997717a14 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_too_short.afb @@ -0,0 +1,21 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_root_table_too_short.bin + +header: + +0x00 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x44 | offset to root table `AnnotatedBinary.Foo` + +0x04 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +unknown (no known references): + +0x08 | 00 00 3A 00 68 00 0C 00 | ?uint8_t[60] | ..:.h... | WARN: nothing refers to this section. + +0x10 | 07 00 00 00 08 00 10 00 | | ........ + +0x18 | 14 00 30 00 34 00 09 00 | | ..0.4... + +0x20 | 38 00 3C 00 40 00 44 00 | | 8.<.@.D. + +0x28 | 00 00 00 00 48 00 4C 00 | | ....H.L. + +0x30 | 50 00 54 00 58 00 0A 00 | | P.T.X... + +0x38 | 5C 00 0B 00 60 00 00 00 | | \...`... + +0x40 | 00 00 64 00 | | ..d. + +root_table (AnnotatedBinary.Foo): + +0x44 | 3A 00 | ?uint8_t[2] | :. | ERROR: offset to vtable. Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_too_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_too_short.bin new file mode 100644 index 00000000000..bb1c7fcc0a4 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_too_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_vtable_offset.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_vtable_offset.afb new file mode 100644 index 00000000000..ddb9f3ee71c --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_vtable_offset.afb @@ -0,0 +1,98 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_root_table_vtable_offset.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +unknown (no known references): + +0x0008 | 00 00 3A 00 68 00 0C 00 | ?uint8_t[60] | ..:.h... | WARN: nothing refers to this section. + +0x0010 | 07 00 00 00 08 00 10 00 | | ........ + +0x0018 | 14 00 30 00 34 00 09 00 | | ..0.4... + +0x0020 | 38 00 3C 00 40 00 44 00 | | 8.<.@.D. + +0x0028 | 00 00 00 00 48 00 4C 00 | | ....H.L. + +0x0030 | 50 00 54 00 58 00 0A 00 | | P.T.X... + +0x0038 | 5C 00 0B 00 60 00 00 00 | | \...`... + +0x0040 | 00 00 64 00 | | ..d. + +root_table (AnnotatedBinary.Foo): + +0x0044 | FF FF 00 00 | SOffset32 | 0x0000FFFF (65535) Loc: 0xFFFFFFFFFFFF0045 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0048 | 00 00 00 01 02 02 01 01 | ?uint8_t[600] | ........ | WARN: nothing refers to this section. + +0x0050 | D2 04 00 00 28 02 00 00 | | ....(... + +0x0058 | 01 00 00 00 02 00 00 00 | | ........ + +0x0060 | 0C 00 00 00 0A 00 00 00 | | ........ + +0x0068 | 0C 00 00 00 14 00 00 00 | | ........ + +0x0070 | 01 02 03 00 C8 01 00 00 | | ........ + +0x0078 | 5C 01 00 00 50 01 00 00 | | \...P... + +0x0080 | 34 01 00 00 24 01 00 00 | | 4...$... + +0x0088 | 14 01 00 00 0D 00 00 00 | | ........ + +0x0090 | DC 00 00 00 A0 00 00 00 | | ........ + +0x0098 | 94 00 00 00 38 00 00 00 | | ....8... + +0x00A0 | 33 00 00 00 1C 00 00 00 | | 3....... + +0x00A8 | 04 00 00 00 05 00 00 00 | | ........ + +0x00B0 | 61 6C 69 63 65 00 00 00 | | alice... + +0x00B8 | 08 00 13 00 08 00 04 00 | | ........ + +0x00C0 | 08 00 00 00 00 80 23 44 | | ......#D + +0x00C8 | 00 00 00 00 00 10 74 40 | | ......t@ + +0x00D0 | 00 00 00 05 03 00 00 00 | | ........ + +0x00D8 | 34 00 00 00 2C 00 00 00 | | 4...,... + +0x00E0 | 04 00 00 00 D2 FE FF FF | | ........ + +0x00E8 | 00 80 23 44 10 00 00 00 | | ..#D.... + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 04 00 04 00 | | ........ + +0x0108 | 04 00 00 00 FA FE FF FF | | ........ + +0x0110 | 00 00 E4 43 10 00 00 00 | | ...C.... + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 03 00 00 00 | | ........ + +0x0130 | 01 02 01 00 03 00 00 00 | | ........ + +0x0138 | 33 33 33 33 33 A3 45 40 | | 33333.E@ + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | | ~W..[.S. + +0x0148 | 8D F0 F6 20 04 B6 42 40 | | ... ..B@ + +0x0150 | 9F 77 63 41 61 85 5E C0 | | .wcAa.^. + +0x0158 | 8F 35 23 83 DC 35 4B C0 | | .5#..5K. + +0x0160 | F6 97 DD 93 87 C5 0A 40 | | .......@ + +0x0168 | 00 00 00 00 03 00 00 00 | | ........ + +0x0170 | 20 00 00 00 14 00 00 00 | | ....... + +0x0178 | 04 00 00 00 07 00 00 00 | | ........ + +0x0180 | 63 68 61 72 6C 69 65 00 | | charlie. + +0x0188 | 03 00 00 00 62 6F 62 00 | | ....bob. + +0x0190 | 05 00 00 00 61 6C 69 63 | | ....alic + +0x0198 | 65 00 00 00 07 00 00 00 | | e....... + +0x01A0 | 63 68 61 72 6C 69 65 00 | | charlie. + +0x01A8 | 07 00 00 00 63 68 61 72 | | ....char + +0x01B0 | 6C 69 65 00 09 00 00 00 | | lie..... + +0x01B8 | 09 00 08 00 07 00 01 00 | | ........ + +0x01C0 | 02 00 03 00 06 00 05 00 | | ........ + +0x01C8 | 04 00 00 00 3A FF FF FF | | ....:... + +0x01D0 | 00 00 00 03 02 00 00 00 | | ........ + +0x01D8 | 44 00 00 00 10 00 00 00 | | D....... + +0x01E0 | 00 00 0A 00 1A 00 0C 00 | | ........ + +0x01E8 | 04 00 08 00 0A 00 00 00 | | ........ + +0x01F0 | 00 80 23 44 18 00 00 00 | | ..#D.... + +0x01F8 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x0200 | 00 00 00 00 00 00 06 00 | | ........ + +0x0208 | 06 00 05 00 06 00 00 00 | | ........ + +0x0210 | 00 03 0A 00 18 00 0C 00 | | ........ + +0x0218 | 04 00 08 00 0A 00 00 00 | | ........ + +0x0220 | 00 00 E4 43 10 00 00 00 | | ...C.... + +0x0228 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0230 | 00 00 00 00 A2 FF FF FF | | ........ + +0x0238 | 00 00 00 01 2F 00 00 00 | | ..../... + +0x0240 | 54 68 69 73 20 69 73 20 | | This is + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E 00 | | aks up.. + +0x0270 | 00 00 0A 00 16 00 0C 00 | | ........ + +0x0278 | 04 00 08 00 0A 00 00 00 | | ........ + +0x0280 | 65 20 71 49 14 00 00 00 | | e qI.... + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | | .v...$.@ + +0x0290 | 00 00 06 00 08 00 07 00 | | ........ + +0x0298 | 06 00 00 00 00 00 00 01 | | ........ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_vtable_offset.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_vtable_offset.bin new file mode 100644 index 00000000000..a3075ea0d5e Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_root_table_vtable_offset.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length.afb new file mode 100644 index 00000000000..78ab59c2c3f --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length.afb @@ -0,0 +1,295 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_string_length.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | offset to field `bar` (table) + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | FF FF 00 00 | uint32_t | 0x0000FFFF (65535) | ERROR: length of string. Longer than the binary. + +unknown (no known references): + +0x00B0 | 61 6C 69 63 65 00 00 00 | ?uint8_t[8] | alice... | WARN: nothing refers to this section. + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0298 | offset to field `c` (table) + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123457) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length.bin new file mode 100644 index 00000000000..c4ef6788a49 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length_cut_short.afb new file mode 100644 index 00000000000..060938db5ba --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length_cut_short.afb @@ -0,0 +1,80 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_string_length_cut_short.bin + +header: + +0x00 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x44 | offset to root table `AnnotatedBinary.Foo` + +0x04 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x08 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x0A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x0C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x0E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x10 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x12 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x14 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x16 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x18 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x1A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x1C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x1E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x20 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x22 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x24 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x26 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x44 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x0A | offset to vtable + +0x48 | 00 00 00 | uint8_t[3] | ... | padding + +0x4B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x4C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x4D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x4E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x4F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x50 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x54 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x27C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x5C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x60 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x64 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x68 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x6C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x70 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x71 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x72 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x73 | 00 | uint8_t[1] | . | padding + +0x74 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x23C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x78 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x1D4 | ERROR: offset to field `bars`. Invalid offset, points outside the binary. + +0x7C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x1CC | ERROR: offset to field `bar_baz`. Invalid offset, points outside the binary. + +0x80 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x1B4 | ERROR: offset to field `accounts`. Invalid offset, points outside the binary. + +0x84 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x1A8 | ERROR: offset to field `bob`. Invalid offset, points outside the binary. + +0x88 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x19C | ERROR: offset to field `alice`. Invalid offset, points outside the binary. + +0x8C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x90 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x16C | ERROR: offset to field `names`. Invalid offset, points outside the binary. + +0x94 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x134 | ERROR: offset to field `points_of_interest`. Invalid offset, points outside the binary. + +0x98 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x12C | ERROR: offset to field `foobars_type`. Invalid offset, points outside the binary. + +0x9C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0xD4 | ERROR: offset to field `foobars`. Invalid offset, points outside the binary. + +0xA0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0xD3 | ERROR: offset to field `measurement`. Invalid offset, points outside the binary. + +0xA4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0xC0 | ERROR: offset to field `anything`. Invalid offset, points outside the binary. + +0xA8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0xAC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0xAC | 05 00 | ?uint8_t[2] | .. | ERROR: length of string. Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length_cut_short.bin new file mode 100644 index 00000000000..69f7e11eaa2 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_string_length_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_array_field_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_array_field_cut_short.afb new file mode 100644 index 00000000000..48226a106a0 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_array_field_cut_short.afb @@ -0,0 +1,72 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_struct_array_field_cut_short.bin + +header: + +0x00 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x44 | offset to root table `AnnotatedBinary.Foo` + +0x04 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x08 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x0A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x0C | 68 00 | uint16_t | 0x0068 (104) | ERROR: size of referring table. Longer than the binary. + +0x0E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x10 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x12 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x14 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x16 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x18 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x1A | 30 00 | VOffset16 | 0x0030 (48) | ERROR: offset to field `name` (id: 6). Invalid offset, points outside the binary. + +0x1C | 34 00 | VOffset16 | 0x0034 (52) | ERROR: offset to field `bars` (id: 7). Invalid offset, points outside the binary. + +0x1E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x20 | 38 00 | VOffset16 | 0x0038 (56) | ERROR: offset to field `bar_baz` (id: 9). Invalid offset, points outside the binary. + +0x22 | 3C 00 | VOffset16 | 0x003C (60) | ERROR: offset to field `accounts` (id: 10). Invalid offset, points outside the binary. + +0x24 | 40 00 | VOffset16 | 0x0040 (64) | ERROR: offset to field `bob` (id: 11). Invalid offset, points outside the binary. + +0x26 | 44 00 | VOffset16 | 0x0044 (68) | ERROR: offset to field `alice` (id: 12). Invalid offset, points outside the binary. + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | ERROR: offset to field `just_i32` (id: 15). Invalid offset, points outside the binary. + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | ERROR: offset to field `names` (id: 16). Invalid offset, points outside the binary. + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | ERROR: offset to field `points_of_interest` (id: 17). Invalid offset, points outside the binary. + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | ERROR: offset to field `foobars_type` (id: 18). Invalid offset, points outside the binary. + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | ERROR: offset to field `foobars` (id: 19). Invalid offset, points outside the binary. + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | ERROR: offset to field `measurement` (id: 21). Invalid offset, points outside the binary. + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | ERROR: offset to field `anything` (id: 23). Invalid offset, points outside the binary. + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | ERROR: offset to field `charlie` (id: 26). Invalid offset, points outside the binary. + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 13) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 14) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | offset to unknown field (id: 15) + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | offset to unknown field (id: 16) + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | offset to unknown field (id: 17) + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | offset to unknown field (id: 18) + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | offset to unknown field (id: 19) + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to unknown field (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | offset to unknown field (id: 21) + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to unknown field (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | offset to unknown field (id: 23) + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 24) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 25) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | offset to unknown field (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x44 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x0A | offset to vtable + +0x48 | 00 00 00 | uint8_t[3] | ... | padding + +0x4B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x4C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x4D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x4E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x4F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x50 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x54 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x27C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x5C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x60 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x64 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x68 | 0C 00 | ?uint8_t[2] | .. | ERROR: array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int). Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_array_field_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_array_field_cut_short.bin new file mode 100644 index 00000000000..b701f73551e Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_array_field_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_field_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_field_cut_short.afb new file mode 100644 index 00000000000..eafef0e7f2f --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_field_cut_short.afb @@ -0,0 +1,69 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_struct_field_cut_short.bin + +header: + +0x00 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x44 | offset to root table `AnnotatedBinary.Foo` + +0x04 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x08 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x0A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x0C | 68 00 | uint16_t | 0x0068 (104) | ERROR: size of referring table. Longer than the binary. + +0x0E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x10 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x12 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x14 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x16 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x18 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x1A | 30 00 | VOffset16 | 0x0030 (48) | ERROR: offset to field `name` (id: 6). Invalid offset, points outside the binary. + +0x1C | 34 00 | VOffset16 | 0x0034 (52) | ERROR: offset to field `bars` (id: 7). Invalid offset, points outside the binary. + +0x1E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x20 | 38 00 | VOffset16 | 0x0038 (56) | ERROR: offset to field `bar_baz` (id: 9). Invalid offset, points outside the binary. + +0x22 | 3C 00 | VOffset16 | 0x003C (60) | ERROR: offset to field `accounts` (id: 10). Invalid offset, points outside the binary. + +0x24 | 40 00 | VOffset16 | 0x0040 (64) | ERROR: offset to field `bob` (id: 11). Invalid offset, points outside the binary. + +0x26 | 44 00 | VOffset16 | 0x0044 (68) | ERROR: offset to field `alice` (id: 12). Invalid offset, points outside the binary. + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | ERROR: offset to field `just_i32` (id: 15). Invalid offset, points outside the binary. + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | ERROR: offset to field `names` (id: 16). Invalid offset, points outside the binary. + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | ERROR: offset to field `points_of_interest` (id: 17). Invalid offset, points outside the binary. + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | ERROR: offset to field `foobars_type` (id: 18). Invalid offset, points outside the binary. + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | ERROR: offset to field `foobars` (id: 19). Invalid offset, points outside the binary. + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | ERROR: offset to field `measurement` (id: 21). Invalid offset, points outside the binary. + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | ERROR: offset to field `anything` (id: 23). Invalid offset, points outside the binary. + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | ERROR: offset to field `charlie` (id: 26). Invalid offset, points outside the binary. + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 13) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 14) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | offset to unknown field (id: 15) + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | offset to unknown field (id: 16) + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | offset to unknown field (id: 17) + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | offset to unknown field (id: 18) + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | offset to unknown field (id: 19) + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to unknown field (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | offset to unknown field (id: 21) + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to unknown field (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | offset to unknown field (id: 23) + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 24) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 25) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | offset to unknown field (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x44 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x0A | offset to vtable + +0x48 | 00 00 00 | uint8_t[3] | ... | padding + +0x4B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x4C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x4D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x4E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x4F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x50 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x54 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x27C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x5C | 02 00 | ?uint8_t[2] | .. | ERROR: struct field `home.doors` of 'AnnotatedBinary.Building' (Int). Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_field_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_field_cut_short.bin new file mode 100644 index 00000000000..537352dbfb8 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_struct_field_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_offset.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_offset.afb new file mode 100644 index 00000000000..4268d024330 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_offset.afb @@ -0,0 +1,77 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_table_field_offset.bin + +header: + +0x00 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x44 | offset to root table `AnnotatedBinary.Foo` + +0x04 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x08 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x0A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x0C | 68 00 | uint16_t | 0x0068 (104) | ERROR: size of referring table. Longer than the binary. + +0x0E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x10 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x12 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x14 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x16 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x18 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x1A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x1C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x1E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x20 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x22 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x24 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x26 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | ERROR: offset to field `foobars_type` (id: 18). Invalid offset, points outside the binary. + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | ERROR: offset to field `foobars` (id: 19). Invalid offset, points outside the binary. + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | ERROR: offset to field `measurement` (id: 21). Invalid offset, points outside the binary. + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | ERROR: offset to field `anything` (id: 23). Invalid offset, points outside the binary. + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | ERROR: offset to field `charlie` (id: 26). Invalid offset, points outside the binary. + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to unknown field (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | offset to unknown field (id: 23) + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 24) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 25) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | offset to unknown field (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x44 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x0A | offset to vtable + +0x48 | 00 00 00 | uint8_t[3] | ... | padding + +0x4B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x4C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x4D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x4E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x4F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x50 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x54 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x27C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x5C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x60 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x64 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x68 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x6C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x70 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x71 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x72 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x73 | 00 | uint8_t[1] | . | padding + +0x74 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x23C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x78 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x1D4 | ERROR: offset to field `bars`. Invalid offset, points outside the binary. + +0x7C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x1CC | ERROR: offset to field `bar_baz`. Invalid offset, points outside the binary. + +0x80 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x1B4 | ERROR: offset to field `accounts`. Invalid offset, points outside the binary. + +0x84 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x1A8 | ERROR: offset to field `bob`. Invalid offset, points outside the binary. + +0x88 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x19C | ERROR: offset to field `alice`. Invalid offset, points outside the binary. + +0x8C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x90 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x16C | ERROR: offset to field `names`. Invalid offset, points outside the binary. + +0x94 | A0 00 | ?uint8_t[2] | .. | ERROR: offset to field `points_of_interest`. Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_offset.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_offset.bin new file mode 100644 index 00000000000..f3a79edf6fe Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_offset.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_size.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_size.afb new file mode 100644 index 00000000000..677493fda12 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_size.afb @@ -0,0 +1,68 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_table_field_size.bin + +header: + +0x00 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x44 | offset to root table `AnnotatedBinary.Foo` + +0x04 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x08 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x0A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x0C | 68 00 | uint16_t | 0x0068 (104) | ERROR: size of referring table. Longer than the binary. + +0x0E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x10 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x12 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x14 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x16 | 10 00 | VOffset16 | 0x0010 (16) | ERROR: offset to field `bar` (id: 4). Invalid offset, points outside the binary. + +0x18 | 14 00 | VOffset16 | 0x0014 (20) | ERROR: offset to field `home` (id: 5). Invalid offset, points outside the binary. + +0x1A | 30 00 | VOffset16 | 0x0030 (48) | ERROR: offset to field `name` (id: 6). Invalid offset, points outside the binary. + +0x1C | 34 00 | VOffset16 | 0x0034 (52) | ERROR: offset to field `bars` (id: 7). Invalid offset, points outside the binary. + +0x1E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x20 | 38 00 | VOffset16 | 0x0038 (56) | ERROR: offset to field `bar_baz` (id: 9). Invalid offset, points outside the binary. + +0x22 | 3C 00 | VOffset16 | 0x003C (60) | ERROR: offset to field `accounts` (id: 10). Invalid offset, points outside the binary. + +0x24 | 40 00 | VOffset16 | 0x0040 (64) | ERROR: offset to field `bob` (id: 11). Invalid offset, points outside the binary. + +0x26 | 44 00 | VOffset16 | 0x0044 (68) | ERROR: offset to field `alice` (id: 12). Invalid offset, points outside the binary. + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | ERROR: offset to field `just_i32` (id: 15). Invalid offset, points outside the binary. + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | ERROR: offset to field `names` (id: 16). Invalid offset, points outside the binary. + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | ERROR: offset to field `points_of_interest` (id: 17). Invalid offset, points outside the binary. + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | ERROR: offset to field `foobars_type` (id: 18). Invalid offset, points outside the binary. + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | ERROR: offset to field `foobars` (id: 19). Invalid offset, points outside the binary. + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | ERROR: offset to field `measurement` (id: 21). Invalid offset, points outside the binary. + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | ERROR: offset to field `anything` (id: 23). Invalid offset, points outside the binary. + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | ERROR: offset to field `charlie` (id: 26). Invalid offset, points outside the binary. + +0x24 | 40 00 | VOffset16 | 0x0040 (64) | offset to unknown field (id: 11) + +0x26 | 44 00 | VOffset16 | 0x0044 (68) | offset to unknown field (id: 12) + +0x28 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 13) + +0x2A | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 14) + +0x2C | 48 00 | VOffset16 | 0x0048 (72) | offset to unknown field (id: 15) + +0x2E | 4C 00 | VOffset16 | 0x004C (76) | offset to unknown field (id: 16) + +0x30 | 50 00 | VOffset16 | 0x0050 (80) | offset to unknown field (id: 17) + +0x32 | 54 00 | VOffset16 | 0x0054 (84) | offset to unknown field (id: 18) + +0x34 | 58 00 | VOffset16 | 0x0058 (88) | offset to unknown field (id: 19) + +0x36 | 0A 00 | VOffset16 | 0x000A (10) | offset to unknown field (id: 20) + +0x38 | 5C 00 | VOffset16 | 0x005C (92) | offset to unknown field (id: 21) + +0x3A | 0B 00 | VOffset16 | 0x000B (11) | offset to unknown field (id: 22) + +0x3C | 60 00 | VOffset16 | 0x0060 (96) | offset to unknown field (id: 23) + +0x3E | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 24) + +0x40 | 00 00 | VOffset16 | 0x0000 (0) | offset to unknown field (id: 25) + +0x42 | 64 00 | VOffset16 | 0x0064 (100) | offset to unknown field (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x44 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x0A | offset to vtable + +0x48 | 00 00 00 | uint8_t[3] | ... | padding + +0x4B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x4C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x4D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x4E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x4F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x50 | D2 04 | ?uint8_t[2] | .. | ERROR: table field `counter` (Int). Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_size.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_size.bin new file mode 100644 index 00000000000..4fbbbdfed45 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_table_field_size.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_union_type_value.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_union_type_value.afb new file mode 100644 index 00000000000..0b9c3c27afc --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_union_type_value.afb @@ -0,0 +1,293 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_union_type_value.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | FF | UType8 | 0xFF (255) | ERROR: table field `bar_baz_type` (UType). Invalid union type value. + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | offset to field `bar` (table) + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | ?uint8_t[4] | P... | WARN: nothing refers to this section. + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +unknown (no known references): + +0x01CA | 00 00 3A FF FF FF 00 00 | ?uint8_t[10] | ..:..... | WARN: nothing refers to this section. + +0x01D2 | 00 03 | | .. + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0298 | offset to field `c` (table) + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123457) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_union_type_value.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_union_type_value.bin new file mode 100644 index 00000000000..22f2dd5ed29 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_union_type_value.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_length_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_length_cut_short.afb new file mode 100644 index 00000000000..fc8656b7497 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_length_cut_short.afb @@ -0,0 +1,140 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_length_cut_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | ERROR: offset to field `bars`. Invalid offset, points outside the binary. + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | ERROR: offset to field `bar_baz`. Invalid offset, points outside the binary. + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | ERROR: offset to field `accounts`. Invalid offset, points outside the binary. + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | ERROR: offset to field `bob`. Invalid offset, points outside the binary. + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | ERROR: offset to field `alice`. Invalid offset, points outside the binary. + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | ERROR: offset to field `names`. Invalid offset, points outside the binary. + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x00E8 | 00 80 23 44 10 00 00 00 | ?uint8_t[28] | ..#D.... | WARN: nothing refers to this section. + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 | | .... + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0110 | 00 00 E4 43 10 00 00 00 | ?uint8_t[28] | ...C.... | WARN: nothing refers to this section. + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 | | .... + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 | ?uint8_t[2] | .. | ERROR: length of vector (# items). Incomplete binary, expected to read 4 bytes. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_length_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_length_cut_short.bin new file mode 100644 index 00000000000..2d622dae144 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_length_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_scalars_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_scalars_cut_short.afb new file mode 100644 index 00000000000..a7640d5c805 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_scalars_cut_short.afb @@ -0,0 +1,190 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_scalars_cut_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | ERROR: offset to field `bars`. Invalid offset, points outside the binary. + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | ERROR: offset to field `bar_baz`. Invalid offset, points outside the binary. + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x00E8 | 00 80 23 44 10 00 00 00 | ?uint8_t[28] | ..#D.... | WARN: nothing refers to this section. + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 | | .... + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0110 | 00 00 E4 43 10 00 00 00 | ?uint8_t[28] | ...C.... | WARN: nothing refers to this section. + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 | | .... + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | ERROR: length of vector (# items). Longer than the binary. + +unknown (no known references): + +0x01B8 | 09 00 08 00 07 00 01 00 | ?uint8_t[9] | ........ | WARN: nothing refers to this section. + +0x01C0 | 02 | | . diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_scalars_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_scalars_cut_short.bin new file mode 100644 index 00000000000..79dc7969b98 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_scalars_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_strings_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_strings_cut_short.afb new file mode 100644 index 00000000000..a9ef88970c5 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_strings_cut_short.afb @@ -0,0 +1,155 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_strings_cut_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | ERROR: offset to field `bars`. Invalid offset, points outside the binary. + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | ERROR: offset to field `bar_baz`. Invalid offset, points outside the binary. + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | ERROR: offset to field `accounts`. Invalid offset, points outside the binary. + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | ERROR: offset to field `bob`. Invalid offset, points outside the binary. + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | ERROR: offset to field `alice`. Invalid offset, points outside the binary. + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x00E8 | 00 80 23 44 10 00 00 00 | ?uint8_t[28] | ..#D.... | WARN: nothing refers to this section. + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 | | .... + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0110 | 00 00 E4 43 10 00 00 00 | ?uint8_t[28] | ...C.... | WARN: nothing refers to this section. + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 | | .... + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | ERROR: length of vector (# items). Longer than the binary. + +unknown (no known references): + +0x0170 | 20 00 00 00 14 00 | ?uint8_t[6] | ..... | WARN: could be corrupted padding region. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_strings_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_strings_cut_short.bin new file mode 100644 index 00000000000..434aba1541a Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_strings_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_structs_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_structs_cut_short.afb new file mode 100644 index 00000000000..552b5fe64ce --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_structs_cut_short.afb @@ -0,0 +1,146 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_structs_cut_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | ERROR: offset to field `bars`. Invalid offset, points outside the binary. + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | ERROR: offset to field `bar_baz`. Invalid offset, points outside the binary. + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | ERROR: offset to field `accounts`. Invalid offset, points outside the binary. + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | ERROR: offset to field `bob`. Invalid offset, points outside the binary. + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | ERROR: offset to field `alice`. Invalid offset, points outside the binary. + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | ERROR: offset to field `names`. Invalid offset, points outside the binary. + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x00E8 | 00 80 23 44 10 00 00 00 | ?uint8_t[28] | ..#D.... | WARN: nothing refers to this section. + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 | | .... + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0110 | 00 00 E4 43 10 00 00 00 | ?uint8_t[28] | ...C.... | WARN: nothing refers to this section. + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 | | .... + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | ERROR: length of vector (# items). Longer than the binary. + +unknown (no known references): + +0x0138 | 33 33 33 33 33 A3 45 40 | ?uint8_t[28] | 33333.E@ | WARN: nothing refers to this section. + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | | ~W..[.S. + +0x0148 | 8D F0 F6 20 04 B6 42 40 | | ... ..B@ + +0x0150 | 9F 77 63 41 | | .wcA diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_structs_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_structs_cut_short.bin new file mode 100644 index 00000000000..44da4088b55 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_structs_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_tables_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_tables_cut_short.afb new file mode 100644 index 00000000000..00baa8a0ad7 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_tables_cut_short.afb @@ -0,0 +1,210 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_tables_cut_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x00E8 | 00 80 23 44 10 00 00 00 | ?uint8_t[28] | ..#D.... | WARN: nothing refers to this section. + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 | | .... + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0110 | 00 00 E4 43 10 00 00 00 | ?uint8_t[28] | ...C.... | WARN: nothing refers to this section. + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 | | .... + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x01D0 | 00 00 00 03 | ?uint8_t[4] | .... | WARN: could be corrupted padding region. + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | ERROR: length of vector (# items). Longer than the binary. + +unknown (no known references): + +0x01D8 | 44 00 00 00 10 00 | ?uint8_t[6] | D..... | WARN: could be corrupted padding region. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_tables_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_tables_cut_short.bin new file mode 100644 index 00000000000..2823d83ef92 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_tables_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_union_type_value.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_union_type_value.afb new file mode 100644 index 00000000000..9300d3fac20 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_union_type_value.afb @@ -0,0 +1,293 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_union_type_value.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | offset to field `bar` (table) + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | ?uint8_t[4] | ,... | WARN: nothing refers to this section. + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +unknown (no known references): + +0x0104 | 04 00 04 00 04 00 00 00 | ?uint8_t[8] | ........ | WARN: nothing refers to this section. + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | FF | UType8 | 0xFF (255) | ERROR: value[1]. Invalid union type value. + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0298 | offset to field `c` (table) + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123457) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_union_type_value.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_union_type_value.bin new file mode 100644 index 00000000000..8725971fd13 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_union_type_value.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_unions_cut_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_unions_cut_short.afb new file mode 100644 index 00000000000..4d5f71c9d88 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_unions_cut_short.afb @@ -0,0 +1,210 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vector_unions_cut_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | ERROR: offset to field `bar`. Invalid offset, points outside the binary. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | ERROR: offset to field `name`. Invalid offset, points outside the binary. + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x00E8 | 00 80 23 44 10 00 00 00 | ?uint8_t[28] | ..#D.... | WARN: nothing refers to this section. + +0x00F0 | 00 00 00 00 00 D8 8E 40 | | .......@ + +0x00F8 | 00 00 00 00 6A FE FF FF | | ....j... + +0x0100 | 00 00 00 03 | | .... + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x0110 | 00 00 E4 43 10 00 00 00 | ?uint8_t[28] | ...C.... | WARN: nothing refers to this section. + +0x0118 | 00 00 00 00 00 C0 5E 40 | | ......^@ + +0x0120 | 00 00 00 00 92 FE FF FF | | ........ + +0x0128 | 00 00 00 01 | | .... + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | ERROR: offset to vtable. Invalid offset, points outside the binary. + +unknown (no known references): + +0x01D0 | 00 00 00 03 | ?uint8_t[4] | .... | WARN: could be corrupted padding region. + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | ERROR: length of vector (# items). Longer than the binary. + +unknown (no known references): + +0x01D8 | 44 00 00 00 10 00 | ?uint8_t[6] | D..... | WARN: could be corrupted padding region. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_unions_cut_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_unions_cut_short.bin new file mode 100644 index 00000000000..2823d83ef92 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vector_unions_cut_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_field_offset.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_field_offset.afb new file mode 100644 index 00000000000..cbd73d7895d --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_field_offset.afb @@ -0,0 +1,286 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vtable_field_offset.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 68 00 | uint16_t | 0x0068 (104) | size of referring table + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | FF FF | VOffset16 | 0xFFFF (65535) | ERROR: offset to field `bar` (id: 4). Invalid offset, points outside the binary. + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to unknown field (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | ?uint8_t[4] | (... | WARN: nothing refers to this section. + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +unknown (no known references): + +0x0270 | 00 00 0A 00 16 00 0C 00 | ?uint8_t[34] | ........ | WARN: nothing refers to this section. + +0x0278 | 04 00 08 00 0A 00 00 00 | | ........ + +0x0280 | 65 20 71 49 14 00 00 00 | | e qI.... + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | | .v...$.@ + +0x0290 | 00 00 | | .. + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +unknown (no known references): + +0x0298 | 06 00 00 00 00 00 00 01 | ?uint8_t[8] | ........ | WARN: nothing refers to this section. diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_field_offset.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_field_offset.bin new file mode 100644 index 00000000000..e32ce5be8a8 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_field_offset.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size.afb new file mode 100644 index 00000000000..f7ffc8b90de --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size.afb @@ -0,0 +1,360 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vtable_ref_table_size.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | FF FF | uint16_t | 0xFFFF (65535) | ERROR: size of referring table. Longer than the binary. + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | offset to field `bar` (table) + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +0x00AC | 05 00 00 00 61 6C 69 63 | uint8_t[500] | ....alic | padding + +0x00B4 | 65 00 00 00 08 00 13 00 | | e....... + +0x00BC | 08 00 04 00 08 00 00 00 | | ........ + +0x00C4 | 00 80 23 44 00 00 00 00 | | ..#D.... + +0x00CC | 00 10 74 40 00 00 00 05 | | ..t@.... + +0x00D4 | 03 00 00 00 34 00 00 00 | | ....4... + +0x00DC | 2C 00 00 00 04 00 00 00 | | ,....... + +0x00E4 | D2 FE FF FF 00 80 23 44 | | ......#D + +0x00EC | 10 00 00 00 00 00 00 00 | | ........ + +0x00F4 | 00 D8 8E 40 00 00 00 00 | | ...@.... + +0x00FC | 6A FE FF FF 00 00 00 03 | | j....... + +0x0104 | 04 00 04 00 04 00 00 00 | | ........ + +0x010C | FA FE FF FF 00 00 E4 43 | | .......C + +0x0114 | 10 00 00 00 00 00 00 00 | | ........ + +0x011C | 00 C0 5E 40 00 00 00 00 | | ..^@.... + +0x0124 | 92 FE FF FF 00 00 00 01 | | ........ + +0x012C | 03 00 00 00 01 02 01 00 | | ........ + +0x0134 | 03 00 00 00 33 33 33 33 | | ....3333 + +0x013C | 33 A3 45 40 7E 57 04 FF | | 3.E@~W.. + +0x0144 | 5B 87 53 C0 8D F0 F6 20 | | [.S.... + +0x014C | 04 B6 42 40 9F 77 63 41 | | ..B@.wcA + +0x0154 | 61 85 5E C0 8F 35 23 83 | | a.^..5#. + +0x015C | DC 35 4B C0 F6 97 DD 93 | | .5K..... + +0x0164 | 87 C5 0A 40 00 00 00 00 | | ...@.... + +0x016C | 03 00 00 00 20 00 00 00 | | .... ... + +0x0174 | 14 00 00 00 04 00 00 00 | | ........ + +0x017C | 07 00 00 00 63 68 61 72 | | ....char + +0x0184 | 6C 69 65 00 03 00 00 00 | | lie..... + +0x018C | 62 6F 62 00 05 00 00 00 | | bob..... + +0x0194 | 61 6C 69 63 65 00 00 00 | | alice... + +0x019C | 07 00 00 00 63 68 61 72 | | ....char + +0x01A4 | 6C 69 65 00 07 00 00 00 | | lie..... + +0x01AC | 63 68 61 72 6C 69 65 00 | | charlie. + +0x01B4 | 09 00 00 00 09 00 08 00 | | ........ + +0x01BC | 07 00 01 00 02 00 03 00 | | ........ + +0x01C4 | 06 00 05 00 04 00 00 00 | | ........ + +0x01CC | 3A FF FF FF 00 00 00 03 | | :....... + +0x01D4 | 02 00 00 00 44 00 00 00 | | ....D... + +0x01DC | 10 00 00 00 00 00 0A 00 | | ........ + +0x01E4 | 1A 00 0C 00 04 00 08 00 | | ........ + +0x01EC | 0A 00 00 00 00 80 23 44 | | ......#D + +0x01F4 | 18 00 00 00 00 00 00 00 | | ........ + +0x01FC | 00 D8 8E 40 00 00 00 00 | | ...@.... + +0x0204 | 00 00 06 00 06 00 05 00 | | ........ + +0x020C | 06 00 00 00 00 03 0A 00 | | ........ + +0x0214 | 18 00 0C 00 04 00 08 00 | | ........ + +0x021C | 0A 00 00 00 00 00 E4 43 | | .......C + +0x0224 | 10 00 00 00 00 00 00 00 | | ........ + +0x022C | 00 C0 5E 40 00 00 00 00 | | ..^@.... + +0x0234 | A2 FF FF FF 00 00 00 01 | | ........ + +0x023C | 2F 00 00 00 54 68 69 73 | | /...This + +0x0244 | 20 69 73 20 61 20 6C 6F | | is a lo + +0x024C | 6E 67 20 73 74 72 69 6E | | ng strin + +0x0254 | 67 20 74 6F 20 73 68 6F | | g to sho + +0x025C | 77 20 68 6F 77 20 69 74 | | w how it + +0x0264 | 20 62 72 65 61 6B 73 20 | | breaks + +0x026C | 75 70 2E 00 00 00 0A 00 | | up...... + +0x0274 | 16 00 0C 00 04 00 08 00 | | ........ + +0x027C | 0A 00 00 00 65 20 71 49 | | ....e qI + +0x0284 | 14 00 00 00 C9 76 BE 9F | | .....v.. + +0x028C | 0C 24 FE 40 00 00 06 00 | | .$.@.... + +0x0294 | 08 00 07 00 06 00 00 00 | | ........ + +0x029C | 00 00 00 01 | | .... + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0298 | offset to field `c` (table) + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123457) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size.bin new file mode 100644 index 00000000000..6b5024224fa Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size_short.afb new file mode 100644 index 00000000000..a6ec6b07a8e --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size_short.afb @@ -0,0 +1,297 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vtable_ref_table_size_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 3A 00 | uint16_t | 0x003A (58) | size of this vtable + +0x000C | 01 00 | uint16_t | 0x0001 (1) | ERROR: size of referring table. Shorter than the minimum length: + +0x000E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `counter` (id: 0) + +0x0010 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `healthy` (id: 1) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `level` (id: 2) (Long) + +0x0014 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `meal` (id: 3) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `bar` (id: 4) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `home` (id: 5) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `name` (id: 6) + +0x001C | 34 00 | VOffset16 | 0x0034 (52) | offset to field `bars` (id: 7) + +0x001E | 09 00 | VOffset16 | 0x0009 (9) | offset to field `bar_baz_type` (id: 8) + +0x0020 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `bar_baz` (id: 9) + +0x0022 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `accounts` (id: 10) + +0x0024 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `bob` (id: 11) + +0x0026 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `alice` (id: 12) + +0x0028 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `maybe_i32` (id: 13) (Int) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_i32` (id: 14) (Int) + +0x002C | 48 00 | VOffset16 | 0x0048 (72) | offset to field `just_i32` (id: 15) + +0x002E | 4C 00 | VOffset16 | 0x004C (76) | offset to field `names` (id: 16) + +0x0030 | 50 00 | VOffset16 | 0x0050 (80) | offset to field `points_of_interest` (id: 17) + +0x0032 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `foobars_type` (id: 18) + +0x0034 | 58 00 | VOffset16 | 0x0058 (88) | offset to field `foobars` (id: 19) + +0x0036 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `measurement_type` (id: 20) + +0x0038 | 5C 00 | VOffset16 | 0x005C (92) | offset to field `measurement` (id: 21) + +0x003A | 0B 00 | VOffset16 | 0x000B (11) | offset to field `anything_type` (id: 22) + +0x003C | 60 00 | VOffset16 | 0x0060 (96) | offset to field `anything` (id: 23) + +0x003E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `temperature` (id: 24) (Float) + +0x0040 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `teetotaler` (id: 25) (Obj) + +0x0042 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `charlie` (id: 26) + +root_table (AnnotatedBinary.Foo): + +0x0044 | 3A 00 00 00 | SOffset32 | 0x0000003A (58) Loc: 0x000A | offset to vtable + +0x0048 | 00 00 00 | uint8_t[3] | ... | padding + +0x004B | 01 | uint8_t | 0x01 (1) | table field `healthy` (Bool) + +0x004C | 02 | uint8_t | 0x02 (2) | table field `meal` (Byte) + +0x004D | 02 | UType8 | 0x02 (2) | table field `bar_baz_type` (UType) + +0x004E | 01 | UType8 | 0x01 (1) | table field `measurement_type` (UType) + +0x004F | 01 | UType8 | 0x01 (1) | table field `anything_type` (UType) + +0x0050 | D2 04 00 00 | uint32_t | 0x000004D2 (1234) | table field `counter` (Int) + +0x0054 | 28 02 00 00 | UOffset32 | 0x00000228 (552) Loc: 0x027C | offset to field `bar` (table) + +0x0058 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `home.floors` of 'AnnotatedBinary.Building' (Int) + +0x005C | 02 00 00 00 | uint32_t | 0x00000002 (2) | struct field `home.doors` of 'AnnotatedBinary.Building' (Int) + +0x0060 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `home.windows` of 'AnnotatedBinary.Building' (Int) + +0x0064 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | array field `home.dimensions.values`[0] of 'AnnotatedBinary.Dimension' (Int) + +0x0068 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | array field `home.dimensions.values`[1] of 'AnnotatedBinary.Dimension' (Int) + +0x006C | 14 00 00 00 | uint32_t | 0x00000014 (20) | array field `home.dimensions.values`[2] of 'AnnotatedBinary.Dimension' (Int) + +0x0070 | 01 | uint8_t | 0x01 (1) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0071 | 02 | uint8_t | 0x02 (2) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0072 | 03 | uint8_t | 0x03 (3) | struct field `home.dimensions.tolerances.width` of 'AnnotatedBinary.Tolerance' (UByte) + +0x0073 | 00 | uint8_t[1] | . | padding + +0x0074 | C8 01 00 00 | UOffset32 | 0x000001C8 (456) Loc: 0x023C | offset to field `name` (string) + +0x0078 | 5C 01 00 00 | UOffset32 | 0x0000015C (348) Loc: 0x01D4 | offset to field `bars` (vector) + +0x007C | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x01CC | offset to field `bar_baz` (union of type `Baz`) + +0x0080 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x01B4 | offset to field `accounts` (vector) + +0x0084 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x01A8 | offset to field `bob` (string) + +0x0088 | 14 01 00 00 | UOffset32 | 0x00000114 (276) Loc: 0x019C | offset to field `alice` (string) + +0x008C | 0D 00 00 00 | uint32_t | 0x0000000D (13) | table field `just_i32` (Int) + +0x0090 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x016C | offset to field `names` (vector) + +0x0094 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0134 | offset to field `points_of_interest` (vector) + +0x0098 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x012C | offset to field `foobars_type` (vector) + +0x009C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00D4 | offset to field `foobars` (vector) + +0x00A0 | 33 00 00 00 | UOffset32 | 0x00000033 (51) Loc: 0x00D3 | offset to field `measurement` (union of type `Tolerance`) + +0x00A4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00C0 | offset to field `anything` (union of type `Bar`) + +0x00A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00AC | offset to field `charlie` (string) + +string (AnnotatedBinary.Foo.charlie): + +0x00AC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x00B0 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x00B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x00B6 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x00B8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x00BA | 13 00 | uint16_t | 0x0013 (19) | size of referring table + +0x00BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `a` (id: 0) + +0x00BE | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +table (AnnotatedBinary.Bar): + +0x00C0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x00B8 | offset to vtable + +0x00C4 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00C8 | 00 00 00 00 00 10 74 40 | double | 0x4074100000000000 (321) | table field `a` (Double) + +0x00D0 | 00 00 00 | uint8_t[3] | ... | padding + +union (AnnotatedBinary.Tolerance.measurement): + +0x00D3 | 05 | uint8_t | 0x05 (5) | struct field `measurement.width` of 'AnnotatedBinary.Tolerance' (UByte) + +vector (AnnotatedBinary.Foo.foobars): + +0x00D4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00D8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x010C | offset to union[0] (`Bar`) + +0x00DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0108 | offset to union[1] (`Baz`) + +0x00E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00E4 | offset to union[2] (`Bar`) + +table (AnnotatedBinary.Bar): + +0x00E4 | D2 FE FF FF | SOffset32 | 0xFFFFFED2 (-302) Loc: 0x0212 | offset to vtable + +0x00E8 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x00EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x00FC | offset to field `c` (table) + +0x00F0 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x00F8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x00FC | 6A FE FF FF | SOffset32 | 0xFFFFFE6A (-406) Loc: 0x0292 | offset to vtable + +0x0100 | 00 00 00 | uint8_t[3] | ... | padding + +0x0103 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Baz): + +0x0104 | 04 00 | uint16_t | 0x0004 (4) | size of this vtable + +0x0106 | 04 00 | uint16_t | 0x0004 (4) | size of referring table + +table (AnnotatedBinary.Baz): + +0x0108 | 04 00 00 00 | SOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to vtable + +table (AnnotatedBinary.Bar): + +0x010C | FA FE FF FF | SOffset32 | 0xFFFFFEFA (-262) Loc: 0x0212 | offset to vtable + +0x0110 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0114 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0124 | offset to field `c` (table) + +0x0118 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0120 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0124 | 92 FE FF FF | SOffset32 | 0xFFFFFE92 (-366) Loc: 0x0292 | offset to vtable + +0x0128 | 00 00 00 | uint8_t[3] | ... | padding + +0x012B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.foobars_type): + +0x012C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0130 | 01 | UType8 | 0x01 (1) | value[0] + +0x0131 | 02 | UType8 | 0x02 (2) | value[1] + +0x0132 | 01 | UType8 | 0x01 (1) | value[2] + +vector (AnnotatedBinary.Foo.points_of_interest): + +0x0134 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0138 | 33 33 33 33 33 A3 45 40 | double | 0x4045A33333333333 (43.275) | struct field `[0].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0140 | 7E 57 04 FF 5B 87 53 C0 | double | 0xC053875BFF04577E (-78.115) | struct field `[0].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0148 | 8D F0 F6 20 04 B6 42 40 | double | 0x4042B60420F6F08D (37.422) | struct field `[1].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0150 | 9F 77 63 41 61 85 5E C0 | double | 0xC05E85614163779F (-122.084) | struct field `[1].longitude` of 'AnnotatedBinary.Location' (Double) + +0x0158 | 8F 35 23 83 DC 35 4B C0 | double | 0xC04B35DC8323358F (-54.4208) | struct field `[2].latitude` of 'AnnotatedBinary.Location' (Double) + +0x0160 | F6 97 DD 93 87 C5 0A 40 | double | 0x400AC58793DD97F6 (3.34645) | struct field `[2].longitude` of 'AnnotatedBinary.Location' (Double) + +padding: + +0x0168 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (AnnotatedBinary.Foo.names): + +0x016C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0170 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0190 | offset to string[0] + +0x0174 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0188 | offset to string[1] + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to string[2] + +string (AnnotatedBinary.Foo.names): + +0x017C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0180 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x0187 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0188 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x018C | 62 6F 62 | char[3] | bob | string literal + +0x018F | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.names): + +0x0190 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0194 | 61 6C 69 63 65 | char[5] | alice | string literal + +0x0199 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x019A | 00 00 | uint8_t[2] | .. | padding + +string (AnnotatedBinary.Foo.alice): + +0x019C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01A0 | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01A7 | 00 | char | 0x00 (0) | string terminator + +string (AnnotatedBinary.Foo.bob): + +0x01A8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x01AC | 63 68 61 72 6C 69 65 | char[7] | charlie | string literal + +0x01B3 | 00 | char | 0x00 (0) | string terminator + +vector (AnnotatedBinary.Foo.accounts): + +0x01B4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of vector (# items) + +0x01B8 | 09 00 | uint16_t | 0x0009 (9) | value[0] + +0x01BA | 08 00 | uint16_t | 0x0008 (8) | value[1] + +0x01BC | 07 00 | uint16_t | 0x0007 (7) | value[2] + +0x01BE | 01 00 | uint16_t | 0x0001 (1) | value[3] + +0x01C0 | 02 00 | uint16_t | 0x0002 (2) | value[4] + +0x01C2 | 03 00 | uint16_t | 0x0003 (3) | value[5] + +0x01C4 | 06 00 | uint16_t | 0x0006 (6) | value[6] + +0x01C6 | 05 00 | uint16_t | 0x0005 (5) | value[7] + +0x01C8 | 04 00 | uint16_t | 0x0004 (4) | value[8] + +padding: + +0x01CA | 00 00 | uint8_t[2] | .. | padding + +table (AnnotatedBinary.Baz): + +0x01CC | 3A FF FF FF | SOffset32 | 0xFFFFFF3A (-198) Loc: 0x0292 | offset to vtable + +0x01D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x01D3 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vector (AnnotatedBinary.Foo.bars): + +0x01D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01D8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x021C | offset to table[0] + +0x01DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x01EC | offset to table[1] + +padding: + +0x01E0 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x01E2 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x01E4 | 1A 00 | uint16_t | 0x001A (26) | size of referring table + +0x01E6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x01E8 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x01EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x01EC | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x01E2 | offset to vtable + +0x01F0 | 00 80 23 44 | float | 0x44238000 (654) | table field `b` (Float) + +0x01F4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x020C | offset to field `c` (table) + +0x01F8 | 00 00 00 00 00 D8 8E 40 | double | 0x408ED80000000000 (987) | table field `a` (Double) + +0x0200 | 00 00 00 00 00 00 | uint8_t[6] | ...... | padding + +vtable (AnnotatedBinary.Baz): + +0x0206 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0208 | 06 00 | uint16_t | 0x0006 (6) | size of referring table + +0x020A | 05 00 | VOffset16 | 0x0005 (5) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x020C | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0206 | offset to vtable + +0x0210 | 00 | uint8_t[1] | . | padding + +0x0211 | 03 | uint8_t | 0x03 (3) | table field `meal` (Byte) + +vtable (AnnotatedBinary.Bar): + +0x0212 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0214 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0216 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0218 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x021A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x021C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0212 | offset to vtable + +0x0220 | 00 00 E4 43 | float | 0x43E40000 (456) | table field `b` (Float) + +0x0224 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0234 | offset to field `c` (table) + +0x0228 | 00 00 00 00 00 C0 5E 40 | double | 0x405EC00000000000 (123) | table field `a` (Double) + +0x0230 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (AnnotatedBinary.Baz): + +0x0234 | A2 FF FF FF | SOffset32 | 0xFFFFFFA2 (-94) Loc: 0x0292 | offset to vtable + +0x0238 | 00 00 00 | uint8_t[3] | ... | padding + +0x023B | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) + +string (AnnotatedBinary.Foo.name): + +0x023C | 2F 00 00 00 | uint32_t | 0x0000002F (47) | length of string + +0x0240 | 54 68 69 73 20 69 73 20 | char[47] | This is | string literal + +0x0248 | 61 20 6C 6F 6E 67 20 73 | | a long s + +0x0250 | 74 72 69 6E 67 20 74 6F | | tring to + +0x0258 | 20 73 68 6F 77 20 68 6F | | show ho + +0x0260 | 77 20 69 74 20 62 72 65 | | w it bre + +0x0268 | 61 6B 73 20 75 70 2E | | aks up. + +0x026F | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0270 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Bar): + +0x0272 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0274 | 16 00 | uint16_t | 0x0016 (22) | size of referring table + +0x0276 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `a` (id: 0) + +0x0278 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `b` (id: 1) + +0x027A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `c` (id: 2) + +table (AnnotatedBinary.Bar): + +0x027C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0272 | offset to vtable + +0x0280 | 65 20 71 49 | float | 0x49712065 (987654) | table field `b` (Float) + +0x0284 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0298 | offset to field `c` (table) + +0x0288 | C9 76 BE 9F 0C 24 FE 40 | double | 0x40FE240C9FBE76C9 (123457) | table field `a` (Double) + +0x0290 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Baz): + +0x0292 | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x0294 | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x0296 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `meal` (id: 0) + +table (AnnotatedBinary.Baz): + +0x0298 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x0292 | offset to vtable + +0x029C | 00 00 00 | uint8_t[3] | ... | padding + +0x029F | 01 | uint8_t | 0x01 (1) | table field `meal` (Byte) diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size_short.bin new file mode 100644 index 00000000000..e1db9b790f1 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_ref_table_size_short.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size.afb new file mode 100644 index 00000000000..2a7db32825d --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size.afb @@ -0,0 +1,99 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vtable_size.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | FF FF | uint16_t | 0xFFFF (65535) | ERROR: size of this vtable. Longer than the binary. + +unknown (no known references): + +0x000C | 68 00 0C 00 07 00 00 00 | ?uint8_t[660] | h....... | WARN: nothing refers to this section. + +0x0014 | 08 00 10 00 14 00 30 00 | | ......0. + +0x001C | 34 00 09 00 38 00 3C 00 | | 4...8.<. + +0x0024 | 40 00 44 00 00 00 00 00 | | @.D..... + +0x002C | 48 00 4C 00 50 00 54 00 | | H.L.P.T. + +0x0034 | 58 00 0A 00 5C 00 0B 00 | | X...\... + +0x003C | 60 00 00 00 00 00 64 00 | | `.....d. + +0x0044 | 3A 00 00 00 00 00 00 01 | | :....... + +0x004C | 02 02 01 01 D2 04 00 00 | | ........ + +0x0054 | 28 02 00 00 01 00 00 00 | | (....... + +0x005C | 02 00 00 00 0C 00 00 00 | | ........ + +0x0064 | 0A 00 00 00 0C 00 00 00 | | ........ + +0x006C | 14 00 00 00 01 02 03 00 | | ........ + +0x0074 | C8 01 00 00 5C 01 00 00 | | ....\... + +0x007C | 50 01 00 00 34 01 00 00 | | P...4... + +0x0084 | 24 01 00 00 14 01 00 00 | | $....... + +0x008C | 0D 00 00 00 DC 00 00 00 | | ........ + +0x0094 | A0 00 00 00 94 00 00 00 | | ........ + +0x009C | 38 00 00 00 33 00 00 00 | | 8...3... + +0x00A4 | 1C 00 00 00 04 00 00 00 | | ........ + +0x00AC | 05 00 00 00 61 6C 69 63 | | ....alic + +0x00B4 | 65 00 00 00 08 00 13 00 | | e....... + +0x00BC | 08 00 04 00 08 00 00 00 | | ........ + +0x00C4 | 00 80 23 44 00 00 00 00 | | ..#D.... + +0x00CC | 00 10 74 40 00 00 00 05 | | ..t@.... + +0x00D4 | 03 00 00 00 34 00 00 00 | | ....4... + +0x00DC | 2C 00 00 00 04 00 00 00 | | ,....... + +0x00E4 | D2 FE FF FF 00 80 23 44 | | ......#D + +0x00EC | 10 00 00 00 00 00 00 00 | | ........ + +0x00F4 | 00 D8 8E 40 00 00 00 00 | | ...@.... + +0x00FC | 6A FE FF FF 00 00 00 03 | | j....... + +0x0104 | 04 00 04 00 04 00 00 00 | | ........ + +0x010C | FA FE FF FF 00 00 E4 43 | | .......C + +0x0114 | 10 00 00 00 00 00 00 00 | | ........ + +0x011C | 00 C0 5E 40 00 00 00 00 | | ..^@.... + +0x0124 | 92 FE FF FF 00 00 00 01 | | ........ + +0x012C | 03 00 00 00 01 02 01 00 | | ........ + +0x0134 | 03 00 00 00 33 33 33 33 | | ....3333 + +0x013C | 33 A3 45 40 7E 57 04 FF | | 3.E@~W.. + +0x0144 | 5B 87 53 C0 8D F0 F6 20 | | [.S.... + +0x014C | 04 B6 42 40 9F 77 63 41 | | ..B@.wcA + +0x0154 | 61 85 5E C0 8F 35 23 83 | | a.^..5#. + +0x015C | DC 35 4B C0 F6 97 DD 93 | | .5K..... + +0x0164 | 87 C5 0A 40 00 00 00 00 | | ...@.... + +0x016C | 03 00 00 00 20 00 00 00 | | .... ... + +0x0174 | 14 00 00 00 04 00 00 00 | | ........ + +0x017C | 07 00 00 00 63 68 61 72 | | ....char + +0x0184 | 6C 69 65 00 03 00 00 00 | | lie..... + +0x018C | 62 6F 62 00 05 00 00 00 | | bob..... + +0x0194 | 61 6C 69 63 65 00 00 00 | | alice... + +0x019C | 07 00 00 00 63 68 61 72 | | ....char + +0x01A4 | 6C 69 65 00 07 00 00 00 | | lie..... + +0x01AC | 63 68 61 72 6C 69 65 00 | | charlie. + +0x01B4 | 09 00 00 00 09 00 08 00 | | ........ + +0x01BC | 07 00 01 00 02 00 03 00 | | ........ + +0x01C4 | 06 00 05 00 04 00 00 00 | | ........ + +0x01CC | 3A FF FF FF 00 00 00 03 | | :....... + +0x01D4 | 02 00 00 00 44 00 00 00 | | ....D... + +0x01DC | 10 00 00 00 00 00 0A 00 | | ........ + +0x01E4 | 1A 00 0C 00 04 00 08 00 | | ........ + +0x01EC | 0A 00 00 00 00 80 23 44 | | ......#D + +0x01F4 | 18 00 00 00 00 00 00 00 | | ........ + +0x01FC | 00 D8 8E 40 00 00 00 00 | | ...@.... + +0x0204 | 00 00 06 00 06 00 05 00 | | ........ + +0x020C | 06 00 00 00 00 03 0A 00 | | ........ + +0x0214 | 18 00 0C 00 04 00 08 00 | | ........ + +0x021C | 0A 00 00 00 00 00 E4 43 | | .......C + +0x0224 | 10 00 00 00 00 00 00 00 | | ........ + +0x022C | 00 C0 5E 40 00 00 00 00 | | ..^@.... + +0x0234 | A2 FF FF FF 00 00 00 01 | | ........ + +0x023C | 2F 00 00 00 54 68 69 73 | | /...This + +0x0244 | 20 69 73 20 61 20 6C 6F | | is a lo + +0x024C | 6E 67 20 73 74 72 69 6E | | ng strin + +0x0254 | 67 20 74 6F 20 73 68 6F | | g to sho + +0x025C | 77 20 68 6F 77 20 69 74 | | w how it + +0x0264 | 20 62 72 65 61 6B 73 20 | | breaks + +0x026C | 75 70 2E 00 00 00 0A 00 | | up...... + +0x0274 | 16 00 0C 00 04 00 08 00 | | ........ + +0x027C | 0A 00 00 00 65 20 71 49 | | ....e qI + +0x0284 | 14 00 00 00 C9 76 BE 9F | | .....v.. + +0x028C | 0C 24 FE 40 00 00 06 00 | | .$.@.... + +0x0294 | 08 00 07 00 06 00 00 00 | | ........ + +0x029C | 00 00 00 01 | | .... diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size.bin new file mode 100644 index 00000000000..fdc7e98f639 Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size.bin differ diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size_short.afb b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size_short.afb new file mode 100644 index 00000000000..1566830bcf2 --- /dev/null +++ b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size_short.afb @@ -0,0 +1,99 @@ +// Annotated Flatbuffer Binary +// +// Schema file: annotated_binary.fbs +// Binary file: tests/invalid_vtable_size_short.bin + +header: + +0x0000 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0044 | offset to root table `AnnotatedBinary.Foo` + +0x0004 | 41 4E 4E 4F | char[4] | ANNO | File Identifier + +padding: + +0x0008 | 00 00 | uint8_t[2] | .. | padding + +vtable (AnnotatedBinary.Foo): + +0x000A | 01 00 | uint16_t | 0x0001 (1) | ERROR: size of this vtable. Shorter than the minimum length: + +unknown (no known references): + +0x000C | 68 00 0C 00 07 00 00 00 | ?uint8_t[660] | h....... | WARN: nothing refers to this section. + +0x0014 | 08 00 10 00 14 00 30 00 | | ......0. + +0x001C | 34 00 09 00 38 00 3C 00 | | 4...8.<. + +0x0024 | 40 00 44 00 00 00 00 00 | | @.D..... + +0x002C | 48 00 4C 00 50 00 54 00 | | H.L.P.T. + +0x0034 | 58 00 0A 00 5C 00 0B 00 | | X...\... + +0x003C | 60 00 00 00 00 00 64 00 | | `.....d. + +0x0044 | 3A 00 00 00 00 00 00 01 | | :....... + +0x004C | 02 02 01 01 D2 04 00 00 | | ........ + +0x0054 | 28 02 00 00 01 00 00 00 | | (....... + +0x005C | 02 00 00 00 0C 00 00 00 | | ........ + +0x0064 | 0A 00 00 00 0C 00 00 00 | | ........ + +0x006C | 14 00 00 00 01 02 03 00 | | ........ + +0x0074 | C8 01 00 00 5C 01 00 00 | | ....\... + +0x007C | 50 01 00 00 34 01 00 00 | | P...4... + +0x0084 | 24 01 00 00 14 01 00 00 | | $....... + +0x008C | 0D 00 00 00 DC 00 00 00 | | ........ + +0x0094 | A0 00 00 00 94 00 00 00 | | ........ + +0x009C | 38 00 00 00 33 00 00 00 | | 8...3... + +0x00A4 | 1C 00 00 00 04 00 00 00 | | ........ + +0x00AC | 05 00 00 00 61 6C 69 63 | | ....alic + +0x00B4 | 65 00 00 00 08 00 13 00 | | e....... + +0x00BC | 08 00 04 00 08 00 00 00 | | ........ + +0x00C4 | 00 80 23 44 00 00 00 00 | | ..#D.... + +0x00CC | 00 10 74 40 00 00 00 05 | | ..t@.... + +0x00D4 | 03 00 00 00 34 00 00 00 | | ....4... + +0x00DC | 2C 00 00 00 04 00 00 00 | | ,....... + +0x00E4 | D2 FE FF FF 00 80 23 44 | | ......#D + +0x00EC | 10 00 00 00 00 00 00 00 | | ........ + +0x00F4 | 00 D8 8E 40 00 00 00 00 | | ...@.... + +0x00FC | 6A FE FF FF 00 00 00 03 | | j....... + +0x0104 | 04 00 04 00 04 00 00 00 | | ........ + +0x010C | FA FE FF FF 00 00 E4 43 | | .......C + +0x0114 | 10 00 00 00 00 00 00 00 | | ........ + +0x011C | 00 C0 5E 40 00 00 00 00 | | ..^@.... + +0x0124 | 92 FE FF FF 00 00 00 01 | | ........ + +0x012C | 03 00 00 00 01 02 01 00 | | ........ + +0x0134 | 03 00 00 00 33 33 33 33 | | ....3333 + +0x013C | 33 A3 45 40 7E 57 04 FF | | 3.E@~W.. + +0x0144 | 5B 87 53 C0 8D F0 F6 20 | | [.S.... + +0x014C | 04 B6 42 40 9F 77 63 41 | | ..B@.wcA + +0x0154 | 61 85 5E C0 8F 35 23 83 | | a.^..5#. + +0x015C | DC 35 4B C0 F6 97 DD 93 | | .5K..... + +0x0164 | 87 C5 0A 40 00 00 00 00 | | ...@.... + +0x016C | 03 00 00 00 20 00 00 00 | | .... ... + +0x0174 | 14 00 00 00 04 00 00 00 | | ........ + +0x017C | 07 00 00 00 63 68 61 72 | | ....char + +0x0184 | 6C 69 65 00 03 00 00 00 | | lie..... + +0x018C | 62 6F 62 00 05 00 00 00 | | bob..... + +0x0194 | 61 6C 69 63 65 00 00 00 | | alice... + +0x019C | 07 00 00 00 63 68 61 72 | | ....char + +0x01A4 | 6C 69 65 00 07 00 00 00 | | lie..... + +0x01AC | 63 68 61 72 6C 69 65 00 | | charlie. + +0x01B4 | 09 00 00 00 09 00 08 00 | | ........ + +0x01BC | 07 00 01 00 02 00 03 00 | | ........ + +0x01C4 | 06 00 05 00 04 00 00 00 | | ........ + +0x01CC | 3A FF FF FF 00 00 00 03 | | :....... + +0x01D4 | 02 00 00 00 44 00 00 00 | | ....D... + +0x01DC | 10 00 00 00 00 00 0A 00 | | ........ + +0x01E4 | 1A 00 0C 00 04 00 08 00 | | ........ + +0x01EC | 0A 00 00 00 00 80 23 44 | | ......#D + +0x01F4 | 18 00 00 00 00 00 00 00 | | ........ + +0x01FC | 00 D8 8E 40 00 00 00 00 | | ...@.... + +0x0204 | 00 00 06 00 06 00 05 00 | | ........ + +0x020C | 06 00 00 00 00 03 0A 00 | | ........ + +0x0214 | 18 00 0C 00 04 00 08 00 | | ........ + +0x021C | 0A 00 00 00 00 00 E4 43 | | .......C + +0x0224 | 10 00 00 00 00 00 00 00 | | ........ + +0x022C | 00 C0 5E 40 00 00 00 00 | | ..^@.... + +0x0234 | A2 FF FF FF 00 00 00 01 | | ........ + +0x023C | 2F 00 00 00 54 68 69 73 | | /...This + +0x0244 | 20 69 73 20 61 20 6C 6F | | is a lo + +0x024C | 6E 67 20 73 74 72 69 6E | | ng strin + +0x0254 | 67 20 74 6F 20 73 68 6F | | g to sho + +0x025C | 77 20 68 6F 77 20 69 74 | | w how it + +0x0264 | 20 62 72 65 61 6B 73 20 | | breaks + +0x026C | 75 70 2E 00 00 00 0A 00 | | up...... + +0x0274 | 16 00 0C 00 04 00 08 00 | | ........ + +0x027C | 0A 00 00 00 65 20 71 49 | | ....e qI + +0x0284 | 14 00 00 00 C9 76 BE 9F | | .....v.. + +0x028C | 0C 24 FE 40 00 00 06 00 | | .$.@.... + +0x0294 | 08 00 07 00 06 00 00 00 | | ........ + +0x029C | 00 00 00 01 | | .... diff --git a/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size_short.bin b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size_short.bin new file mode 100644 index 00000000000..435bd742d9c Binary files /dev/null and b/third_party/flatbuffers/tests/annotated_binary/tests/invalid_vtable_size_short.bin differ diff --git a/third_party/flatbuffers/tests/arrays_test.bfbs b/third_party/flatbuffers/tests/arrays_test.bfbs new file mode 100644 index 00000000000..117630a1668 Binary files /dev/null and b/third_party/flatbuffers/tests/arrays_test.bfbs differ diff --git a/third_party/flatbuffers/tests/arrays_test.fbs b/third_party/flatbuffers/tests/arrays_test.fbs new file mode 100644 index 00000000000..90cb0d7267c --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test.fbs @@ -0,0 +1,27 @@ +namespace MyGame.Example; + +enum TestEnum : byte { A, B, C } + +struct NestedStruct{ + a:[int:2]; + b:TestEnum; + c:[TestEnum:2]; + d:[int64:2]; +} + +struct ArrayStruct{ + a:float; + b:[int:0xF]; + c:byte; + d:[NestedStruct:2]; + e:int32; + f:[int64:2]; +} + +table ArrayTable{ + a:ArrayStruct; +} + +root_type ArrayTable; +file_identifier "ARRT"; +file_extension "mon"; diff --git a/third_party/flatbuffers/tests/arrays_test.golden b/third_party/flatbuffers/tests/arrays_test.golden new file mode 100644 index 00000000000..c7037d7a1a0 --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test.golden @@ -0,0 +1,23 @@ +{ + a : { + a: 12.34, + b: [1,2,3,4,5,6,7,8,9,0xA,0xB,0xC,0xD,0xE,0xF], + c: -127, + d: [ + { + a : [-1,2], + b : A, + c : [C, B], + d : [0x1122334455667788, -0x1122334455667788] + }, + { + a : [3,-4], + b : B, + c : [B, A], + d : [-0x1122334455667788, 0x1122334455667788] + } + ], + e: 1, + f: [-0x8000000000000000, 0x7FFFFFFFFFFFFFFF] + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/arrays_test.schema.json b/third_party/flatbuffers/tests/arrays_test.schema.json new file mode 100644 index 00000000000..c33dc6caf43 --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test.schema.json @@ -0,0 +1,73 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "definitions": { + "MyGame_Example_TestEnum" : { + "type" : "string", + "enum": ["A", "B", "C"] + }, + "MyGame_Example_NestedStruct" : { + "type" : "object", + "properties" : { + "a" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647}, + "minItems": 2, + "maxItems": 2 + }, + "b" : { + "$ref" : "#/definitions/MyGame_Example_TestEnum" + }, + "c" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_TestEnum"}, + "minItems": 2, + "maxItems": 2 + }, + "d" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807}, + "minItems": 2, + "maxItems": 2 + } + }, + "additionalProperties" : false + }, + "MyGame_Example_ArrayStruct" : { + "type" : "object", + "properties" : { + "a" : { + "type" : "number" + }, + "b" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647}, + "minItems": 15, + "maxItems": 15 + }, + "c" : { + "type" : "integer", "minimum" : -128, "maximum" : 127 + }, + "d" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_NestedStruct"}, + "minItems": 2, + "maxItems": 2 + }, + "e" : { + "type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647 + }, + "f" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807}, + "minItems": 2, + "maxItems": 2 + } + }, + "additionalProperties" : false + }, + "MyGame_Example_ArrayTable" : { + "type" : "object", + "properties" : { + "a" : { + "$ref" : "#/definitions/MyGame_Example_ArrayStruct" + } + }, + "additionalProperties" : false + } + }, + "$ref" : "#/definitions/MyGame_Example_ArrayTable" +} diff --git a/third_party/flatbuffers/tests/arrays_test/mod.rs b/third_party/flatbuffers/tests/arrays_test/mod.rs new file mode 100644 index 00000000000..5a649d5e8eb --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test/mod.rs @@ -0,0 +1,16 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod my_game { + use super::*; + pub mod example { + use super::*; + mod test_enum_generated; + pub use self::test_enum_generated::*; + mod nested_struct_generated; + pub use self::nested_struct_generated::*; + mod array_struct_generated; + pub use self::array_struct_generated::*; + mod array_table_generated; + pub use self::array_table_generated::*; + } // example +} // my_game diff --git a/third_party/flatbuffers/tests/arrays_test/my_game/example/array_struct_generated.rs b/third_party/flatbuffers/tests/arrays_test/my_game/example/array_struct_generated.rs new file mode 100644 index 00000000000..65c7ca6cfcf --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test/my_game/example/array_struct_generated.rs @@ -0,0 +1,264 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct ArrayStruct, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct ArrayStruct(pub [u8; 160]); +impl Default for ArrayStruct { + fn default() -> Self { + Self([0; 160]) + } +} +impl core::fmt::Debug for ArrayStruct { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("ArrayStruct") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .field("d", &self.d()) + .field("e", &self.e()) + .field("f", &self.f()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for ArrayStruct {} +impl<'a> flatbuffers::Follow<'a> for ArrayStruct { + type Inner = &'a ArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a ArrayStruct>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a ArrayStruct { + type Inner = &'a ArrayStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for ArrayStruct { + type Output = ArrayStruct; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const ArrayStruct as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> flatbuffers::Verifiable for ArrayStruct { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> ArrayStruct { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: f32, + b: &[i32; 15], + c: i8, + d: &[NestedStruct; 2], + e: i32, + f: &[i64; 2], + ) -> Self { + let mut s = Self([0; 160]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s.set_d(d); + s.set_e(e); + s.set_f(f); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.ArrayStruct" + } + + pub fn a(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn b(&'a self) -> flatbuffers::Array<'a, i32, 15> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::Array::follow(&self.0, 4) } + } + + pub fn set_b(&mut self, items: &[i32; 15]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::emplace_scalar_array(&mut self.0, 4, items) }; + } + + pub fn c(&self) -> i8 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[64..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_c(&mut self, x: i8) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[64..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn d(&'a self) -> flatbuffers::Array<'a, NestedStruct, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::Array::follow(&self.0, 72) } + } + + pub fn set_d(&mut self, x: &[NestedStruct; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(72), + 64, + ); + } + } + + pub fn e(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[136..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_e(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[136..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn f(&'a self) -> flatbuffers::Array<'a, i64, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::Array::follow(&self.0, 144) } + } + + pub fn set_f(&mut self, items: &[i64; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::emplace_scalar_array(&mut self.0, 144, items) }; + } + + pub fn unpack(&self) -> ArrayStructT { + ArrayStructT { + a: self.a(), + b: self.b().into(), + c: self.c(), + d: { let d = self.d(); flatbuffers::array_init(|i| d.get(i).unpack()) }, + e: self.e(), + f: self.f().into(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct ArrayStructT { + pub a: f32, + pub b: [i32; 15], + pub c: i8, + pub d: [NestedStructT; 2], + pub e: i32, + pub f: [i64; 2], +} +impl ArrayStructT { + pub fn pack(&self) -> ArrayStruct { + ArrayStruct::new( + self.a, + &self.b, + self.c, + &flatbuffers::array_init(|i| self.d[i].pack()), + self.e, + &self.f, + ) + } +} + diff --git a/third_party/flatbuffers/tests/arrays_test/my_game/example/array_table_generated.rs b/third_party/flatbuffers/tests/arrays_test/my_game/example/array_table_generated.rs new file mode 100644 index 00000000000..3bb05d2f439 --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test/my_game/example/array_table_generated.rs @@ -0,0 +1,229 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum ArrayTableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct ArrayTable<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for ArrayTable<'a> { + type Inner = ArrayTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> ArrayTable<'a> { + pub const VT_A: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.ArrayTable" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + ArrayTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ArrayTableArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = ArrayTableBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } + + pub fn unpack(&self) -> ArrayTableT { + let a = self.a().map(|x| { + x.unpack() + }); + ArrayTableT { + a, + } + } + + #[inline] + pub fn a(&self) -> Option<&'a ArrayStruct> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ArrayTable::VT_A, None)} + } +} + +impl flatbuffers::Verifiable for ArrayTable<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct ArrayTableArgs<'a> { + pub a: Option<&'a ArrayStruct>, +} +impl<'a> Default for ArrayTableArgs<'a> { + #[inline] + fn default() -> Self { + ArrayTableArgs { + a: None, + } + } +} + +pub struct ArrayTableBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ArrayTableBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: &ArrayStruct) { + self.fbb_.push_slot_always::<&ArrayStruct>(ArrayTable::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ArrayTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ArrayTableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for ArrayTable<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("ArrayTable"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct ArrayTableT { + pub a: Option, +} +impl Default for ArrayTableT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl ArrayTableT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let a_tmp = self.a.as_ref().map(|x| x.pack()); + let a = a_tmp.as_ref(); + ArrayTable::create(_fbb, &ArrayTableArgs{ + a, + }) + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `ArrayTable` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_array_table_unchecked`. +pub fn root_as_array_table(buf: &[u8]) -> Result { + flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `ArrayTable` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_array_table_unchecked`. +pub fn size_prefixed_root_as_array_table(buf: &[u8]) -> Result { + flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `ArrayTable` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_array_table_unchecked`. +pub fn root_as_array_table_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `ArrayTable` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_array_table_unchecked`. +pub fn size_prefixed_root_as_array_table_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a ArrayTable and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `ArrayTable`. +pub unsafe fn root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable { + flatbuffers::root_unchecked::(buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed ArrayTable and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `ArrayTable`. +pub unsafe fn size_prefixed_root_as_array_table_unchecked(buf: &[u8]) -> ArrayTable { + flatbuffers::size_prefixed_root_unchecked::(buf) +} +pub const ARRAY_TABLE_IDENTIFIER: &str = "ARRT"; + +#[inline] +pub fn array_table_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, false) +} + +#[inline] +pub fn array_table_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, ARRAY_TABLE_IDENTIFIER, true) +} + +pub const ARRAY_TABLE_EXTENSION: &str = "mon"; + +#[inline] +pub fn finish_array_table_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( + fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + root: flatbuffers::WIPOffset>) { + fbb.finish(root, Some(ARRAY_TABLE_IDENTIFIER)); +} + +#[inline] +pub fn finish_size_prefixed_array_table_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(ARRAY_TABLE_IDENTIFIER)); +} diff --git a/third_party/flatbuffers/tests/arrays_test/my_game/example/nested_struct_generated.rs b/third_party/flatbuffers/tests/arrays_test/my_game/example/nested_struct_generated.rs new file mode 100644 index 00000000000..0015f228260 --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test/my_game/example/nested_struct_generated.rs @@ -0,0 +1,194 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct NestedStruct, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct NestedStruct(pub [u8; 32]); +impl Default for NestedStruct { + fn default() -> Self { + Self([0; 32]) + } +} +impl core::fmt::Debug for NestedStruct { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("NestedStruct") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .field("d", &self.d()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for NestedStruct {} +impl<'a> flatbuffers::Follow<'a> for NestedStruct { + type Inner = &'a NestedStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a NestedStruct>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a NestedStruct { + type Inner = &'a NestedStruct; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for NestedStruct { + type Output = NestedStruct; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const NestedStruct as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> flatbuffers::Verifiable for NestedStruct { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> NestedStruct { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &[i32; 2], + b: TestEnum, + c: &[TestEnum; 2], + d: &[i64; 2], + ) -> Self { + let mut s = Self([0; 32]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s.set_d(d); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.NestedStruct" + } + + pub fn a(&'a self) -> flatbuffers::Array<'a, i32, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::Array::follow(&self.0, 0) } + } + + pub fn set_a(&mut self, items: &[i32; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::emplace_scalar_array(&mut self.0, 0, items) }; + } + + pub fn b(&self) -> TestEnum { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_b(&mut self, x: TestEnum) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn c(&'a self) -> flatbuffers::Array<'a, TestEnum, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::Array::follow(&self.0, 9) } + } + + pub fn set_c(&mut self, x: &[TestEnum; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { + core::ptr::copy( + x.as_ptr() as *const u8, + self.0.as_mut_ptr().add(9), + 2, + ); + } + } + + pub fn d(&'a self) -> flatbuffers::Array<'a, i64, 2> { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::Array::follow(&self.0, 16) } + } + + pub fn set_d(&mut self, items: &[i64; 2]) { + // Safety: + // Created from a valid Table for this object + // Which contains a valid array in this slot + unsafe { flatbuffers::emplace_scalar_array(&mut self.0, 16, items) }; + } + + pub fn unpack(&self) -> NestedStructT { + NestedStructT { + a: self.a().into(), + b: self.b(), + c: self.c().into(), + d: self.d().into(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct NestedStructT { + pub a: [i32; 2], + pub b: TestEnum, + pub c: [TestEnum; 2], + pub d: [i64; 2], +} +impl NestedStructT { + pub fn pack(&self) -> NestedStruct { + NestedStruct::new( + &self.a, + self.b, + &self.c, + &self.d, + ) + } +} + diff --git a/third_party/flatbuffers/tests/arrays_test/my_game/example/test_enum_generated.rs b/third_party/flatbuffers/tests/arrays_test/my_game/example/test_enum_generated.rs new file mode 100644 index 00000000000..6721484ae26 --- /dev/null +++ b/third_party/flatbuffers/tests/arrays_test/my_game/example/test_enum_generated.rs @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_TEST_ENUM: i8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_TEST_ENUM: i8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_TEST_ENUM: [TestEnum; 3] = [ + TestEnum::A, + TestEnum::B, + TestEnum::C, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct TestEnum(pub i8); +#[allow(non_upper_case_globals)] +impl TestEnum { + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); + + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, + } + } +} +impl core::fmt::Debug for TestEnum { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for TestEnum { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for TestEnum { + type Output = TestEnum; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for TestEnum { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for TestEnum { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for TestEnum {} diff --git a/third_party/flatbuffers/tests/bazel_repository_test_dir/.bazelrc b/third_party/flatbuffers/tests/bazel_repository_test_dir/.bazelrc new file mode 100644 index 00000000000..78003332b01 --- /dev/null +++ b/third_party/flatbuffers/tests/bazel_repository_test_dir/.bazelrc @@ -0,0 +1 @@ +build --symlink_prefix=/ diff --git a/third_party/flatbuffers/tests/bazel_repository_test_dir/.gitignore b/third_party/flatbuffers/tests/bazel_repository_test_dir/.gitignore new file mode 100644 index 00000000000..ac51a054d2d --- /dev/null +++ b/third_party/flatbuffers/tests/bazel_repository_test_dir/.gitignore @@ -0,0 +1 @@ +bazel-* diff --git a/third_party/flatbuffers/tests/bazel_repository_test_dir/BUILD b/third_party/flatbuffers/tests/bazel_repository_test_dir/BUILD new file mode 100644 index 00000000000..ea91b1baa83 --- /dev/null +++ b/third_party/flatbuffers/tests/bazel_repository_test_dir/BUILD @@ -0,0 +1,12 @@ +load("@rules_cc//cc:defs.bzl", "cc_test") + +# This test doesn't actually make use of the flatbuffers library. It's just +# here to make sure we can link the library properly when it comes from an +# external repository. You're welcome to expand this test to do more. +cc_test( + name = "pulls_in_flatbuffers_test", + srcs = ["pulls_in_flatbuffers_test.cpp"], + deps = [ + "@com_github_google_flatbuffers//:flatbuffers", + ], +) diff --git a/third_party/flatbuffers/tests/bazel_repository_test_dir/MODULE.bazel b/third_party/flatbuffers/tests/bazel_repository_test_dir/MODULE.bazel new file mode 100644 index 00000000000..d37d66dd4b7 --- /dev/null +++ b/third_party/flatbuffers/tests/bazel_repository_test_dir/MODULE.bazel @@ -0,0 +1,12 @@ +module(name = "bazel_repository_test") + +bazel_dep(name = "flatbuffers", repo_name = "com_github_google_flatbuffers") +local_path_override( + module_name = "flatbuffers", + path = "../../", +) + +bazel_dep( + name = "rules_cc", + version = "0.0.16", +) diff --git a/third_party/flatbuffers/tests/bazel_repository_test_dir/README.md b/third_party/flatbuffers/tests/bazel_repository_test_dir/README.md new file mode 100644 index 00000000000..981ff561fec --- /dev/null +++ b/third_party/flatbuffers/tests/bazel_repository_test_dir/README.md @@ -0,0 +1,3 @@ +This directory is not intended to be used independently of the flatbuffers +repository. Instead, this whole directory serves as a unit test for the +C++ integration in the flatbuffers repo. diff --git a/third_party/flatbuffers/tests/bazel_repository_test_dir/pulls_in_flatbuffers_test.cpp b/third_party/flatbuffers/tests/bazel_repository_test_dir/pulls_in_flatbuffers_test.cpp new file mode 100644 index 00000000000..76e8197013a --- /dev/null +++ b/third_party/flatbuffers/tests/bazel_repository_test_dir/pulls_in_flatbuffers_test.cpp @@ -0,0 +1 @@ +int main() { return 0; } diff --git a/third_party/flatbuffers/tests/cpp17/generated_cpp17/monster_test_generated.h b/third_party/flatbuffers/tests/cpp17/generated_cpp17/monster_test_generated.h new file mode 100644 index 00000000000..037027fb9f0 --- /dev/null +++ b/third_party/flatbuffers/tests/cpp17/generated_cpp17/monster_test_generated.h @@ -0,0 +1,4285 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ +#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/flex_flat_util.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace MyGame { + +struct InParentNamespace; +struct InParentNamespaceBuilder; +struct InParentNamespaceT; + +namespace Example2 { + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +} // namespace Example2 + +namespace Example { + +struct Test; + +struct TestSimpleTableWithEnum; +struct TestSimpleTableWithEnumBuilder; +struct TestSimpleTableWithEnumT; + +struct Vec3; + +struct Ability; + +struct StructOfStructs; + +struct StructOfStructsOfStructs; + +struct Stat; +struct StatBuilder; +struct StatT; + +struct Referrable; +struct ReferrableBuilder; +struct ReferrableT; + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +struct TypeAliases; +struct TypeAliasesBuilder; +struct TypeAliasesT; + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable(); + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable(); + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable(); + +inline const ::flatbuffers::TypeTable *Vec3TypeTable(); + +inline const ::flatbuffers::TypeTable *AbilityTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StatTypeTable(); + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable(); + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable(); + +/// Composite components of Monster color. +enum class Color : uint8_t { + Red = 1, + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Green = 2, + /// \brief color Blue (1u << 3) + Blue = 8, + NONE = 0, + ANY = 11 +}; +FLATBUFFERS_DEFINE_BITMASK_OPERATORS(Color, uint8_t) + +inline const Color (&EnumValuesColor())[3] { + static const Color values[] = { + Color::Red, + Color::Green, + Color::Blue + }; + return values; +} + +inline const char * const *EnumNamesColor() { + static const char * const names[9] = { + "Red", + "Green", + "", + "", + "", + "", + "", + "Blue", + nullptr + }; + return names; +} + +inline const char *EnumNameColor(Color e) { + if (::flatbuffers::IsOutRange(e, Color::Red, Color::Blue)) return ""; + const size_t index = static_cast(e) - static_cast(Color::Red); + return EnumNamesColor()[index]; +} + +enum class Race : int8_t { + None = -1, + Human = 0, + Dwarf = 1, + Elf = 2, + MIN = None, + MAX = Elf +}; + +inline const Race (&EnumValuesRace())[4] { + static const Race values[] = { + Race::None, + Race::Human, + Race::Dwarf, + Race::Elf + }; + return values; +} + +inline const char * const *EnumNamesRace() { + static const char * const names[5] = { + "None", + "Human", + "Dwarf", + "Elf", + nullptr + }; + return names; +} + +inline const char *EnumNameRace(Race e) { + if (::flatbuffers::IsOutRange(e, Race::None, Race::Elf)) return ""; + const size_t index = static_cast(e) - static_cast(Race::None); + return EnumNamesRace()[index]; +} + +enum class LongEnum : uint64_t { + LongOne = 2ULL, + LongTwo = 4ULL, + LongBig = 1099511627776ULL, + NONE = 0, + ANY = 1099511627782ULL +}; +FLATBUFFERS_DEFINE_BITMASK_OPERATORS(LongEnum, uint64_t) + +inline const LongEnum (&EnumValuesLongEnum())[3] { + static const LongEnum values[] = { + LongEnum::LongOne, + LongEnum::LongTwo, + LongEnum::LongBig + }; + return values; +} + +inline const char *EnumNameLongEnum(LongEnum e) { + switch (e) { + case LongEnum::LongOne: return "LongOne"; + case LongEnum::LongTwo: return "LongTwo"; + case LongEnum::LongBig: return "LongBig"; + default: return ""; + } +} + +enum class Any : uint8_t { + NONE = 0, + Monster = 1, + TestSimpleTableWithEnum = 2, + MyGame_Example2_Monster = 3, + MIN = NONE, + MAX = MyGame_Example2_Monster +}; + +inline const Any (&EnumValuesAny())[4] { + static const Any values[] = { + Any::NONE, + Any::Monster, + Any::TestSimpleTableWithEnum, + Any::MyGame_Example2_Monster + }; + return values; +} + +inline const char * const *EnumNamesAny() { + static const char * const names[5] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster", + nullptr + }; + return names; +} + +inline const char *EnumNameAny(Any e) { + if (::flatbuffers::IsOutRange(e, Any::NONE, Any::MyGame_Example2_Monster)) return ""; + const size_t index = static_cast(e); + return EnumNamesAny()[index]; +} + +template struct AnyTraits { + static const Any enum_value = Any::NONE; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any::Monster; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any::TestSimpleTableWithEnum; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any::MyGame_Example2_Monster; +}; + +template struct AnyUnionTraits { + static const Any enum_value = Any::NONE; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any::Monster; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any::TestSimpleTableWithEnum; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any::MyGame_Example2_Monster; +}; + +struct AnyUnion { + Any type; + void *value; + + AnyUnion() : type(Any::NONE), value(nullptr) {} + AnyUnion(AnyUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Any::NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUnion(const AnyUnion &); + AnyUnion &operator=(const AnyUnion &u) + { AnyUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUnion &operator=(AnyUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUnionTraits::enum_value; + if (type != Any::NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsMonster() { + return type == Any::Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsMonster() const { + return type == Any::Monster ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() { + return type == Any::TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() const { + return type == Any::TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() { + return type == Any::MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() const { + return type == Any::MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } +}; + +bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type); +bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum class AnyUniqueAliases : uint8_t { + NONE = 0, + M = 1, + TS = 2, + M2 = 3, + MIN = NONE, + MAX = M2 +}; + +inline const AnyUniqueAliases (&EnumValuesAnyUniqueAliases())[4] { + static const AnyUniqueAliases values[] = { + AnyUniqueAliases::NONE, + AnyUniqueAliases::M, + AnyUniqueAliases::TS, + AnyUniqueAliases::M2 + }; + return values; +} + +inline const char * const *EnumNamesAnyUniqueAliases() { + static const char * const names[5] = { + "NONE", + "M", + "TS", + "M2", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyUniqueAliases(AnyUniqueAliases e) { + if (::flatbuffers::IsOutRange(e, AnyUniqueAliases::NONE, AnyUniqueAliases::M2)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyUniqueAliases()[index]; +} + +template struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::NONE; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::M; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::TS; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::M2; +}; + +template struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::NONE; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::M; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::TS; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases::M2; +}; + +struct AnyUniqueAliasesUnion { + AnyUniqueAliases type; + void *value; + + AnyUniqueAliasesUnion() : type(AnyUniqueAliases::NONE), value(nullptr) {} + AnyUniqueAliasesUnion(AnyUniqueAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyUniqueAliases::NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &); + AnyUniqueAliasesUnion &operator=(const AnyUniqueAliasesUnion &u) + { AnyUniqueAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUniqueAliasesUnion &operator=(AnyUniqueAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUniqueAliasesUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUniqueAliasesUnionTraits::enum_value; + if (type != AnyUniqueAliases::NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM() { + return type == AnyUniqueAliases::M ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM() const { + return type == AnyUniqueAliases::M ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTS() { + return type == AnyUniqueAliases::TS ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTS() const { + return type == AnyUniqueAliases::TS ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsM2() { + return type == AnyUniqueAliases::M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsM2() const { + return type == AnyUniqueAliases::M2 ? + reinterpret_cast(value) : nullptr; + } +}; + +bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type); +bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum class AnyAmbiguousAliases : uint8_t { + NONE = 0, + M1 = 1, + M2 = 2, + M3 = 3, + MIN = NONE, + MAX = M3 +}; + +inline const AnyAmbiguousAliases (&EnumValuesAnyAmbiguousAliases())[4] { + static const AnyAmbiguousAliases values[] = { + AnyAmbiguousAliases::NONE, + AnyAmbiguousAliases::M1, + AnyAmbiguousAliases::M2, + AnyAmbiguousAliases::M3 + }; + return values; +} + +inline const char * const *EnumNamesAnyAmbiguousAliases() { + static const char * const names[5] = { + "NONE", + "M1", + "M2", + "M3", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyAmbiguousAliases(AnyAmbiguousAliases e) { + if (::flatbuffers::IsOutRange(e, AnyAmbiguousAliases::NONE, AnyAmbiguousAliases::M3)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyAmbiguousAliases()[index]; +} + +struct AnyAmbiguousAliasesUnion { + AnyAmbiguousAliases type; + void *value; + + AnyAmbiguousAliasesUnion() : type(AnyAmbiguousAliases::NONE), value(nullptr) {} + AnyAmbiguousAliasesUnion(AnyAmbiguousAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyAmbiguousAliases::NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &); + AnyAmbiguousAliasesUnion &operator=(const AnyAmbiguousAliasesUnion &u) + { AnyAmbiguousAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyAmbiguousAliasesUnion &operator=(AnyAmbiguousAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyAmbiguousAliasesUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM1() { + return type == AnyAmbiguousAliases::M1 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM1() const { + return type == AnyAmbiguousAliases::M1 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM2() { + return type == AnyAmbiguousAliases::M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM2() const { + return type == AnyAmbiguousAliases::M2 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM3() { + return type == AnyAmbiguousAliases::M3 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM3() const { + return type == AnyAmbiguousAliases::M3 ? + reinterpret_cast(value) : nullptr; + } +}; + +bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type); +bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS { + private: + int16_t a_; + int8_t b_; + int8_t padding0__; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestTypeTable(); + } + Test() + : a_(0), + b_(0), + padding0__(0) { + (void)padding0__; + } + Test(int16_t _a, int8_t _b) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0) { + (void)padding0__; + } + int16_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int16_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + int8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(int8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } + template + auto get_field() const { + if constexpr (Index == 0) return a(); + else if constexpr (Index == 1) return b(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(Test, 4); + +struct Test::Traits { + using type = Test; + static constexpr auto name = "Test"; + static constexpr auto fully_qualified_name = "MyGame.Example.Test"; + static constexpr size_t fields_number = 2; + static constexpr std::array field_names = { + "a", + "b" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Vec3 FLATBUFFERS_FINAL_CLASS { + private: + float x_; + float y_; + float z_; + int32_t padding0__; + double test1_; + uint8_t test2_; + int8_t padding1__; + MyGame::Example::Test test3_; + int16_t padding2__; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vec3TypeTable(); + } + Vec3() + : x_(0), + y_(0), + z_(0), + padding0__(0), + test1_(0), + test2_(0), + padding1__(0), + test3_(), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + Vec3(float _x, float _y, float _z, double _test1, MyGame::Example::Color _test2, const MyGame::Example::Test &_test3) + : x_(::flatbuffers::EndianScalar(_x)), + y_(::flatbuffers::EndianScalar(_y)), + z_(::flatbuffers::EndianScalar(_z)), + padding0__(0), + test1_(::flatbuffers::EndianScalar(_test1)), + test2_(::flatbuffers::EndianScalar(static_cast(_test2))), + padding1__(0), + test3_(_test3), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + float x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(float _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } + float y() const { + return ::flatbuffers::EndianScalar(y_); + } + void mutate_y(float _y) { + ::flatbuffers::WriteScalar(&y_, _y); + } + float z() const { + return ::flatbuffers::EndianScalar(z_); + } + void mutate_z(float _z) { + ::flatbuffers::WriteScalar(&z_, _z); + } + double test1() const { + return ::flatbuffers::EndianScalar(test1_); + } + void mutate_test1(double _test1) { + ::flatbuffers::WriteScalar(&test1_, _test1); + } + MyGame::Example::Color test2() const { + return static_cast(::flatbuffers::EndianScalar(test2_)); + } + void mutate_test2(MyGame::Example::Color _test2) { + ::flatbuffers::WriteScalar(&test2_, static_cast(_test2)); + } + const MyGame::Example::Test &test3() const { + return test3_; + } + MyGame::Example::Test &mutable_test3() { + return test3_; + } + template + auto get_field() const { + if constexpr (Index == 0) return x(); + else if constexpr (Index == 1) return y(); + else if constexpr (Index == 2) return z(); + else if constexpr (Index == 3) return test1(); + else if constexpr (Index == 4) return test2(); + else if constexpr (Index == 5) return test3(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(Vec3, 32); + +struct Vec3::Traits { + using type = Vec3; + static constexpr auto name = "Vec3"; + static constexpr auto fully_qualified_name = "MyGame.Example.Vec3"; + static constexpr size_t fields_number = 6; + static constexpr std::array field_names = { + "x", + "y", + "z", + "test1", + "test2", + "test3" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Ability FLATBUFFERS_FINAL_CLASS { + private: + uint32_t id_; + uint32_t distance_; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AbilityTypeTable(); + } + Ability() + : id_(0), + distance_(0) { + } + Ability(uint32_t _id, uint32_t _distance) + : id_(::flatbuffers::EndianScalar(_id)), + distance_(::flatbuffers::EndianScalar(_distance)) { + } + uint32_t id() const { + return ::flatbuffers::EndianScalar(id_); + } + void mutate_id(uint32_t _id) { + ::flatbuffers::WriteScalar(&id_, _id); + } + bool KeyCompareLessThan(const Ability * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint32_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + uint32_t distance() const { + return ::flatbuffers::EndianScalar(distance_); + } + void mutate_distance(uint32_t _distance) { + ::flatbuffers::WriteScalar(&distance_, _distance); + } + template + auto get_field() const { + if constexpr (Index == 0) return id(); + else if constexpr (Index == 1) return distance(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(Ability, 8); + +struct Ability::Traits { + using type = Ability; + static constexpr auto name = "Ability"; + static constexpr auto fully_qualified_name = "MyGame.Example.Ability"; + static constexpr size_t fields_number = 2; + static constexpr std::array field_names = { + "id", + "distance" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::Ability a_; + MyGame::Example::Test b_; + MyGame::Example::Ability c_; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsTypeTable(); + } + StructOfStructs() + : a_(), + b_(), + c_() { + } + StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c) + : a_(_a), + b_(_b), + c_(_c) { + } + const MyGame::Example::Ability &a() const { + return a_; + } + MyGame::Example::Ability &mutable_a() { + return a_; + } + const MyGame::Example::Test &b() const { + return b_; + } + MyGame::Example::Test &mutable_b() { + return b_; + } + const MyGame::Example::Ability &c() const { + return c_; + } + MyGame::Example::Ability &mutable_c() { + return c_; + } + template + auto get_field() const { + if constexpr (Index == 0) return a(); + else if constexpr (Index == 1) return b(); + else if constexpr (Index == 2) return c(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructs, 20); + +struct StructOfStructs::Traits { + using type = StructOfStructs; + static constexpr auto name = "StructOfStructs"; + static constexpr auto fully_qualified_name = "MyGame.Example.StructOfStructs"; + static constexpr size_t fields_number = 3; + static constexpr std::array field_names = { + "a", + "b", + "c" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructsOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::StructOfStructs a_; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsOfStructsTypeTable(); + } + StructOfStructsOfStructs() + : a_() { + } + StructOfStructsOfStructs(const MyGame::Example::StructOfStructs &_a) + : a_(_a) { + } + const MyGame::Example::StructOfStructs &a() const { + return a_; + } + MyGame::Example::StructOfStructs &mutable_a() { + return a_; + } + template + auto get_field() const { + if constexpr (Index == 0) return a(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructsOfStructs, 20); + +struct StructOfStructsOfStructs::Traits { + using type = StructOfStructsOfStructs; + static constexpr auto name = "StructOfStructsOfStructs"; + static constexpr auto fully_qualified_name = "MyGame.Example.StructOfStructsOfStructs"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "a" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +} // namespace Example + +struct InParentNamespaceT : public ::flatbuffers::NativeTable { + typedef InParentNamespace TableType; +}; + +struct InParentNamespace FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef InParentNamespaceT NativeTableType; + typedef InParentNamespaceBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return InParentNamespaceTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + InParentNamespaceT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct InParentNamespaceBuilder { + typedef InParentNamespace Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit InParentNamespaceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateInParentNamespace( + ::flatbuffers::FlatBufferBuilder &_fbb) { + InParentNamespaceBuilder builder_(_fbb); + return builder_.Finish(); +} + +struct InParentNamespace::Traits { + using type = InParentNamespace; + static auto constexpr Create = CreateInParentNamespace; + static constexpr auto name = "InParentNamespace"; + static constexpr auto fully_qualified_name = "MyGame.InParentNamespace"; + static constexpr size_t fields_number = 0; + static constexpr std::array field_names = {}; +}; + +::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +namespace Example2 { + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; +}; + +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb) { + MonsterBuilder builder_(_fbb); + return builder_.Finish(); +} + +struct Monster::Traits { + using type = Monster; + static auto constexpr Create = CreateMonster; + static constexpr auto name = "Monster"; + static constexpr auto fully_qualified_name = "MyGame.Example2.Monster"; + static constexpr size_t fields_number = 0; + static constexpr std::array field_names = {}; +}; + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example2 + +namespace Example { + +struct TestSimpleTableWithEnumT : public ::flatbuffers::NativeTable { + typedef TestSimpleTableWithEnum TableType; + MyGame::Example::Color color = MyGame::Example::Color::Green; +}; + +struct TestSimpleTableWithEnum FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TestSimpleTableWithEnumT NativeTableType; + typedef TestSimpleTableWithEnumBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestSimpleTableWithEnumTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_COLOR = 4 + }; + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 2)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(2)) { + return SetField(VT_COLOR, static_cast(_color), 2); + } + template + auto get_field() const { + if constexpr (Index == 0) return color(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_COLOR, 1) && + verifier.EndTable(); + } + TestSimpleTableWithEnumT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TestSimpleTableWithEnumBuilder { + typedef TestSimpleTableWithEnum Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(TestSimpleTableWithEnum::VT_COLOR, static_cast(color), 2); + } + explicit TestSimpleTableWithEnumBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum( + ::flatbuffers::FlatBufferBuilder &_fbb, + MyGame::Example::Color color = MyGame::Example::Color::Green) { + TestSimpleTableWithEnumBuilder builder_(_fbb); + builder_.add_color(color); + return builder_.Finish(); +} + +struct TestSimpleTableWithEnum::Traits { + using type = TestSimpleTableWithEnum; + static auto constexpr Create = CreateTestSimpleTableWithEnum; + static constexpr auto name = "TestSimpleTableWithEnum"; + static constexpr auto fully_qualified_name = "MyGame.Example.TestSimpleTableWithEnum"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "color" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct StatT : public ::flatbuffers::NativeTable { + typedef Stat TableType; + std::string id{}; + int64_t val = 0; + uint16_t count = 0; +}; + +struct Stat FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StatT NativeTableType; + typedef StatBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StatTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4, + VT_VAL = 6, + VT_COUNT = 8 + }; + const ::flatbuffers::String *id() const { + return GetPointer(VT_ID); + } + ::flatbuffers::String *mutable_id() { + return GetPointer<::flatbuffers::String *>(VT_ID); + } + int64_t val() const { + return GetField(VT_VAL, 0); + } + bool mutate_val(int64_t _val = 0) { + return SetField(VT_VAL, _val, 0); + } + uint16_t count() const { + return GetField(VT_COUNT, 0); + } + bool mutate_count(uint16_t _count = 0) { + return SetField(VT_COUNT, _count, 0); + } + bool KeyCompareLessThan(const Stat * const o) const { + return count() < o->count(); + } + int KeyCompareWithValue(uint16_t _count) const { + return static_cast(count() > _count) - static_cast(count() < _count); + } + template + auto get_field() const { + if constexpr (Index == 0) return id(); + else if constexpr (Index == 1) return val(); + else if constexpr (Index == 2) return count(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ID) && + verifier.VerifyString(id()) && + VerifyField(verifier, VT_VAL, 8) && + VerifyField(verifier, VT_COUNT, 2) && + verifier.EndTable(); + } + StatT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct StatBuilder { + typedef Stat Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(::flatbuffers::Offset<::flatbuffers::String> id) { + fbb_.AddOffset(Stat::VT_ID, id); + } + void add_val(int64_t val) { + fbb_.AddElement(Stat::VT_VAL, val, 0); + } + void add_count(uint16_t count) { + fbb_.AddElement(Stat::VT_COUNT, count, 0); + } + explicit StatBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStat( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> id = 0, + int64_t val = 0, + uint16_t count = 0) { + StatBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_id(id); + builder_.add_count(count); + return builder_.Finish(); +} + +struct Stat::Traits { + using type = Stat; + static auto constexpr Create = CreateStat; + static constexpr auto name = "Stat"; + static constexpr auto fully_qualified_name = "MyGame.Example.Stat"; + static constexpr size_t fields_number = 3; + static constexpr std::array field_names = { + "id", + "val", + "count" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +inline ::flatbuffers::Offset CreateStatDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *id = nullptr, + int64_t val = 0, + uint16_t count = 0) { + auto id__ = id ? _fbb.CreateString(id) : 0; + return MyGame::Example::CreateStat( + _fbb, + id__, + val, + count); +} + +::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct ReferrableT : public ::flatbuffers::NativeTable { + typedef Referrable TableType; + uint64_t id = 0; +}; + +struct Referrable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ReferrableT NativeTableType; + typedef ReferrableBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ReferrableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4 + }; + uint64_t id() const { + return GetField(VT_ID, 0); + } + bool mutate_id(uint64_t _id = 0) { + return SetField(VT_ID, _id, 0); + } + bool KeyCompareLessThan(const Referrable * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint64_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + template + auto get_field() const { + if constexpr (Index == 0) return id(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_ID, 8) && + verifier.EndTable(); + } + ReferrableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ReferrableBuilder { + typedef Referrable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(uint64_t id) { + fbb_.AddElement(Referrable::VT_ID, id, 0); + } + explicit ReferrableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateReferrable( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint64_t id = 0) { + ReferrableBuilder builder_(_fbb); + builder_.add_id(id); + return builder_.Finish(); +} + +struct Referrable::Traits { + using type = Referrable; + static auto constexpr Create = CreateReferrable; + static constexpr auto name = "Referrable"; + static constexpr auto fully_qualified_name = "MyGame.Example.Referrable"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "id" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; + std::unique_ptr pos{}; + int16_t mana = 150; + int16_t hp = 100; + std::string name{}; + std::vector inventory{}; + MyGame::Example::Color color = MyGame::Example::Color::Blue; + MyGame::Example::AnyUnion test{}; + std::vector test4{}; + std::vector testarrayofstring{}; + std::vector> testarrayoftables{}; + std::unique_ptr enemy{}; + std::vector testnestedflatbuffer{}; + std::unique_ptr testempty{}; + bool testbool = false; + int32_t testhashs32_fnv1 = 0; + uint32_t testhashu32_fnv1 = 0; + int64_t testhashs64_fnv1 = 0; + uint64_t testhashu64_fnv1 = 0; + int32_t testhashs32_fnv1a = 0; + Stat *testhashu32_fnv1a = nullptr; + int64_t testhashs64_fnv1a = 0; + uint64_t testhashu64_fnv1a = 0; + std::vector testarrayofbools{}; + float testf = 3.14159f; + float testf2 = 3.0f; + float testf3 = 0.0f; + std::vector testarrayofstring2{}; + std::vector testarrayofsortedstruct{}; + std::vector flex{}; + std::vector test5{}; + std::vector vector_of_longs{}; + std::vector vector_of_doubles{}; + std::unique_ptr parent_namespace_test{}; + std::vector> vector_of_referrables{}; + ReferrableT *single_weak_reference = nullptr; + std::vector vector_of_weak_references{}; + std::vector> vector_of_strong_referrables{}; + ReferrableT *co_owning_reference = nullptr; + std::vector> vector_of_co_owning_references{}; + ReferrableT *non_owning_reference = nullptr; + std::vector vector_of_non_owning_references{}; + MyGame::Example::AnyUniqueAliasesUnion any_unique{}; + MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous{}; + std::vector vector_of_enums{}; + MyGame::Example::Race signed_enum = MyGame::Example::Race::None; + std::vector testrequirednestedflatbuffer{}; + std::vector> scalar_key_sorted_tables{}; + MyGame::Example::Test native_inline{}; + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0); + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum::LongOne; + float nan_default = std::numeric_limits::quiet_NaN(); + float inf_default = std::numeric_limits::infinity(); + float positive_inf_default = std::numeric_limits::infinity(); + float infinity_default = std::numeric_limits::infinity(); + float positive_infinity_default = std::numeric_limits::infinity(); + float negative_inf_default = -std::numeric_limits::infinity(); + float negative_infinity_default = -std::numeric_limits::infinity(); + double double_inf_default = std::numeric_limits::infinity(); + MonsterT() = default; + MonsterT(const MonsterT &o); + MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default; + MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT; +}; + +/// an example documentation comment: "monster object" +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_POS = 4, + VT_MANA = 6, + VT_HP = 8, + VT_NAME = 10, + VT_INVENTORY = 14, + VT_COLOR = 16, + VT_TEST_TYPE = 18, + VT_TEST = 20, + VT_TEST4 = 22, + VT_TESTARRAYOFSTRING = 24, + VT_TESTARRAYOFTABLES = 26, + VT_ENEMY = 28, + VT_TESTNESTEDFLATBUFFER = 30, + VT_TESTEMPTY = 32, + VT_TESTBOOL = 34, + VT_TESTHASHS32_FNV1 = 36, + VT_TESTHASHU32_FNV1 = 38, + VT_TESTHASHS64_FNV1 = 40, + VT_TESTHASHU64_FNV1 = 42, + VT_TESTHASHS32_FNV1A = 44, + VT_TESTHASHU32_FNV1A = 46, + VT_TESTHASHS64_FNV1A = 48, + VT_TESTHASHU64_FNV1A = 50, + VT_TESTARRAYOFBOOLS = 52, + VT_TESTF = 54, + VT_TESTF2 = 56, + VT_TESTF3 = 58, + VT_TESTARRAYOFSTRING2 = 60, + VT_TESTARRAYOFSORTEDSTRUCT = 62, + VT_FLEX = 64, + VT_TEST5 = 66, + VT_VECTOR_OF_LONGS = 68, + VT_VECTOR_OF_DOUBLES = 70, + VT_PARENT_NAMESPACE_TEST = 72, + VT_VECTOR_OF_REFERRABLES = 74, + VT_SINGLE_WEAK_REFERENCE = 76, + VT_VECTOR_OF_WEAK_REFERENCES = 78, + VT_VECTOR_OF_STRONG_REFERRABLES = 80, + VT_CO_OWNING_REFERENCE = 82, + VT_VECTOR_OF_CO_OWNING_REFERENCES = 84, + VT_NON_OWNING_REFERENCE = 86, + VT_VECTOR_OF_NON_OWNING_REFERENCES = 88, + VT_ANY_UNIQUE_TYPE = 90, + VT_ANY_UNIQUE = 92, + VT_ANY_AMBIGUOUS_TYPE = 94, + VT_ANY_AMBIGUOUS = 96, + VT_VECTOR_OF_ENUMS = 98, + VT_SIGNED_ENUM = 100, + VT_TESTREQUIREDNESTEDFLATBUFFER = 102, + VT_SCALAR_KEY_SORTED_TABLES = 104, + VT_NATIVE_INLINE = 106, + VT_LONG_ENUM_NON_ENUM_DEFAULT = 108, + VT_LONG_ENUM_NORMAL_DEFAULT = 110, + VT_NAN_DEFAULT = 112, + VT_INF_DEFAULT = 114, + VT_POSITIVE_INF_DEFAULT = 116, + VT_INFINITY_DEFAULT = 118, + VT_POSITIVE_INFINITY_DEFAULT = 120, + VT_NEGATIVE_INF_DEFAULT = 122, + VT_NEGATIVE_INFINITY_DEFAULT = 124, + VT_DOUBLE_INF_DEFAULT = 126 + }; + const MyGame::Example::Vec3 *pos() const { + return GetStruct(VT_POS); + } + MyGame::Example::Vec3 *mutable_pos() { + return GetStruct(VT_POS); + } + int16_t mana() const { + return GetField(VT_MANA, 150); + } + bool mutate_mana(int16_t _mana = 150) { + return SetField(VT_MANA, _mana, 150); + } + int16_t hp() const { + return GetField(VT_HP, 100); + } + bool mutate_hp(int16_t _hp = 100) { + return SetField(VT_HP, _hp, 100); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + bool KeyCompareLessThan(const Monster * const o) const { + return *name() < *o->name(); + } + int KeyCompareWithValue(const char *_name) const { + return strcmp(name()->c_str(), _name); + } + template + int KeyCompareWithValue(const StringType& _name) const { + if (name()->c_str() < _name) return -1; + if (_name < name()->c_str()) return 1; + return 0; + } + const ::flatbuffers::Vector *inventory() const { + return GetPointer *>(VT_INVENTORY); + } + ::flatbuffers::Vector *mutable_inventory() { + return GetPointer<::flatbuffers::Vector *>(VT_INVENTORY); + } + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 8)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(8)) { + return SetField(VT_COLOR, static_cast(_color), 8); + } + MyGame::Example::Any test_type() const { + return static_cast(GetField(VT_TEST_TYPE, 0)); + } + const void *test() const { + return GetPointer(VT_TEST); + } + template const T *test_as() const; + const MyGame::Example::Monster *test_as_Monster() const { + return test_type() == MyGame::Example::Any::Monster ? static_cast(test()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *test_as_TestSimpleTableWithEnum() const { + return test_type() == MyGame::Example::Any::TestSimpleTableWithEnum ? static_cast(test()) : nullptr; + } + const MyGame::Example2::Monster *test_as_MyGame_Example2_Monster() const { + return test_type() == MyGame::Example::Any::MyGame_Example2_Monster ? static_cast(test()) : nullptr; + } + void *mutable_test() { + return GetPointer(VT_TEST); + } + const ::flatbuffers::Vector *test4() const { + return GetPointer *>(VT_TEST4); + } + ::flatbuffers::Vector *mutable_test4() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST4); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING); + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + const ::flatbuffers::Vector<::flatbuffers::Offset> *testarrayoftables() const { + return GetPointer> *>(VT_TESTARRAYOFTABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_testarrayoftables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_TESTARRAYOFTABLES); + } + const MyGame::Example::Monster *enemy() const { + return GetPointer(VT_ENEMY); + } + MyGame::Example::Monster *mutable_enemy() { + return GetPointer(VT_ENEMY); + } + const ::flatbuffers::Vector *testnestedflatbuffer() const { + return GetPointer *>(VT_TESTNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testnestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testnestedflatbuffer_nested_root() const { + const auto _f = testnestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const MyGame::Example::Stat *testempty() const { + return GetPointer(VT_TESTEMPTY); + } + MyGame::Example::Stat *mutable_testempty() { + return GetPointer(VT_TESTEMPTY); + } + bool testbool() const { + return GetField(VT_TESTBOOL, 0) != 0; + } + bool mutate_testbool(bool _testbool = 0) { + return SetField(VT_TESTBOOL, static_cast(_testbool), 0); + } + int32_t testhashs32_fnv1() const { + return GetField(VT_TESTHASHS32_FNV1, 0); + } + bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) { + return SetField(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0); + } + uint32_t testhashu32_fnv1() const { + return GetField(VT_TESTHASHU32_FNV1, 0); + } + bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) { + return SetField(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0); + } + int64_t testhashs64_fnv1() const { + return GetField(VT_TESTHASHS64_FNV1, 0); + } + bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) { + return SetField(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0); + } + uint64_t testhashu64_fnv1() const { + return GetField(VT_TESTHASHU64_FNV1, 0); + } + bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) { + return SetField(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0); + } + int32_t testhashs32_fnv1a() const { + return GetField(VT_TESTHASHS32_FNV1A, 0); + } + bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) { + return SetField(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0); + } + uint32_t testhashu32_fnv1a() const { + return GetField(VT_TESTHASHU32_FNV1A, 0); + } + bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) { + return SetField(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0); + } + int64_t testhashs64_fnv1a() const { + return GetField(VT_TESTHASHS64_FNV1A, 0); + } + bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) { + return SetField(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0); + } + uint64_t testhashu64_fnv1a() const { + return GetField(VT_TESTHASHU64_FNV1A, 0); + } + bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) { + return SetField(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0); + } + const ::flatbuffers::Vector *testarrayofbools() const { + return GetPointer *>(VT_TESTARRAYOFBOOLS); + } + ::flatbuffers::Vector *mutable_testarrayofbools() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFBOOLS); + } + float testf() const { + return GetField(VT_TESTF, 3.14159f); + } + bool mutate_testf(float _testf = 3.14159f) { + return SetField(VT_TESTF, _testf, 3.14159f); + } + float testf2() const { + return GetField(VT_TESTF2, 3.0f); + } + bool mutate_testf2(float _testf2 = 3.0f) { + return SetField(VT_TESTF2, _testf2, 3.0f); + } + float testf3() const { + return GetField(VT_TESTF3, 0.0f); + } + bool mutate_testf3(float _testf3 = 0.0f) { + return SetField(VT_TESTF3, _testf3, 0.0f); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING2); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring2() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING2); + } + const ::flatbuffers::Vector *testarrayofsortedstruct() const { + return GetPointer *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + ::flatbuffers::Vector *mutable_testarrayofsortedstruct() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + const ::flatbuffers::Vector *flex() const { + return GetPointer *>(VT_FLEX); + } + ::flatbuffers::Vector *mutable_flex() { + return GetPointer<::flatbuffers::Vector *>(VT_FLEX); + } + flexbuffers::Reference flex_flexbuffer_root() const { + const auto _f = flex(); + return _f ? flexbuffers::GetRoot(_f->Data(), _f->size()) + : flexbuffers::Reference(); + } + const ::flatbuffers::Vector *test5() const { + return GetPointer *>(VT_TEST5); + } + ::flatbuffers::Vector *mutable_test5() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST5); + } + const ::flatbuffers::Vector *vector_of_longs() const { + return GetPointer *>(VT_VECTOR_OF_LONGS); + } + ::flatbuffers::Vector *mutable_vector_of_longs() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_LONGS); + } + const ::flatbuffers::Vector *vector_of_doubles() const { + return GetPointer *>(VT_VECTOR_OF_DOUBLES); + } + ::flatbuffers::Vector *mutable_vector_of_doubles() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_DOUBLES); + } + const MyGame::InParentNamespace *parent_namespace_test() const { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + MyGame::InParentNamespace *mutable_parent_namespace_test() { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_REFERRABLES); + } + uint64_t single_weak_reference() const { + return GetField(VT_SINGLE_WEAK_REFERENCE, 0); + } + bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) { + return SetField(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0); + } + const ::flatbuffers::Vector *vector_of_weak_references() const { + return GetPointer *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_weak_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_strong_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_strong_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + uint64_t co_owning_reference() const { + return GetField(VT_CO_OWNING_REFERENCE, 0); + } + bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) { + return SetField(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_co_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_co_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + uint64_t non_owning_reference() const { + return GetField(VT_NON_OWNING_REFERENCE, 0); + } + bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) { + return SetField(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_non_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_non_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + MyGame::Example::AnyUniqueAliases any_unique_type() const { + return static_cast(GetField(VT_ANY_UNIQUE_TYPE, 0)); + } + const void *any_unique() const { + return GetPointer(VT_ANY_UNIQUE); + } + template const T *any_unique_as() const; + const MyGame::Example::Monster *any_unique_as_M() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases::M ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *any_unique_as_TS() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases::TS ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example2::Monster *any_unique_as_M2() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases::M2 ? static_cast(any_unique()) : nullptr; + } + void *mutable_any_unique() { + return GetPointer(VT_ANY_UNIQUE); + } + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type() const { + return static_cast(GetField(VT_ANY_AMBIGUOUS_TYPE, 0)); + } + const void *any_ambiguous() const { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const MyGame::Example::Monster *any_ambiguous_as_M1() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases::M1 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M2() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases::M2 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M3() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases::M3 ? static_cast(any_ambiguous()) : nullptr; + } + void *mutable_any_ambiguous() { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const ::flatbuffers::Vector *vector_of_enums() const { + return GetPointer *>(VT_VECTOR_OF_ENUMS); + } + ::flatbuffers::Vector *mutable_vector_of_enums() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_ENUMS); + } + MyGame::Example::Race signed_enum() const { + return static_cast(GetField(VT_SIGNED_ENUM, -1)); + } + bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast(-1)) { + return SetField(VT_SIGNED_ENUM, static_cast(_signed_enum), -1); + } + const ::flatbuffers::Vector *testrequirednestedflatbuffer() const { + return GetPointer *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testrequirednestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const { + const auto _f = testrequirednestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *scalar_key_sorted_tables() const { + return GetPointer> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_scalar_key_sorted_tables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + const MyGame::Example::Test *native_inline() const { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::Test *mutable_native_inline() { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::LongEnum long_enum_non_enum_default() const { + return static_cast(GetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0)); + } + bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast(0)) { + return SetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(_long_enum_non_enum_default), 0); + } + MyGame::Example::LongEnum long_enum_normal_default() const { + return static_cast(GetField(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL)); + } + bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast(2ULL)) { + return SetField(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(_long_enum_normal_default), 2ULL); + } + float nan_default() const { + return GetField(VT_NAN_DEFAULT, std::numeric_limits::quiet_NaN()); + } + bool mutate_nan_default(float _nan_default = std::numeric_limits::quiet_NaN()) { + return SetField(VT_NAN_DEFAULT, _nan_default, std::numeric_limits::quiet_NaN()); + } + float inf_default() const { + return GetField(VT_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_inf_default(float _inf_default = std::numeric_limits::infinity()) { + return SetField(VT_INF_DEFAULT, _inf_default, std::numeric_limits::infinity()); + } + float positive_inf_default() const { + return GetField(VT_POSITIVE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_inf_default(float _positive_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INF_DEFAULT, _positive_inf_default, std::numeric_limits::infinity()); + } + float infinity_default() const { + return GetField(VT_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_infinity_default(float _infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_INFINITY_DEFAULT, _infinity_default, std::numeric_limits::infinity()); + } + float positive_infinity_default() const { + return GetField(VT_POSITIVE_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_infinity_default(float _positive_infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INFINITY_DEFAULT, _positive_infinity_default, std::numeric_limits::infinity()); + } + float negative_inf_default() const { + return GetField(VT_NEGATIVE_INF_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_inf_default(float _negative_inf_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INF_DEFAULT, _negative_inf_default, -std::numeric_limits::infinity()); + } + float negative_infinity_default() const { + return GetField(VT_NEGATIVE_INFINITY_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_infinity_default(float _negative_infinity_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INFINITY_DEFAULT, _negative_infinity_default, -std::numeric_limits::infinity()); + } + double double_inf_default() const { + return GetField(VT_DOUBLE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_double_inf_default(double _double_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_DOUBLE_INF_DEFAULT, _double_inf_default, std::numeric_limits::infinity()); + } + template + auto get_field() const { + if constexpr (Index == 0) return pos(); + else if constexpr (Index == 1) return mana(); + else if constexpr (Index == 2) return hp(); + else if constexpr (Index == 3) return name(); + else if constexpr (Index == 4) return inventory(); + else if constexpr (Index == 5) return color(); + else if constexpr (Index == 6) return test_type(); + else if constexpr (Index == 7) return test(); + else if constexpr (Index == 8) return test4(); + else if constexpr (Index == 9) return testarrayofstring(); + else if constexpr (Index == 10) return testarrayoftables(); + else if constexpr (Index == 11) return enemy(); + else if constexpr (Index == 12) return testnestedflatbuffer(); + else if constexpr (Index == 13) return testempty(); + else if constexpr (Index == 14) return testbool(); + else if constexpr (Index == 15) return testhashs32_fnv1(); + else if constexpr (Index == 16) return testhashu32_fnv1(); + else if constexpr (Index == 17) return testhashs64_fnv1(); + else if constexpr (Index == 18) return testhashu64_fnv1(); + else if constexpr (Index == 19) return testhashs32_fnv1a(); + else if constexpr (Index == 20) return testhashu32_fnv1a(); + else if constexpr (Index == 21) return testhashs64_fnv1a(); + else if constexpr (Index == 22) return testhashu64_fnv1a(); + else if constexpr (Index == 23) return testarrayofbools(); + else if constexpr (Index == 24) return testf(); + else if constexpr (Index == 25) return testf2(); + else if constexpr (Index == 26) return testf3(); + else if constexpr (Index == 27) return testarrayofstring2(); + else if constexpr (Index == 28) return testarrayofsortedstruct(); + else if constexpr (Index == 29) return flex(); + else if constexpr (Index == 30) return test5(); + else if constexpr (Index == 31) return vector_of_longs(); + else if constexpr (Index == 32) return vector_of_doubles(); + else if constexpr (Index == 33) return parent_namespace_test(); + else if constexpr (Index == 34) return vector_of_referrables(); + else if constexpr (Index == 35) return single_weak_reference(); + else if constexpr (Index == 36) return vector_of_weak_references(); + else if constexpr (Index == 37) return vector_of_strong_referrables(); + else if constexpr (Index == 38) return co_owning_reference(); + else if constexpr (Index == 39) return vector_of_co_owning_references(); + else if constexpr (Index == 40) return non_owning_reference(); + else if constexpr (Index == 41) return vector_of_non_owning_references(); + else if constexpr (Index == 42) return any_unique_type(); + else if constexpr (Index == 43) return any_unique(); + else if constexpr (Index == 44) return any_ambiguous_type(); + else if constexpr (Index == 45) return any_ambiguous(); + else if constexpr (Index == 46) return vector_of_enums(); + else if constexpr (Index == 47) return signed_enum(); + else if constexpr (Index == 48) return testrequirednestedflatbuffer(); + else if constexpr (Index == 49) return scalar_key_sorted_tables(); + else if constexpr (Index == 50) return native_inline(); + else if constexpr (Index == 51) return long_enum_non_enum_default(); + else if constexpr (Index == 52) return long_enum_normal_default(); + else if constexpr (Index == 53) return nan_default(); + else if constexpr (Index == 54) return inf_default(); + else if constexpr (Index == 55) return positive_inf_default(); + else if constexpr (Index == 56) return infinity_default(); + else if constexpr (Index == 57) return positive_infinity_default(); + else if constexpr (Index == 58) return negative_inf_default(); + else if constexpr (Index == 59) return negative_infinity_default(); + else if constexpr (Index == 60) return double_inf_default(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_POS, 8) && + VerifyField(verifier, VT_MANA, 2) && + VerifyField(verifier, VT_HP, 2) && + VerifyOffsetRequired(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_INVENTORY) && + verifier.VerifyVector(inventory()) && + VerifyField(verifier, VT_COLOR, 1) && + VerifyField(verifier, VT_TEST_TYPE, 1) && + VerifyOffset(verifier, VT_TEST) && + VerifyAny(verifier, test(), test_type()) && + VerifyOffset(verifier, VT_TEST4) && + verifier.VerifyVector(test4()) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING) && + verifier.VerifyVector(testarrayofstring()) && + verifier.VerifyVectorOfStrings(testarrayofstring()) && + VerifyOffset(verifier, VT_TESTARRAYOFTABLES) && + verifier.VerifyVector(testarrayoftables()) && + verifier.VerifyVectorOfTables(testarrayoftables()) && + VerifyOffset(verifier, VT_ENEMY) && + verifier.VerifyTable(enemy()) && + VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) && + verifier.VerifyVector(testnestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testnestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_TESTEMPTY) && + verifier.VerifyTable(testempty()) && + VerifyField(verifier, VT_TESTBOOL, 1) && + VerifyField(verifier, VT_TESTHASHS32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHS32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1A, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1A, 8) && + VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) && + verifier.VerifyVector(testarrayofbools()) && + VerifyField(verifier, VT_TESTF, 4) && + VerifyField(verifier, VT_TESTF2, 4) && + VerifyField(verifier, VT_TESTF3, 4) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) && + verifier.VerifyVector(testarrayofstring2()) && + verifier.VerifyVectorOfStrings(testarrayofstring2()) && + VerifyOffset(verifier, VT_TESTARRAYOFSORTEDSTRUCT) && + verifier.VerifyVector(testarrayofsortedstruct()) && + VerifyOffset(verifier, VT_FLEX) && + verifier.VerifyVector(flex()) && + flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) && + VerifyOffset(verifier, VT_TEST5) && + verifier.VerifyVector(test5()) && + VerifyOffset(verifier, VT_VECTOR_OF_LONGS) && + verifier.VerifyVector(vector_of_longs()) && + VerifyOffset(verifier, VT_VECTOR_OF_DOUBLES) && + verifier.VerifyVector(vector_of_doubles()) && + VerifyOffset(verifier, VT_PARENT_NAMESPACE_TEST) && + verifier.VerifyTable(parent_namespace_test()) && + VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) && + verifier.VerifyVector(vector_of_referrables()) && + verifier.VerifyVectorOfTables(vector_of_referrables()) && + VerifyField(verifier, VT_SINGLE_WEAK_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) && + verifier.VerifyVector(vector_of_weak_references()) && + VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) && + verifier.VerifyVector(vector_of_strong_referrables()) && + verifier.VerifyVectorOfTables(vector_of_strong_referrables()) && + VerifyField(verifier, VT_CO_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_co_owning_references()) && + VerifyField(verifier, VT_NON_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_non_owning_references()) && + VerifyField(verifier, VT_ANY_UNIQUE_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_UNIQUE) && + VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) && + VerifyField(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_AMBIGUOUS) && + VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) && + VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) && + verifier.VerifyVector(vector_of_enums()) && + VerifyField(verifier, VT_SIGNED_ENUM, 1) && + VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) && + verifier.VerifyVector(testrequirednestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testrequirednestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) && + verifier.VerifyVector(scalar_key_sorted_tables()) && + verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) && + VerifyField(verifier, VT_NATIVE_INLINE, 2) && + VerifyField(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) && + VerifyField(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) && + VerifyField(verifier, VT_NAN_DEFAULT, 4) && + VerifyField(verifier, VT_INF_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_DOUBLE_INF_DEFAULT, 8) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const MyGame::Example::Monster *Monster::test_as() const { + return test_as_Monster(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::test_as() const { + return test_as_TestSimpleTableWithEnum(); +} + +template<> inline const MyGame::Example2::Monster *Monster::test_as() const { + return test_as_MyGame_Example2_Monster(); +} + +template<> inline const MyGame::Example::Monster *Monster::any_unique_as() const { + return any_unique_as_M(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::any_unique_as() const { + return any_unique_as_TS(); +} + +template<> inline const MyGame::Example2::Monster *Monster::any_unique_as() const { + return any_unique_as_M2(); +} + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_pos(const MyGame::Example::Vec3 *pos) { + fbb_.AddStruct(Monster::VT_POS, pos); + } + void add_mana(int16_t mana) { + fbb_.AddElement(Monster::VT_MANA, mana, 150); + } + void add_hp(int16_t hp) { + fbb_.AddElement(Monster::VT_HP, hp, 100); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Monster::VT_NAME, name); + } + void add_inventory(::flatbuffers::Offset<::flatbuffers::Vector> inventory) { + fbb_.AddOffset(Monster::VT_INVENTORY, inventory); + } + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(Monster::VT_COLOR, static_cast(color), 8); + } + void add_test_type(MyGame::Example::Any test_type) { + fbb_.AddElement(Monster::VT_TEST_TYPE, static_cast(test_type), 0); + } + void add_test(::flatbuffers::Offset test) { + fbb_.AddOffset(Monster::VT_TEST, test); + } + void add_test4(::flatbuffers::Offset<::flatbuffers::Vector> test4) { + fbb_.AddOffset(Monster::VT_TEST4, test4); + } + void add_testarrayofstring(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + void add_testarrayoftables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + void add_enemy(::flatbuffers::Offset enemy) { + fbb_.AddOffset(Monster::VT_ENEMY, enemy); + } + void add_testnestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + void add_testempty(::flatbuffers::Offset testempty) { + fbb_.AddOffset(Monster::VT_TESTEMPTY, testempty); + } + void add_testbool(bool testbool) { + fbb_.AddElement(Monster::VT_TESTBOOL, static_cast(testbool), 0); + } + void add_testhashs32_fnv1(int32_t testhashs32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + void add_testhashu32_fnv1(uint32_t testhashu32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + void add_testhashs64_fnv1(int64_t testhashs64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + void add_testhashu64_fnv1(uint64_t testhashu64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + void add_testhashs32_fnv1a(int32_t testhashs32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + void add_testhashu32_fnv1a(uint32_t testhashu32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + void add_testhashs64_fnv1a(int64_t testhashs64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + void add_testhashu64_fnv1a(uint64_t testhashu64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + void add_testarrayofbools(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + void add_testf(float testf) { + fbb_.AddElement(Monster::VT_TESTF, testf, 3.14159f); + } + void add_testf2(float testf2) { + fbb_.AddElement(Monster::VT_TESTF2, testf2, 3.0f); + } + void add_testf3(float testf3) { + fbb_.AddElement(Monster::VT_TESTF3, testf3, 0.0f); + } + void add_testarrayofstring2(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + void add_testarrayofsortedstruct(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + void add_flex(::flatbuffers::Offset<::flatbuffers::Vector> flex) { + fbb_.AddOffset(Monster::VT_FLEX, flex); + } + void add_test5(::flatbuffers::Offset<::flatbuffers::Vector> test5) { + fbb_.AddOffset(Monster::VT_TEST5, test5); + } + void add_vector_of_longs(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + void add_vector_of_doubles(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + void add_parent_namespace_test(::flatbuffers::Offset parent_namespace_test) { + fbb_.AddOffset(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + void add_vector_of_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + void add_single_weak_reference(uint64_t single_weak_reference) { + fbb_.AddElement(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + void add_vector_of_weak_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + void add_vector_of_strong_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + void add_co_owning_reference(uint64_t co_owning_reference) { + fbb_.AddElement(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + void add_vector_of_co_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + void add_non_owning_reference(uint64_t non_owning_reference) { + fbb_.AddElement(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + void add_vector_of_non_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + void add_any_unique_type(MyGame::Example::AnyUniqueAliases any_unique_type) { + fbb_.AddElement(Monster::VT_ANY_UNIQUE_TYPE, static_cast(any_unique_type), 0); + } + void add_any_unique(::flatbuffers::Offset any_unique) { + fbb_.AddOffset(Monster::VT_ANY_UNIQUE, any_unique); + } + void add_any_ambiguous_type(MyGame::Example::AnyAmbiguousAliases any_ambiguous_type) { + fbb_.AddElement(Monster::VT_ANY_AMBIGUOUS_TYPE, static_cast(any_ambiguous_type), 0); + } + void add_any_ambiguous(::flatbuffers::Offset any_ambiguous) { + fbb_.AddOffset(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + void add_vector_of_enums(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + void add_signed_enum(MyGame::Example::Race signed_enum) { + fbb_.AddElement(Monster::VT_SIGNED_ENUM, static_cast(signed_enum), -1); + } + void add_testrequirednestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + void add_scalar_key_sorted_tables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables) { + fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + void add_native_inline(const MyGame::Example::Test *native_inline) { + fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline); + } + void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(long_enum_non_enum_default), 0); + } + void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(long_enum_normal_default), 2ULL); + } + void add_nan_default(float nan_default) { + fbb_.AddElement(Monster::VT_NAN_DEFAULT, nan_default, std::numeric_limits::quiet_NaN()); + } + void add_inf_default(float inf_default) { + fbb_.AddElement(Monster::VT_INF_DEFAULT, inf_default, std::numeric_limits::infinity()); + } + void add_positive_inf_default(float positive_inf_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, std::numeric_limits::infinity()); + } + void add_infinity_default(float infinity_default) { + fbb_.AddElement(Monster::VT_INFINITY_DEFAULT, infinity_default, std::numeric_limits::infinity()); + } + void add_positive_infinity_default(float positive_infinity_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, std::numeric_limits::infinity()); + } + void add_negative_inf_default(float negative_inf_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, -std::numeric_limits::infinity()); + } + void add_negative_infinity_default(float negative_infinity_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, -std::numeric_limits::infinity()); + } + void add_double_inf_default(double double_inf_default) { + fbb_.AddElement(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, std::numeric_limits::infinity()); + } + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + fbb_.Required(o, Monster::VT_NAME); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> inventory = 0, + MyGame::Example::Color color = MyGame::Example::Color::Blue, + MyGame::Example::Any test_type = MyGame::Example::Any::NONE, + ::flatbuffers::Offset test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test4 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables = 0, + ::flatbuffers::Offset enemy = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer = 0, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools = 0, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> flex = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test5 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles = 0, + ::flatbuffers::Offset parent_namespace_test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables = 0, + uint64_t single_weak_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables = 0, + uint64_t co_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references = 0, + uint64_t non_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references = 0, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases::NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases::NONE, + ::flatbuffers::Offset any_ambiguous = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums = 0, + MyGame::Example::Race signed_enum = MyGame::Example::Race::None, + ::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables = 0, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum::LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + MonsterBuilder builder_(_fbb); + builder_.add_double_inf_default(double_inf_default); + builder_.add_long_enum_normal_default(long_enum_normal_default); + builder_.add_long_enum_non_enum_default(long_enum_non_enum_default); + builder_.add_non_owning_reference(non_owning_reference); + builder_.add_co_owning_reference(co_owning_reference); + builder_.add_single_weak_reference(single_weak_reference); + builder_.add_testhashu64_fnv1a(testhashu64_fnv1a); + builder_.add_testhashs64_fnv1a(testhashs64_fnv1a); + builder_.add_testhashu64_fnv1(testhashu64_fnv1); + builder_.add_testhashs64_fnv1(testhashs64_fnv1); + builder_.add_negative_infinity_default(negative_infinity_default); + builder_.add_negative_inf_default(negative_inf_default); + builder_.add_positive_infinity_default(positive_infinity_default); + builder_.add_infinity_default(infinity_default); + builder_.add_positive_inf_default(positive_inf_default); + builder_.add_inf_default(inf_default); + builder_.add_nan_default(nan_default); + builder_.add_native_inline(native_inline); + builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables); + builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer); + builder_.add_vector_of_enums(vector_of_enums); + builder_.add_any_ambiguous(any_ambiguous); + builder_.add_any_unique(any_unique); + builder_.add_vector_of_non_owning_references(vector_of_non_owning_references); + builder_.add_vector_of_co_owning_references(vector_of_co_owning_references); + builder_.add_vector_of_strong_referrables(vector_of_strong_referrables); + builder_.add_vector_of_weak_references(vector_of_weak_references); + builder_.add_vector_of_referrables(vector_of_referrables); + builder_.add_parent_namespace_test(parent_namespace_test); + builder_.add_vector_of_doubles(vector_of_doubles); + builder_.add_vector_of_longs(vector_of_longs); + builder_.add_test5(test5); + builder_.add_flex(flex); + builder_.add_testarrayofsortedstruct(testarrayofsortedstruct); + builder_.add_testarrayofstring2(testarrayofstring2); + builder_.add_testf3(testf3); + builder_.add_testf2(testf2); + builder_.add_testf(testf); + builder_.add_testarrayofbools(testarrayofbools); + builder_.add_testhashu32_fnv1a(testhashu32_fnv1a); + builder_.add_testhashs32_fnv1a(testhashs32_fnv1a); + builder_.add_testhashu32_fnv1(testhashu32_fnv1); + builder_.add_testhashs32_fnv1(testhashs32_fnv1); + builder_.add_testempty(testempty); + builder_.add_testnestedflatbuffer(testnestedflatbuffer); + builder_.add_enemy(enemy); + builder_.add_testarrayoftables(testarrayoftables); + builder_.add_testarrayofstring(testarrayofstring); + builder_.add_test4(test4); + builder_.add_test(test); + builder_.add_inventory(inventory); + builder_.add_name(name); + builder_.add_pos(pos); + builder_.add_hp(hp); + builder_.add_mana(mana); + builder_.add_signed_enum(signed_enum); + builder_.add_any_ambiguous_type(any_ambiguous_type); + builder_.add_any_unique_type(any_unique_type); + builder_.add_testbool(testbool); + builder_.add_test_type(test_type); + builder_.add_color(color); + return builder_.Finish(); +} + +struct Monster::Traits { + using type = Monster; + static auto constexpr Create = CreateMonster; + static constexpr auto name = "Monster"; + static constexpr auto fully_qualified_name = "MyGame.Example.Monster"; + static constexpr size_t fields_number = 61; + static constexpr std::array field_names = { + "pos", + "mana", + "hp", + "name", + "inventory", + "color", + "test_type", + "test", + "test4", + "testarrayofstring", + "testarrayoftables", + "enemy", + "testnestedflatbuffer", + "testempty", + "testbool", + "testhashs32_fnv1", + "testhashu32_fnv1", + "testhashs64_fnv1", + "testhashu64_fnv1", + "testhashs32_fnv1a", + "testhashu32_fnv1a", + "testhashs64_fnv1a", + "testhashu64_fnv1a", + "testarrayofbools", + "testf", + "testf2", + "testf3", + "testarrayofstring2", + "testarrayofsortedstruct", + "flex", + "test5", + "vector_of_longs", + "vector_of_doubles", + "parent_namespace_test", + "vector_of_referrables", + "single_weak_reference", + "vector_of_weak_references", + "vector_of_strong_referrables", + "co_owning_reference", + "vector_of_co_owning_references", + "non_owning_reference", + "vector_of_non_owning_references", + "any_unique_type", + "any_unique", + "any_ambiguous_type", + "any_ambiguous", + "vector_of_enums", + "signed_enum", + "testrequirednestedflatbuffer", + "scalar_key_sorted_tables", + "native_inline", + "long_enum_non_enum_default", + "long_enum_normal_default", + "nan_default", + "inf_default", + "positive_inf_default", + "infinity_default", + "positive_infinity_default", + "negative_inf_default", + "negative_infinity_default", + "double_inf_default" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +inline ::flatbuffers::Offset CreateMonsterDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + const char *name = nullptr, + const std::vector *inventory = nullptr, + MyGame::Example::Color color = MyGame::Example::Color::Blue, + MyGame::Example::Any test_type = MyGame::Example::Any::NONE, + ::flatbuffers::Offset test = 0, + const std::vector *test4 = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring = nullptr, + std::vector<::flatbuffers::Offset> *testarrayoftables = nullptr, + ::flatbuffers::Offset enemy = 0, + const std::vector *testnestedflatbuffer = nullptr, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + const std::vector *testarrayofbools = nullptr, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2 = nullptr, + std::vector *testarrayofsortedstruct = nullptr, + const std::vector *flex = nullptr, + const std::vector *test5 = nullptr, + const std::vector *vector_of_longs = nullptr, + const std::vector *vector_of_doubles = nullptr, + ::flatbuffers::Offset parent_namespace_test = 0, + std::vector<::flatbuffers::Offset> *vector_of_referrables = nullptr, + uint64_t single_weak_reference = 0, + const std::vector *vector_of_weak_references = nullptr, + std::vector<::flatbuffers::Offset> *vector_of_strong_referrables = nullptr, + uint64_t co_owning_reference = 0, + const std::vector *vector_of_co_owning_references = nullptr, + uint64_t non_owning_reference = 0, + const std::vector *vector_of_non_owning_references = nullptr, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases::NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases::NONE, + ::flatbuffers::Offset any_ambiguous = 0, + const std::vector *vector_of_enums = nullptr, + MyGame::Example::Race signed_enum = MyGame::Example::Race::None, + const std::vector *testrequirednestedflatbuffer = nullptr, + std::vector<::flatbuffers::Offset> *scalar_key_sorted_tables = nullptr, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum::LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto inventory__ = inventory ? _fbb.CreateVector(*inventory) : 0; + auto test4__ = test4 ? _fbb.CreateVectorOfStructs(*test4) : 0; + auto testarrayofstring__ = testarrayofstring ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring) : 0; + auto testarrayoftables__ = testarrayoftables ? _fbb.CreateVectorOfSortedTables(testarrayoftables) : 0; + auto testnestedflatbuffer__ = testnestedflatbuffer ? _fbb.CreateVector(*testnestedflatbuffer) : 0; + auto testarrayofbools__ = testarrayofbools ? _fbb.CreateVector(*testarrayofbools) : 0; + auto testarrayofstring2__ = testarrayofstring2 ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring2) : 0; + auto testarrayofsortedstruct__ = testarrayofsortedstruct ? _fbb.CreateVectorOfSortedStructs(testarrayofsortedstruct) : 0; + auto flex__ = flex ? _fbb.CreateVector(*flex) : 0; + auto test5__ = test5 ? _fbb.CreateVectorOfStructs(*test5) : 0; + auto vector_of_longs__ = vector_of_longs ? _fbb.CreateVector(*vector_of_longs) : 0; + auto vector_of_doubles__ = vector_of_doubles ? _fbb.CreateVector(*vector_of_doubles) : 0; + auto vector_of_referrables__ = vector_of_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_referrables) : 0; + auto vector_of_weak_references__ = vector_of_weak_references ? _fbb.CreateVector(*vector_of_weak_references) : 0; + auto vector_of_strong_referrables__ = vector_of_strong_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_strong_referrables) : 0; + auto vector_of_co_owning_references__ = vector_of_co_owning_references ? _fbb.CreateVector(*vector_of_co_owning_references) : 0; + auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector(*vector_of_non_owning_references) : 0; + auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector(*vector_of_enums) : 0; + auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector(*testrequirednestedflatbuffer) : 0; + auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables(scalar_key_sorted_tables) : 0; + return MyGame::Example::CreateMonster( + _fbb, + pos, + mana, + hp, + name__, + inventory__, + color, + test_type, + test, + test4__, + testarrayofstring__, + testarrayoftables__, + enemy, + testnestedflatbuffer__, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools__, + testf, + testf2, + testf3, + testarrayofstring2__, + testarrayofsortedstruct__, + flex__, + test5__, + vector_of_longs__, + vector_of_doubles__, + parent_namespace_test, + vector_of_referrables__, + single_weak_reference, + vector_of_weak_references__, + vector_of_strong_referrables__, + co_owning_reference, + vector_of_co_owning_references__, + non_owning_reference, + vector_of_non_owning_references__, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums__, + signed_enum, + testrequirednestedflatbuffer__, + scalar_key_sorted_tables__, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct TypeAliasesT : public ::flatbuffers::NativeTable { + typedef TypeAliases TableType; + int8_t i8 = 0; + uint8_t u8 = 0; + int16_t i16 = 0; + uint16_t u16 = 0; + int32_t i32 = 0; + uint32_t u32 = 0; + int64_t i64 = 0; + uint64_t u64 = 0; + float f32 = 0.0f; + double f64 = 0.0; + std::vector v8{}; + std::vector vf64{}; +}; + +struct TypeAliases FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TypeAliasesT NativeTableType; + typedef TypeAliasesBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TypeAliasesTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_I8 = 4, + VT_U8 = 6, + VT_I16 = 8, + VT_U16 = 10, + VT_I32 = 12, + VT_U32 = 14, + VT_I64 = 16, + VT_U64 = 18, + VT_F32 = 20, + VT_F64 = 22, + VT_V8 = 24, + VT_VF64 = 26 + }; + int8_t i8() const { + return GetField(VT_I8, 0); + } + bool mutate_i8(int8_t _i8 = 0) { + return SetField(VT_I8, _i8, 0); + } + uint8_t u8() const { + return GetField(VT_U8, 0); + } + bool mutate_u8(uint8_t _u8 = 0) { + return SetField(VT_U8, _u8, 0); + } + int16_t i16() const { + return GetField(VT_I16, 0); + } + bool mutate_i16(int16_t _i16 = 0) { + return SetField(VT_I16, _i16, 0); + } + uint16_t u16() const { + return GetField(VT_U16, 0); + } + bool mutate_u16(uint16_t _u16 = 0) { + return SetField(VT_U16, _u16, 0); + } + int32_t i32() const { + return GetField(VT_I32, 0); + } + bool mutate_i32(int32_t _i32 = 0) { + return SetField(VT_I32, _i32, 0); + } + uint32_t u32() const { + return GetField(VT_U32, 0); + } + bool mutate_u32(uint32_t _u32 = 0) { + return SetField(VT_U32, _u32, 0); + } + int64_t i64() const { + return GetField(VT_I64, 0); + } + bool mutate_i64(int64_t _i64 = 0) { + return SetField(VT_I64, _i64, 0); + } + uint64_t u64() const { + return GetField(VT_U64, 0); + } + bool mutate_u64(uint64_t _u64 = 0) { + return SetField(VT_U64, _u64, 0); + } + float f32() const { + return GetField(VT_F32, 0.0f); + } + bool mutate_f32(float _f32 = 0.0f) { + return SetField(VT_F32, _f32, 0.0f); + } + double f64() const { + return GetField(VT_F64, 0.0); + } + bool mutate_f64(double _f64 = 0.0) { + return SetField(VT_F64, _f64, 0.0); + } + const ::flatbuffers::Vector *v8() const { + return GetPointer *>(VT_V8); + } + ::flatbuffers::Vector *mutable_v8() { + return GetPointer<::flatbuffers::Vector *>(VT_V8); + } + const ::flatbuffers::Vector *vf64() const { + return GetPointer *>(VT_VF64); + } + ::flatbuffers::Vector *mutable_vf64() { + return GetPointer<::flatbuffers::Vector *>(VT_VF64); + } + template + auto get_field() const { + if constexpr (Index == 0) return i8(); + else if constexpr (Index == 1) return u8(); + else if constexpr (Index == 2) return i16(); + else if constexpr (Index == 3) return u16(); + else if constexpr (Index == 4) return i32(); + else if constexpr (Index == 5) return u32(); + else if constexpr (Index == 6) return i64(); + else if constexpr (Index == 7) return u64(); + else if constexpr (Index == 8) return f32(); + else if constexpr (Index == 9) return f64(); + else if constexpr (Index == 10) return v8(); + else if constexpr (Index == 11) return vf64(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_I8, 1) && + VerifyField(verifier, VT_U8, 1) && + VerifyField(verifier, VT_I16, 2) && + VerifyField(verifier, VT_U16, 2) && + VerifyField(verifier, VT_I32, 4) && + VerifyField(verifier, VT_U32, 4) && + VerifyField(verifier, VT_I64, 8) && + VerifyField(verifier, VT_U64, 8) && + VerifyField(verifier, VT_F32, 4) && + VerifyField(verifier, VT_F64, 8) && + VerifyOffset(verifier, VT_V8) && + verifier.VerifyVector(v8()) && + VerifyOffset(verifier, VT_VF64) && + verifier.VerifyVector(vf64()) && + verifier.EndTable(); + } + TypeAliasesT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TypeAliasesBuilder { + typedef TypeAliases Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_i8(int8_t i8) { + fbb_.AddElement(TypeAliases::VT_I8, i8, 0); + } + void add_u8(uint8_t u8) { + fbb_.AddElement(TypeAliases::VT_U8, u8, 0); + } + void add_i16(int16_t i16) { + fbb_.AddElement(TypeAliases::VT_I16, i16, 0); + } + void add_u16(uint16_t u16) { + fbb_.AddElement(TypeAliases::VT_U16, u16, 0); + } + void add_i32(int32_t i32) { + fbb_.AddElement(TypeAliases::VT_I32, i32, 0); + } + void add_u32(uint32_t u32) { + fbb_.AddElement(TypeAliases::VT_U32, u32, 0); + } + void add_i64(int64_t i64) { + fbb_.AddElement(TypeAliases::VT_I64, i64, 0); + } + void add_u64(uint64_t u64) { + fbb_.AddElement(TypeAliases::VT_U64, u64, 0); + } + void add_f32(float f32) { + fbb_.AddElement(TypeAliases::VT_F32, f32, 0.0f); + } + void add_f64(double f64) { + fbb_.AddElement(TypeAliases::VT_F64, f64, 0.0); + } + void add_v8(::flatbuffers::Offset<::flatbuffers::Vector> v8) { + fbb_.AddOffset(TypeAliases::VT_V8, v8); + } + void add_vf64(::flatbuffers::Offset<::flatbuffers::Vector> vf64) { + fbb_.AddOffset(TypeAliases::VT_VF64, vf64); + } + explicit TypeAliasesBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTypeAliases( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + ::flatbuffers::Offset<::flatbuffers::Vector> v8 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vf64 = 0) { + TypeAliasesBuilder builder_(_fbb); + builder_.add_f64(f64); + builder_.add_u64(u64); + builder_.add_i64(i64); + builder_.add_vf64(vf64); + builder_.add_v8(v8); + builder_.add_f32(f32); + builder_.add_u32(u32); + builder_.add_i32(i32); + builder_.add_u16(u16); + builder_.add_i16(i16); + builder_.add_u8(u8); + builder_.add_i8(i8); + return builder_.Finish(); +} + +struct TypeAliases::Traits { + using type = TypeAliases; + static auto constexpr Create = CreateTypeAliases; + static constexpr auto name = "TypeAliases"; + static constexpr auto fully_qualified_name = "MyGame.Example.TypeAliases"; + static constexpr size_t fields_number = 12; + static constexpr std::array field_names = { + "i8", + "u8", + "i16", + "u16", + "i32", + "u32", + "i64", + "u64", + "f32", + "f64", + "v8", + "vf64" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +inline ::flatbuffers::Offset CreateTypeAliasesDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + const std::vector *v8 = nullptr, + const std::vector *vf64 = nullptr) { + auto v8__ = v8 ? _fbb.CreateVector(*v8) : 0; + auto vf64__ = vf64 ? _fbb.CreateVector(*vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + i8, + u8, + i16, + u16, + i32, + u32, + i64, + u64, + f32, + f64, + v8__, + vf64__); +} + +::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example + +inline InParentNamespaceT *InParentNamespace::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void InParentNamespace::UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset InParentNamespace::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateInParentNamespace(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const InParentNamespaceT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::CreateInParentNamespace( + _fbb); +} + +namespace Example2 { + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::Example2::CreateMonster( + _fbb); +} + +} // namespace Example2 + +namespace Example { + +inline TestSimpleTableWithEnumT *TestSimpleTableWithEnum::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TestSimpleTableWithEnum::UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = color(); _o->color = _e; } +} + +inline ::flatbuffers::Offset TestSimpleTableWithEnum::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTestSimpleTableWithEnum(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TestSimpleTableWithEnumT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _color = _o->color; + return MyGame::Example::CreateTestSimpleTableWithEnum( + _fbb, + _color); +} + +inline StatT *Stat::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Stat::UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); if (_e) _o->id = _e->str(); } + { auto _e = val(); _o->val = _e; } + { auto _e = count(); _o->count = _e; } +} + +inline ::flatbuffers::Offset Stat::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateStat(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const StatT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id.empty() ? 0 : _fbb.CreateString(_o->id); + auto _val = _o->val; + auto _count = _o->count; + return MyGame::Example::CreateStat( + _fbb, + _id, + _val, + _count); +} + +inline ReferrableT *Referrable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Referrable::UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); _o->id = _e; } +} + +inline ::flatbuffers::Offset Referrable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateReferrable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ReferrableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id; + return MyGame::Example::CreateReferrable( + _fbb, + _id); +} + +inline MonsterT::MonsterT(const MonsterT &o) + : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr), + mana(o.mana), + hp(o.hp), + name(o.name), + inventory(o.inventory), + color(o.color), + test(o.test), + test4(o.test4), + testarrayofstring(o.testarrayofstring), + enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr), + testnestedflatbuffer(o.testnestedflatbuffer), + testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr), + testbool(o.testbool), + testhashs32_fnv1(o.testhashs32_fnv1), + testhashu32_fnv1(o.testhashu32_fnv1), + testhashs64_fnv1(o.testhashs64_fnv1), + testhashu64_fnv1(o.testhashu64_fnv1), + testhashs32_fnv1a(o.testhashs32_fnv1a), + testhashu32_fnv1a(o.testhashu32_fnv1a), + testhashs64_fnv1a(o.testhashs64_fnv1a), + testhashu64_fnv1a(o.testhashu64_fnv1a), + testarrayofbools(o.testarrayofbools), + testf(o.testf), + testf2(o.testf2), + testf3(o.testf3), + testarrayofstring2(o.testarrayofstring2), + testarrayofsortedstruct(o.testarrayofsortedstruct), + flex(o.flex), + test5(o.test5), + vector_of_longs(o.vector_of_longs), + vector_of_doubles(o.vector_of_doubles), + parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr), + single_weak_reference(o.single_weak_reference), + vector_of_weak_references(o.vector_of_weak_references), + co_owning_reference(o.co_owning_reference), + non_owning_reference(o.non_owning_reference), + vector_of_non_owning_references(o.vector_of_non_owning_references), + any_unique(o.any_unique), + any_ambiguous(o.any_ambiguous), + vector_of_enums(o.vector_of_enums), + signed_enum(o.signed_enum), + testrequirednestedflatbuffer(o.testrequirednestedflatbuffer), + native_inline(o.native_inline), + long_enum_non_enum_default(o.long_enum_non_enum_default), + long_enum_normal_default(o.long_enum_normal_default), + nan_default(o.nan_default), + inf_default(o.inf_default), + positive_inf_default(o.positive_inf_default), + infinity_default(o.infinity_default), + positive_infinity_default(o.positive_infinity_default), + negative_inf_default(o.negative_inf_default), + negative_infinity_default(o.negative_infinity_default), + double_inf_default(o.double_inf_default) { + testarrayoftables.reserve(o.testarrayoftables.size()); + for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); } + vector_of_referrables.reserve(o.vector_of_referrables.size()); + for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); } + vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size()); + for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); } + vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size()); + for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); } + scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size()); + for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); } +} + +inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT { + std::swap(pos, o.pos); + std::swap(mana, o.mana); + std::swap(hp, o.hp); + std::swap(name, o.name); + std::swap(inventory, o.inventory); + std::swap(color, o.color); + std::swap(test, o.test); + std::swap(test4, o.test4); + std::swap(testarrayofstring, o.testarrayofstring); + std::swap(testarrayoftables, o.testarrayoftables); + std::swap(enemy, o.enemy); + std::swap(testnestedflatbuffer, o.testnestedflatbuffer); + std::swap(testempty, o.testempty); + std::swap(testbool, o.testbool); + std::swap(testhashs32_fnv1, o.testhashs32_fnv1); + std::swap(testhashu32_fnv1, o.testhashu32_fnv1); + std::swap(testhashs64_fnv1, o.testhashs64_fnv1); + std::swap(testhashu64_fnv1, o.testhashu64_fnv1); + std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a); + std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a); + std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a); + std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a); + std::swap(testarrayofbools, o.testarrayofbools); + std::swap(testf, o.testf); + std::swap(testf2, o.testf2); + std::swap(testf3, o.testf3); + std::swap(testarrayofstring2, o.testarrayofstring2); + std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct); + std::swap(flex, o.flex); + std::swap(test5, o.test5); + std::swap(vector_of_longs, o.vector_of_longs); + std::swap(vector_of_doubles, o.vector_of_doubles); + std::swap(parent_namespace_test, o.parent_namespace_test); + std::swap(vector_of_referrables, o.vector_of_referrables); + std::swap(single_weak_reference, o.single_weak_reference); + std::swap(vector_of_weak_references, o.vector_of_weak_references); + std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables); + std::swap(co_owning_reference, o.co_owning_reference); + std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references); + std::swap(non_owning_reference, o.non_owning_reference); + std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references); + std::swap(any_unique, o.any_unique); + std::swap(any_ambiguous, o.any_ambiguous); + std::swap(vector_of_enums, o.vector_of_enums); + std::swap(signed_enum, o.signed_enum); + std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer); + std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables); + std::swap(native_inline, o.native_inline); + std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default); + std::swap(long_enum_normal_default, o.long_enum_normal_default); + std::swap(nan_default, o.nan_default); + std::swap(inf_default, o.inf_default); + std::swap(positive_inf_default, o.positive_inf_default); + std::swap(infinity_default, o.infinity_default); + std::swap(positive_infinity_default, o.positive_infinity_default); + std::swap(negative_inf_default, o.negative_inf_default); + std::swap(negative_infinity_default, o.negative_infinity_default); + std::swap(double_inf_default, o.double_inf_default); + return *this; +} + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = pos(); if (_e) _o->pos = std::unique_ptr(new MyGame::Example::Vec3(*_e)); } + { auto _e = mana(); _o->mana = _e; } + { auto _e = hp(); _o->hp = _e; } + { auto _e = name(); if (_e) _o->name = _e->str(); } + { auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } } + { auto _e = color(); _o->color = _e; } + { auto _e = test_type(); _o->test.type = _e; } + { auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); } + { auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } else { _o->test4.resize(0); } } + { auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring.resize(0); } } + { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->testarrayoftables.resize(0); } } + { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->enemy) { _o->enemy.reset(); } } + { auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } } + { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->testempty) { _o->testempty.reset(); } } + { auto _e = testbool(); _o->testbool = _e; } + { auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; } + { auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; } + { auto _e = testhashs64_fnv1(); _o->testhashs64_fnv1 = _e; } + { auto _e = testhashu64_fnv1(); _o->testhashu64_fnv1 = _e; } + { auto _e = testhashs32_fnv1a(); _o->testhashs32_fnv1a = _e; } + { auto _e = testhashu32_fnv1a(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->testhashu32_fnv1a), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->testhashu32_fnv1a = nullptr; } + { auto _e = testhashs64_fnv1a(); _o->testhashs64_fnv1a = _e; } + { auto _e = testhashu64_fnv1a(); _o->testhashu64_fnv1a = _e; } + { auto _e = testarrayofbools(); if (_e) { _o->testarrayofbools.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofbools[_i] = _e->Get(_i) != 0; } } else { _o->testarrayofbools.resize(0); } } + { auto _e = testf(); _o->testf = _e; } + { auto _e = testf2(); _o->testf2 = _e; } + { auto _e = testf3(); _o->testf3 = _e; } + { auto _e = testarrayofstring2(); if (_e) { _o->testarrayofstring2.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring2[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring2.resize(0); } } + { auto _e = testarrayofsortedstruct(); if (_e) { _o->testarrayofsortedstruct.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofsortedstruct[_i] = *_e->Get(_i); } } else { _o->testarrayofsortedstruct.resize(0); } } + { auto _e = flex(); if (_e) { _o->flex.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->flex.begin()); } } + { auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } else { _o->test5.resize(0); } } + { auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } else { _o->vector_of_longs.resize(0); } } + { auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } else { _o->vector_of_doubles.resize(0); } } + { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->parent_namespace_test) { _o->parent_namespace_test.reset(); } } + { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_referrables.resize(0); } } + { auto _e = single_weak_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->single_weak_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; } + { auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_weak_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } else { _o->vector_of_weak_references.resize(0); } } + { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_strong_referrables.resize(0); } } + { auto _e = co_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->co_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; } + { auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, default_ptr_type*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_co_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i)));/* else do nothing */} } else { _o->vector_of_co_owning_references.resize(0); } } + { auto _e = non_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->non_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->non_owning_reference = nullptr; } + { auto _e = vector_of_non_owning_references(); if (_e) { _o->vector_of_non_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_non_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_non_owning_references[_i] = nullptr; } } else { _o->vector_of_non_owning_references.resize(0); } } + { auto _e = any_unique_type(); _o->any_unique.type = _e; } + { auto _e = any_unique(); if (_e) _o->any_unique.value = MyGame::Example::AnyUniqueAliasesUnion::UnPack(_e, any_unique_type(), _resolver); } + { auto _e = any_ambiguous_type(); _o->any_ambiguous.type = _e; } + { auto _e = any_ambiguous(); if (_e) _o->any_ambiguous.value = MyGame::Example::AnyAmbiguousAliasesUnion::UnPack(_e, any_ambiguous_type(), _resolver); } + { auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast(_e->Get(_i)); } } else { _o->vector_of_enums.resize(0); } } + { auto _e = signed_enum(); _o->signed_enum = _e; } + { auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } } + { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->scalar_key_sorted_tables.resize(0); } } + { auto _e = native_inline(); if (_e) _o->native_inline = *_e; } + { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; } + { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; } + { auto _e = nan_default(); _o->nan_default = _e; } + { auto _e = inf_default(); _o->inf_default = _e; } + { auto _e = positive_inf_default(); _o->positive_inf_default = _e; } + { auto _e = infinity_default(); _o->infinity_default = _e; } + { auto _e = positive_infinity_default(); _o->positive_infinity_default = _e; } + { auto _e = negative_inf_default(); _o->negative_inf_default = _e; } + { auto _e = negative_infinity_default(); _o->negative_infinity_default = _e; } + { auto _e = double_inf_default(); _o->double_inf_default = _e; } +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _pos = _o->pos ? _o->pos.get() : nullptr; + auto _mana = _o->mana; + auto _hp = _o->hp; + auto _name = _fbb.CreateString(_o->name); + auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0; + auto _color = _o->color; + auto _test_type = _o->test.type; + auto _test = _o->test.Pack(_fbb); + auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; + auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testbool = _o->testbool; + auto _testhashs32_fnv1 = _o->testhashs32_fnv1; + auto _testhashu32_fnv1 = _o->testhashu32_fnv1; + auto _testhashs64_fnv1 = _o->testhashs64_fnv1; + auto _testhashu64_fnv1 = _o->testhashu64_fnv1; + auto _testhashs32_fnv1a = _o->testhashs32_fnv1a; + auto _testhashu32_fnv1a = _rehasher ? static_cast((*_rehasher)(_o->testhashu32_fnv1a)) : 0; + auto _testhashs64_fnv1a = _o->testhashs64_fnv1a; + auto _testhashu64_fnv1a = _o->testhashu64_fnv1a; + auto _testarrayofbools = _o->testarrayofbools.size() ? _fbb.CreateVector(_o->testarrayofbools) : 0; + auto _testf = _o->testf; + auto _testf2 = _o->testf2; + auto _testf3 = _o->testf3; + auto _testarrayofstring2 = _o->testarrayofstring2.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring2) : 0; + auto _testarrayofsortedstruct = _o->testarrayofsortedstruct.size() ? _fbb.CreateVectorOfStructs(_o->testarrayofsortedstruct) : 0; + auto _flex = _o->flex.size() ? _fbb.CreateVector(_o->flex) : 0; + auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; + auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; + auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; + auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; + auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; + auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; + auto _vector_of_non_owning_references = _o->vector_of_non_owning_references.size() ? _fbb.CreateVector(_o->vector_of_non_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_non_owning_references[i])) : 0; }, &_va ) : 0; + auto _any_unique_type = _o->any_unique.type; + auto _any_unique = _o->any_unique.Pack(_fbb); + auto _any_ambiguous_type = _o->any_ambiguous.type; + auto _any_ambiguous = _o->any_ambiguous.Pack(_fbb); + auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVector(_o->vector_of_enums) : 0; + auto _signed_enum = _o->signed_enum; + auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _native_inline = &_o->native_inline; + auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; + auto _long_enum_normal_default = _o->long_enum_normal_default; + auto _nan_default = _o->nan_default; + auto _inf_default = _o->inf_default; + auto _positive_inf_default = _o->positive_inf_default; + auto _infinity_default = _o->infinity_default; + auto _positive_infinity_default = _o->positive_infinity_default; + auto _negative_inf_default = _o->negative_inf_default; + auto _negative_infinity_default = _o->negative_infinity_default; + auto _double_inf_default = _o->double_inf_default; + return MyGame::Example::CreateMonster( + _fbb, + _pos, + _mana, + _hp, + _name, + _inventory, + _color, + _test_type, + _test, + _test4, + _testarrayofstring, + _testarrayoftables, + _enemy, + _testnestedflatbuffer, + _testempty, + _testbool, + _testhashs32_fnv1, + _testhashu32_fnv1, + _testhashs64_fnv1, + _testhashu64_fnv1, + _testhashs32_fnv1a, + _testhashu32_fnv1a, + _testhashs64_fnv1a, + _testhashu64_fnv1a, + _testarrayofbools, + _testf, + _testf2, + _testf3, + _testarrayofstring2, + _testarrayofsortedstruct, + _flex, + _test5, + _vector_of_longs, + _vector_of_doubles, + _parent_namespace_test, + _vector_of_referrables, + _single_weak_reference, + _vector_of_weak_references, + _vector_of_strong_referrables, + _co_owning_reference, + _vector_of_co_owning_references, + _non_owning_reference, + _vector_of_non_owning_references, + _any_unique_type, + _any_unique, + _any_ambiguous_type, + _any_ambiguous, + _vector_of_enums, + _signed_enum, + _testrequirednestedflatbuffer, + _scalar_key_sorted_tables, + _native_inline, + _long_enum_non_enum_default, + _long_enum_normal_default, + _nan_default, + _inf_default, + _positive_inf_default, + _infinity_default, + _positive_infinity_default, + _negative_inf_default, + _negative_infinity_default, + _double_inf_default); +} + +inline TypeAliasesT *TypeAliases::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TypeAliases::UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = i8(); _o->i8 = _e; } + { auto _e = u8(); _o->u8 = _e; } + { auto _e = i16(); _o->i16 = _e; } + { auto _e = u16(); _o->u16 = _e; } + { auto _e = i32(); _o->i32 = _e; } + { auto _e = u32(); _o->u32 = _e; } + { auto _e = i64(); _o->i64 = _e; } + { auto _e = u64(); _o->u64 = _e; } + { auto _e = f32(); _o->f32 = _e; } + { auto _e = f64(); _o->f64 = _e; } + { auto _e = v8(); if (_e) { _o->v8.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->v8.begin()); } } + { auto _e = vf64(); if (_e) { _o->vf64.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vf64[_i] = _e->Get(_i); } } else { _o->vf64.resize(0); } } +} + +inline ::flatbuffers::Offset TypeAliases::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTypeAliases(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TypeAliasesT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _i8 = _o->i8; + auto _u8 = _o->u8; + auto _i16 = _o->i16; + auto _u16 = _o->u16; + auto _i32 = _o->i32; + auto _u32 = _o->u32; + auto _i64 = _o->i64; + auto _u64 = _o->u64; + auto _f32 = _o->f32; + auto _f64 = _o->f64; + auto _v8 = _o->v8.size() ? _fbb.CreateVector(_o->v8) : 0; + auto _vf64 = _o->vf64.size() ? _fbb.CreateVector(_o->vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + _i8, + _u8, + _i16, + _u16, + _i32, + _u32, + _i64, + _u64, + _f32, + _f64, + _v8, + _vf64); +} + +inline bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type) { + switch (type) { + case Any::NONE: { + return true; + } + case Any::Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any::TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any::MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAny( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUnion::UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Any::Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any::TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any::MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Any::Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case Any::TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case Any::MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Any::Monster: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case Any::TestSimpleTableWithEnum: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case Any::MyGame_Example2_Monster: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUnion::Reset() { + switch (type) { + case Any::Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any::TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any::MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Any::NONE; +} + +inline bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type) { + switch (type) { + case AnyUniqueAliases::NONE: { + return true; + } + case AnyUniqueAliases::M: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases::TS: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases::M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyUniqueAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyUniqueAliases::M: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases::TS: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases::M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUniqueAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyUniqueAliases::M: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases::TS: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases::M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyUniqueAliases::M: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases::TS: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases::M2: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUniqueAliasesUnion::Reset() { + switch (type) { + case AnyUniqueAliases::M: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases::TS: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases::M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyUniqueAliases::NONE; +} + +inline bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type) { + switch (type) { + case AnyAmbiguousAliases::NONE: { + return true; + } + case AnyAmbiguousAliases::M1: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases::M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases::M3: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyAmbiguousAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyAmbiguousAliases::M1: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases::M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases::M3: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyAmbiguousAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyAmbiguousAliases::M1: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases::M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases::M3: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyAmbiguousAliases::M1: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases::M2: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases::M3: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyAmbiguousAliasesUnion::Reset() { + switch (type) { + case AnyAmbiguousAliases::M1: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases::M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases::M3: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyAmbiguousAliases::NONE; +} + +inline const ::flatbuffers::TypeTable *ColorTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const int64_t values[] = { 1, 2, 8 }; + static const char * const names[] = { + "Red", + "Green", + "Blue" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RaceTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::RaceTypeTable + }; + static const int64_t values[] = { -1, 0, 1, 2 }; + static const char * const names[] = { + "None", + "Human", + "Dwarf", + "Elf" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 4, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *LongEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::LongEnumTypeTable + }; + static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL }; + static const char * const names[] = { + "LongOne", + "LongTwo", + "LongBig" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyUniqueAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M", + "TS", + "M2" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyAmbiguousAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M1", + "M2", + "M3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 } + }; + static const int64_t values[] = { 0, 2, 4 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const char * const names[] = { + "color" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *Vec3TypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 4, 8, 16, 24, 26, 32 }; + static const char * const names[] = { + "x", + "y", + "z", + "test1", + "test2", + "test3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 6, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AbilityTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "id", + "distance" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::AbilityTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 8, 12, 20 }; + static const char * const names[] = { + "a", + "b", + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::StructOfStructsTypeTable + }; + static const int64_t values[] = { 0, 20 }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StatTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 } + }; + static const char * const names[] = { + "id", + "val", + "count" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, -1 } + }; + static const char * const names[] = { + "id" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 1 }, + { ::flatbuffers::ET_UTYPE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 4 }, + { ::flatbuffers::ET_SEQUENCE, 0, 4 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 5 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_BOOL, 1, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 6 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_LONG, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 7 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_UTYPE, 0, 9 }, + { ::flatbuffers::ET_SEQUENCE, 0, 9 }, + { ::flatbuffers::ET_UTYPE, 0, 10 }, + { ::flatbuffers::ET_SEQUENCE, 0, 10 }, + { ::flatbuffers::ET_UCHAR, 1, 1 }, + { ::flatbuffers::ET_CHAR, 0, 11 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 5 }, + { ::flatbuffers::ET_SEQUENCE, 0, 3 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::Vec3TypeTable, + MyGame::Example::ColorTypeTable, + MyGame::Example::AnyTypeTable, + MyGame::Example::TestTypeTable, + MyGame::Example::MonsterTypeTable, + MyGame::Example::StatTypeTable, + MyGame::Example::AbilityTypeTable, + MyGame::InParentNamespaceTypeTable, + MyGame::Example::ReferrableTypeTable, + MyGame::Example::AnyUniqueAliasesTypeTable, + MyGame::Example::AnyAmbiguousAliasesTypeTable, + MyGame::Example::RaceTypeTable, + MyGame::Example::LongEnumTypeTable + }; + static const char * const names[] = { + "pos", + "mana", + "hp", + "name", + "friendly", + "inventory", + "color", + "test_type", + "test", + "test4", + "testarrayofstring", + "testarrayoftables", + "enemy", + "testnestedflatbuffer", + "testempty", + "testbool", + "testhashs32_fnv1", + "testhashu32_fnv1", + "testhashs64_fnv1", + "testhashu64_fnv1", + "testhashs32_fnv1a", + "testhashu32_fnv1a", + "testhashs64_fnv1a", + "testhashu64_fnv1a", + "testarrayofbools", + "testf", + "testf2", + "testf3", + "testarrayofstring2", + "testarrayofsortedstruct", + "flex", + "test5", + "vector_of_longs", + "vector_of_doubles", + "parent_namespace_test", + "vector_of_referrables", + "single_weak_reference", + "vector_of_weak_references", + "vector_of_strong_referrables", + "co_owning_reference", + "vector_of_co_owning_references", + "non_owning_reference", + "vector_of_non_owning_references", + "any_unique_type", + "any_unique", + "any_ambiguous_type", + "any_ambiguous", + "vector_of_enums", + "signed_enum", + "testrequirednestedflatbuffer", + "scalar_key_sorted_tables", + "native_inline", + "long_enum_non_enum_default", + "long_enum_normal_default", + "nan_default", + "inf_default", + "positive_inf_default", + "infinity_default", + "positive_infinity_default", + "negative_inf_default", + "negative_infinity_default", + "double_inf_default" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 62, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_CHAR, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 } + }; + static const char * const names[] = { + "i8", + "u8", + "i16", + "u16", + "i32", + "u32", + "i64", + "u64", + "f32", + "f64", + "v8", + "vf64" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 12, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const MyGame::Example::Monster *GetMonster(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const MyGame::Example::Monster *GetSizePrefixedMonster(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Monster *GetMutableMonster(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MonsterIdentifier() { + return "MONS"; +} + +inline bool MonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier()); +} + +inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier(), true); +} + +inline bool VerifyMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MonsterIdentifier()); +} + +inline bool VerifySizePrefixedMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MonsterIdentifier()); +} + +inline const char *MonsterExtension() { + return "mon"; +} + +inline void FinishMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MonsterIdentifier()); +} + +inline void FinishSizePrefixedMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MonsterIdentifier()); +} + +inline std::unique_ptr UnPackMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMonster(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMonster(buf)->UnPack(res)); +} + +} // namespace Example +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ diff --git a/third_party/flatbuffers/tests/cpp17/generated_cpp17/optional_scalars2_generated.h b/third_party/flatbuffers/tests/cpp17/generated_cpp17/optional_scalars2_generated.h new file mode 100644 index 00000000000..1aba093e6a8 --- /dev/null +++ b/third_party/flatbuffers/tests/cpp17/generated_cpp17/optional_scalars2_generated.h @@ -0,0 +1,902 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_OPTIONALSCALARS2_OPTIONAL_SCALARS_H_ +#define FLATBUFFERS_GENERATED_OPTIONALSCALARS2_OPTIONAL_SCALARS_H_ + +#include "flatbuffers/flatbuffers.h" + +namespace optional_scalars { + +struct ScalarStuff; +struct ScalarStuffBuilder; +struct ScalarStuffT; + +inline const flatbuffers::TypeTable *ScalarStuffTypeTable(); + +enum class OptionalByte : int8_t { + None = 0, + One = 1, + Two = 2, + MIN = None, + MAX = Two +}; + +inline const OptionalByte (&EnumValuesOptionalByte())[3] { + static const OptionalByte values[] = { + OptionalByte::None, + OptionalByte::One, + OptionalByte::Two + }; + return values; +} + +inline const char * const *EnumNamesOptionalByte() { + static const char * const names[4] = { + "None", + "One", + "Two", + nullptr + }; + return names; +} + +inline const char *EnumNameOptionalByte(OptionalByte e) { + if (flatbuffers::IsOutRange(e, OptionalByte::None, OptionalByte::Two)) return ""; + const size_t index = static_cast(e); + return EnumNamesOptionalByte()[index]; +} + +struct ScalarStuffT : public flatbuffers::NativeTable { + typedef ScalarStuff TableType; + int8_t just_i8 = 0; + flatbuffers::Optional maybe_i8 = flatbuffers::nullopt; + int8_t default_i8 = 42; + uint8_t just_u8 = 0; + flatbuffers::Optional maybe_u8 = flatbuffers::nullopt; + uint8_t default_u8 = 42; + int16_t just_i16 = 0; + flatbuffers::Optional maybe_i16 = flatbuffers::nullopt; + int16_t default_i16 = 42; + uint16_t just_u16 = 0; + flatbuffers::Optional maybe_u16 = flatbuffers::nullopt; + uint16_t default_u16 = 42; + int32_t just_i32 = 0; + flatbuffers::Optional maybe_i32 = flatbuffers::nullopt; + int32_t default_i32 = 42; + uint32_t just_u32 = 0; + flatbuffers::Optional maybe_u32 = flatbuffers::nullopt; + uint32_t default_u32 = 42; + int64_t just_i64 = 0; + flatbuffers::Optional maybe_i64 = flatbuffers::nullopt; + int64_t default_i64 = 42LL; + uint64_t just_u64 = 0; + flatbuffers::Optional maybe_u64 = flatbuffers::nullopt; + uint64_t default_u64 = 42ULL; + float just_f32 = 0.0f; + flatbuffers::Optional maybe_f32 = flatbuffers::nullopt; + float default_f32 = 42.0f; + double just_f64 = 0.0; + flatbuffers::Optional maybe_f64 = flatbuffers::nullopt; + double default_f64 = 42.0; + bool just_bool = false; + flatbuffers::Optional maybe_bool = flatbuffers::nullopt; + bool default_bool = true; + optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte::None; + flatbuffers::Optional maybe_enum = flatbuffers::nullopt; + optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte::One; +}; + +struct ScalarStuff FLATBUFFERS_FINAL_CLASS : private flatbuffers::Table { + typedef ScalarStuffT NativeTableType; + typedef ScalarStuffBuilder Builder; + struct Traits; + static const flatbuffers::TypeTable *MiniReflectTypeTable() { + return ScalarStuffTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_JUST_I8 = 4, + VT_MAYBE_I8 = 6, + VT_DEFAULT_I8 = 8, + VT_JUST_U8 = 10, + VT_MAYBE_U8 = 12, + VT_DEFAULT_U8 = 14, + VT_JUST_I16 = 16, + VT_MAYBE_I16 = 18, + VT_DEFAULT_I16 = 20, + VT_JUST_U16 = 22, + VT_MAYBE_U16 = 24, + VT_DEFAULT_U16 = 26, + VT_JUST_I32 = 28, + VT_MAYBE_I32 = 30, + VT_DEFAULT_I32 = 32, + VT_JUST_U32 = 34, + VT_MAYBE_U32 = 36, + VT_DEFAULT_U32 = 38, + VT_JUST_I64 = 40, + VT_MAYBE_I64 = 42, + VT_DEFAULT_I64 = 44, + VT_JUST_U64 = 46, + VT_MAYBE_U64 = 48, + VT_DEFAULT_U64 = 50, + VT_JUST_F32 = 52, + VT_MAYBE_F32 = 54, + VT_DEFAULT_F32 = 56, + VT_JUST_F64 = 58, + VT_MAYBE_F64 = 60, + VT_DEFAULT_F64 = 62, + VT_JUST_BOOL = 64, + VT_MAYBE_BOOL = 66, + VT_DEFAULT_BOOL = 68, + VT_JUST_ENUM = 70, + VT_MAYBE_ENUM = 72, + VT_DEFAULT_ENUM = 74 + }; + int8_t just_i8() const { + return GetField(VT_JUST_I8, 0); + } + bool mutate_just_i8(int8_t _just_i8) { + return SetField(VT_JUST_I8, _just_i8, 0); + } + flatbuffers::Optional maybe_i8() const { + return GetOptional(VT_MAYBE_I8); + } + bool mutate_maybe_i8(int8_t _maybe_i8) { + return SetField(VT_MAYBE_I8, _maybe_i8); + } + int8_t default_i8() const { + return GetField(VT_DEFAULT_I8, 42); + } + bool mutate_default_i8(int8_t _default_i8) { + return SetField(VT_DEFAULT_I8, _default_i8, 42); + } + uint8_t just_u8() const { + return GetField(VT_JUST_U8, 0); + } + bool mutate_just_u8(uint8_t _just_u8) { + return SetField(VT_JUST_U8, _just_u8, 0); + } + flatbuffers::Optional maybe_u8() const { + return GetOptional(VT_MAYBE_U8); + } + bool mutate_maybe_u8(uint8_t _maybe_u8) { + return SetField(VT_MAYBE_U8, _maybe_u8); + } + uint8_t default_u8() const { + return GetField(VT_DEFAULT_U8, 42); + } + bool mutate_default_u8(uint8_t _default_u8) { + return SetField(VT_DEFAULT_U8, _default_u8, 42); + } + int16_t just_i16() const { + return GetField(VT_JUST_I16, 0); + } + bool mutate_just_i16(int16_t _just_i16) { + return SetField(VT_JUST_I16, _just_i16, 0); + } + flatbuffers::Optional maybe_i16() const { + return GetOptional(VT_MAYBE_I16); + } + bool mutate_maybe_i16(int16_t _maybe_i16) { + return SetField(VT_MAYBE_I16, _maybe_i16); + } + int16_t default_i16() const { + return GetField(VT_DEFAULT_I16, 42); + } + bool mutate_default_i16(int16_t _default_i16) { + return SetField(VT_DEFAULT_I16, _default_i16, 42); + } + uint16_t just_u16() const { + return GetField(VT_JUST_U16, 0); + } + bool mutate_just_u16(uint16_t _just_u16) { + return SetField(VT_JUST_U16, _just_u16, 0); + } + flatbuffers::Optional maybe_u16() const { + return GetOptional(VT_MAYBE_U16); + } + bool mutate_maybe_u16(uint16_t _maybe_u16) { + return SetField(VT_MAYBE_U16, _maybe_u16); + } + uint16_t default_u16() const { + return GetField(VT_DEFAULT_U16, 42); + } + bool mutate_default_u16(uint16_t _default_u16) { + return SetField(VT_DEFAULT_U16, _default_u16, 42); + } + int32_t just_i32() const { + return GetField(VT_JUST_I32, 0); + } + bool mutate_just_i32(int32_t _just_i32) { + return SetField(VT_JUST_I32, _just_i32, 0); + } + flatbuffers::Optional maybe_i32() const { + return GetOptional(VT_MAYBE_I32); + } + bool mutate_maybe_i32(int32_t _maybe_i32) { + return SetField(VT_MAYBE_I32, _maybe_i32); + } + int32_t default_i32() const { + return GetField(VT_DEFAULT_I32, 42); + } + bool mutate_default_i32(int32_t _default_i32) { + return SetField(VT_DEFAULT_I32, _default_i32, 42); + } + uint32_t just_u32() const { + return GetField(VT_JUST_U32, 0); + } + bool mutate_just_u32(uint32_t _just_u32) { + return SetField(VT_JUST_U32, _just_u32, 0); + } + flatbuffers::Optional maybe_u32() const { + return GetOptional(VT_MAYBE_U32); + } + bool mutate_maybe_u32(uint32_t _maybe_u32) { + return SetField(VT_MAYBE_U32, _maybe_u32); + } + uint32_t default_u32() const { + return GetField(VT_DEFAULT_U32, 42); + } + bool mutate_default_u32(uint32_t _default_u32) { + return SetField(VT_DEFAULT_U32, _default_u32, 42); + } + int64_t just_i64() const { + return GetField(VT_JUST_I64, 0); + } + bool mutate_just_i64(int64_t _just_i64) { + return SetField(VT_JUST_I64, _just_i64, 0); + } + flatbuffers::Optional maybe_i64() const { + return GetOptional(VT_MAYBE_I64); + } + bool mutate_maybe_i64(int64_t _maybe_i64) { + return SetField(VT_MAYBE_I64, _maybe_i64); + } + int64_t default_i64() const { + return GetField(VT_DEFAULT_I64, 42LL); + } + bool mutate_default_i64(int64_t _default_i64) { + return SetField(VT_DEFAULT_I64, _default_i64, 42LL); + } + uint64_t just_u64() const { + return GetField(VT_JUST_U64, 0); + } + bool mutate_just_u64(uint64_t _just_u64) { + return SetField(VT_JUST_U64, _just_u64, 0); + } + flatbuffers::Optional maybe_u64() const { + return GetOptional(VT_MAYBE_U64); + } + bool mutate_maybe_u64(uint64_t _maybe_u64) { + return SetField(VT_MAYBE_U64, _maybe_u64); + } + uint64_t default_u64() const { + return GetField(VT_DEFAULT_U64, 42ULL); + } + bool mutate_default_u64(uint64_t _default_u64) { + return SetField(VT_DEFAULT_U64, _default_u64, 42ULL); + } + float just_f32() const { + return GetField(VT_JUST_F32, 0.0f); + } + bool mutate_just_f32(float _just_f32) { + return SetField(VT_JUST_F32, _just_f32, 0.0f); + } + flatbuffers::Optional maybe_f32() const { + return GetOptional(VT_MAYBE_F32); + } + bool mutate_maybe_f32(float _maybe_f32) { + return SetField(VT_MAYBE_F32, _maybe_f32); + } + float default_f32() const { + return GetField(VT_DEFAULT_F32, 42.0f); + } + bool mutate_default_f32(float _default_f32) { + return SetField(VT_DEFAULT_F32, _default_f32, 42.0f); + } + double just_f64() const { + return GetField(VT_JUST_F64, 0.0); + } + bool mutate_just_f64(double _just_f64) { + return SetField(VT_JUST_F64, _just_f64, 0.0); + } + flatbuffers::Optional maybe_f64() const { + return GetOptional(VT_MAYBE_F64); + } + bool mutate_maybe_f64(double _maybe_f64) { + return SetField(VT_MAYBE_F64, _maybe_f64); + } + double default_f64() const { + return GetField(VT_DEFAULT_F64, 42.0); + } + bool mutate_default_f64(double _default_f64) { + return SetField(VT_DEFAULT_F64, _default_f64, 42.0); + } + bool just_bool() const { + return GetField(VT_JUST_BOOL, 0) != 0; + } + bool mutate_just_bool(bool _just_bool) { + return SetField(VT_JUST_BOOL, static_cast(_just_bool), 0); + } + flatbuffers::Optional maybe_bool() const { + return GetOptional(VT_MAYBE_BOOL); + } + bool mutate_maybe_bool(bool _maybe_bool) { + return SetField(VT_MAYBE_BOOL, static_cast(_maybe_bool)); + } + bool default_bool() const { + return GetField(VT_DEFAULT_BOOL, 1) != 0; + } + bool mutate_default_bool(bool _default_bool) { + return SetField(VT_DEFAULT_BOOL, static_cast(_default_bool), 1); + } + optional_scalars::OptionalByte just_enum() const { + return static_cast(GetField(VT_JUST_ENUM, 0)); + } + bool mutate_just_enum(optional_scalars::OptionalByte _just_enum) { + return SetField(VT_JUST_ENUM, static_cast(_just_enum), 0); + } + flatbuffers::Optional maybe_enum() const { + return GetOptional(VT_MAYBE_ENUM); + } + bool mutate_maybe_enum(optional_scalars::OptionalByte _maybe_enum) { + return SetField(VT_MAYBE_ENUM, static_cast(_maybe_enum)); + } + optional_scalars::OptionalByte default_enum() const { + return static_cast(GetField(VT_DEFAULT_ENUM, 1)); + } + bool mutate_default_enum(optional_scalars::OptionalByte _default_enum) { + return SetField(VT_DEFAULT_ENUM, static_cast(_default_enum), 1); + } + bool Verify(flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_JUST_I8) && + VerifyField(verifier, VT_MAYBE_I8) && + VerifyField(verifier, VT_DEFAULT_I8) && + VerifyField(verifier, VT_JUST_U8) && + VerifyField(verifier, VT_MAYBE_U8) && + VerifyField(verifier, VT_DEFAULT_U8) && + VerifyField(verifier, VT_JUST_I16) && + VerifyField(verifier, VT_MAYBE_I16) && + VerifyField(verifier, VT_DEFAULT_I16) && + VerifyField(verifier, VT_JUST_U16) && + VerifyField(verifier, VT_MAYBE_U16) && + VerifyField(verifier, VT_DEFAULT_U16) && + VerifyField(verifier, VT_JUST_I32) && + VerifyField(verifier, VT_MAYBE_I32) && + VerifyField(verifier, VT_DEFAULT_I32) && + VerifyField(verifier, VT_JUST_U32) && + VerifyField(verifier, VT_MAYBE_U32) && + VerifyField(verifier, VT_DEFAULT_U32) && + VerifyField(verifier, VT_JUST_I64) && + VerifyField(verifier, VT_MAYBE_I64) && + VerifyField(verifier, VT_DEFAULT_I64) && + VerifyField(verifier, VT_JUST_U64) && + VerifyField(verifier, VT_MAYBE_U64) && + VerifyField(verifier, VT_DEFAULT_U64) && + VerifyField(verifier, VT_JUST_F32) && + VerifyField(verifier, VT_MAYBE_F32) && + VerifyField(verifier, VT_DEFAULT_F32) && + VerifyField(verifier, VT_JUST_F64) && + VerifyField(verifier, VT_MAYBE_F64) && + VerifyField(verifier, VT_DEFAULT_F64) && + VerifyField(verifier, VT_JUST_BOOL) && + VerifyField(verifier, VT_MAYBE_BOOL) && + VerifyField(verifier, VT_DEFAULT_BOOL) && + VerifyField(verifier, VT_JUST_ENUM) && + VerifyField(verifier, VT_MAYBE_ENUM) && + VerifyField(verifier, VT_DEFAULT_ENUM) && + verifier.EndTable(); + } + ScalarStuffT *UnPack(const flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ScalarStuffT *_o, const flatbuffers::resolver_function_t *_resolver = nullptr) const; + static flatbuffers::Offset Pack(flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT* _o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ScalarStuffBuilder { + typedef ScalarStuff Table; + flatbuffers::FlatBufferBuilder &fbb_; + flatbuffers::uoffset_t start_; + void add_just_i8(int8_t just_i8) { + fbb_.AddElement(ScalarStuff::VT_JUST_I8, just_i8, 0); + } + void add_maybe_i8(int8_t maybe_i8) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I8, maybe_i8); + } + void add_default_i8(int8_t default_i8) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I8, default_i8, 42); + } + void add_just_u8(uint8_t just_u8) { + fbb_.AddElement(ScalarStuff::VT_JUST_U8, just_u8, 0); + } + void add_maybe_u8(uint8_t maybe_u8) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U8, maybe_u8); + } + void add_default_u8(uint8_t default_u8) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U8, default_u8, 42); + } + void add_just_i16(int16_t just_i16) { + fbb_.AddElement(ScalarStuff::VT_JUST_I16, just_i16, 0); + } + void add_maybe_i16(int16_t maybe_i16) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I16, maybe_i16); + } + void add_default_i16(int16_t default_i16) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I16, default_i16, 42); + } + void add_just_u16(uint16_t just_u16) { + fbb_.AddElement(ScalarStuff::VT_JUST_U16, just_u16, 0); + } + void add_maybe_u16(uint16_t maybe_u16) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U16, maybe_u16); + } + void add_default_u16(uint16_t default_u16) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U16, default_u16, 42); + } + void add_just_i32(int32_t just_i32) { + fbb_.AddElement(ScalarStuff::VT_JUST_I32, just_i32, 0); + } + void add_maybe_i32(int32_t maybe_i32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I32, maybe_i32); + } + void add_default_i32(int32_t default_i32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I32, default_i32, 42); + } + void add_just_u32(uint32_t just_u32) { + fbb_.AddElement(ScalarStuff::VT_JUST_U32, just_u32, 0); + } + void add_maybe_u32(uint32_t maybe_u32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U32, maybe_u32); + } + void add_default_u32(uint32_t default_u32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U32, default_u32, 42); + } + void add_just_i64(int64_t just_i64) { + fbb_.AddElement(ScalarStuff::VT_JUST_I64, just_i64, 0); + } + void add_maybe_i64(int64_t maybe_i64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I64, maybe_i64); + } + void add_default_i64(int64_t default_i64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I64, default_i64, 42LL); + } + void add_just_u64(uint64_t just_u64) { + fbb_.AddElement(ScalarStuff::VT_JUST_U64, just_u64, 0); + } + void add_maybe_u64(uint64_t maybe_u64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U64, maybe_u64); + } + void add_default_u64(uint64_t default_u64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U64, default_u64, 42ULL); + } + void add_just_f32(float just_f32) { + fbb_.AddElement(ScalarStuff::VT_JUST_F32, just_f32, 0.0f); + } + void add_maybe_f32(float maybe_f32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_F32, maybe_f32); + } + void add_default_f32(float default_f32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0f); + } + void add_just_f64(double just_f64) { + fbb_.AddElement(ScalarStuff::VT_JUST_F64, just_f64, 0.0); + } + void add_maybe_f64(double maybe_f64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_F64, maybe_f64); + } + void add_default_f64(double default_f64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0); + } + void add_just_bool(bool just_bool) { + fbb_.AddElement(ScalarStuff::VT_JUST_BOOL, static_cast(just_bool), 0); + } + void add_maybe_bool(bool maybe_bool) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_BOOL, static_cast(maybe_bool)); + } + void add_default_bool(bool default_bool) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_BOOL, static_cast(default_bool), 1); + } + void add_just_enum(optional_scalars::OptionalByte just_enum) { + fbb_.AddElement(ScalarStuff::VT_JUST_ENUM, static_cast(just_enum), 0); + } + void add_maybe_enum(optional_scalars::OptionalByte maybe_enum) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_ENUM, static_cast(maybe_enum)); + } + void add_default_enum(optional_scalars::OptionalByte default_enum) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_ENUM, static_cast(default_enum), 1); + } + explicit ScalarStuffBuilder(flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = flatbuffers::Offset(end); + return o; + } +}; + +inline flatbuffers::Offset CreateScalarStuff( + flatbuffers::FlatBufferBuilder &_fbb, + int8_t just_i8 = 0, + flatbuffers::Optional maybe_i8 = flatbuffers::nullopt, + int8_t default_i8 = 42, + uint8_t just_u8 = 0, + flatbuffers::Optional maybe_u8 = flatbuffers::nullopt, + uint8_t default_u8 = 42, + int16_t just_i16 = 0, + flatbuffers::Optional maybe_i16 = flatbuffers::nullopt, + int16_t default_i16 = 42, + uint16_t just_u16 = 0, + flatbuffers::Optional maybe_u16 = flatbuffers::nullopt, + uint16_t default_u16 = 42, + int32_t just_i32 = 0, + flatbuffers::Optional maybe_i32 = flatbuffers::nullopt, + int32_t default_i32 = 42, + uint32_t just_u32 = 0, + flatbuffers::Optional maybe_u32 = flatbuffers::nullopt, + uint32_t default_u32 = 42, + int64_t just_i64 = 0, + flatbuffers::Optional maybe_i64 = flatbuffers::nullopt, + int64_t default_i64 = 42LL, + uint64_t just_u64 = 0, + flatbuffers::Optional maybe_u64 = flatbuffers::nullopt, + uint64_t default_u64 = 42ULL, + float just_f32 = 0.0f, + flatbuffers::Optional maybe_f32 = flatbuffers::nullopt, + float default_f32 = 42.0f, + double just_f64 = 0.0, + flatbuffers::Optional maybe_f64 = flatbuffers::nullopt, + double default_f64 = 42.0, + bool just_bool = false, + flatbuffers::Optional maybe_bool = flatbuffers::nullopt, + bool default_bool = true, + optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte::None, + flatbuffers::Optional maybe_enum = flatbuffers::nullopt, + optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte::One) { + ScalarStuffBuilder builder_(_fbb); + builder_.add_default_f64(default_f64); + if(maybe_f64) { builder_.add_maybe_f64(*maybe_f64); } + builder_.add_just_f64(just_f64); + builder_.add_default_u64(default_u64); + if(maybe_u64) { builder_.add_maybe_u64(*maybe_u64); } + builder_.add_just_u64(just_u64); + builder_.add_default_i64(default_i64); + if(maybe_i64) { builder_.add_maybe_i64(*maybe_i64); } + builder_.add_just_i64(just_i64); + builder_.add_default_f32(default_f32); + if(maybe_f32) { builder_.add_maybe_f32(*maybe_f32); } + builder_.add_just_f32(just_f32); + builder_.add_default_u32(default_u32); + if(maybe_u32) { builder_.add_maybe_u32(*maybe_u32); } + builder_.add_just_u32(just_u32); + builder_.add_default_i32(default_i32); + if(maybe_i32) { builder_.add_maybe_i32(*maybe_i32); } + builder_.add_just_i32(just_i32); + builder_.add_default_u16(default_u16); + if(maybe_u16) { builder_.add_maybe_u16(*maybe_u16); } + builder_.add_just_u16(just_u16); + builder_.add_default_i16(default_i16); + if(maybe_i16) { builder_.add_maybe_i16(*maybe_i16); } + builder_.add_just_i16(just_i16); + builder_.add_default_enum(default_enum); + if(maybe_enum) { builder_.add_maybe_enum(*maybe_enum); } + builder_.add_just_enum(just_enum); + builder_.add_default_bool(default_bool); + if(maybe_bool) { builder_.add_maybe_bool(*maybe_bool); } + builder_.add_just_bool(just_bool); + builder_.add_default_u8(default_u8); + if(maybe_u8) { builder_.add_maybe_u8(*maybe_u8); } + builder_.add_just_u8(just_u8); + builder_.add_default_i8(default_i8); + if(maybe_i8) { builder_.add_maybe_i8(*maybe_i8); } + builder_.add_just_i8(just_i8); + return builder_.Finish(); +} + +struct ScalarStuff::Traits { + using type = ScalarStuff; + static auto constexpr Create = CreateScalarStuff; +}; + +flatbuffers::Offset CreateScalarStuff(flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const flatbuffers::rehasher_function_t *_rehasher = nullptr); + +inline ScalarStuffT *ScalarStuff::UnPack(const flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void ScalarStuff::UnPackTo(ScalarStuffT *_o, const flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = just_i8(); _o->just_i8 = _e; } + { auto _e = maybe_i8(); _o->maybe_i8 = _e; } + { auto _e = default_i8(); _o->default_i8 = _e; } + { auto _e = just_u8(); _o->just_u8 = _e; } + { auto _e = maybe_u8(); _o->maybe_u8 = _e; } + { auto _e = default_u8(); _o->default_u8 = _e; } + { auto _e = just_i16(); _o->just_i16 = _e; } + { auto _e = maybe_i16(); _o->maybe_i16 = _e; } + { auto _e = default_i16(); _o->default_i16 = _e; } + { auto _e = just_u16(); _o->just_u16 = _e; } + { auto _e = maybe_u16(); _o->maybe_u16 = _e; } + { auto _e = default_u16(); _o->default_u16 = _e; } + { auto _e = just_i32(); _o->just_i32 = _e; } + { auto _e = maybe_i32(); _o->maybe_i32 = _e; } + { auto _e = default_i32(); _o->default_i32 = _e; } + { auto _e = just_u32(); _o->just_u32 = _e; } + { auto _e = maybe_u32(); _o->maybe_u32 = _e; } + { auto _e = default_u32(); _o->default_u32 = _e; } + { auto _e = just_i64(); _o->just_i64 = _e; } + { auto _e = maybe_i64(); _o->maybe_i64 = _e; } + { auto _e = default_i64(); _o->default_i64 = _e; } + { auto _e = just_u64(); _o->just_u64 = _e; } + { auto _e = maybe_u64(); _o->maybe_u64 = _e; } + { auto _e = default_u64(); _o->default_u64 = _e; } + { auto _e = just_f32(); _o->just_f32 = _e; } + { auto _e = maybe_f32(); _o->maybe_f32 = _e; } + { auto _e = default_f32(); _o->default_f32 = _e; } + { auto _e = just_f64(); _o->just_f64 = _e; } + { auto _e = maybe_f64(); _o->maybe_f64 = _e; } + { auto _e = default_f64(); _o->default_f64 = _e; } + { auto _e = just_bool(); _o->just_bool = _e; } + { auto _e = maybe_bool(); _o->maybe_bool = _e; } + { auto _e = default_bool(); _o->default_bool = _e; } + { auto _e = just_enum(); _o->just_enum = _e; } + { auto _e = maybe_enum(); _o->maybe_enum = _e; } + { auto _e = default_enum(); _o->default_enum = _e; } +} + +inline flatbuffers::Offset ScalarStuff::Pack(flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT* _o, const flatbuffers::rehasher_function_t *_rehasher) { + return CreateScalarStuff(_fbb, _o, _rehasher); +} + +inline flatbuffers::Offset CreateScalarStuff(flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { flatbuffers::FlatBufferBuilder *__fbb; const ScalarStuffT* __o; const flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _just_i8 = _o->just_i8; + auto _maybe_i8 = _o->maybe_i8; + auto _default_i8 = _o->default_i8; + auto _just_u8 = _o->just_u8; + auto _maybe_u8 = _o->maybe_u8; + auto _default_u8 = _o->default_u8; + auto _just_i16 = _o->just_i16; + auto _maybe_i16 = _o->maybe_i16; + auto _default_i16 = _o->default_i16; + auto _just_u16 = _o->just_u16; + auto _maybe_u16 = _o->maybe_u16; + auto _default_u16 = _o->default_u16; + auto _just_i32 = _o->just_i32; + auto _maybe_i32 = _o->maybe_i32; + auto _default_i32 = _o->default_i32; + auto _just_u32 = _o->just_u32; + auto _maybe_u32 = _o->maybe_u32; + auto _default_u32 = _o->default_u32; + auto _just_i64 = _o->just_i64; + auto _maybe_i64 = _o->maybe_i64; + auto _default_i64 = _o->default_i64; + auto _just_u64 = _o->just_u64; + auto _maybe_u64 = _o->maybe_u64; + auto _default_u64 = _o->default_u64; + auto _just_f32 = _o->just_f32; + auto _maybe_f32 = _o->maybe_f32; + auto _default_f32 = _o->default_f32; + auto _just_f64 = _o->just_f64; + auto _maybe_f64 = _o->maybe_f64; + auto _default_f64 = _o->default_f64; + auto _just_bool = _o->just_bool; + auto _maybe_bool = _o->maybe_bool; + auto _default_bool = _o->default_bool; + auto _just_enum = _o->just_enum; + auto _maybe_enum = _o->maybe_enum; + auto _default_enum = _o->default_enum; + return optional_scalars::CreateScalarStuff( + _fbb, + _just_i8, + _maybe_i8, + _default_i8, + _just_u8, + _maybe_u8, + _default_u8, + _just_i16, + _maybe_i16, + _default_i16, + _just_u16, + _maybe_u16, + _default_u16, + _just_i32, + _maybe_i32, + _default_i32, + _just_u32, + _maybe_u32, + _default_u32, + _just_i64, + _maybe_i64, + _default_i64, + _just_u64, + _maybe_u64, + _default_u64, + _just_f32, + _maybe_f32, + _default_f32, + _just_f64, + _maybe_f64, + _default_f64, + _just_bool, + _maybe_bool, + _default_bool, + _just_enum, + _maybe_enum, + _default_enum); +} + +inline const flatbuffers::TypeTable *OptionalByteTypeTable() { + static const flatbuffers::TypeCode type_codes[] = { + { flatbuffers::ET_CHAR, 0, 0 }, + { flatbuffers::ET_CHAR, 0, 0 }, + { flatbuffers::ET_CHAR, 0, 0 } + }; + static const flatbuffers::TypeFunction type_refs[] = { + optional_scalars::OptionalByteTypeTable + }; + static const char * const names[] = { + "None", + "One", + "Two" + }; + static const flatbuffers::TypeTable tt = { + flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const flatbuffers::TypeTable *ScalarStuffTypeTable() { + static const flatbuffers::TypeCode type_codes[] = { + { flatbuffers::ET_CHAR, 0, -1 }, + { flatbuffers::ET_CHAR, 0, -1 }, + { flatbuffers::ET_CHAR, 0, -1 }, + { flatbuffers::ET_UCHAR, 0, -1 }, + { flatbuffers::ET_UCHAR, 0, -1 }, + { flatbuffers::ET_UCHAR, 0, -1 }, + { flatbuffers::ET_SHORT, 0, -1 }, + { flatbuffers::ET_SHORT, 0, -1 }, + { flatbuffers::ET_SHORT, 0, -1 }, + { flatbuffers::ET_USHORT, 0, -1 }, + { flatbuffers::ET_USHORT, 0, -1 }, + { flatbuffers::ET_USHORT, 0, -1 }, + { flatbuffers::ET_INT, 0, -1 }, + { flatbuffers::ET_INT, 0, -1 }, + { flatbuffers::ET_INT, 0, -1 }, + { flatbuffers::ET_UINT, 0, -1 }, + { flatbuffers::ET_UINT, 0, -1 }, + { flatbuffers::ET_UINT, 0, -1 }, + { flatbuffers::ET_LONG, 0, -1 }, + { flatbuffers::ET_LONG, 0, -1 }, + { flatbuffers::ET_LONG, 0, -1 }, + { flatbuffers::ET_ULONG, 0, -1 }, + { flatbuffers::ET_ULONG, 0, -1 }, + { flatbuffers::ET_ULONG, 0, -1 }, + { flatbuffers::ET_FLOAT, 0, -1 }, + { flatbuffers::ET_FLOAT, 0, -1 }, + { flatbuffers::ET_FLOAT, 0, -1 }, + { flatbuffers::ET_DOUBLE, 0, -1 }, + { flatbuffers::ET_DOUBLE, 0, -1 }, + { flatbuffers::ET_DOUBLE, 0, -1 }, + { flatbuffers::ET_BOOL, 0, -1 }, + { flatbuffers::ET_BOOL, 0, -1 }, + { flatbuffers::ET_BOOL, 0, -1 }, + { flatbuffers::ET_CHAR, 0, 0 }, + { flatbuffers::ET_CHAR, 0, 0 }, + { flatbuffers::ET_CHAR, 0, 0 } + }; + static const flatbuffers::TypeFunction type_refs[] = { + optional_scalars::OptionalByteTypeTable + }; + static const char * const names[] = { + "just_i8", + "maybe_i8", + "default_i8", + "just_u8", + "maybe_u8", + "default_u8", + "just_i16", + "maybe_i16", + "default_i16", + "just_u16", + "maybe_u16", + "default_u16", + "just_i32", + "maybe_i32", + "default_i32", + "just_u32", + "maybe_u32", + "default_u32", + "just_i64", + "maybe_i64", + "default_i64", + "just_u64", + "maybe_u64", + "default_u64", + "just_f32", + "maybe_f32", + "default_f32", + "just_f64", + "maybe_f64", + "default_f64", + "just_bool", + "maybe_bool", + "default_bool", + "just_enum", + "maybe_enum", + "default_enum" + }; + static const flatbuffers::TypeTable tt = { + flatbuffers::ST_TABLE, 36, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const optional_scalars::ScalarStuff *GetScalarStuff(const void *buf) { + return flatbuffers::GetRoot(buf); +} + +inline const optional_scalars::ScalarStuff *GetSizePrefixedScalarStuff(const void *buf) { + return flatbuffers::GetSizePrefixedRoot(buf); +} + +inline ScalarStuff *GetMutableScalarStuff(void *buf) { + return flatbuffers::GetMutableRoot(buf); +} + +inline const char *ScalarStuffIdentifier() { + return "NULL"; +} + +inline bool ScalarStuffBufferHasIdentifier(const void *buf) { + return flatbuffers::BufferHasIdentifier( + buf, ScalarStuffIdentifier()); +} + +inline bool VerifyScalarStuffBuffer( + flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(ScalarStuffIdentifier()); +} + +inline bool VerifySizePrefixedScalarStuffBuffer( + flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(ScalarStuffIdentifier()); +} + +inline const char *ScalarStuffExtension() { + return "mon"; +} + +inline void FinishScalarStuffBuffer( + flatbuffers::FlatBufferBuilder &fbb, + flatbuffers::Offset root) { + fbb.Finish(root, ScalarStuffIdentifier()); +} + +inline void FinishSizePrefixedScalarStuffBuffer( + flatbuffers::FlatBufferBuilder &fbb, + flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, ScalarStuffIdentifier()); +} + +inline std::unique_ptr UnPackScalarStuff( + const void *buf, + const flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetScalarStuff(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedScalarStuff( + const void *buf, + const flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedScalarStuff(buf)->UnPack(res)); +} + +} // namespace optional_scalars + +#endif // FLATBUFFERS_GENERATED_OPTIONALSCALARS2_OPTIONAL_SCALARS_H_ diff --git a/third_party/flatbuffers/tests/cpp17/generated_cpp17/optional_scalars_generated.h b/third_party/flatbuffers/tests/cpp17/generated_cpp17/optional_scalars_generated.h new file mode 100644 index 00000000000..c69e3cdd84c --- /dev/null +++ b/third_party/flatbuffers/tests/cpp17/generated_cpp17/optional_scalars_generated.h @@ -0,0 +1,1001 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_OPTIONALSCALARS_OPTIONAL_SCALARS_H_ +#define FLATBUFFERS_GENERATED_OPTIONALSCALARS_OPTIONAL_SCALARS_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace optional_scalars { + +struct ScalarStuff; +struct ScalarStuffBuilder; +struct ScalarStuffT; + +inline const ::flatbuffers::TypeTable *ScalarStuffTypeTable(); + +enum class OptionalByte : int8_t { + None = 0, + One = 1, + Two = 2, + MIN = None, + MAX = Two +}; + +inline const OptionalByte (&EnumValuesOptionalByte())[3] { + static const OptionalByte values[] = { + OptionalByte::None, + OptionalByte::One, + OptionalByte::Two + }; + return values; +} + +inline const char * const *EnumNamesOptionalByte() { + static const char * const names[4] = { + "None", + "One", + "Two", + nullptr + }; + return names; +} + +inline const char *EnumNameOptionalByte(OptionalByte e) { + if (::flatbuffers::IsOutRange(e, OptionalByte::None, OptionalByte::Two)) return ""; + const size_t index = static_cast(e); + return EnumNamesOptionalByte()[index]; +} + +struct ScalarStuffT : public ::flatbuffers::NativeTable { + typedef ScalarStuff TableType; + int8_t just_i8 = 0; + ::flatbuffers::Optional maybe_i8 = ::flatbuffers::nullopt; + int8_t default_i8 = 42; + uint8_t just_u8 = 0; + ::flatbuffers::Optional maybe_u8 = ::flatbuffers::nullopt; + uint8_t default_u8 = 42; + int16_t just_i16 = 0; + ::flatbuffers::Optional maybe_i16 = ::flatbuffers::nullopt; + int16_t default_i16 = 42; + uint16_t just_u16 = 0; + ::flatbuffers::Optional maybe_u16 = ::flatbuffers::nullopt; + uint16_t default_u16 = 42; + int32_t just_i32 = 0; + ::flatbuffers::Optional maybe_i32 = ::flatbuffers::nullopt; + int32_t default_i32 = 42; + uint32_t just_u32 = 0; + ::flatbuffers::Optional maybe_u32 = ::flatbuffers::nullopt; + uint32_t default_u32 = 42; + int64_t just_i64 = 0; + ::flatbuffers::Optional maybe_i64 = ::flatbuffers::nullopt; + int64_t default_i64 = 42LL; + uint64_t just_u64 = 0; + ::flatbuffers::Optional maybe_u64 = ::flatbuffers::nullopt; + uint64_t default_u64 = 42ULL; + float just_f32 = 0.0f; + ::flatbuffers::Optional maybe_f32 = ::flatbuffers::nullopt; + float default_f32 = 42.0f; + double just_f64 = 0.0; + ::flatbuffers::Optional maybe_f64 = ::flatbuffers::nullopt; + double default_f64 = 42.0; + bool just_bool = false; + ::flatbuffers::Optional maybe_bool = ::flatbuffers::nullopt; + bool default_bool = true; + optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte::None; + ::flatbuffers::Optional maybe_enum = ::flatbuffers::nullopt; + optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte::One; +}; + +struct ScalarStuff FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ScalarStuffT NativeTableType; + typedef ScalarStuffBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ScalarStuffTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_JUST_I8 = 4, + VT_MAYBE_I8 = 6, + VT_DEFAULT_I8 = 8, + VT_JUST_U8 = 10, + VT_MAYBE_U8 = 12, + VT_DEFAULT_U8 = 14, + VT_JUST_I16 = 16, + VT_MAYBE_I16 = 18, + VT_DEFAULT_I16 = 20, + VT_JUST_U16 = 22, + VT_MAYBE_U16 = 24, + VT_DEFAULT_U16 = 26, + VT_JUST_I32 = 28, + VT_MAYBE_I32 = 30, + VT_DEFAULT_I32 = 32, + VT_JUST_U32 = 34, + VT_MAYBE_U32 = 36, + VT_DEFAULT_U32 = 38, + VT_JUST_I64 = 40, + VT_MAYBE_I64 = 42, + VT_DEFAULT_I64 = 44, + VT_JUST_U64 = 46, + VT_MAYBE_U64 = 48, + VT_DEFAULT_U64 = 50, + VT_JUST_F32 = 52, + VT_MAYBE_F32 = 54, + VT_DEFAULT_F32 = 56, + VT_JUST_F64 = 58, + VT_MAYBE_F64 = 60, + VT_DEFAULT_F64 = 62, + VT_JUST_BOOL = 64, + VT_MAYBE_BOOL = 66, + VT_DEFAULT_BOOL = 68, + VT_JUST_ENUM = 70, + VT_MAYBE_ENUM = 72, + VT_DEFAULT_ENUM = 74 + }; + int8_t just_i8() const { + return GetField(VT_JUST_I8, 0); + } + bool mutate_just_i8(int8_t _just_i8 = 0) { + return SetField(VT_JUST_I8, _just_i8, 0); + } + ::flatbuffers::Optional maybe_i8() const { + return GetOptional(VT_MAYBE_I8); + } + bool mutate_maybe_i8(int8_t _maybe_i8) { + return SetField(VT_MAYBE_I8, _maybe_i8); + } + int8_t default_i8() const { + return GetField(VT_DEFAULT_I8, 42); + } + bool mutate_default_i8(int8_t _default_i8 = 42) { + return SetField(VT_DEFAULT_I8, _default_i8, 42); + } + uint8_t just_u8() const { + return GetField(VT_JUST_U8, 0); + } + bool mutate_just_u8(uint8_t _just_u8 = 0) { + return SetField(VT_JUST_U8, _just_u8, 0); + } + ::flatbuffers::Optional maybe_u8() const { + return GetOptional(VT_MAYBE_U8); + } + bool mutate_maybe_u8(uint8_t _maybe_u8) { + return SetField(VT_MAYBE_U8, _maybe_u8); + } + uint8_t default_u8() const { + return GetField(VT_DEFAULT_U8, 42); + } + bool mutate_default_u8(uint8_t _default_u8 = 42) { + return SetField(VT_DEFAULT_U8, _default_u8, 42); + } + int16_t just_i16() const { + return GetField(VT_JUST_I16, 0); + } + bool mutate_just_i16(int16_t _just_i16 = 0) { + return SetField(VT_JUST_I16, _just_i16, 0); + } + ::flatbuffers::Optional maybe_i16() const { + return GetOptional(VT_MAYBE_I16); + } + bool mutate_maybe_i16(int16_t _maybe_i16) { + return SetField(VT_MAYBE_I16, _maybe_i16); + } + int16_t default_i16() const { + return GetField(VT_DEFAULT_I16, 42); + } + bool mutate_default_i16(int16_t _default_i16 = 42) { + return SetField(VT_DEFAULT_I16, _default_i16, 42); + } + uint16_t just_u16() const { + return GetField(VT_JUST_U16, 0); + } + bool mutate_just_u16(uint16_t _just_u16 = 0) { + return SetField(VT_JUST_U16, _just_u16, 0); + } + ::flatbuffers::Optional maybe_u16() const { + return GetOptional(VT_MAYBE_U16); + } + bool mutate_maybe_u16(uint16_t _maybe_u16) { + return SetField(VT_MAYBE_U16, _maybe_u16); + } + uint16_t default_u16() const { + return GetField(VT_DEFAULT_U16, 42); + } + bool mutate_default_u16(uint16_t _default_u16 = 42) { + return SetField(VT_DEFAULT_U16, _default_u16, 42); + } + int32_t just_i32() const { + return GetField(VT_JUST_I32, 0); + } + bool mutate_just_i32(int32_t _just_i32 = 0) { + return SetField(VT_JUST_I32, _just_i32, 0); + } + ::flatbuffers::Optional maybe_i32() const { + return GetOptional(VT_MAYBE_I32); + } + bool mutate_maybe_i32(int32_t _maybe_i32) { + return SetField(VT_MAYBE_I32, _maybe_i32); + } + int32_t default_i32() const { + return GetField(VT_DEFAULT_I32, 42); + } + bool mutate_default_i32(int32_t _default_i32 = 42) { + return SetField(VT_DEFAULT_I32, _default_i32, 42); + } + uint32_t just_u32() const { + return GetField(VT_JUST_U32, 0); + } + bool mutate_just_u32(uint32_t _just_u32 = 0) { + return SetField(VT_JUST_U32, _just_u32, 0); + } + ::flatbuffers::Optional maybe_u32() const { + return GetOptional(VT_MAYBE_U32); + } + bool mutate_maybe_u32(uint32_t _maybe_u32) { + return SetField(VT_MAYBE_U32, _maybe_u32); + } + uint32_t default_u32() const { + return GetField(VT_DEFAULT_U32, 42); + } + bool mutate_default_u32(uint32_t _default_u32 = 42) { + return SetField(VT_DEFAULT_U32, _default_u32, 42); + } + int64_t just_i64() const { + return GetField(VT_JUST_I64, 0); + } + bool mutate_just_i64(int64_t _just_i64 = 0) { + return SetField(VT_JUST_I64, _just_i64, 0); + } + ::flatbuffers::Optional maybe_i64() const { + return GetOptional(VT_MAYBE_I64); + } + bool mutate_maybe_i64(int64_t _maybe_i64) { + return SetField(VT_MAYBE_I64, _maybe_i64); + } + int64_t default_i64() const { + return GetField(VT_DEFAULT_I64, 42LL); + } + bool mutate_default_i64(int64_t _default_i64 = 42LL) { + return SetField(VT_DEFAULT_I64, _default_i64, 42LL); + } + uint64_t just_u64() const { + return GetField(VT_JUST_U64, 0); + } + bool mutate_just_u64(uint64_t _just_u64 = 0) { + return SetField(VT_JUST_U64, _just_u64, 0); + } + ::flatbuffers::Optional maybe_u64() const { + return GetOptional(VT_MAYBE_U64); + } + bool mutate_maybe_u64(uint64_t _maybe_u64) { + return SetField(VT_MAYBE_U64, _maybe_u64); + } + uint64_t default_u64() const { + return GetField(VT_DEFAULT_U64, 42ULL); + } + bool mutate_default_u64(uint64_t _default_u64 = 42ULL) { + return SetField(VT_DEFAULT_U64, _default_u64, 42ULL); + } + float just_f32() const { + return GetField(VT_JUST_F32, 0.0f); + } + bool mutate_just_f32(float _just_f32 = 0.0f) { + return SetField(VT_JUST_F32, _just_f32, 0.0f); + } + ::flatbuffers::Optional maybe_f32() const { + return GetOptional(VT_MAYBE_F32); + } + bool mutate_maybe_f32(float _maybe_f32) { + return SetField(VT_MAYBE_F32, _maybe_f32); + } + float default_f32() const { + return GetField(VT_DEFAULT_F32, 42.0f); + } + bool mutate_default_f32(float _default_f32 = 42.0f) { + return SetField(VT_DEFAULT_F32, _default_f32, 42.0f); + } + double just_f64() const { + return GetField(VT_JUST_F64, 0.0); + } + bool mutate_just_f64(double _just_f64 = 0.0) { + return SetField(VT_JUST_F64, _just_f64, 0.0); + } + ::flatbuffers::Optional maybe_f64() const { + return GetOptional(VT_MAYBE_F64); + } + bool mutate_maybe_f64(double _maybe_f64) { + return SetField(VT_MAYBE_F64, _maybe_f64); + } + double default_f64() const { + return GetField(VT_DEFAULT_F64, 42.0); + } + bool mutate_default_f64(double _default_f64 = 42.0) { + return SetField(VT_DEFAULT_F64, _default_f64, 42.0); + } + bool just_bool() const { + return GetField(VT_JUST_BOOL, 0) != 0; + } + bool mutate_just_bool(bool _just_bool = 0) { + return SetField(VT_JUST_BOOL, static_cast(_just_bool), 0); + } + ::flatbuffers::Optional maybe_bool() const { + return GetOptional(VT_MAYBE_BOOL); + } + bool mutate_maybe_bool(bool _maybe_bool) { + return SetField(VT_MAYBE_BOOL, static_cast(_maybe_bool)); + } + bool default_bool() const { + return GetField(VT_DEFAULT_BOOL, 1) != 0; + } + bool mutate_default_bool(bool _default_bool = 1) { + return SetField(VT_DEFAULT_BOOL, static_cast(_default_bool), 1); + } + optional_scalars::OptionalByte just_enum() const { + return static_cast(GetField(VT_JUST_ENUM, 0)); + } + bool mutate_just_enum(optional_scalars::OptionalByte _just_enum = static_cast(0)) { + return SetField(VT_JUST_ENUM, static_cast(_just_enum), 0); + } + ::flatbuffers::Optional maybe_enum() const { + return GetOptional(VT_MAYBE_ENUM); + } + bool mutate_maybe_enum(optional_scalars::OptionalByte _maybe_enum) { + return SetField(VT_MAYBE_ENUM, static_cast(_maybe_enum)); + } + optional_scalars::OptionalByte default_enum() const { + return static_cast(GetField(VT_DEFAULT_ENUM, 1)); + } + bool mutate_default_enum(optional_scalars::OptionalByte _default_enum = static_cast(1)) { + return SetField(VT_DEFAULT_ENUM, static_cast(_default_enum), 1); + } + template + auto get_field() const { + if constexpr (Index == 0) return just_i8(); + else if constexpr (Index == 1) return maybe_i8(); + else if constexpr (Index == 2) return default_i8(); + else if constexpr (Index == 3) return just_u8(); + else if constexpr (Index == 4) return maybe_u8(); + else if constexpr (Index == 5) return default_u8(); + else if constexpr (Index == 6) return just_i16(); + else if constexpr (Index == 7) return maybe_i16(); + else if constexpr (Index == 8) return default_i16(); + else if constexpr (Index == 9) return just_u16(); + else if constexpr (Index == 10) return maybe_u16(); + else if constexpr (Index == 11) return default_u16(); + else if constexpr (Index == 12) return just_i32(); + else if constexpr (Index == 13) return maybe_i32(); + else if constexpr (Index == 14) return default_i32(); + else if constexpr (Index == 15) return just_u32(); + else if constexpr (Index == 16) return maybe_u32(); + else if constexpr (Index == 17) return default_u32(); + else if constexpr (Index == 18) return just_i64(); + else if constexpr (Index == 19) return maybe_i64(); + else if constexpr (Index == 20) return default_i64(); + else if constexpr (Index == 21) return just_u64(); + else if constexpr (Index == 22) return maybe_u64(); + else if constexpr (Index == 23) return default_u64(); + else if constexpr (Index == 24) return just_f32(); + else if constexpr (Index == 25) return maybe_f32(); + else if constexpr (Index == 26) return default_f32(); + else if constexpr (Index == 27) return just_f64(); + else if constexpr (Index == 28) return maybe_f64(); + else if constexpr (Index == 29) return default_f64(); + else if constexpr (Index == 30) return just_bool(); + else if constexpr (Index == 31) return maybe_bool(); + else if constexpr (Index == 32) return default_bool(); + else if constexpr (Index == 33) return just_enum(); + else if constexpr (Index == 34) return maybe_enum(); + else if constexpr (Index == 35) return default_enum(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_JUST_I8, 1) && + VerifyField(verifier, VT_MAYBE_I8, 1) && + VerifyField(verifier, VT_DEFAULT_I8, 1) && + VerifyField(verifier, VT_JUST_U8, 1) && + VerifyField(verifier, VT_MAYBE_U8, 1) && + VerifyField(verifier, VT_DEFAULT_U8, 1) && + VerifyField(verifier, VT_JUST_I16, 2) && + VerifyField(verifier, VT_MAYBE_I16, 2) && + VerifyField(verifier, VT_DEFAULT_I16, 2) && + VerifyField(verifier, VT_JUST_U16, 2) && + VerifyField(verifier, VT_MAYBE_U16, 2) && + VerifyField(verifier, VT_DEFAULT_U16, 2) && + VerifyField(verifier, VT_JUST_I32, 4) && + VerifyField(verifier, VT_MAYBE_I32, 4) && + VerifyField(verifier, VT_DEFAULT_I32, 4) && + VerifyField(verifier, VT_JUST_U32, 4) && + VerifyField(verifier, VT_MAYBE_U32, 4) && + VerifyField(verifier, VT_DEFAULT_U32, 4) && + VerifyField(verifier, VT_JUST_I64, 8) && + VerifyField(verifier, VT_MAYBE_I64, 8) && + VerifyField(verifier, VT_DEFAULT_I64, 8) && + VerifyField(verifier, VT_JUST_U64, 8) && + VerifyField(verifier, VT_MAYBE_U64, 8) && + VerifyField(verifier, VT_DEFAULT_U64, 8) && + VerifyField(verifier, VT_JUST_F32, 4) && + VerifyField(verifier, VT_MAYBE_F32, 4) && + VerifyField(verifier, VT_DEFAULT_F32, 4) && + VerifyField(verifier, VT_JUST_F64, 8) && + VerifyField(verifier, VT_MAYBE_F64, 8) && + VerifyField(verifier, VT_DEFAULT_F64, 8) && + VerifyField(verifier, VT_JUST_BOOL, 1) && + VerifyField(verifier, VT_MAYBE_BOOL, 1) && + VerifyField(verifier, VT_DEFAULT_BOOL, 1) && + VerifyField(verifier, VT_JUST_ENUM, 1) && + VerifyField(verifier, VT_MAYBE_ENUM, 1) && + VerifyField(verifier, VT_DEFAULT_ENUM, 1) && + verifier.EndTable(); + } + ScalarStuffT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ScalarStuffT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ScalarStuffBuilder { + typedef ScalarStuff Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_just_i8(int8_t just_i8) { + fbb_.AddElement(ScalarStuff::VT_JUST_I8, just_i8, 0); + } + void add_maybe_i8(int8_t maybe_i8) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I8, maybe_i8); + } + void add_default_i8(int8_t default_i8) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I8, default_i8, 42); + } + void add_just_u8(uint8_t just_u8) { + fbb_.AddElement(ScalarStuff::VT_JUST_U8, just_u8, 0); + } + void add_maybe_u8(uint8_t maybe_u8) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U8, maybe_u8); + } + void add_default_u8(uint8_t default_u8) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U8, default_u8, 42); + } + void add_just_i16(int16_t just_i16) { + fbb_.AddElement(ScalarStuff::VT_JUST_I16, just_i16, 0); + } + void add_maybe_i16(int16_t maybe_i16) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I16, maybe_i16); + } + void add_default_i16(int16_t default_i16) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I16, default_i16, 42); + } + void add_just_u16(uint16_t just_u16) { + fbb_.AddElement(ScalarStuff::VT_JUST_U16, just_u16, 0); + } + void add_maybe_u16(uint16_t maybe_u16) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U16, maybe_u16); + } + void add_default_u16(uint16_t default_u16) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U16, default_u16, 42); + } + void add_just_i32(int32_t just_i32) { + fbb_.AddElement(ScalarStuff::VT_JUST_I32, just_i32, 0); + } + void add_maybe_i32(int32_t maybe_i32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I32, maybe_i32); + } + void add_default_i32(int32_t default_i32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I32, default_i32, 42); + } + void add_just_u32(uint32_t just_u32) { + fbb_.AddElement(ScalarStuff::VT_JUST_U32, just_u32, 0); + } + void add_maybe_u32(uint32_t maybe_u32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U32, maybe_u32); + } + void add_default_u32(uint32_t default_u32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U32, default_u32, 42); + } + void add_just_i64(int64_t just_i64) { + fbb_.AddElement(ScalarStuff::VT_JUST_I64, just_i64, 0); + } + void add_maybe_i64(int64_t maybe_i64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I64, maybe_i64); + } + void add_default_i64(int64_t default_i64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I64, default_i64, 42LL); + } + void add_just_u64(uint64_t just_u64) { + fbb_.AddElement(ScalarStuff::VT_JUST_U64, just_u64, 0); + } + void add_maybe_u64(uint64_t maybe_u64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U64, maybe_u64); + } + void add_default_u64(uint64_t default_u64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U64, default_u64, 42ULL); + } + void add_just_f32(float just_f32) { + fbb_.AddElement(ScalarStuff::VT_JUST_F32, just_f32, 0.0f); + } + void add_maybe_f32(float maybe_f32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_F32, maybe_f32); + } + void add_default_f32(float default_f32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0f); + } + void add_just_f64(double just_f64) { + fbb_.AddElement(ScalarStuff::VT_JUST_F64, just_f64, 0.0); + } + void add_maybe_f64(double maybe_f64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_F64, maybe_f64); + } + void add_default_f64(double default_f64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0); + } + void add_just_bool(bool just_bool) { + fbb_.AddElement(ScalarStuff::VT_JUST_BOOL, static_cast(just_bool), 0); + } + void add_maybe_bool(bool maybe_bool) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_BOOL, static_cast(maybe_bool)); + } + void add_default_bool(bool default_bool) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_BOOL, static_cast(default_bool), 1); + } + void add_just_enum(optional_scalars::OptionalByte just_enum) { + fbb_.AddElement(ScalarStuff::VT_JUST_ENUM, static_cast(just_enum), 0); + } + void add_maybe_enum(optional_scalars::OptionalByte maybe_enum) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_ENUM, static_cast(maybe_enum)); + } + void add_default_enum(optional_scalars::OptionalByte default_enum) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_ENUM, static_cast(default_enum), 1); + } + explicit ScalarStuffBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateScalarStuff( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t just_i8 = 0, + ::flatbuffers::Optional maybe_i8 = ::flatbuffers::nullopt, + int8_t default_i8 = 42, + uint8_t just_u8 = 0, + ::flatbuffers::Optional maybe_u8 = ::flatbuffers::nullopt, + uint8_t default_u8 = 42, + int16_t just_i16 = 0, + ::flatbuffers::Optional maybe_i16 = ::flatbuffers::nullopt, + int16_t default_i16 = 42, + uint16_t just_u16 = 0, + ::flatbuffers::Optional maybe_u16 = ::flatbuffers::nullopt, + uint16_t default_u16 = 42, + int32_t just_i32 = 0, + ::flatbuffers::Optional maybe_i32 = ::flatbuffers::nullopt, + int32_t default_i32 = 42, + uint32_t just_u32 = 0, + ::flatbuffers::Optional maybe_u32 = ::flatbuffers::nullopt, + uint32_t default_u32 = 42, + int64_t just_i64 = 0, + ::flatbuffers::Optional maybe_i64 = ::flatbuffers::nullopt, + int64_t default_i64 = 42LL, + uint64_t just_u64 = 0, + ::flatbuffers::Optional maybe_u64 = ::flatbuffers::nullopt, + uint64_t default_u64 = 42ULL, + float just_f32 = 0.0f, + ::flatbuffers::Optional maybe_f32 = ::flatbuffers::nullopt, + float default_f32 = 42.0f, + double just_f64 = 0.0, + ::flatbuffers::Optional maybe_f64 = ::flatbuffers::nullopt, + double default_f64 = 42.0, + bool just_bool = false, + ::flatbuffers::Optional maybe_bool = ::flatbuffers::nullopt, + bool default_bool = true, + optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte::None, + ::flatbuffers::Optional maybe_enum = ::flatbuffers::nullopt, + optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte::One) { + ScalarStuffBuilder builder_(_fbb); + builder_.add_default_f64(default_f64); + if(maybe_f64) { builder_.add_maybe_f64(*maybe_f64); } + builder_.add_just_f64(just_f64); + builder_.add_default_u64(default_u64); + if(maybe_u64) { builder_.add_maybe_u64(*maybe_u64); } + builder_.add_just_u64(just_u64); + builder_.add_default_i64(default_i64); + if(maybe_i64) { builder_.add_maybe_i64(*maybe_i64); } + builder_.add_just_i64(just_i64); + builder_.add_default_f32(default_f32); + if(maybe_f32) { builder_.add_maybe_f32(*maybe_f32); } + builder_.add_just_f32(just_f32); + builder_.add_default_u32(default_u32); + if(maybe_u32) { builder_.add_maybe_u32(*maybe_u32); } + builder_.add_just_u32(just_u32); + builder_.add_default_i32(default_i32); + if(maybe_i32) { builder_.add_maybe_i32(*maybe_i32); } + builder_.add_just_i32(just_i32); + builder_.add_default_u16(default_u16); + if(maybe_u16) { builder_.add_maybe_u16(*maybe_u16); } + builder_.add_just_u16(just_u16); + builder_.add_default_i16(default_i16); + if(maybe_i16) { builder_.add_maybe_i16(*maybe_i16); } + builder_.add_just_i16(just_i16); + builder_.add_default_enum(default_enum); + if(maybe_enum) { builder_.add_maybe_enum(*maybe_enum); } + builder_.add_just_enum(just_enum); + builder_.add_default_bool(default_bool); + if(maybe_bool) { builder_.add_maybe_bool(*maybe_bool); } + builder_.add_just_bool(just_bool); + builder_.add_default_u8(default_u8); + if(maybe_u8) { builder_.add_maybe_u8(*maybe_u8); } + builder_.add_just_u8(just_u8); + builder_.add_default_i8(default_i8); + if(maybe_i8) { builder_.add_maybe_i8(*maybe_i8); } + builder_.add_just_i8(just_i8); + return builder_.Finish(); +} + +struct ScalarStuff::Traits { + using type = ScalarStuff; + static auto constexpr Create = CreateScalarStuff; + static constexpr auto name = "ScalarStuff"; + static constexpr auto fully_qualified_name = "optional_scalars.ScalarStuff"; + static constexpr size_t fields_number = 36; + static constexpr std::array field_names = { + "just_i8", + "maybe_i8", + "default_i8", + "just_u8", + "maybe_u8", + "default_u8", + "just_i16", + "maybe_i16", + "default_i16", + "just_u16", + "maybe_u16", + "default_u16", + "just_i32", + "maybe_i32", + "default_i32", + "just_u32", + "maybe_u32", + "default_u32", + "just_i64", + "maybe_i64", + "default_i64", + "just_u64", + "maybe_u64", + "default_u64", + "just_f32", + "maybe_f32", + "default_f32", + "just_f64", + "maybe_f64", + "default_f64", + "just_bool", + "maybe_bool", + "default_bool", + "just_enum", + "maybe_enum", + "default_enum" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +::flatbuffers::Offset CreateScalarStuff(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +inline ScalarStuffT *ScalarStuff::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void ScalarStuff::UnPackTo(ScalarStuffT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = just_i8(); _o->just_i8 = _e; } + { auto _e = maybe_i8(); _o->maybe_i8 = _e; } + { auto _e = default_i8(); _o->default_i8 = _e; } + { auto _e = just_u8(); _o->just_u8 = _e; } + { auto _e = maybe_u8(); _o->maybe_u8 = _e; } + { auto _e = default_u8(); _o->default_u8 = _e; } + { auto _e = just_i16(); _o->just_i16 = _e; } + { auto _e = maybe_i16(); _o->maybe_i16 = _e; } + { auto _e = default_i16(); _o->default_i16 = _e; } + { auto _e = just_u16(); _o->just_u16 = _e; } + { auto _e = maybe_u16(); _o->maybe_u16 = _e; } + { auto _e = default_u16(); _o->default_u16 = _e; } + { auto _e = just_i32(); _o->just_i32 = _e; } + { auto _e = maybe_i32(); _o->maybe_i32 = _e; } + { auto _e = default_i32(); _o->default_i32 = _e; } + { auto _e = just_u32(); _o->just_u32 = _e; } + { auto _e = maybe_u32(); _o->maybe_u32 = _e; } + { auto _e = default_u32(); _o->default_u32 = _e; } + { auto _e = just_i64(); _o->just_i64 = _e; } + { auto _e = maybe_i64(); _o->maybe_i64 = _e; } + { auto _e = default_i64(); _o->default_i64 = _e; } + { auto _e = just_u64(); _o->just_u64 = _e; } + { auto _e = maybe_u64(); _o->maybe_u64 = _e; } + { auto _e = default_u64(); _o->default_u64 = _e; } + { auto _e = just_f32(); _o->just_f32 = _e; } + { auto _e = maybe_f32(); _o->maybe_f32 = _e; } + { auto _e = default_f32(); _o->default_f32 = _e; } + { auto _e = just_f64(); _o->just_f64 = _e; } + { auto _e = maybe_f64(); _o->maybe_f64 = _e; } + { auto _e = default_f64(); _o->default_f64 = _e; } + { auto _e = just_bool(); _o->just_bool = _e; } + { auto _e = maybe_bool(); _o->maybe_bool = _e; } + { auto _e = default_bool(); _o->default_bool = _e; } + { auto _e = just_enum(); _o->just_enum = _e; } + { auto _e = maybe_enum(); _o->maybe_enum = _e; } + { auto _e = default_enum(); _o->default_enum = _e; } +} + +inline ::flatbuffers::Offset ScalarStuff::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateScalarStuff(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateScalarStuff(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ScalarStuffT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _just_i8 = _o->just_i8; + auto _maybe_i8 = _o->maybe_i8; + auto _default_i8 = _o->default_i8; + auto _just_u8 = _o->just_u8; + auto _maybe_u8 = _o->maybe_u8; + auto _default_u8 = _o->default_u8; + auto _just_i16 = _o->just_i16; + auto _maybe_i16 = _o->maybe_i16; + auto _default_i16 = _o->default_i16; + auto _just_u16 = _o->just_u16; + auto _maybe_u16 = _o->maybe_u16; + auto _default_u16 = _o->default_u16; + auto _just_i32 = _o->just_i32; + auto _maybe_i32 = _o->maybe_i32; + auto _default_i32 = _o->default_i32; + auto _just_u32 = _o->just_u32; + auto _maybe_u32 = _o->maybe_u32; + auto _default_u32 = _o->default_u32; + auto _just_i64 = _o->just_i64; + auto _maybe_i64 = _o->maybe_i64; + auto _default_i64 = _o->default_i64; + auto _just_u64 = _o->just_u64; + auto _maybe_u64 = _o->maybe_u64; + auto _default_u64 = _o->default_u64; + auto _just_f32 = _o->just_f32; + auto _maybe_f32 = _o->maybe_f32; + auto _default_f32 = _o->default_f32; + auto _just_f64 = _o->just_f64; + auto _maybe_f64 = _o->maybe_f64; + auto _default_f64 = _o->default_f64; + auto _just_bool = _o->just_bool; + auto _maybe_bool = _o->maybe_bool; + auto _default_bool = _o->default_bool; + auto _just_enum = _o->just_enum; + auto _maybe_enum = _o->maybe_enum; + auto _default_enum = _o->default_enum; + return optional_scalars::CreateScalarStuff( + _fbb, + _just_i8, + _maybe_i8, + _default_i8, + _just_u8, + _maybe_u8, + _default_u8, + _just_i16, + _maybe_i16, + _default_i16, + _just_u16, + _maybe_u16, + _default_u16, + _just_i32, + _maybe_i32, + _default_i32, + _just_u32, + _maybe_u32, + _default_u32, + _just_i64, + _maybe_i64, + _default_i64, + _just_u64, + _maybe_u64, + _default_u64, + _just_f32, + _maybe_f32, + _default_f32, + _just_f64, + _maybe_f64, + _default_f64, + _just_bool, + _maybe_bool, + _default_bool, + _just_enum, + _maybe_enum, + _default_enum); +} + +inline const ::flatbuffers::TypeTable *OptionalByteTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + optional_scalars::OptionalByteTypeTable + }; + static const char * const names[] = { + "None", + "One", + "Two" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ScalarStuffTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + optional_scalars::OptionalByteTypeTable + }; + static const char * const names[] = { + "just_i8", + "maybe_i8", + "default_i8", + "just_u8", + "maybe_u8", + "default_u8", + "just_i16", + "maybe_i16", + "default_i16", + "just_u16", + "maybe_u16", + "default_u16", + "just_i32", + "maybe_i32", + "default_i32", + "just_u32", + "maybe_u32", + "default_u32", + "just_i64", + "maybe_i64", + "default_i64", + "just_u64", + "maybe_u64", + "default_u64", + "just_f32", + "maybe_f32", + "default_f32", + "just_f64", + "maybe_f64", + "default_f64", + "just_bool", + "maybe_bool", + "default_bool", + "just_enum", + "maybe_enum", + "default_enum" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 36, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const optional_scalars::ScalarStuff *GetScalarStuff(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const optional_scalars::ScalarStuff *GetSizePrefixedScalarStuff(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline ScalarStuff *GetMutableScalarStuff(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline optional_scalars::ScalarStuff *GetMutableSizePrefixedScalarStuff(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *ScalarStuffIdentifier() { + return "NULL"; +} + +inline bool ScalarStuffBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ScalarStuffIdentifier()); +} + +inline bool SizePrefixedScalarStuffBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ScalarStuffIdentifier(), true); +} + +inline bool VerifyScalarStuffBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(ScalarStuffIdentifier()); +} + +inline bool VerifySizePrefixedScalarStuffBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(ScalarStuffIdentifier()); +} + +inline const char *ScalarStuffExtension() { + return "mon"; +} + +inline void FinishScalarStuffBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, ScalarStuffIdentifier()); +} + +inline void FinishSizePrefixedScalarStuffBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, ScalarStuffIdentifier()); +} + +inline std::unique_ptr UnPackScalarStuff( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetScalarStuff(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedScalarStuff( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedScalarStuff(buf)->UnPack(res)); +} + +} // namespace optional_scalars + +#endif // FLATBUFFERS_GENERATED_OPTIONALSCALARS_OPTIONAL_SCALARS_H_ diff --git a/third_party/flatbuffers/tests/cpp17/generated_cpp17/union_vector_generated.h b/third_party/flatbuffers/tests/cpp17/generated_cpp17/union_vector_generated.h new file mode 100644 index 00000000000..39df53f3a6c --- /dev/null +++ b/third_party/flatbuffers/tests/cpp17/generated_cpp17/union_vector_generated.h @@ -0,0 +1,1263 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_UNIONVECTOR_H_ +#define FLATBUFFERS_GENERATED_UNIONVECTOR_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +struct Attacker; +struct AttackerBuilder; +struct AttackerT; + +struct Rapunzel; + +struct BookReader; + +struct FallingTub; + +struct HandFan; +struct HandFanBuilder; +struct HandFanT; + +struct Movie; +struct MovieBuilder; +struct MovieT; + +inline const ::flatbuffers::TypeTable *AttackerTypeTable(); + +inline const ::flatbuffers::TypeTable *RapunzelTypeTable(); + +inline const ::flatbuffers::TypeTable *BookReaderTypeTable(); + +inline const ::flatbuffers::TypeTable *FallingTubTypeTable(); + +inline const ::flatbuffers::TypeTable *HandFanTypeTable(); + +inline const ::flatbuffers::TypeTable *MovieTypeTable(); + +enum class Character : uint8_t { + NONE = 0, + MuLan = 1, + Rapunzel = 2, + Belle = 3, + BookFan = 4, + Other = 5, + Unused = 6, + MIN = NONE, + MAX = Unused +}; + +inline const Character (&EnumValuesCharacter())[7] { + static const Character values[] = { + Character::NONE, + Character::MuLan, + Character::Rapunzel, + Character::Belle, + Character::BookFan, + Character::Other, + Character::Unused + }; + return values; +} + +inline const char * const *EnumNamesCharacter() { + static const char * const names[8] = { + "NONE", + "MuLan", + "Rapunzel", + "Belle", + "BookFan", + "Other", + "Unused", + nullptr + }; + return names; +} + +inline const char *EnumNameCharacter(Character e) { + if (::flatbuffers::IsOutRange(e, Character::NONE, Character::Unused)) return ""; + const size_t index = static_cast(e); + return EnumNamesCharacter()[index]; +} + +struct CharacterUnion { + Character type; + void *value; + + CharacterUnion() : type(Character::NONE), value(nullptr) {} + CharacterUnion(CharacterUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Character::NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + CharacterUnion(const CharacterUnion &); + CharacterUnion &operator=(const CharacterUnion &u) + { CharacterUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + CharacterUnion &operator=(CharacterUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~CharacterUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, Character type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + AttackerT *AsMuLan() { + return type == Character::MuLan ? + reinterpret_cast(value) : nullptr; + } + const AttackerT *AsMuLan() const { + return type == Character::MuLan ? + reinterpret_cast(value) : nullptr; + } + Rapunzel *AsRapunzel() { + return type == Character::Rapunzel ? + reinterpret_cast(value) : nullptr; + } + const Rapunzel *AsRapunzel() const { + return type == Character::Rapunzel ? + reinterpret_cast(value) : nullptr; + } + BookReader *AsBelle() { + return type == Character::Belle ? + reinterpret_cast(value) : nullptr; + } + const BookReader *AsBelle() const { + return type == Character::Belle ? + reinterpret_cast(value) : nullptr; + } + BookReader *AsBookFan() { + return type == Character::BookFan ? + reinterpret_cast(value) : nullptr; + } + const BookReader *AsBookFan() const { + return type == Character::BookFan ? + reinterpret_cast(value) : nullptr; + } + std::string *AsOther() { + return type == Character::Other ? + reinterpret_cast(value) : nullptr; + } + const std::string *AsOther() const { + return type == Character::Other ? + reinterpret_cast(value) : nullptr; + } + std::string *AsUnused() { + return type == Character::Unused ? + reinterpret_cast(value) : nullptr; + } + const std::string *AsUnused() const { + return type == Character::Unused ? + reinterpret_cast(value) : nullptr; + } +}; + +bool VerifyCharacter(::flatbuffers::Verifier &verifier, const void *obj, Character type); +bool VerifyCharacterVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum class Gadget : uint8_t { + NONE = 0, + FallingTub = 1, + HandFan = 2, + MIN = NONE, + MAX = HandFan +}; + +inline const Gadget (&EnumValuesGadget())[3] { + static const Gadget values[] = { + Gadget::NONE, + Gadget::FallingTub, + Gadget::HandFan + }; + return values; +} + +inline const char * const *EnumNamesGadget() { + static const char * const names[4] = { + "NONE", + "FallingTub", + "HandFan", + nullptr + }; + return names; +} + +inline const char *EnumNameGadget(Gadget e) { + if (::flatbuffers::IsOutRange(e, Gadget::NONE, Gadget::HandFan)) return ""; + const size_t index = static_cast(e); + return EnumNamesGadget()[index]; +} + +template struct GadgetTraits { + static const Gadget enum_value = Gadget::NONE; +}; + +template<> struct GadgetTraits { + static const Gadget enum_value = Gadget::FallingTub; +}; + +template<> struct GadgetTraits { + static const Gadget enum_value = Gadget::HandFan; +}; + +template struct GadgetUnionTraits { + static const Gadget enum_value = Gadget::NONE; +}; + +template<> struct GadgetUnionTraits { + static const Gadget enum_value = Gadget::FallingTub; +}; + +template<> struct GadgetUnionTraits { + static const Gadget enum_value = Gadget::HandFan; +}; + +struct GadgetUnion { + Gadget type; + void *value; + + GadgetUnion() : type(Gadget::NONE), value(nullptr) {} + GadgetUnion(GadgetUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Gadget::NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + GadgetUnion(const GadgetUnion &); + GadgetUnion &operator=(const GadgetUnion &u) + { GadgetUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + GadgetUnion &operator=(GadgetUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~GadgetUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = GadgetUnionTraits::enum_value; + if (type != Gadget::NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Gadget type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + FallingTub *AsFallingTub() { + return type == Gadget::FallingTub ? + reinterpret_cast(value) : nullptr; + } + const FallingTub *AsFallingTub() const { + return type == Gadget::FallingTub ? + reinterpret_cast(value) : nullptr; + } + HandFanT *AsHandFan() { + return type == Gadget::HandFan ? + reinterpret_cast(value) : nullptr; + } + const HandFanT *AsHandFan() const { + return type == Gadget::HandFan ? + reinterpret_cast(value) : nullptr; + } +}; + +bool VerifyGadget(::flatbuffers::Verifier &verifier, const void *obj, Gadget type); +bool VerifyGadgetVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Rapunzel FLATBUFFERS_FINAL_CLASS { + private: + int32_t hair_length_; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RapunzelTypeTable(); + } + Rapunzel() + : hair_length_(0) { + } + Rapunzel(int32_t _hair_length) + : hair_length_(::flatbuffers::EndianScalar(_hair_length)) { + } + int32_t hair_length() const { + return ::flatbuffers::EndianScalar(hair_length_); + } + void mutate_hair_length(int32_t _hair_length) { + ::flatbuffers::WriteScalar(&hair_length_, _hair_length); + } + template + auto get_field() const { + if constexpr (Index == 0) return hair_length(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(Rapunzel, 4); + +struct Rapunzel::Traits { + using type = Rapunzel; + static constexpr auto name = "Rapunzel"; + static constexpr auto fully_qualified_name = "Rapunzel"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "hair_length" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) BookReader FLATBUFFERS_FINAL_CLASS { + private: + int32_t books_read_; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return BookReaderTypeTable(); + } + BookReader() + : books_read_(0) { + } + BookReader(int32_t _books_read) + : books_read_(::flatbuffers::EndianScalar(_books_read)) { + } + int32_t books_read() const { + return ::flatbuffers::EndianScalar(books_read_); + } + void mutate_books_read(int32_t _books_read) { + ::flatbuffers::WriteScalar(&books_read_, _books_read); + } + template + auto get_field() const { + if constexpr (Index == 0) return books_read(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(BookReader, 4); + +struct BookReader::Traits { + using type = BookReader; + static constexpr auto name = "BookReader"; + static constexpr auto fully_qualified_name = "BookReader"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "books_read" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) FallingTub FLATBUFFERS_FINAL_CLASS { + private: + int32_t weight_; + + public: + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return FallingTubTypeTable(); + } + FallingTub() + : weight_(0) { + } + FallingTub(int32_t _weight) + : weight_(::flatbuffers::EndianScalar(_weight)) { + } + int32_t weight() const { + return ::flatbuffers::EndianScalar(weight_); + } + void mutate_weight(int32_t _weight) { + ::flatbuffers::WriteScalar(&weight_, _weight); + } + template + auto get_field() const { + if constexpr (Index == 0) return weight(); + else static_assert(Index != -1, "Invalid Field Index"); + } +}; +FLATBUFFERS_STRUCT_END(FallingTub, 4); + +struct FallingTub::Traits { + using type = FallingTub; + static constexpr auto name = "FallingTub"; + static constexpr auto fully_qualified_name = "FallingTub"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "weight" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +struct AttackerT : public ::flatbuffers::NativeTable { + typedef Attacker TableType; + int32_t sword_attack_damage = 0; +}; + +struct Attacker FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef AttackerT NativeTableType; + typedef AttackerBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AttackerTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_SWORD_ATTACK_DAMAGE = 4 + }; + int32_t sword_attack_damage() const { + return GetField(VT_SWORD_ATTACK_DAMAGE, 0); + } + bool mutate_sword_attack_damage(int32_t _sword_attack_damage = 0) { + return SetField(VT_SWORD_ATTACK_DAMAGE, _sword_attack_damage, 0); + } + template + auto get_field() const { + if constexpr (Index == 0) return sword_attack_damage(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_SWORD_ATTACK_DAMAGE, 4) && + verifier.EndTable(); + } + AttackerT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(AttackerT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct AttackerBuilder { + typedef Attacker Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_sword_attack_damage(int32_t sword_attack_damage) { + fbb_.AddElement(Attacker::VT_SWORD_ATTACK_DAMAGE, sword_attack_damage, 0); + } + explicit AttackerBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateAttacker( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t sword_attack_damage = 0) { + AttackerBuilder builder_(_fbb); + builder_.add_sword_attack_damage(sword_attack_damage); + return builder_.Finish(); +} + +struct Attacker::Traits { + using type = Attacker; + static auto constexpr Create = CreateAttacker; + static constexpr auto name = "Attacker"; + static constexpr auto fully_qualified_name = "Attacker"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "sword_attack_damage" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +::flatbuffers::Offset CreateAttacker(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct HandFanT : public ::flatbuffers::NativeTable { + typedef HandFan TableType; + int32_t length = 0; +}; + +struct HandFan FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef HandFanT NativeTableType; + typedef HandFanBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return HandFanTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_LENGTH = 4 + }; + int32_t length() const { + return GetField(VT_LENGTH, 0); + } + bool mutate_length(int32_t _length = 0) { + return SetField(VT_LENGTH, _length, 0); + } + template + auto get_field() const { + if constexpr (Index == 0) return length(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_LENGTH, 4) && + verifier.EndTable(); + } + HandFanT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(HandFanT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct HandFanBuilder { + typedef HandFan Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_length(int32_t length) { + fbb_.AddElement(HandFan::VT_LENGTH, length, 0); + } + explicit HandFanBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateHandFan( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t length = 0) { + HandFanBuilder builder_(_fbb); + builder_.add_length(length); + return builder_.Finish(); +} + +struct HandFan::Traits { + using type = HandFan; + static auto constexpr Create = CreateHandFan; + static constexpr auto name = "HandFan"; + static constexpr auto fully_qualified_name = "HandFan"; + static constexpr size_t fields_number = 1; + static constexpr std::array field_names = { + "length" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +::flatbuffers::Offset CreateHandFan(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MovieT : public ::flatbuffers::NativeTable { + typedef Movie TableType; + CharacterUnion main_character{}; + std::vector characters{}; +}; + +struct Movie FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MovieT NativeTableType; + typedef MovieBuilder Builder; + struct Traits; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MovieTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_MAIN_CHARACTER_TYPE = 4, + VT_MAIN_CHARACTER = 6, + VT_CHARACTERS_TYPE = 8, + VT_CHARACTERS = 10 + }; + Character main_character_type() const { + return static_cast(GetField(VT_MAIN_CHARACTER_TYPE, 0)); + } + const void *main_character() const { + return GetPointer(VT_MAIN_CHARACTER); + } + const Attacker *main_character_as_MuLan() const { + return main_character_type() == Character::MuLan ? static_cast(main_character()) : nullptr; + } + const Rapunzel *main_character_as_Rapunzel() const { + return main_character_type() == Character::Rapunzel ? static_cast(main_character()) : nullptr; + } + const BookReader *main_character_as_Belle() const { + return main_character_type() == Character::Belle ? static_cast(main_character()) : nullptr; + } + const BookReader *main_character_as_BookFan() const { + return main_character_type() == Character::BookFan ? static_cast(main_character()) : nullptr; + } + const ::flatbuffers::String *main_character_as_Other() const { + return main_character_type() == Character::Other ? static_cast(main_character()) : nullptr; + } + const ::flatbuffers::String *main_character_as_Unused() const { + return main_character_type() == Character::Unused ? static_cast(main_character()) : nullptr; + } + void *mutable_main_character() { + return GetPointer(VT_MAIN_CHARACTER); + } + const ::flatbuffers::Vector *characters_type() const { + return GetPointer *>(VT_CHARACTERS_TYPE); + } + ::flatbuffers::Vector *mutable_characters_type() { + return GetPointer<::flatbuffers::Vector *>(VT_CHARACTERS_TYPE); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *characters() const { + return GetPointer> *>(VT_CHARACTERS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_characters() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_CHARACTERS); + } + template + auto get_field() const { + if constexpr (Index == 0) return main_character_type(); + else if constexpr (Index == 1) return main_character(); + else if constexpr (Index == 2) return characters_type(); + else if constexpr (Index == 3) return characters(); + else static_assert(Index != -1, "Invalid Field Index"); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_MAIN_CHARACTER_TYPE, 1) && + VerifyOffset(verifier, VT_MAIN_CHARACTER) && + VerifyCharacter(verifier, main_character(), main_character_type()) && + VerifyOffset(verifier, VT_CHARACTERS_TYPE) && + verifier.VerifyVector(characters_type()) && + VerifyOffset(verifier, VT_CHARACTERS) && + verifier.VerifyVector(characters()) && + VerifyCharacterVector(verifier, characters(), characters_type()) && + verifier.EndTable(); + } + MovieT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MovieT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MovieBuilder { + typedef Movie Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_main_character_type(Character main_character_type) { + fbb_.AddElement(Movie::VT_MAIN_CHARACTER_TYPE, static_cast(main_character_type), 0); + } + void add_main_character(::flatbuffers::Offset main_character) { + fbb_.AddOffset(Movie::VT_MAIN_CHARACTER, main_character); + } + void add_characters_type(::flatbuffers::Offset<::flatbuffers::Vector> characters_type) { + fbb_.AddOffset(Movie::VT_CHARACTERS_TYPE, characters_type); + } + void add_characters(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> characters) { + fbb_.AddOffset(Movie::VT_CHARACTERS, characters); + } + explicit MovieBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMovie( + ::flatbuffers::FlatBufferBuilder &_fbb, + Character main_character_type = Character::NONE, + ::flatbuffers::Offset main_character = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> characters_type = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> characters = 0) { + MovieBuilder builder_(_fbb); + builder_.add_characters(characters); + builder_.add_characters_type(characters_type); + builder_.add_main_character(main_character); + builder_.add_main_character_type(main_character_type); + return builder_.Finish(); +} + +struct Movie::Traits { + using type = Movie; + static auto constexpr Create = CreateMovie; + static constexpr auto name = "Movie"; + static constexpr auto fully_qualified_name = "Movie"; + static constexpr size_t fields_number = 4; + static constexpr std::array field_names = { + "main_character_type", + "main_character", + "characters_type", + "characters" + }; + template + using FieldType = decltype(std::declval().get_field()); +}; + +inline ::flatbuffers::Offset CreateMovieDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + Character main_character_type = Character::NONE, + ::flatbuffers::Offset main_character = 0, + const std::vector *characters_type = nullptr, + const std::vector<::flatbuffers::Offset> *characters = nullptr) { + auto characters_type__ = characters_type ? _fbb.CreateVector(*characters_type) : 0; + auto characters__ = characters ? _fbb.CreateVector<::flatbuffers::Offset>(*characters) : 0; + return CreateMovie( + _fbb, + main_character_type, + main_character, + characters_type__, + characters__); +} + +::flatbuffers::Offset CreateMovie(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +inline AttackerT *Attacker::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Attacker::UnPackTo(AttackerT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = sword_attack_damage(); _o->sword_attack_damage = _e; } +} + +inline ::flatbuffers::Offset Attacker::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateAttacker(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateAttacker(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const AttackerT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _sword_attack_damage = _o->sword_attack_damage; + return CreateAttacker( + _fbb, + _sword_attack_damage); +} + +inline HandFanT *HandFan::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void HandFan::UnPackTo(HandFanT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = length(); _o->length = _e; } +} + +inline ::flatbuffers::Offset HandFan::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateHandFan(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateHandFan(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const HandFanT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _length = _o->length; + return CreateHandFan( + _fbb, + _length); +} + +inline MovieT *Movie::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::make_unique(); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Movie::UnPackTo(MovieT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = main_character_type(); _o->main_character.type = _e; } + { auto _e = main_character(); if (_e) _o->main_character.value = CharacterUnion::UnPack(_e, main_character_type(), _resolver); } + { auto _e = characters_type(); if (_e) { _o->characters.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->characters[_i].type = static_cast(_e->Get(_i)); } } else { _o->characters.resize(0); } } + { auto _e = characters(); if (_e) { _o->characters.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->characters[_i].value = CharacterUnion::UnPack(_e->Get(_i), characters_type()->GetEnum(_i), _resolver); } } else { _o->characters.resize(0); } } +} + +inline ::flatbuffers::Offset Movie::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMovie(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMovie(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MovieT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _main_character_type = _o->main_character.type; + auto _main_character = _o->main_character.Pack(_fbb); + auto _characters_type = _o->characters.size() ? _fbb.CreateVector(_o->characters.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->characters[i].type; }, &_va) : 0; + auto _characters = _o->characters.size() ? _fbb.CreateVector<::flatbuffers::Offset>(_o->characters.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->characters[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va) : 0; + return CreateMovie( + _fbb, + _main_character_type, + _main_character, + _characters_type, + _characters); +} + +inline bool VerifyCharacter(::flatbuffers::Verifier &verifier, const void *obj, Character type) { + switch (type) { + case Character::NONE: { + return true; + } + case Character::MuLan: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Character::Rapunzel: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Character::Belle: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Character::BookFan: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Character::Other: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyString(ptr); + } + case Character::Unused: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyString(ptr); + } + default: return true; + } +} + +inline bool VerifyCharacterVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyCharacter( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *CharacterUnion::UnPack(const void *obj, Character type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Character::MuLan: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Character::Rapunzel: { + auto ptr = reinterpret_cast(obj); + return new Rapunzel(*ptr); + } + case Character::Belle: { + auto ptr = reinterpret_cast(obj); + return new BookReader(*ptr); + } + case Character::BookFan: { + auto ptr = reinterpret_cast(obj); + return new BookReader(*ptr); + } + case Character::Other: { + auto ptr = reinterpret_cast(obj); + return new std::string(ptr->c_str(), ptr->size()); + } + case Character::Unused: { + auto ptr = reinterpret_cast(obj); + return new std::string(ptr->c_str(), ptr->size()); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset CharacterUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Character::MuLan: { + auto ptr = reinterpret_cast(value); + return CreateAttacker(_fbb, ptr, _rehasher).Union(); + } + case Character::Rapunzel: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Character::Belle: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Character::BookFan: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Character::Other: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateString(*ptr).Union(); + } + case Character::Unused: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateString(*ptr).Union(); + } + default: return 0; + } +} + +inline CharacterUnion::CharacterUnion(const CharacterUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Character::MuLan: { + value = new AttackerT(*reinterpret_cast(u.value)); + break; + } + case Character::Rapunzel: { + value = new Rapunzel(*reinterpret_cast(u.value)); + break; + } + case Character::Belle: { + value = new BookReader(*reinterpret_cast(u.value)); + break; + } + case Character::BookFan: { + value = new BookReader(*reinterpret_cast(u.value)); + break; + } + case Character::Other: { + value = new std::string(*reinterpret_cast(u.value)); + break; + } + case Character::Unused: { + value = new std::string(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void CharacterUnion::Reset() { + switch (type) { + case Character::MuLan: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character::Rapunzel: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character::Belle: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character::BookFan: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character::Other: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character::Unused: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Character::NONE; +} + +inline bool VerifyGadget(::flatbuffers::Verifier &verifier, const void *obj, Gadget type) { + switch (type) { + case Gadget::NONE: { + return true; + } + case Gadget::FallingTub: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Gadget::HandFan: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyGadgetVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyGadget( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *GadgetUnion::UnPack(const void *obj, Gadget type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Gadget::FallingTub: { + auto ptr = reinterpret_cast(obj); + return new FallingTub(*ptr); + } + case Gadget::HandFan: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset GadgetUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Gadget::FallingTub: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Gadget::HandFan: { + auto ptr = reinterpret_cast(value); + return CreateHandFan(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline GadgetUnion::GadgetUnion(const GadgetUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Gadget::FallingTub: { + value = new FallingTub(*reinterpret_cast(u.value)); + break; + } + case Gadget::HandFan: { + value = new HandFanT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void GadgetUnion::Reset() { + switch (type) { + case Gadget::FallingTub: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Gadget::HandFan: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Gadget::NONE; +} + +inline const ::flatbuffers::TypeTable *CharacterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + AttackerTypeTable, + RapunzelTypeTable, + BookReaderTypeTable + }; + static const char * const names[] = { + "NONE", + "MuLan", + "Rapunzel", + "Belle", + "BookFan", + "Other", + "Unused" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 7, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *GadgetTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + FallingTubTypeTable, + HandFanTypeTable + }; + static const char * const names[] = { + "NONE", + "FallingTub", + "HandFan" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 3, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AttackerTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "sword_attack_damage" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RapunzelTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4 }; + static const char * const names[] = { + "hair_length" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *BookReaderTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4 }; + static const char * const names[] = { + "books_read" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *FallingTubTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4 }; + static const char * const names[] = { + "weight" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *HandFanTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "length" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MovieTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UTYPE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_UTYPE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + CharacterTypeTable + }; + static const char * const names[] = { + "main_character_type", + "main_character", + "characters_type", + "characters" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const Movie *GetMovie(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const Movie *GetSizePrefixedMovie(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Movie *GetMutableMovie(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline Movie *GetMutableSizePrefixedMovie(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MovieIdentifier() { + return "MOVI"; +} + +inline bool MovieBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MovieIdentifier()); +} + +inline bool SizePrefixedMovieBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MovieIdentifier(), true); +} + +inline bool VerifyMovieBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MovieIdentifier()); +} + +inline bool VerifySizePrefixedMovieBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MovieIdentifier()); +} + +inline void FinishMovieBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MovieIdentifier()); +} + +inline void FinishSizePrefixedMovieBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MovieIdentifier()); +} + +inline std::unique_ptr UnPackMovie( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMovie(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMovie( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMovie(buf)->UnPack(res)); +} + +#endif // FLATBUFFERS_GENERATED_UNIONVECTOR_H_ diff --git a/third_party/flatbuffers/tests/cpp17/stringify_util.h b/third_party/flatbuffers/tests/cpp17/stringify_util.h new file mode 100644 index 00000000000..e2e7e2230b6 --- /dev/null +++ b/third_party/flatbuffers/tests/cpp17/stringify_util.h @@ -0,0 +1,189 @@ +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This contains some utilities/examples for how to leverage the static reflec- +// tion features of tables and structs in the C++17 code generation to recur- +// sively produce a string representation of any Flatbuffer table or struct use +// compile-time iteration over the fields. Note that this code is completely +// generic in that it makes no reference to any particular Flatbuffer type. + +#include +#include +#include +#include +#include + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/util.h" + +namespace cpp17 { + +// User calls this; need to forward declare it since it is called recursively. +template +std::optional StringifyFlatbufferValue( + T &&val, const std::string &indent = ""); + +namespace detail { + +/******************************************************************************* +** Metaprogramming helpers for detecting Flatbuffers Tables, Structs, & Vectors. +*******************************************************************************/ +template +struct is_flatbuffers_table_or_struct : std::false_type {}; + +// We know it's a table or struct when it has a Traits subclass. +template +struct is_flatbuffers_table_or_struct> + : std::true_type {}; + +template +inline constexpr bool is_flatbuffers_table_or_struct_v = + is_flatbuffers_table_or_struct::value; + +template struct is_flatbuffers_vector : std::false_type {}; + +template +struct is_flatbuffers_vector> : std::true_type {}; + +template +inline constexpr bool is_flatbuffers_vector_v = is_flatbuffers_vector::value; + +/******************************************************************************* +** Compile-time Iteration & Recursive Stringification over Flatbuffers types. +*******************************************************************************/ +template +std::string AddStringifiedField(const FBS &fbs, const std::string &indent) { + auto value_string = + StringifyFlatbufferValue(fbs.template get_field(), indent); + if (!value_string) { return ""; } + return indent + FBS::Traits::field_names[Index] + " = " + *value_string + + "\n"; +} + +template +std::string StringifyTableOrStructImpl(const FBS &fbs, + const std::string &indent, + std::index_sequence) { + // This line is where the compile-time iteration happens! + return (AddStringifiedField(fbs, indent) + ...); +} + +template +std::string StringifyTableOrStruct(const FBS &fbs, const std::string &indent) { + (void)fbs; + (void)indent; + static constexpr size_t field_count = FBS::Traits::fields_number; + std::string out; + if constexpr (field_count > 0) { + out = std::string(FBS::Traits::fully_qualified_name) + "{\n" + + StringifyTableOrStructImpl(fbs, indent + " ", + std::make_index_sequence{}) + + indent + '}'; + } + return out; +} + +template +std::string StringifyVector(const flatbuffers::Vector &vec, + const std::string &indent) { + const auto prologue = indent + std::string(" "); + const auto epilogue = std::string(",\n"); + std::string text; + text += "[\n"; + for (auto it = vec.cbegin(), end = vec.cend(); it != end; ++it) { + text += prologue; + text += StringifyFlatbufferValue(*it).value_or("(field absent)"); + text += epilogue; + } + if (vec.cbegin() != vec.cend()) { + text.resize(text.size() - epilogue.size()); + } + text += '\n' + indent + ']'; + return text; +} + +template std::string StringifyArithmeticType(T val) { + return flatbuffers::NumToString(val); +} + +} // namespace detail + +/******************************************************************************* +** Take any flatbuffer type (table, struct, Vector, int...) and stringify it. +*******************************************************************************/ +template +std::optional StringifyFlatbufferValue(T &&val, + const std::string &indent) { + (void)indent; + constexpr bool is_pointer = std::is_pointer_v>; + if constexpr (is_pointer) { + if (val == nullptr) return std::nullopt; // Field is absent. + } + using decayed = + std::decay_t>>; + + // Is it a Flatbuffers Table or Struct? + if constexpr (detail::is_flatbuffers_table_or_struct_v) { + // We have a nested table or struct; use recursion! + if constexpr (is_pointer) + return detail::StringifyTableOrStruct(*val, indent); + else + return detail::StringifyTableOrStruct(val, indent); + } + + // Is it an 8-bit number? If so, print it like an int (not char). + else if constexpr (std::is_same_v || + std::is_same_v) { + return detail::StringifyArithmeticType(static_cast(val)); + } + + // Is it an enum? If so, print it like an int, since Flatbuffers doesn't yet + // have type-based reflection for enums, so we can't print the enum's name :( + else if constexpr (std::is_enum_v) { + return StringifyFlatbufferValue( + static_cast>(val), indent); + } + + // Is it an int, double, float, uint32_t, etc.? + else if constexpr (std::is_arithmetic_v) { + return detail::StringifyArithmeticType(val); + } + + // Is it a Flatbuffers string? + else if constexpr (std::is_same_v) { + return '"' + val->str() + '"'; + } + + // Is it a Flatbuffers Vector? + else if constexpr (detail::is_flatbuffers_vector_v) { + return detail::StringifyVector(*val, indent); + } + + // Is it a void pointer? + else if constexpr (std::is_same_v) { + // Can't format it. + return std::nullopt; + } + + else { + // Not sure how to format this type, whatever it is. + static_assert(sizeof(T) != sizeof(T), + "Do not know how to format this type T (the compiler error " + "should tell you nearby what T is)."); + } +} + +} // namespace cpp17 diff --git a/third_party/flatbuffers/tests/cpp17/test_cpp17.cpp b/third_party/flatbuffers/tests/cpp17/test_cpp17.cpp new file mode 100644 index 00000000000..6c1929120e3 --- /dev/null +++ b/third_party/flatbuffers/tests/cpp17/test_cpp17.cpp @@ -0,0 +1,277 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// This is a sandbox for modeling C++17 code generator. +// C++17 code generator: "flatc --cpp-std c++17". +// Warning: +// This is an experimental feature and could change at any time. + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/flex_flat_util.h" +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/idl.h" +#include "flatbuffers/minireflect.h" +#include "flatbuffers/registry.h" +#include "flatbuffers/util.h" +#include "stringify_util.h" +#include "test_assert.h" + +// Embed generated code into an isolated namespace. +namespace cpp17 { +#include "generated_cpp17/monster_test_generated.h" +#include "generated_cpp17/optional_scalars_generated.h" +#include "generated_cpp17/union_vector_generated.h" +} // namespace cpp17 + +namespace cpp11 { +#include "../monster_test_generated.h" +#include "../optional_scalars_generated.h" +} // namespace cpp11 + +using ::cpp17::MyGame::Example::Monster; +using ::cpp17::MyGame::Example::Vec3; + +/******************************************************************************* +** Build some FB objects. +*******************************************************************************/ +namespace { +const Monster *BuildMonster(flatbuffers::FlatBufferBuilder &fbb) { + using ::cpp17::MyGame::Example::Color; + using ::cpp17::MyGame::Example::MonsterBuilder; + using ::cpp17::MyGame::Example::Test; + auto name = fbb.CreateString("my_monster"); + auto inventory = fbb.CreateVector(std::vector{ 4, 5, 6, 7 }); + MonsterBuilder builder(fbb); + auto vec3 = Vec3{ /*x=*/1.1f, + /*y=*/2.2f, + /*z=*/3.3f, + /*test1=*/6.6, + /*test2=*/Color::Green, + /*test3=*/ + Test( + /*a=*/11, + /*b=*/90) }; + builder.add_pos(&vec3); + builder.add_name(name); + builder.add_mana(1); + builder.add_hp(2); + builder.add_testbool(true); + builder.add_testhashs32_fnv1(4); + builder.add_testhashu32_fnv1(5); + builder.add_testhashs64_fnv1(6); + builder.add_testhashu64_fnv1(7); + builder.add_testhashs32_fnv1a(8); + builder.add_testhashu32_fnv1a(9); + builder.add_testhashs64_fnv1a(10); + builder.add_testhashu64_fnv1a(11); + builder.add_testf(12.1f); + builder.add_testf2(13.1f); + builder.add_testf3(14.1f); + builder.add_single_weak_reference(15); + builder.add_co_owning_reference(16); + builder.add_non_owning_reference(17); + builder.add_inventory(inventory); + fbb.Finish(builder.Finish()); + const Monster *monster = + flatbuffers::GetRoot(fbb.GetBufferPointer()); + return monster; +} + +/******************************************************************************* +** Test Case: Static Field Reflection Traits for Table & Structs. +*******************************************************************************/ +// This test tests & demonstrates the power of the static reflection. Using it, +// we can given any Flatbuffer type to a generic function and it will be able to +// produce is full recursive string representation of it. +// +// This test covers all types: primitive types, structs, tables, Vectors, etc. +// +void StringifyAnyFlatbuffersTypeTest() { + flatbuffers::FlatBufferBuilder fbb; + // We are using a Monster here, but we could have used any type, because the + // code that follows is totally generic! + const auto *monster = BuildMonster(fbb); + + std::string expected = R"(MyGame.Example.Monster{ + pos = MyGame.Example.Vec3{ + x = 1.1 + y = 2.2 + z = 3.3 + test1 = 6.6 + test2 = 2 + test3 = MyGame.Example.Test{ + a = 11 + b = 90 + } + } + mana = 1 + hp = 2 + name = "my_monster" + inventory = [ + 4, + 5, + 6, + 7 + ] + color = 8 + test_type = 0 + testbool = 1 + testhashs32_fnv1 = 4 + testhashu32_fnv1 = 5 + testhashs64_fnv1 = 6 + testhashu64_fnv1 = 7 + testhashs32_fnv1a = 8 + testhashu32_fnv1a = 9 + testhashs64_fnv1a = 10 + testhashu64_fnv1a = 11 + testf = 12.1 + testf2 = 13.1 + testf3 = 14.1 + single_weak_reference = 15 + co_owning_reference = 16 + non_owning_reference = 17 + any_unique_type = 0 + any_ambiguous_type = 0 + signed_enum = -1 + long_enum_non_enum_default = 0 + long_enum_normal_default = 2 + nan_default = nan + inf_default = inf + positive_inf_default = inf + infinity_default = inf + positive_infinity_default = inf + negative_inf_default = -inf + negative_infinity_default = -inf + double_inf_default = inf + })"; + + // Call a generic function that has no specific knowledge of the flatbuffer we + // are passing in; it should use only static reflection to produce a string + // representations of the field names and values recursively. We give it an + // initial indentation so that the result can be compared with our raw string + // above, which we wanted to indent so that it will look nicer in this code. + // + // A note about JSON: as can be seen from the string above, this produces a + // JSON-like notation, but we are not using any of Flatbuffers' JSON infra to + // produce this! It is produced entirely using compile-time reflection, and + // thus does not require any runtime access to the *.fbs definition files! + std::optional result = + cpp17::StringifyFlatbufferValue(*monster, /*indent=*/" "); + + TEST_ASSERT(result.has_value()); + TEST_EQ_STR(expected.c_str(), result->c_str()); +} + +/******************************************************************************* +** Test Traits::FieldType +*******************************************************************************/ +using pos_type = Monster::Traits::FieldType<0>; +static_assert(std::is_same_v); + +using mana_type = Monster::Traits::FieldType<1>; +static_assert(std::is_same_v); + +using name_type = Monster::Traits::FieldType<3>; +static_assert(std::is_same_v); + +/******************************************************************************* +** Generic Create Function Test. +*******************************************************************************/ +void CreateTableByTypeTest() { + flatbuffers::FlatBufferBuilder builder; + + // We will create an object of this type using only the type. + using type_to_create_t = cpp17::MyGame::Example::Stat; + + [&builder] { + auto id_str = builder.CreateString("my_id"); + auto table = type_to_create_t::Traits::Create(builder, id_str, 42, 7); + // Be sure that the correct return type was inferred. + static_assert( + std::is_same_v>); + builder.Finish(table); + }(); + + // Access it. + auto stat = + flatbuffers::GetRoot(builder.GetBufferPointer()); + TEST_EQ_STR(stat->id()->c_str(), "my_id"); + TEST_EQ(stat->val(), 42); + TEST_EQ(stat->count(), 7); +} + +void OptionalScalarsTest() { + static_assert( + std::is_same, std::optional>::value); + static_assert(std::is_same::value); + + // test C++ nullable + flatbuffers::FlatBufferBuilder fbb; + FinishScalarStuffBuffer(fbb, cpp17::optional_scalars::CreateScalarStuff( + fbb, 1, static_cast(2))); + auto opts = + cpp17::optional_scalars::GetMutableScalarStuff(fbb.GetBufferPointer()); + TEST_ASSERT(!opts->maybe_bool()); + TEST_ASSERT(!opts->maybe_f32().has_value()); + TEST_ASSERT(opts->maybe_i8().has_value()); + TEST_EQ(opts->maybe_i8().value(), 2); + TEST_ASSERT(opts->mutate_maybe_i8(3)); + TEST_ASSERT(opts->maybe_i8().has_value()); + TEST_EQ(opts->maybe_i8().value(), 3); + TEST_ASSERT(!opts->mutate_maybe_i16(-10)); + + cpp17::optional_scalars::ScalarStuffT obj; + opts->UnPackTo(&obj); + TEST_ASSERT(!obj.maybe_bool); + TEST_ASSERT(!obj.maybe_f32.has_value()); + TEST_ASSERT(obj.maybe_i8.has_value() && obj.maybe_i8.value() == 3); + TEST_ASSERT(obj.maybe_i8 && *obj.maybe_i8 == 3); + obj.maybe_i32 = -1; + + fbb.Clear(); + FinishScalarStuffBuffer( + fbb, cpp17::optional_scalars::ScalarStuff::Pack(fbb, &obj)); + opts = cpp17::optional_scalars::GetMutableScalarStuff(fbb.GetBufferPointer()); + TEST_ASSERT(opts->maybe_i8().has_value()); + TEST_EQ(opts->maybe_i8().value(), 3); + TEST_ASSERT(opts->maybe_i32().has_value()); + TEST_EQ(opts->maybe_i32().value(), -1); + + TEST_EQ(std::optional(opts->maybe_i32()).value(), -1); + TEST_EQ(std::optional(opts->maybe_i32()).value(), -1); + TEST_ASSERT(opts->maybe_i32() == std::optional(-1)); +} + +int FlatBufferCpp17Tests() { + CreateTableByTypeTest(); + OptionalScalarsTest(); + StringifyAnyFlatbuffersTypeTest(); + return 0; +} +} // namespace + +int main(int /*argc*/, const char * /*argv*/[]) { + InitTestEngine(); + + FlatBufferCpp17Tests(); + + if (!testing_fails) { + TEST_OUTPUT_LINE("C++17: ALL TESTS PASSED"); + } else { + TEST_OUTPUT_LINE("C++17: %d FAILED TESTS", testing_fails); + } + return CloseTestEngine(); +} diff --git a/third_party/flatbuffers/tests/dictionary_lookup.fbs b/third_party/flatbuffers/tests/dictionary_lookup.fbs new file mode 100644 index 00000000000..45b9dce47a0 --- /dev/null +++ b/third_party/flatbuffers/tests/dictionary_lookup.fbs @@ -0,0 +1,11 @@ +namespace DictionaryLookup; + +table LongFloatEntry { + key: long (key); + value: float; +} + +table LongFloatMap { + entries: [LongFloatEntry]; +} +root_type LongFloatMap; diff --git a/third_party/flatbuffers/tests/docker/Dockerfile.testing.build_flatc_debian_stretch b/third_party/flatbuffers/tests/docker/Dockerfile.testing.build_flatc_debian_stretch new file mode 100644 index 00000000000..197a555743b --- /dev/null +++ b/third_party/flatbuffers/tests/docker/Dockerfile.testing.build_flatc_debian_stretch @@ -0,0 +1,9 @@ +FROM debian:9.6-slim as base +RUN apt -qq update >/dev/null +RUN apt -qq install -y cmake make build-essential >/dev/null +FROM base +WORKDIR /code +ADD . . +RUN cmake -G "Unix Makefiles" +RUN make flatc +RUN ls flatc diff --git a/third_party/flatbuffers/tests/docker/Dockerfile.testing.cpp.debian_buster b/third_party/flatbuffers/tests/docker/Dockerfile.testing.cpp.debian_buster new file mode 100644 index 00000000000..7b0cce2de2c --- /dev/null +++ b/third_party/flatbuffers/tests/docker/Dockerfile.testing.cpp.debian_buster @@ -0,0 +1,10 @@ +FROM debian:10.1-slim as base +RUN apt -qq update >/dev/null +RUN apt -qq install -y cmake make build-essential >/dev/null +RUN apt -qq install -y autoconf git libtool >/dev/null +RUN apt -qq install -y clang >/dev/null +FROM base +# Travis machines have 2 cores. Can be redefined with 'run --env PAR_JOBS=N'. +ENV JOBS=2 +WORKDIR /flatbuffers +ADD . . diff --git a/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.php.hhvm_2019_01_16 b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.php.hhvm_2019_01_16 new file mode 100644 index 00000000000..e5023fa1b30 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.php.hhvm_2019_01_16 @@ -0,0 +1,18 @@ +# This does not pass tests due to the following error: +# +# Fatal error: Uncaught exception 'InvalidArgumentException' with message 'Google\FlatBuffers\ByteBuffer::getX() expects parameter 1 by reference, but the call was not annotated with '&'. in /code/php/FlatbufferBuilder.php:971 +# Stack trace: +# #0 /code/tests/phpTest.php(277): Google\FlatBuffers\FlatbufferBuilder->sizedByteArray() +# #1 /code/tests/phpTest.php(79): fuzzTest1() +# #2 /code/tests/phpTest.php(86): main() +# #3 {main} +# thrown in in /code/php/FlatbufferBuilder.php:971 +FROM hhvm/hhvm:2019.01.16 as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN hhvm --version +RUN hhvm phpTest.php +RUN ../flatc --php -o php union_vector/union_vector.fbs +RUN hhvm phpUnionVectorTest.php diff --git a/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.cpython_with_conda b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.cpython_with_conda new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.cpython_with_numpy b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.cpython_with_numpy new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.pypy_6_0_0_py2 b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.pypy_6_0_0_py2 new file mode 100644 index 00000000000..849b92e8679 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.pypy_6_0_0_py2 @@ -0,0 +1,7 @@ +FROM pypy:2-6.0.0-slim as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN pypy --version +RUN ./PythonTest.sh diff --git a/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.pypy_6_0_0_py3 b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.pypy_6_0_0_py3 new file mode 100644 index 00000000000..2df6b2aa645 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/TODO.Dockerfile.testing.python.pypy_6_0_0_py3 @@ -0,0 +1,7 @@ +FROM pypy:3-6.0.0-slim as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN pypy --version +RUN ./PythonTest.sh diff --git a/third_party/flatbuffers/tests/docker/build_flatc.run.sh b/third_party/flatbuffers/tests/docker/build_flatc.run.sh new file mode 100755 index 00000000000..c00adf68daa --- /dev/null +++ b/third_party/flatbuffers/tests/docker/build_flatc.run.sh @@ -0,0 +1,15 @@ +set -e + +JOBS=${JOBS:-1} +config=$1 +echo "" +echo "Build 'flatc' compiler for '$config'" + +cmake . -DCMAKE_BUILD_TYPE=$config \ + -DFLATBUFFERS_BUILD_FLATC=1 -DFLATBUFFERS_STATIC_FLATC=1 \ + -DFLATBUFFERS_BUILD_TESTS=0 -DFLATBUFFERS_INSTALL=0 +cmake --build . --target flatc --clean-first -- -j$JOBS + +echo "Checking generated code" +scripts/check_generate_code.py +echo "Done" diff --git a/third_party/flatbuffers/tests/docker/cpp_test.run.sh b/third_party/flatbuffers/tests/docker/cpp_test.run.sh new file mode 100755 index 00000000000..370662ab406 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/cpp_test.run.sh @@ -0,0 +1,20 @@ +set -e + +JOBS=${JOBS:-1} +export UBSAN_OPTIONS=halt_on_error=1 +export ASAN_OPTIONS=halt_on_error=1 +export MAKEFLAGS="-j$JOBS" + +config=$1 +echo "" +echo "Build Flatbuffers project for '$config' with jobs=$JOBS" + +cmake . -DCMAKE_BUILD_TYPE=$config \ + -DFLATBUFFERS_BUILD_TESTS=ON -DFLATBUFFERS_CODE_SANITIZE=ON +cmake --build . --target all --clean-first -- -j$JOBS +ctest --extra-verbose --output-on-failure -j$JOBS + +echo "Checking generated code" +scripts/check_generate_code.py + +echo "C++ tests done" diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.csharp.mono_5_18 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.csharp.mono_5_18 new file mode 100644 index 00000000000..e6ba5504c09 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.csharp.mono_5_18 @@ -0,0 +1,8 @@ +FROM mono:5.18 as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN mono --version +WORKDIR /code/tests/FlatBuffers.Test +RUN sh NetTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.golang.1_11 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.golang.1_11 new file mode 100644 index 00000000000..81707ea5843 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.golang.1_11 @@ -0,0 +1,7 @@ +FROM golang:1.11-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN go version +RUN ./GoTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.java.openjdk_10_0_2 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.java.openjdk_10_0_2 new file mode 100644 index 00000000000..82c3adda3db --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.java.openjdk_10_0_2 @@ -0,0 +1,7 @@ +FROM openjdk:10.0.2-jdk-slim-sid as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN java -version +RUN ./JavaTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.java.openjdk_11_0_1 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.java.openjdk_11_0_1 new file mode 100644 index 00000000000..ac1c3cc9ce5 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.java.openjdk_11_0_1 @@ -0,0 +1,7 @@ +FROM openjdk:11.0.1-jdk-slim-sid as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN java -version +RUN ./JavaTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.node.12_20_1 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.node.12_20_1 new file mode 100644 index 00000000000..013661f5330 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.node.12_20_1 @@ -0,0 +1,6 @@ +FROM node:12.20.1-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +RUN npm install +RUN npm test diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.node.14_15_4 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.node.14_15_4 new file mode 100644 index 00000000000..fb546bcbc9e --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.node.14_15_4 @@ -0,0 +1,6 @@ +FROM node:14.15.4-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +RUN npm install +RUN npm test diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.php.zend_7_3 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.php.zend_7_3 new file mode 100644 index 00000000000..6cdf43c9cf7 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.php.zend_7_3 @@ -0,0 +1,8 @@ +FROM php:7.3-cli-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN php --version +RUN php phpTest.php +RUN sh phpUnionVectorTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.cpython_2_7_15 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.cpython_2_7_15 new file mode 100644 index 00000000000..e68303e39e9 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.cpython_2_7_15 @@ -0,0 +1,8 @@ +FROM python:2.7.15-slim-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN python --version +RUN pip install coverage +RUN ./PythonTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.cpython_3_7_1 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.cpython_3_7_1 new file mode 100644 index 00000000000..7c2f15c804d --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.cpython_3_7_1 @@ -0,0 +1,8 @@ +FROM python:3.7.1-slim-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN python --version +RUN pip install coverage +RUN ./PythonTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.numpy.cpython_2_7_15 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.numpy.cpython_2_7_15 new file mode 100644 index 00000000000..718c5ac5afe --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.numpy.cpython_2_7_15 @@ -0,0 +1,9 @@ +FROM python:2.7.15-slim-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN python --version +RUN pip install numpy +RUN pip install coverage +RUN ./PythonTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.numpy.cpython_3_7_1 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.numpy.cpython_3_7_1 new file mode 100644 index 00000000000..1de2c26809f --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.python.numpy.cpython_3_7_1 @@ -0,0 +1,9 @@ +FROM python:3.7.1-slim-stretch as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN python --version +RUN pip install numpy +RUN pip install coverage +RUN ./PythonTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.1_51_0 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.1_51_0 new file mode 100644 index 00000000000..38c1d26d07e --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.1_51_0 @@ -0,0 +1,7 @@ +FROM rust:1.51.0-slim as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN rustc --version +RUN ./RustTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_51_0 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_51_0 new file mode 100644 index 00000000000..aa35ed7b5a5 --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.big_endian.1_51_0 @@ -0,0 +1,15 @@ +FROM rust:1.51.0-slim as base +RUN apt -qq update -y && apt -qq install -y \ + gcc-mips-linux-gnu \ + libexpat1 \ + libmagic1 \ + libmpdec2 \ + libreadline7 \ + qemu-user +RUN rustup target add mips-unknown-linux-gnu +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN rustc --version +RUN ./RustTest.sh mips-unknown-linux-gnu diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.nightly b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.nightly new file mode 100644 index 00000000000..5194d6db85d --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.rust.nightly @@ -0,0 +1,8 @@ +FROM rustlang/rust:nightly-stretch-slim as base +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN rustc --version +RUN export RUST_NIGHTLY=1 +RUN ./RustTest.sh diff --git a/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.swift_5_2 b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.swift_5_2 new file mode 100644 index 00000000000..22995d247ba --- /dev/null +++ b/third_party/flatbuffers/tests/docker/languages/Dockerfile.testing.swift_5_2 @@ -0,0 +1,8 @@ +FROM swift:5.2 +WORKDIR /code +ADD . . +RUN cp flatc_debian_stretch flatc +WORKDIR /code/tests +RUN swift --version +WORKDIR /code/tests/swift/tests/ +RUN sh SwiftTest.sh diff --git a/third_party/flatbuffers/tests/evolution_test.cpp b/third_party/flatbuffers/tests/evolution_test.cpp new file mode 100644 index 00000000000..51c2e8131e2 --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test.cpp @@ -0,0 +1,190 @@ +#include "evolution_test.h" + +#include "evolution_test/evolution_v1_generated.h" +#include "evolution_test/evolution_v2_generated.h" +#include "flatbuffers/idl.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +void EvolutionTest(const std::string &tests_data_path) { + // VS10 does not support typed enums, exclude from tests +#if !defined(_MSC_VER) || _MSC_VER >= 1700 + const int NUM_VERSIONS = 2; + std::string schemas[NUM_VERSIONS]; + std::string jsonfiles[NUM_VERSIONS]; + std::vector binaries[NUM_VERSIONS]; + + flatbuffers::IDLOptions idl_opts; + idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kBinary; + flatbuffers::Parser parser(idl_opts); + + // Load all the schema versions and their associated data. + for (int i = 0; i < NUM_VERSIONS; ++i) { + std::string schema = tests_data_path + "evolution_test/evolution_v" + + flatbuffers::NumToString(i + 1) + ".fbs"; + TEST_ASSERT(flatbuffers::LoadFile(schema.c_str(), false, &schemas[i])); + std::string json = tests_data_path + "evolution_test/evolution_v" + + flatbuffers::NumToString(i + 1) + ".json"; + TEST_ASSERT(flatbuffers::LoadFile(json.c_str(), false, &jsonfiles[i])); + + TEST_ASSERT(parser.Parse(schemas[i].c_str())); + TEST_ASSERT(parser.Parse(jsonfiles[i].c_str())); + + auto bufLen = parser.builder_.GetSize(); + auto buf = parser.builder_.GetBufferPointer(); + binaries[i].reserve(bufLen); + std::copy(buf, buf + bufLen, std::back_inserter(binaries[i])); + } + + // Assert that all the verifiers for the different schema versions properly + // verify any version data. + for (int i = 0; i < NUM_VERSIONS; ++i) { + flatbuffers::Verifier verifier(&binaries[i].front(), binaries[i].size()); + TEST_ASSERT(Evolution::V1::VerifyRootBuffer(verifier)); + TEST_ASSERT(Evolution::V2::VerifyRootBuffer(verifier)); + } + + // Test backwards compatibility by reading old data with an evolved schema. + auto root_v1_viewed_from_v2 = Evolution::V2::GetRoot(&binaries[0].front()); + // field 'k' is new in version 2, so it should be null. + TEST_ASSERT(nullptr == root_v1_viewed_from_v2->k()); + // field 'l' is new in version 2 with a default of 56. + TEST_EQ(root_v1_viewed_from_v2->l(), 56); + // field 'c' of 'TableA' is new in version 2, so it should be null. + TEST_ASSERT(nullptr == root_v1_viewed_from_v2->e()->c()); + // 'TableC' was added to field 'c' union in version 2, so it should be null. + TEST_ASSERT(nullptr == root_v1_viewed_from_v2->c_as_TableC()); + // The field 'c' union should be of type 'TableB' regardless of schema version + TEST_ASSERT(root_v1_viewed_from_v2->c_type() == Evolution::V2::Union::TableB); + // The field 'f' was renamed to 'ff' in version 2, it should still be + // readable. + TEST_EQ(root_v1_viewed_from_v2->ff()->a(), 16); + + // Test forwards compatibility by reading new data with an old schema. + auto root_v2_viewed_from_v1 = Evolution::V1::GetRoot(&binaries[1].front()); + // The field 'c' union in version 2 is a new table (index = 3) and should + // still be accessible, but not interpretable. + TEST_EQ(static_cast(root_v2_viewed_from_v1->c_type()), 3); + TEST_NOTNULL(root_v2_viewed_from_v1->c()); + // The field 'd' enum in verison 2 has new members and should still be + // accessible, but not interpretable. + TEST_EQ(static_cast(root_v2_viewed_from_v1->d()), 3); + // The field 'a' in version 2 is deprecated and should return the default + // value (0) instead of the value stored in the in the buffer (42). + TEST_EQ(root_v2_viewed_from_v1->a(), 0); + // The field 'ff' was originally named 'f' in version 1, it should still be + // readable. + TEST_EQ(root_v2_viewed_from_v1->f()->a(), 35); +#endif +} + +void ConformTest() { + const char ref[] = "table T { A:int; } enum E:byte { A }"; + + auto test_conform = [](const char *ref, const char *test, + const char *expected_err) { + flatbuffers::Parser parser1; + TEST_EQ(parser1.Parse(ref), true); + flatbuffers::Parser parser2; + TEST_EQ(parser2.Parse(test), true); + auto err = parser2.ConformTo(parser1); + if (*expected_err == '\0') { + TEST_EQ_STR(err.c_str(), expected_err); + } else { + TEST_NOTNULL(strstr(err.c_str(), expected_err)); + } + }; + + test_conform(ref, "table T { A:byte; }", "types differ for field: T.A"); + test_conform(ref, "table T { B:int; A:int; }", + "offsets differ for field: T.A"); + test_conform(ref, "table T { A:int = 1; }", "defaults differ for field: T.A"); + test_conform(ref, "table T { B:float; }", + "field renamed to different type: T.B (renamed from T.A)"); + test_conform(ref, "enum E:byte { B, A }", "values differ for enum: A"); + test_conform(ref, "table T { }", "field deleted: T.A"); + test_conform(ref, "table T { B:int; }", ""); // renaming a field is allowed + + const char ref2[] = "enum E:byte { A } table T2 { f:E; } "; + test_conform(ref2, "enum E:int32 { A } table T2 { df:byte; f:E; }", + "field renamed to different type: T2.df (renamed from T2.f)"); + + // Check enum underlying type changes. + test_conform("enum E:int32 {A}", "enum E: byte {A}", "underlying type differ for enum: E"); + + // Check union underlying type changes. + const char ref3[] = "table A {} table B {} union C {A, B}"; + test_conform(ref3, "table A {} table B {} union C:int32 {A, B}", "underlying type differ for union: C"); + + // Check conformity for Offset64-related changes. + { + const char ref[] = "table T { a:[uint8]; b:string; }"; + + // Adding a 'vector64' changes the type. + test_conform(ref, "table T { a:[uint8] (vector64); b:string; }", + "types differ for field: T.a"); + + // Adding a 'offset64' to the vector changes the type. + test_conform(ref, "table T { a:[uint8] (offset64); b:string; }", + "offset types differ for field: T.a"); + + // Adding a 'offset64' to the string also changes the type. + test_conform(ref, "table T { a:[uint8]; b:string (offset64); }", + "offset types differ for field: T.b"); + + // Now try the opposite direction of removing an attribute from an existing + // field. + + // Removing a 'vector64' changes the type. + test_conform("table T { a:[uint8] (vector64); b:string; }", ref, + "types differ for field: T.a"); + + // Removing a 'offset64' to the string also changes the type. + test_conform("table T { a:[uint8] (offset64); b:string; }", ref, + "offset types differ for field: T.a"); + + // Remove a 'offset64' to the string also changes the type. + test_conform("table T { a:[uint8]; b:string (offset64); }", ref, + "offset types differ for field: T.b"); + } +} + +void UnionDeprecationTest(const std::string &tests_data_path) { + const int NUM_VERSIONS = 2; + std::string schemas[NUM_VERSIONS]; + std::string jsonfiles[NUM_VERSIONS]; + std::vector binaries[NUM_VERSIONS]; + + flatbuffers::IDLOptions idl_opts; + idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kBinary; + flatbuffers::Parser parser(idl_opts); + + // Load all the schema versions and their associated data. + for (int i = 0; i < NUM_VERSIONS; ++i) { + std::string schema = tests_data_path + "evolution_test/evolution_v" + + flatbuffers::NumToString(i + 1) + ".fbs"; + TEST_ASSERT(flatbuffers::LoadFile(schema.c_str(), false, &schemas[i])); + std::string json = tests_data_path + "evolution_test/evolution_v" + + flatbuffers::NumToString(i + 1) + ".json"; + TEST_ASSERT(flatbuffers::LoadFile(json.c_str(), false, &jsonfiles[i])); + + TEST_ASSERT(parser.Parse(schemas[i].c_str())); + TEST_ASSERT(parser.Parse(jsonfiles[i].c_str())); + + auto bufLen = parser.builder_.GetSize(); + auto buf = parser.builder_.GetBufferPointer(); + binaries[i].reserve(bufLen); + std::copy(buf, buf + bufLen, std::back_inserter(binaries[i])); + } + + auto v2 = parser.LookupStruct("Evolution.V2.Root"); + TEST_NOTNULL(v2); + auto j_type_field = v2->fields.Lookup("j_type"); + TEST_NOTNULL(j_type_field); + TEST_ASSERT(j_type_field->deprecated); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/evolution_test.h b/third_party/flatbuffers/tests/evolution_test.h new file mode 100644 index 00000000000..3933c3b2e36 --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test.h @@ -0,0 +1,16 @@ +#ifndef TESTS_EVOLUTION_TEST_H +#define TESTS_EVOLUTION_TEST_H + +#include + +namespace flatbuffers { +namespace tests { + +void EvolutionTest(const std::string &tests_data_path); +void ConformTest(); +void UnionDeprecationTest(const std::string &tests_data_path); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/evolution_test/evolution_v1.fbs b/third_party/flatbuffers/tests/evolution_test/evolution_v1.fbs new file mode 100644 index 00000000000..e9d3b8d86d4 --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test/evolution_v1.fbs @@ -0,0 +1,40 @@ +namespace Evolution.V1; + +table TableA { + a:float; + b:int; +} + +table TableB { + a:int; +} + +enum Enum : byte { + King, + Queen +} + +union Union { + TableA, + TableB +} + +struct Struct { + a:int; + b:double; +} + +table Root { + a:int; + b:bool; + c:Union; + d:Enum; + e:TableA; + f:Struct; + g:[int]; + h:[TableB]; + i:int = 1234; + j:Union; +} + +root_type Root; diff --git a/third_party/flatbuffers/tests/evolution_test/evolution_v1.json b/third_party/flatbuffers/tests/evolution_test/evolution_v1.json new file mode 100644 index 00000000000..c90fdb9c543 --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test/evolution_v1.json @@ -0,0 +1,29 @@ +{ + "a": 42, + "b": true, + "c_type": "TableB", + "c": { + "a": 15 + }, + "d": "King", + "e": { + "a": 3.1452, + "b": 325 + }, + "f":{ + "a": 16, + "b": 243.980943 + }, + "g": [ 7, 8, 9], + "h": [ + { + "a": 212 + }, + { + "a": 459 + } + ], + "j": { + "a": 984 + } +} diff --git a/third_party/flatbuffers/tests/evolution_test/evolution_v1_generated.h b/third_party/flatbuffers/tests/evolution_test/evolution_v1_generated.h new file mode 100644 index 00000000000..59c627a5db7 --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test/evolution_v1_generated.h @@ -0,0 +1,520 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_EVOLUTIONV1_EVOLUTION_V1_H_ +#define FLATBUFFERS_GENERATED_EVOLUTIONV1_EVOLUTION_V1_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace Evolution { +namespace V1 { + +struct TableA; +struct TableABuilder; + +struct TableB; +struct TableBBuilder; + +struct Struct; + +struct Root; +struct RootBuilder; + +enum class Enum : int8_t { + King = 0, + Queen = 1, + MIN = King, + MAX = Queen +}; + +inline const Enum (&EnumValuesEnum())[2] { + static const Enum values[] = { + Enum::King, + Enum::Queen + }; + return values; +} + +inline const char * const *EnumNamesEnum() { + static const char * const names[3] = { + "King", + "Queen", + nullptr + }; + return names; +} + +inline const char *EnumNameEnum(Enum e) { + if (::flatbuffers::IsOutRange(e, Enum::King, Enum::Queen)) return ""; + const size_t index = static_cast(e); + return EnumNamesEnum()[index]; +} + +enum class Union : uint8_t { + NONE = 0, + TableA = 1, + TableB = 2, + MIN = NONE, + MAX = TableB +}; + +inline const Union (&EnumValuesUnion())[3] { + static const Union values[] = { + Union::NONE, + Union::TableA, + Union::TableB + }; + return values; +} + +inline const char * const *EnumNamesUnion() { + static const char * const names[4] = { + "NONE", + "TableA", + "TableB", + nullptr + }; + return names; +} + +inline const char *EnumNameUnion(Union e) { + if (::flatbuffers::IsOutRange(e, Union::NONE, Union::TableB)) return ""; + const size_t index = static_cast(e); + return EnumNamesUnion()[index]; +} + +template struct UnionTraits { + static const Union enum_value = Union::NONE; +}; + +template<> struct UnionTraits { + static const Union enum_value = Union::TableA; +}; + +template<> struct UnionTraits { + static const Union enum_value = Union::TableB; +}; + +bool VerifyUnion(::flatbuffers::Verifier &verifier, const void *obj, Union type); +bool VerifyUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Struct FLATBUFFERS_FINAL_CLASS { + private: + int32_t a_; + int32_t padding0__; + double b_; + + public: + Struct() + : a_(0), + padding0__(0), + b_(0) { + (void)padding0__; + } + Struct(int32_t _a, double _b) + : a_(::flatbuffers::EndianScalar(_a)), + padding0__(0), + b_(::flatbuffers::EndianScalar(_b)) { + (void)padding0__; + } + int32_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + double b() const { + return ::flatbuffers::EndianScalar(b_); + } +}; +FLATBUFFERS_STRUCT_END(Struct, 16); + +inline bool operator==(const Struct &lhs, const Struct &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Struct &lhs, const Struct &rhs) { + return !(lhs == rhs); +} + + +struct TableA FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableABuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6 + }; + float a() const { + return GetField(VT_A, 0.0f); + } + int32_t b() const { + return GetField(VT_B, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + VerifyField(verifier, VT_B, 4) && + verifier.EndTable(); + } +}; + +struct TableABuilder { + typedef TableA Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(float a) { + fbb_.AddElement(TableA::VT_A, a, 0.0f); + } + void add_b(int32_t b) { + fbb_.AddElement(TableA::VT_B, b, 0); + } + explicit TableABuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableA( + ::flatbuffers::FlatBufferBuilder &_fbb, + float a = 0.0f, + int32_t b = 0) { + TableABuilder builder_(_fbb); + builder_.add_b(b); + builder_.add_a(a); + return builder_.Finish(); +} + +struct TableB FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableBBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4 + }; + int32_t a() const { + return GetField(VT_A, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + verifier.EndTable(); + } +}; + +struct TableBBuilder { + typedef TableB Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(int32_t a) { + fbb_.AddElement(TableB::VT_A, a, 0); + } + explicit TableBBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableB( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0) { + TableBBuilder builder_(_fbb); + builder_.add_a(a); + return builder_.Finish(); +} + +struct Root FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RootBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6, + VT_C_TYPE = 8, + VT_C = 10, + VT_D = 12, + VT_E = 14, + VT_F = 16, + VT_G = 18, + VT_H = 20, + VT_I = 22, + VT_J_TYPE = 24, + VT_J = 26 + }; + int32_t a() const { + return GetField(VT_A, 0); + } + bool b() const { + return GetField(VT_B, 0) != 0; + } + Evolution::V1::Union c_type() const { + return static_cast(GetField(VT_C_TYPE, 0)); + } + const void *c() const { + return GetPointer(VT_C); + } + template const T *c_as() const; + const Evolution::V1::TableA *c_as_TableA() const { + return c_type() == Evolution::V1::Union::TableA ? static_cast(c()) : nullptr; + } + const Evolution::V1::TableB *c_as_TableB() const { + return c_type() == Evolution::V1::Union::TableB ? static_cast(c()) : nullptr; + } + Evolution::V1::Enum d() const { + return static_cast(GetField(VT_D, 0)); + } + const Evolution::V1::TableA *e() const { + return GetPointer(VT_E); + } + const Evolution::V1::Struct *f() const { + return GetStruct(VT_F); + } + const ::flatbuffers::Vector *g() const { + return GetPointer *>(VT_G); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *h() const { + return GetPointer> *>(VT_H); + } + int32_t i() const { + return GetField(VT_I, 1234); + } + Evolution::V1::Union j_type() const { + return static_cast(GetField(VT_J_TYPE, 0)); + } + const void *j() const { + return GetPointer(VT_J); + } + template const T *j_as() const; + const Evolution::V1::TableA *j_as_TableA() const { + return j_type() == Evolution::V1::Union::TableA ? static_cast(j()) : nullptr; + } + const Evolution::V1::TableB *j_as_TableB() const { + return j_type() == Evolution::V1::Union::TableB ? static_cast(j()) : nullptr; + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + VerifyField(verifier, VT_B, 1) && + VerifyField(verifier, VT_C_TYPE, 1) && + VerifyOffset(verifier, VT_C) && + VerifyUnion(verifier, c(), c_type()) && + VerifyField(verifier, VT_D, 1) && + VerifyOffset(verifier, VT_E) && + verifier.VerifyTable(e()) && + VerifyField(verifier, VT_F, 8) && + VerifyOffset(verifier, VT_G) && + verifier.VerifyVector(g()) && + VerifyOffset(verifier, VT_H) && + verifier.VerifyVector(h()) && + verifier.VerifyVectorOfTables(h()) && + VerifyField(verifier, VT_I, 4) && + VerifyField(verifier, VT_J_TYPE, 1) && + VerifyOffset(verifier, VT_J) && + VerifyUnion(verifier, j(), j_type()) && + verifier.EndTable(); + } +}; + +template<> inline const Evolution::V1::TableA *Root::c_as() const { + return c_as_TableA(); +} + +template<> inline const Evolution::V1::TableB *Root::c_as() const { + return c_as_TableB(); +} + +template<> inline const Evolution::V1::TableA *Root::j_as() const { + return j_as_TableA(); +} + +template<> inline const Evolution::V1::TableB *Root::j_as() const { + return j_as_TableB(); +} + +struct RootBuilder { + typedef Root Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(int32_t a) { + fbb_.AddElement(Root::VT_A, a, 0); + } + void add_b(bool b) { + fbb_.AddElement(Root::VT_B, static_cast(b), 0); + } + void add_c_type(Evolution::V1::Union c_type) { + fbb_.AddElement(Root::VT_C_TYPE, static_cast(c_type), 0); + } + void add_c(::flatbuffers::Offset c) { + fbb_.AddOffset(Root::VT_C, c); + } + void add_d(Evolution::V1::Enum d) { + fbb_.AddElement(Root::VT_D, static_cast(d), 0); + } + void add_e(::flatbuffers::Offset e) { + fbb_.AddOffset(Root::VT_E, e); + } + void add_f(const Evolution::V1::Struct *f) { + fbb_.AddStruct(Root::VT_F, f); + } + void add_g(::flatbuffers::Offset<::flatbuffers::Vector> g) { + fbb_.AddOffset(Root::VT_G, g); + } + void add_h(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> h) { + fbb_.AddOffset(Root::VT_H, h); + } + void add_i(int32_t i) { + fbb_.AddElement(Root::VT_I, i, 1234); + } + void add_j_type(Evolution::V1::Union j_type) { + fbb_.AddElement(Root::VT_J_TYPE, static_cast(j_type), 0); + } + void add_j(::flatbuffers::Offset j) { + fbb_.AddOffset(Root::VT_J, j); + } + explicit RootBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRoot( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0, + bool b = false, + Evolution::V1::Union c_type = Evolution::V1::Union::NONE, + ::flatbuffers::Offset c = 0, + Evolution::V1::Enum d = Evolution::V1::Enum::King, + ::flatbuffers::Offset e = 0, + const Evolution::V1::Struct *f = nullptr, + ::flatbuffers::Offset<::flatbuffers::Vector> g = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> h = 0, + int32_t i = 1234, + Evolution::V1::Union j_type = Evolution::V1::Union::NONE, + ::flatbuffers::Offset j = 0) { + RootBuilder builder_(_fbb); + builder_.add_j(j); + builder_.add_i(i); + builder_.add_h(h); + builder_.add_g(g); + builder_.add_f(f); + builder_.add_e(e); + builder_.add_c(c); + builder_.add_a(a); + builder_.add_j_type(j_type); + builder_.add_d(d); + builder_.add_c_type(c_type); + builder_.add_b(b); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateRootDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0, + bool b = false, + Evolution::V1::Union c_type = Evolution::V1::Union::NONE, + ::flatbuffers::Offset c = 0, + Evolution::V1::Enum d = Evolution::V1::Enum::King, + ::flatbuffers::Offset e = 0, + const Evolution::V1::Struct *f = nullptr, + const std::vector *g = nullptr, + const std::vector<::flatbuffers::Offset> *h = nullptr, + int32_t i = 1234, + Evolution::V1::Union j_type = Evolution::V1::Union::NONE, + ::flatbuffers::Offset j = 0) { + auto g__ = g ? _fbb.CreateVector(*g) : 0; + auto h__ = h ? _fbb.CreateVector<::flatbuffers::Offset>(*h) : 0; + return Evolution::V1::CreateRoot( + _fbb, + a, + b, + c_type, + c, + d, + e, + f, + g__, + h__, + i, + j_type, + j); +} + +inline bool VerifyUnion(::flatbuffers::Verifier &verifier, const void *obj, Union type) { + switch (type) { + case Union::NONE: { + return true; + } + case Union::TableA: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Union::TableB: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyUnion( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline const Evolution::V1::Root *GetRoot(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const Evolution::V1::Root *GetSizePrefixedRoot(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline bool VerifyRootBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedRootBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishRootBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedRootBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +} // namespace V1 +} // namespace Evolution + +#endif // FLATBUFFERS_GENERATED_EVOLUTIONV1_EVOLUTION_V1_H_ diff --git a/third_party/flatbuffers/tests/evolution_test/evolution_v2.fbs b/third_party/flatbuffers/tests/evolution_test/evolution_v2.fbs new file mode 100644 index 00000000000..c7e1ef993ce --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test/evolution_v2.fbs @@ -0,0 +1,51 @@ +namespace Evolution.V2; + +table TableA { + b:int (id: 1); // swapped with 'a' + a:float (id: 0); // swapped with 'b' + c:string (id: 2); // new in v2 +} + +table TableB { + a:int; +} + +table TableC { // new in v2 + a:double; + b:string; +} + +enum Enum : byte { + King, + Queen, + Rook, // new in v2 + Bishop // new in v2 +} + +union Union { + TableA, + TableB, + TableC +} + +struct Struct { + a:int; + b:double; +} + +table Root { + a:int (deprecated); // deprecated in v2 + b:bool; + c:Union; + d:Enum; + e:TableA; + ff:Struct; // renamed from 'f' in v1 + g:[int]; + h:[TableB]; + i:uint = 1234; + j:Union (deprecated); // deprecated in v2 + k:TableC; // new in v2 + l:uint8 = 56; // new in v2 +} + +root_type Root; diff --git a/third_party/flatbuffers/tests/evolution_test/evolution_v2.json b/third_party/flatbuffers/tests/evolution_test/evolution_v2.json new file mode 100644 index 00000000000..b170eb24306 --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test/evolution_v2.json @@ -0,0 +1,34 @@ +{ + "b": false, + "c_type": "TableC", + "c": { + "a": 984.2494 + }, + "d": "Bishop", + "e": { + "a": 3.1452, + "b": 435, + "c": "yummy yummy fig bar bar" + }, + "ff":{ + "a": 35, + "b": 243.980943 + }, + "g": [ 7, 8, 10], + "h": [ + { + "a": 212 + }, + { + "a": 459 + }, + { + "a": 333 + } + ], + "i": 4321, + "k": { + "a": 9874.342, + "b": "more please" + } +} diff --git a/third_party/flatbuffers/tests/evolution_test/evolution_v2_generated.h b/third_party/flatbuffers/tests/evolution_test/evolution_v2_generated.h new file mode 100644 index 00000000000..ab60649ceef --- /dev/null +++ b/third_party/flatbuffers/tests/evolution_test/evolution_v2_generated.h @@ -0,0 +1,607 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_EVOLUTIONV2_EVOLUTION_V2_H_ +#define FLATBUFFERS_GENERATED_EVOLUTIONV2_EVOLUTION_V2_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace Evolution { +namespace V2 { + +struct TableA; +struct TableABuilder; + +struct TableB; +struct TableBBuilder; + +struct TableC; +struct TableCBuilder; + +struct Struct; + +struct Root; +struct RootBuilder; + +enum class Enum : int8_t { + King = 0, + Queen = 1, + Rook = 2, + Bishop = 3, + MIN = King, + MAX = Bishop +}; + +inline const Enum (&EnumValuesEnum())[4] { + static const Enum values[] = { + Enum::King, + Enum::Queen, + Enum::Rook, + Enum::Bishop + }; + return values; +} + +inline const char * const *EnumNamesEnum() { + static const char * const names[5] = { + "King", + "Queen", + "Rook", + "Bishop", + nullptr + }; + return names; +} + +inline const char *EnumNameEnum(Enum e) { + if (::flatbuffers::IsOutRange(e, Enum::King, Enum::Bishop)) return ""; + const size_t index = static_cast(e); + return EnumNamesEnum()[index]; +} + +enum class Union : uint8_t { + NONE = 0, + TableA = 1, + TableB = 2, + TableC = 3, + MIN = NONE, + MAX = TableC +}; + +inline const Union (&EnumValuesUnion())[4] { + static const Union values[] = { + Union::NONE, + Union::TableA, + Union::TableB, + Union::TableC + }; + return values; +} + +inline const char * const *EnumNamesUnion() { + static const char * const names[5] = { + "NONE", + "TableA", + "TableB", + "TableC", + nullptr + }; + return names; +} + +inline const char *EnumNameUnion(Union e) { + if (::flatbuffers::IsOutRange(e, Union::NONE, Union::TableC)) return ""; + const size_t index = static_cast(e); + return EnumNamesUnion()[index]; +} + +template struct UnionTraits { + static const Union enum_value = Union::NONE; +}; + +template<> struct UnionTraits { + static const Union enum_value = Union::TableA; +}; + +template<> struct UnionTraits { + static const Union enum_value = Union::TableB; +}; + +template<> struct UnionTraits { + static const Union enum_value = Union::TableC; +}; + +bool VerifyUnion(::flatbuffers::Verifier &verifier, const void *obj, Union type); +bool VerifyUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Struct FLATBUFFERS_FINAL_CLASS { + private: + int32_t a_; + int32_t padding0__; + double b_; + + public: + Struct() + : a_(0), + padding0__(0), + b_(0) { + (void)padding0__; + } + Struct(int32_t _a, double _b) + : a_(::flatbuffers::EndianScalar(_a)), + padding0__(0), + b_(::flatbuffers::EndianScalar(_b)) { + (void)padding0__; + } + int32_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + double b() const { + return ::flatbuffers::EndianScalar(b_); + } +}; +FLATBUFFERS_STRUCT_END(Struct, 16); + +inline bool operator==(const Struct &lhs, const Struct &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Struct &lhs, const Struct &rhs) { + return !(lhs == rhs); +} + + +struct TableA FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableABuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6, + VT_C = 8 + }; + float a() const { + return GetField(VT_A, 0.0f); + } + int32_t b() const { + return GetField(VT_B, 0); + } + const ::flatbuffers::String *c() const { + return GetPointer(VT_C); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + VerifyField(verifier, VT_B, 4) && + VerifyOffset(verifier, VT_C) && + verifier.VerifyString(c()) && + verifier.EndTable(); + } +}; + +struct TableABuilder { + typedef TableA Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(float a) { + fbb_.AddElement(TableA::VT_A, a, 0.0f); + } + void add_b(int32_t b) { + fbb_.AddElement(TableA::VT_B, b, 0); + } + void add_c(::flatbuffers::Offset<::flatbuffers::String> c) { + fbb_.AddOffset(TableA::VT_C, c); + } + explicit TableABuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableA( + ::flatbuffers::FlatBufferBuilder &_fbb, + float a = 0.0f, + int32_t b = 0, + ::flatbuffers::Offset<::flatbuffers::String> c = 0) { + TableABuilder builder_(_fbb); + builder_.add_c(c); + builder_.add_b(b); + builder_.add_a(a); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTableADirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + float a = 0.0f, + int32_t b = 0, + const char *c = nullptr) { + auto c__ = c ? _fbb.CreateString(c) : 0; + return Evolution::V2::CreateTableA( + _fbb, + a, + b, + c__); +} + +struct TableB FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableBBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4 + }; + int32_t a() const { + return GetField(VT_A, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + verifier.EndTable(); + } +}; + +struct TableBBuilder { + typedef TableB Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(int32_t a) { + fbb_.AddElement(TableB::VT_A, a, 0); + } + explicit TableBBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableB( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0) { + TableBBuilder builder_(_fbb); + builder_.add_a(a); + return builder_.Finish(); +} + +struct TableC FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableCBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6 + }; + double a() const { + return GetField(VT_A, 0.0); + } + const ::flatbuffers::String *b() const { + return GetPointer(VT_B); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 8) && + VerifyOffset(verifier, VT_B) && + verifier.VerifyString(b()) && + verifier.EndTable(); + } +}; + +struct TableCBuilder { + typedef TableC Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(double a) { + fbb_.AddElement(TableC::VT_A, a, 0.0); + } + void add_b(::flatbuffers::Offset<::flatbuffers::String> b) { + fbb_.AddOffset(TableC::VT_B, b); + } + explicit TableCBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableC( + ::flatbuffers::FlatBufferBuilder &_fbb, + double a = 0.0, + ::flatbuffers::Offset<::flatbuffers::String> b = 0) { + TableCBuilder builder_(_fbb); + builder_.add_a(a); + builder_.add_b(b); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTableCDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + double a = 0.0, + const char *b = nullptr) { + auto b__ = b ? _fbb.CreateString(b) : 0; + return Evolution::V2::CreateTableC( + _fbb, + a, + b__); +} + +struct Root FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef RootBuilder Builder; + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_B = 6, + VT_C_TYPE = 8, + VT_C = 10, + VT_D = 12, + VT_E = 14, + VT_FF = 16, + VT_G = 18, + VT_H = 20, + VT_I = 22, + VT_K = 28, + VT_L = 30 + }; + bool b() const { + return GetField(VT_B, 0) != 0; + } + Evolution::V2::Union c_type() const { + return static_cast(GetField(VT_C_TYPE, 0)); + } + const void *c() const { + return GetPointer(VT_C); + } + template const T *c_as() const; + const Evolution::V2::TableA *c_as_TableA() const { + return c_type() == Evolution::V2::Union::TableA ? static_cast(c()) : nullptr; + } + const Evolution::V2::TableB *c_as_TableB() const { + return c_type() == Evolution::V2::Union::TableB ? static_cast(c()) : nullptr; + } + const Evolution::V2::TableC *c_as_TableC() const { + return c_type() == Evolution::V2::Union::TableC ? static_cast(c()) : nullptr; + } + Evolution::V2::Enum d() const { + return static_cast(GetField(VT_D, 0)); + } + const Evolution::V2::TableA *e() const { + return GetPointer(VT_E); + } + const Evolution::V2::Struct *ff() const { + return GetStruct(VT_FF); + } + const ::flatbuffers::Vector *g() const { + return GetPointer *>(VT_G); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *h() const { + return GetPointer> *>(VT_H); + } + uint32_t i() const { + return GetField(VT_I, 1234); + } + const Evolution::V2::TableC *k() const { + return GetPointer(VT_K); + } + uint8_t l() const { + return GetField(VT_L, 56); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_B, 1) && + VerifyField(verifier, VT_C_TYPE, 1) && + VerifyOffset(verifier, VT_C) && + VerifyUnion(verifier, c(), c_type()) && + VerifyField(verifier, VT_D, 1) && + VerifyOffset(verifier, VT_E) && + verifier.VerifyTable(e()) && + VerifyField(verifier, VT_FF, 8) && + VerifyOffset(verifier, VT_G) && + verifier.VerifyVector(g()) && + VerifyOffset(verifier, VT_H) && + verifier.VerifyVector(h()) && + verifier.VerifyVectorOfTables(h()) && + VerifyField(verifier, VT_I, 4) && + VerifyOffset(verifier, VT_K) && + verifier.VerifyTable(k()) && + VerifyField(verifier, VT_L, 1) && + verifier.EndTable(); + } +}; + +template<> inline const Evolution::V2::TableA *Root::c_as() const { + return c_as_TableA(); +} + +template<> inline const Evolution::V2::TableB *Root::c_as() const { + return c_as_TableB(); +} + +template<> inline const Evolution::V2::TableC *Root::c_as() const { + return c_as_TableC(); +} + +struct RootBuilder { + typedef Root Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_b(bool b) { + fbb_.AddElement(Root::VT_B, static_cast(b), 0); + } + void add_c_type(Evolution::V2::Union c_type) { + fbb_.AddElement(Root::VT_C_TYPE, static_cast(c_type), 0); + } + void add_c(::flatbuffers::Offset c) { + fbb_.AddOffset(Root::VT_C, c); + } + void add_d(Evolution::V2::Enum d) { + fbb_.AddElement(Root::VT_D, static_cast(d), 0); + } + void add_e(::flatbuffers::Offset e) { + fbb_.AddOffset(Root::VT_E, e); + } + void add_ff(const Evolution::V2::Struct *ff) { + fbb_.AddStruct(Root::VT_FF, ff); + } + void add_g(::flatbuffers::Offset<::flatbuffers::Vector> g) { + fbb_.AddOffset(Root::VT_G, g); + } + void add_h(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> h) { + fbb_.AddOffset(Root::VT_H, h); + } + void add_i(uint32_t i) { + fbb_.AddElement(Root::VT_I, i, 1234); + } + void add_k(::flatbuffers::Offset k) { + fbb_.AddOffset(Root::VT_K, k); + } + void add_l(uint8_t l) { + fbb_.AddElement(Root::VT_L, l, 56); + } + explicit RootBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateRoot( + ::flatbuffers::FlatBufferBuilder &_fbb, + bool b = false, + Evolution::V2::Union c_type = Evolution::V2::Union::NONE, + ::flatbuffers::Offset c = 0, + Evolution::V2::Enum d = Evolution::V2::Enum::King, + ::flatbuffers::Offset e = 0, + const Evolution::V2::Struct *ff = nullptr, + ::flatbuffers::Offset<::flatbuffers::Vector> g = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> h = 0, + uint32_t i = 1234, + ::flatbuffers::Offset k = 0, + uint8_t l = 56) { + RootBuilder builder_(_fbb); + builder_.add_k(k); + builder_.add_i(i); + builder_.add_h(h); + builder_.add_g(g); + builder_.add_ff(ff); + builder_.add_e(e); + builder_.add_c(c); + builder_.add_l(l); + builder_.add_d(d); + builder_.add_c_type(c_type); + builder_.add_b(b); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateRootDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + bool b = false, + Evolution::V2::Union c_type = Evolution::V2::Union::NONE, + ::flatbuffers::Offset c = 0, + Evolution::V2::Enum d = Evolution::V2::Enum::King, + ::flatbuffers::Offset e = 0, + const Evolution::V2::Struct *ff = nullptr, + const std::vector *g = nullptr, + const std::vector<::flatbuffers::Offset> *h = nullptr, + uint32_t i = 1234, + ::flatbuffers::Offset k = 0, + uint8_t l = 56) { + auto g__ = g ? _fbb.CreateVector(*g) : 0; + auto h__ = h ? _fbb.CreateVector<::flatbuffers::Offset>(*h) : 0; + return Evolution::V2::CreateRoot( + _fbb, + b, + c_type, + c, + d, + e, + ff, + g__, + h__, + i, + k, + l); +} + +inline bool VerifyUnion(::flatbuffers::Verifier &verifier, const void *obj, Union type) { + switch (type) { + case Union::NONE: { + return true; + } + case Union::TableA: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Union::TableB: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Union::TableC: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyUnionVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyUnion( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline const Evolution::V2::Root *GetRoot(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const Evolution::V2::Root *GetSizePrefixedRoot(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline bool VerifyRootBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedRootBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishRootBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedRootBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +} // namespace V2 +} // namespace Evolution + +#endif // FLATBUFFERS_GENERATED_EVOLUTIONV2_EVOLUTION_V2_H_ diff --git a/third_party/flatbuffers/tests/flatc/bar/bar.fbs b/third_party/flatbuffers/tests/flatc/bar/bar.fbs new file mode 100644 index 00000000000..afd4be9a485 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/bar/bar.fbs @@ -0,0 +1,5 @@ +include "baz/baz.fbs"; + +table Bar { + baz:Baz; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/bar/bar_with_foo.fbs b/third_party/flatbuffers/tests/flatc/bar/bar_with_foo.fbs new file mode 100644 index 00000000000..d5c0f9c3f76 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/bar/bar_with_foo.fbs @@ -0,0 +1,6 @@ +include "foo.fbs"; +include "baz/baz.fbs"; + +table BarWithFoo { + foo:Foo; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/bar/bar_with_ns.fbs b/third_party/flatbuffers/tests/flatc/bar/bar_with_ns.fbs new file mode 100644 index 00000000000..f5a800d0743 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/bar/bar_with_ns.fbs @@ -0,0 +1,14 @@ +include "baz/baz_with_ns.fbs"; +include "baz/baz.fbs"; + +namespace bar; + +table Bar { + baz:baz.Baz; + baz2:Baz; + foo:Foo; +} + +table Foo { + a:int; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/bar/baz/baz.fbs b/third_party/flatbuffers/tests/flatc/bar/baz/baz.fbs new file mode 100644 index 00000000000..254e980a09d --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/bar/baz/baz.fbs @@ -0,0 +1,6 @@ +enum Baz : short { + None = 0, + Red, + Green, + Blue, +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/bar/baz/baz_with_ns.fbs b/third_party/flatbuffers/tests/flatc/bar/baz/baz_with_ns.fbs new file mode 100644 index 00000000000..d258413a43d --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/bar/baz/baz_with_ns.fbs @@ -0,0 +1,8 @@ +namespace baz; + +enum Baz : short { + None = 0, + Red, + Green, + Blue, +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/enum_val_attributes.fbs b/third_party/flatbuffers/tests/flatc/enum_val_attributes.fbs new file mode 100644 index 00000000000..33b67d7f22d --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/enum_val_attributes.fbs @@ -0,0 +1,8 @@ +attribute display_name; + +enum ValAttributes : int +{ + Val1 = 0 (display_name: "Value 1"), + Val2 (display_name: "Value 2"), + Val3 (deprecated, display_name: "Value 3 (deprecated)"), +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/flatc_cpp_tests.py b/third_party/flatbuffers/tests/flatc/flatc_cpp_tests.py new file mode 100755 index 00000000000..72b2e9df58f --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/flatc_cpp_tests.py @@ -0,0 +1,254 @@ +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from flatc_test import * + + +class CppTests: + def Flatten(self): + # Generate just foo with a "flatten" import of bar. + flatc(["--cpp", "foo.fbs"]) + + # Foo should be generated in place and include bar flatten + assert_file_and_contents("foo_generated.h", '#include "bar_generated.h"') + + def FlattenAbsolutePath(self): + # Generate just foo with a "flatten" import of bar. + flatc(["--cpp", make_absolute("foo.fbs")]) + + # Foo should be generated in place and include bar flatten + assert_file_and_contents("foo_generated.h", '#include "bar_generated.h"') + + def FlattenSubDirectory(self): + # Generate just foo with a "flatten" import of bar. + flatc(["--cpp", "bar/bar.fbs"]) + + # Bar should be generated in place and include baz + assert_file_and_contents("bar_generated.h", '#include "baz_generated.h"') + + def FlattenOutPath(self): + # Generate just foo with a "flatten" import of bar. + flatc(["--cpp", "-o", ".tmp", "foo.fbs"]) + + # Foo should be generated in the out path and include bar flatten to the out path. + assert_file_and_contents(".tmp/foo_generated.h", '#include "bar_generated.h"') + + def FlattenOutPathSuperDirectory(self): + # Generate just foo with a "flatten" import of bar. + flatc(["--cpp", "-o", "../.tmp", "foo.fbs"]) + + # Foo should be generated in the out path and include bar flatten to the out path. + assert_file_and_contents( + "../.tmp/foo_generated.h", '#include "bar_generated.h"' + ) + + def FlattenOutPathSubDirectory(self): + # Generate just foo with a "flatten" import of bar. + flatc(["--cpp", "-o", ".tmp", "bar/bar.fbs"]) + + # Bar should be generated in the out path and include baz flatten to the out path. + assert_file_and_contents(".tmp/bar_generated.h", '#include "baz_generated.h"') + + def KeepPrefix(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", "foo.fbs"]) + + assert_file_and_contents("foo_generated.h", '#include "bar/bar_generated.h"') + + def KeepPrefixAbsolutePath(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", make_absolute("foo.fbs")]) + + assert_file_and_contents("foo_generated.h", '#include "bar/bar_generated.h"') + + def KeepPrefixSubDirectory(self): + # Generate with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", "bar/bar.fbs"]) + + assert_file_and_contents("bar_generated.h", '#include "baz/baz_generated.h"') + + def KeepPrefixOutPath(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", "-o", ".tmp", "foo.fbs"]) + + assert_file_and_contents( + ".tmp/foo_generated.h", + '#include "bar/bar_generated.h"', + ) + + def KeepPrefixOutPathSubDirectory(self): + # Generate with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", "-o", ".tmp", "bar/bar.fbs"]) + + assert_file_and_contents( + ".tmp/bar_generated.h", '#include "baz/baz_generated.h"' + ) + + def IncludePrefix(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--include-prefix", "test", "foo.fbs"]) + + assert_file_and_contents("foo_generated.h", '#include "test/bar_generated.h"') + + def IncludePrefixAbolutePath(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--include-prefix", "test", make_absolute("foo.fbs")]) + + assert_file_and_contents("foo_generated.h", '#include "test/bar_generated.h"') + + def IncludePrefixSubDirectory(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--include-prefix", "test", "bar/bar.fbs"]) + + assert_file_and_contents("bar_generated.h", '#include "test/baz_generated.h"') + + def IncludePrefixOutPath(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--include-prefix", "test", "-o", ".tmp", "foo.fbs"]) + + assert_file_and_contents( + ".tmp/foo_generated.h", '#include "test/bar_generated.h"' + ) + + def IncludePrefixOutPathSubDirectory(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--include-prefix", "test", "-o", ".tmp", "bar/bar.fbs"]) + + assert_file_and_contents( + ".tmp/bar_generated.h", '#include "test/baz_generated.h"' + ) + + def KeepPrefixIncludePrefix(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", "--include-prefix", "test", "foo.fbs"]) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + "foo_generated.h", '#include "test/bar/bar_generated.h"' + ) + + def KeepPrefixIncludePrefixAbsolutePath(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc( + [ + "--cpp", + "--keep-prefix", + "--include-prefix", + "test", + make_absolute("foo.fbs"), + ] + ) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + "foo_generated.h", '#include "test/bar/bar_generated.h"' + ) + + def KeepPrefixIncludePrefixSubDirectory(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc(["--cpp", "--keep-prefix", "--include-prefix", "test", "bar/bar.fbs"]) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + "bar_generated.h", '#include "test/baz/baz_generated.h"' + ) + + def KeepPrefixIncludePrefixOutPathSubDirectory(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc( + [ + "--cpp", + "--keep-prefix", + "--include-prefix", + "test", + "-o", + ".tmp", + "bar/bar.fbs", + ] + ) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + ".tmp/bar_generated.h", '#include "test/baz/baz_generated.h"' + ) + + def KeepPrefixIncludePrefixOutPathSuperDirectory(self): + # Generate just foo with the import of bar keeping the prefix of where it is located. + flatc( + [ + "--cpp", + "--keep-prefix", + "--include-prefix", + "test", + "-o", + "../.tmp", + "bar/bar.fbs", + ] + ) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + "../.tmp/bar_generated.h", '#include "test/baz/baz_generated.h"' + ) + + def KeepPrefixIncludePrefixoutPathAbsoluePaths_SuperDirectoryReference(self): + # Generate bar_with_foo that references a type in a super directory. + flatc( + [ + "--cpp", + "--keep-prefix", + "--include-prefix", + "generated", + "-I", + str(script_path.absolute()), + "-o", + str(Path(script_path, ".tmp").absolute()), + str(Path(script_path, "bar/bar_with_foo.fbs").absolute()), + ] + ) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + ".tmp/bar_with_foo_generated.h", + [ + '#include "generated/baz/baz_generated.h"', + '#include "generated/foo_generated.h"', + ], + ) + + def KeepPrefixIncludePrefixoutPath_SuperDirectoryReference(self): + # Generate bar_with_foo that references a type in a super directory. + flatc( + [ + "--cpp", + "--keep-prefix", + "--include-prefix", + "generated", + "-I", + "./", + "-o", + ".tmp", + "bar/bar_with_foo.fbs", + ] + ) + + # The include prefix should come first, with the kept prefix next. + assert_file_and_contents( + ".tmp/bar_with_foo_generated.h", + [ + '#include "generated/baz/baz_generated.h"', + '#include "generated/foo_generated.h"', + ], + unlink=False, + ) diff --git a/third_party/flatbuffers/tests/flatc/flatc_kotlin_tests.py b/third_party/flatbuffers/tests/flatc/flatc_kotlin_tests.py new file mode 100644 index 00000000000..bca3cba33e3 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/flatc_kotlin_tests.py @@ -0,0 +1,32 @@ +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from flatc_test import * + + +class KotlinTests: + + def EnumValAttributes(self): + flatc(["--kotlin", "enum_val_attributes.fbs"]) + + subject = assert_file_exists("ValAttributes.kt") + assert_file_doesnt_contains(subject, 'val names : Array = arrayOf("Val1", "Val2", "Val3")') + assert_file_doesnt_contains(subject, 'fun name(e: Int) : String = names[e]') + + def EnumValAttributes_ReflectNames(self): + flatc(["--kotlin", "--reflect-names", "enum_val_attributes.fbs"]) + + subject = assert_file_exists("ValAttributes.kt") + assert_file_contains(subject, 'val names : Array = arrayOf("Val1", "Val2", "Val3")') + assert_file_contains(subject, 'fun name(e: Int) : String = names[e]') diff --git a/third_party/flatbuffers/tests/flatc/flatc_schema_tests.py b/third_party/flatbuffers/tests/flatc/flatc_schema_tests.py new file mode 100644 index 00000000000..e79bb3ce367 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/flatc_schema_tests.py @@ -0,0 +1,43 @@ +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from flatc_test import * +import json + + +class SchemaTests: + def EnumValAttributes(self): + # Generate .bfbs schema first + flatc(["--schema", "--binary", "--bfbs-builtins", "enum_val_attributes.fbs"]) + assert_file_exists("enum_val_attributes.bfbs") + + # Then turn it into JSON + flatc(["--json", "--strict-json", str(reflection_fbs_path()), "--", "enum_val_attributes.bfbs"]) + + # The attributes should be present in JSON + schema_json = json.loads(get_file_contents("enum_val_attributes.json")) + + assert schema_json["enums"][0]["name"] == "ValAttributes" + assert schema_json["enums"][0]["values"][0]["name"] == "Val1" + assert schema_json["enums"][0]["values"][0]["attributes"][0]["key"] == "display_name" + assert schema_json["enums"][0]["values"][0]["attributes"][0]["value"] == "Value 1" + + assert schema_json["enums"][0]["values"][1]["name"] == "Val2" + assert schema_json["enums"][0]["values"][1]["attributes"][0]["key"] == "display_name" + assert schema_json["enums"][0]["values"][1]["attributes"][0]["value"] == "Value 2" + + assert schema_json["enums"][0]["values"][2]["name"] == "Val3" + assert schema_json["enums"][0]["values"][2]["attributes"][0]["key"] == "deprecated" + assert schema_json["enums"][0]["values"][2]["attributes"][1]["key"] == "display_name" + assert schema_json["enums"][0]["values"][2]["attributes"][1]["value"] == "Value 3 (deprecated)" diff --git a/third_party/flatbuffers/tests/flatc/flatc_test.py b/third_party/flatbuffers/tests/flatc/flatc_test.py new file mode 100755 index 00000000000..2e51743e302 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/flatc_test.py @@ -0,0 +1,139 @@ +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import argparse +import platform +import subprocess +from pathlib import Path + +parser = argparse.ArgumentParser() +parser.add_argument( + "--flatc", help="path of the Flat C compiler relative to the root directory" +) + +args = parser.parse_args() + +# Get the path where this script is located so we can invoke the script from +# any directory and have the paths work correctly. +script_path = Path(__file__).parent.resolve() + +# Get the root path as an absolute path, so all derived paths are absolute. +root_path = script_path.parent.parent.absolute() + +# Get the location of the flatc executable, reading from the first command line +# argument or defaulting to default names. +flatc_exe = Path( + ("flatc" if not platform.system() == "Windows" else "flatc.exe") + if not args.flatc + else args.flatc +) + +# Find and assert flatc compiler is present. +if root_path in flatc_exe.parents: + flatc_exe = flatc_exe.relative_to(root_path) +flatc_path = Path(root_path, flatc_exe) +assert flatc_path.exists(), "Cannot find the flatc compiler " + str(flatc_path) + +# Execute the flatc compiler with the specified parameters +def flatc(options, cwd=script_path): + cmd = [str(flatc_path)] + options + subprocess.check_call(cmd, cwd=str(cwd)) + + +def reflection_fbs_path(): + return Path(root_path).joinpath("reflection", "reflection.fbs") + + +def make_absolute(filename, path=script_path): + return str(Path(path, filename).absolute()) + + +def assert_file_exists(filename, path=script_path): + file = Path(path, filename) + assert file.exists(), "could not find file: " + filename + return file + + +def assert_file_doesnt_exists(filename, path=script_path): + file = Path(path, filename) + assert not file.exists(), "file exists but shouldn't: " + filename + return file + + +def get_file_contents(filename, path=script_path): + file = Path(path, filename) + contents = "" + with open(file) as file: + contents = file.read() + return contents + + +def assert_file_contains(file, needles): + with open(file) as file: + contents = file.read() + for needle in [needles] if isinstance(needles, str) else needles: + assert needle in contents, ( + "coudn't find '" + needle + "' in file: " + str(file) + ) + return file + + +def assert_file_doesnt_contains(file, needles): + with open(file) as file: + contents = file.read() + for needle in [needles] if isinstance(needles, str) else needles: + assert needle not in contents, ( + "Found unexpected '" + needle + "' in file: " + str(file) + ) + return file + + +def assert_file_and_contents( + file, needle, doesnt_contain=None, path=script_path, unlink=True +): + assert_file_contains(assert_file_exists(file, path), needle) + if doesnt_contain: + assert_file_doesnt_contains(assert_file_exists(file, path), doesnt_contain) + if unlink: + Path(path, file).unlink() + + +def run_all(*modules): + failing = 0 + passing = 0 + for module in modules: + methods = [ + func + for func in dir(module) + if callable(getattr(module, func)) and not func.startswith("__") + ] + module_failing = 0 + module_passing = 0 + for method in methods: + try: + print("{0}.{1}".format(module.__name__, method)) + getattr(module, method)(module) + print(" [PASSED]") + module_passing = module_passing + 1 + except Exception as e: + print(" [FAILED]: " + str(e)) + module_failing = module_failing + 1 + print( + "{0}: {1} of {2} passsed".format( + module.__name__, module_passing, module_passing + module_failing + ) + ) + passing = passing + module_passing + failing = failing + module_failing + return passing, failing diff --git a/third_party/flatbuffers/tests/flatc/flatc_ts_tests.py b/third_party/flatbuffers/tests/flatc/flatc_ts_tests.py new file mode 100755 index 00000000000..6e444bc417f --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/flatc_ts_tests.py @@ -0,0 +1,242 @@ +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +from flatc_test import * + + +class TsTests(): + + def Base(self): + # Generate just foo with no extra arguments + flatc(["--ts", "foo.fbs"]) + + # Should generate the module that exports both foo and its direct + # include, bar. + assert_file_and_contents( + "foo_generated.ts", + [ + "export { Bar } from './bar.js';", + "export { Foo } from './foo.js';", + ], + ) + + # Foo should be generated in place and exports the Foo table. + assert_file_and_contents("foo.ts", "export class Foo {") + + # Included files, like bar, should not be generated. + assert_file_doesnt_exists("bar.ts") + + def BaseMultipleFiles(self): + # Generate both foo and bar with no extra arguments + flatc(["--ts", "foo.fbs", "bar/bar.fbs"]) + + # Should generate the module that exports both foo and its direct + # include, bar. + assert_file_and_contents( + "foo_generated.ts", + [ + "export { Bar } from './bar.js';", + "export { Foo } from './foo.js';", + ], + ) + + # Foo should be generated in place and exports the Foo table. + assert_file_and_contents("foo.ts", "export class Foo {") + + # Bar should also be generatd in place and exports the Bar table. + assert_file_and_contents("bar.ts", "export class Bar {") + + def BaseWithNamespace(self): + # Generate foo with namespacing, with no extra arguments + flatc(["--ts", "foo_with_ns.fbs"]) + + # Should generate the module that exports both foo in its namespace + # directory and its direct include, bar. + assert_file_and_contents( + "foo_with_ns_generated.ts", + [ + "export { Bar } from './bar/bar.js';", + "export { Foo } from './something/foo.js';", + ], + ) + + # Foo should be placed in the namespaced directory. It should export + # Foo, and the import of Bar should be relative to its location. + assert_file_and_contents( + "something/foo.ts", + [ + "export class Foo {", + "import { Bar } from '../bar/bar.js';", + ], + ) + + # Included files, like bar, should not be generated. + assert_file_doesnt_exists("bar.ts") + + def GenAll(self): + # Generate foo with generate all options + flatc(["--ts", "--gen-all", "foo.fbs"]) + + # Should generate a single file that exports all the generated types. + assert_file_and_contents( + "foo_generated.ts", + [ + "export { Bar } from './bar.js'", + "export { Baz } from './baz.js'", + "export { Foo } from './foo.js'", + ], + ) + + # Foo should be generated with an import to Bar and an export of itself. + assert_file_and_contents( + "foo.ts", + [ + "import { Bar } from './bar.js';", + "export class Foo {", + ], + ) + + # Bar should be generated with an import to Baz and an export of itself. + assert_file_and_contents( + "bar.ts", + [ + "import { Baz } from './baz.js';", + "export class Bar {", + ], + ) + + # Baz should be generated with an export of itself. + assert_file_and_contents( + "baz.ts", + [ + "export enum Baz {", + ], + ) + + + def FlatFiles(self): + # Generate just foo with the flat files option + flatc(["--ts", "--ts-flat-files", "foo.fbs"]) + + # Should generate a single file that imports bar as a single file, and + # exports the Foo table. + assert_file_and_contents( + "foo_generated.ts", + [ + "import {Bar as Bar} from './bar_generated.js';", + "export class Foo {", + ], + ) + + # The root type Foo should not be generated in its own file. + assert_file_doesnt_exists("foo.ts") + + def FlatFilesWithNamespace(self): + # Generate just foo with the flat files option + flatc(["--ts", "--ts-flat-files", "foo_with_ns.fbs"]) + + # Should generate a single file that imports bar as a single file, and + # exports the Foo table. + assert_file_and_contents( + "foo_with_ns_generated.ts", + [ + "import {Bar as Bar} from './bar_with_ns_generated.js';", + "export class Foo {", + ], + ) + + # The root type Foo should not be generated in its own file. + assert_file_doesnt_exists("foo.ts") + + def FlatFilesMultipleFiles(self): + # Generate both foo and bar with the flat files option + flatc(["--ts", "--ts-flat-files", "foo.fbs", "bar/bar.fbs"]) + + # Should generate a single foo file that imports bar as a single file, + # and exports the Foo table. + assert_file_and_contents( + "foo_generated.ts", + [ + "import {Bar as Bar} from './bar_generated.js';", + "export class Foo {", + ], + ) + + # Should generate a single bar file that imports bar as a single file, + # and exports the Bar table. + assert_file_and_contents( + "bar_generated.ts", + [ + "import {Baz as Baz} from './baz_generated.js';", + "export class Bar {", + ], + ) + + # The types Foo and Bar should not be generated in their own files + assert_file_doesnt_exists("foo.ts") + assert_file_doesnt_exists("bar.ts") + + def FlatFilesGenAll(self): + # Generate foo with all of its dependents with the flat files option + flatc(["--ts", "--ts-flat-files", "--gen-all", "foo.fbs"]) + + # Should generate a single foo file + assert_file_and_contents( + "foo_generated.ts", + # Should export each of the types within the single file + [ + "export class Foo {", + "export class Bar {", + "export enum Baz {", + ], + # No includes for the dependent types should be present. + doesnt_contain=[ + "import {Bar as Bar}", + "import {Baz as Baz}", + ], + ) + + # The types Foo, Bar and Baz should not be generated in their own files. + assert_file_doesnt_exists("foo.ts") + assert_file_doesnt_exists("bar.ts") + assert_file_doesnt_exists("baz.ts") + + + def ZFlatFilesGenAllWithNamespacing(self): + # Generate foo with all of its dependents with the flat files option + flatc(["--ts", "--ts-flat-files", "--gen-all", "foo_with_ns.fbs"]) + + # Should generate a single foo file + assert_file_and_contents( + "foo_with_ns_generated.ts", + # Should export each of the types within the single file + [ + "export class bar_Bar {", + "export class bar_Foo {", + "export enum Baz {", + "export enum baz_Baz {", + "export class something_Foo {" + ], + # No includes for the dependent types should be present. + doesnt_contain=[ + "import {Bar as Bar}", + "import {Baz as Baz}", + ], + ) + + # The types Foo, Bar and Baz should not be generated in their own files. + assert_file_doesnt_exists("foo.ts") + assert_file_doesnt_exists("bar.ts") + assert_file_doesnt_exists("baz.ts") + diff --git a/third_party/flatbuffers/tests/flatc/foo.fbs b/third_party/flatbuffers/tests/flatc/foo.fbs new file mode 100644 index 00000000000..a2f27aab9ab --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/foo.fbs @@ -0,0 +1,9 @@ +include "bar/bar.fbs"; +include "bar/bar_with_ns.fbs"; + +table Foo { + bar:Bar; + bar2:bar.Bar; +} + +root_type Foo; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/foo_with_ns.fbs b/third_party/flatbuffers/tests/flatc/foo_with_ns.fbs new file mode 100644 index 00000000000..c348d9b84f1 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/foo_with_ns.fbs @@ -0,0 +1,9 @@ +include "bar/bar_with_ns.fbs"; + +namespace something; + +table Foo { + bar:bar.Bar; +} + +root_type Foo; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/flatc/main.py b/third_party/flatbuffers/tests/flatc/main.py new file mode 100755 index 00000000000..b296c475f31 --- /dev/null +++ b/third_party/flatbuffers/tests/flatc/main.py @@ -0,0 +1,31 @@ +#!/usr/bin/env python3 +# +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import sys + +from flatc_test import run_all +from flatc_cpp_tests import CppTests +from flatc_kotlin_tests import KotlinTests +from flatc_ts_tests import TsTests +from flatc_schema_tests import SchemaTests + +passing, failing = run_all(CppTests, KotlinTests, TsTests, SchemaTests) + +print("") +print("{0} of {1} tests passed".format(passing, passing + failing)) + +if failing > 0: + sys.exit(1) diff --git a/third_party/flatbuffers/tests/flexbuffers_test.cpp b/third_party/flatbuffers/tests/flexbuffers_test.cpp new file mode 100644 index 00000000000..0c7d04e7c95 --- /dev/null +++ b/third_party/flatbuffers/tests/flexbuffers_test.cpp @@ -0,0 +1,300 @@ +#include "flexbuffers_test.h" + +#include + +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/idl.h" +#include "is_quiet_nan.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +// Shortcuts for the infinity. +static const auto infinity_d = std::numeric_limits::infinity(); + +void FlexBuffersTest() { + flexbuffers::Builder slb(512, + flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); + + // Write the equivalent of: + // { vec: [ -100, "Fred", 4.0, false ], bar: [ 1, 2, 3 ], bar3: [ 1, 2, 3 ], + // foo: 100, bool: true, mymap: { foo: "Fred" } } + + // It's possible to do this without std::function support as well. + slb.Map([&]() { + slb.Vector("vec", [&]() { + slb += -100; // Equivalent to slb.Add(-100) or slb.Int(-100); + slb += "Fred"; + slb.IndirectFloat(4.0f); + auto i_f = slb.LastValue(); + uint8_t blob[] = { 77 }; + slb.Blob(blob, 1); + slb += false; + slb.ReuseValue(i_f); + }); + int ints[] = { 1, 2, 3 }; + slb.Vector("bar", ints, 3); + slb.FixedTypedVector("bar3", ints, 3); + bool bools[] = { true, false, true, false }; + slb.Vector("bools", bools, 4); + slb.Bool("bool", true); + slb.Double("foo", 100); + slb.Map("mymap", [&]() { + slb.String("foo", "Fred"); // Testing key and string reuse. + }); + }); + slb.Finish(); + + // clang-format off + #ifdef FLATBUFFERS_TEST_VERBOSE + for (size_t i = 0; i < slb.GetBuffer().size(); i++) + printf("%d ", slb.GetBuffer().data()[i]); + printf("\n"); + #endif + // clang-format on + + std::vector reuse_tracker; + TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(), + slb.GetBuffer().size(), &reuse_tracker), + true); + + auto map = flexbuffers::GetRoot(slb.GetBuffer()).AsMap(); + TEST_EQ(map.size(), 7); + auto vec = map["vec"].AsVector(); + TEST_EQ(vec.size(), 6); + TEST_EQ(vec[0].AsInt64(), -100); + TEST_EQ_STR(vec[1].AsString().c_str(), "Fred"); + TEST_EQ(vec[1].AsInt64(), 0); // Number parsing failed. + TEST_EQ(vec[2].AsDouble(), 4.0); + TEST_EQ(vec[2].AsString().IsTheEmptyString(), true); // Wrong Type. + TEST_EQ_STR(vec[2].AsString().c_str(), ""); // This still works though. + TEST_EQ_STR(vec[2].ToString().c_str(), "4.0"); // Or have it converted. + // Few tests for templated version of As. + TEST_EQ(vec[0].As(), -100); + TEST_EQ_STR(vec[1].As().c_str(), "Fred"); + TEST_EQ(vec[1].As(), 0); // Number parsing failed. + TEST_EQ(vec[2].As(), 4.0); + // Test that the blob can be accessed. + TEST_EQ(vec[3].IsBlob(), true); + auto blob = vec[3].AsBlob(); + TEST_EQ(blob.size(), 1); + TEST_EQ(blob.data()[0], 77); + TEST_EQ(vec[4].IsBool(), true); // Check if type is a bool + TEST_EQ(vec[4].AsBool(), false); // Check if value is false + TEST_EQ(vec[5].AsDouble(), 4.0); // This is shared with vec[2] ! + auto tvec = map["bar"].AsTypedVector(); + TEST_EQ(tvec.size(), 3); + TEST_EQ(tvec[2].AsInt8(), 3); + auto tvec3 = map["bar3"].AsFixedTypedVector(); + TEST_EQ(tvec3.size(), 3); + TEST_EQ(tvec3[2].AsInt8(), 3); + TEST_EQ(map["bool"].AsBool(), true); + auto tvecb = map["bools"].AsTypedVector(); + TEST_EQ(tvecb.ElementType(), flexbuffers::FBT_BOOL); + TEST_EQ(map["foo"].AsUInt8(), 100); + TEST_EQ(map["unknown"].IsNull(), true); + auto mymap = map["mymap"].AsMap(); + // These should be equal by pointer equality, since key and value are shared. + TEST_EQ(mymap.Keys()[0].AsKey(), map.Keys()[4].AsKey()); + TEST_EQ(mymap.Values()[0].AsString().c_str(), vec[1].AsString().c_str()); + // We can mutate values in the buffer. + TEST_EQ(vec[0].MutateInt(-99), true); + TEST_EQ(vec[0].AsInt64(), -99); + TEST_EQ(vec[1].MutateString("John"), true); // Size must match. + TEST_EQ_STR(vec[1].AsString().c_str(), "John"); + TEST_EQ(vec[1].MutateString("Alfred"), false); // Too long. + TEST_EQ(vec[2].MutateFloat(2.0f), true); + TEST_EQ(vec[2].AsFloat(), 2.0f); + TEST_EQ(vec[2].MutateFloat(3.14159), false); // Double does not fit in float. + TEST_EQ(vec[4].AsBool(), false); // Is false before change + TEST_EQ(vec[4].MutateBool(true), true); // Can change a bool + TEST_EQ(vec[4].AsBool(), true); // Changed bool is now true + + // Parse from JSON: + flatbuffers::Parser parser; + slb.Clear(); + auto jsontest = "{ a: [ 123, 456.0 ], b: \"hello\", c: true, d: false }"; + TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true); + TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(), + slb.GetBuffer().size(), &reuse_tracker), + true); + auto jroot = flexbuffers::GetRoot(slb.GetBuffer()); + auto jmap = jroot.AsMap(); + auto jvec = jmap["a"].AsVector(); + TEST_EQ(jvec[0].AsInt64(), 123); + TEST_EQ(jvec[1].AsDouble(), 456.0); + TEST_EQ_STR(jmap["b"].AsString().c_str(), "hello"); + TEST_EQ(jmap["c"].IsBool(), true); // Parsed correctly to a bool + TEST_EQ(jmap["c"].AsBool(), true); // Parsed correctly to true + TEST_EQ(jmap["d"].IsBool(), true); // Parsed correctly to a bool + TEST_EQ(jmap["d"].AsBool(), false); // Parsed correctly to false + // And from FlexBuffer back to JSON: + auto jsonback = jroot.ToString(); + TEST_EQ_STR(jsontest, jsonback.c_str()); + // With indentation: + std::string jsonback_indented; + jroot.ToString(true, false, jsonback_indented, true, 0, " "); + auto jsontest_indented = + "{\n a: [\n 123,\n 456.0\n ],\n b: \"hello\",\n c: true,\n d: false\n}"; + TEST_EQ_STR(jsontest_indented, jsonback_indented.c_str()); + + slb.Clear(); + slb.Vector([&]() { + for (int i = 0; i < 130; ++i) slb.Add(static_cast(255)); + slb.Vector([&]() { + for (int i = 0; i < 130; ++i) slb.Add(static_cast(255)); + slb.Vector([] {}); + }); + }); + slb.Finish(); + TEST_EQ(slb.GetSize(), 664); +} + +void FlexBuffersReuseBugTest() { + flexbuffers::Builder slb; + slb.Map([&]() { + slb.Vector("vec", [&]() {}); + slb.Bool("bool", true); + }); + slb.Finish(); + std::vector reuse_tracker; + // This would fail before, since the reuse_tracker would use the address of + // the vector reference to check for reuse, but in this case we have an empty + // vector, and since the size field is before the pointer, its address is the + // same as thing after it, the key "bool". + // We fix this by using the address of the size field for tracking reuse. + TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(), + slb.GetBuffer().size(), &reuse_tracker), + true); +} + +void FlexBuffersFloatingPointTest() { +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) + flexbuffers::Builder slb(512, + flexbuffers::BUILDER_FLAG_SHARE_KEYS_AND_STRINGS); + // Parse floating-point values from JSON: + flatbuffers::Parser parser; + slb.Clear(); + auto jsontest = + "{ a: [1.0, nan, inf, infinity, -inf, +inf, -infinity, 8.0] }"; + TEST_EQ(parser.ParseFlexBuffer(jsontest, nullptr, &slb), true); + auto jroot = flexbuffers::GetRoot(slb.GetBuffer()); + TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(), + slb.GetBuffer().size(), nullptr), + true); + auto jmap = jroot.AsMap(); + auto jvec = jmap["a"].AsVector(); + TEST_EQ(8, jvec.size()); + TEST_EQ(1.0, jvec[0].AsDouble()); + TEST_ASSERT(is_quiet_nan(jvec[1].AsDouble())); + TEST_EQ(infinity_d, jvec[2].AsDouble()); + TEST_EQ(infinity_d, jvec[3].AsDouble()); + TEST_EQ(-infinity_d, jvec[4].AsDouble()); + TEST_EQ(+infinity_d, jvec[5].AsDouble()); + TEST_EQ(-infinity_d, jvec[6].AsDouble()); + TEST_EQ(8.0, jvec[7].AsDouble()); +#endif +} + +void FlexBuffersDeprecatedTest() { + // FlexBuffers as originally designed had a flaw involving the + // FBT_VECTOR_STRING datatype, and this test documents/tests the fix for it. + // Discussion: https://github.com/google/flatbuffers/issues/5627 + flexbuffers::Builder slb; + // FBT_VECTOR_* are "typed vectors" where all elements are of the same type. + // Problem is, when storing FBT_STRING elements, it relies on that type to + // get the bit-width for the size field of the string, which in this case + // isn't present, and instead defaults to 8-bit. This means that any strings + // stored inside such a vector, when accessed thru the old API that returns + // a String reference, will appear to be truncated if the string stored is + // actually >=256 bytes. + std::string test_data(300, 'A'); + auto start = slb.StartVector(); + // This one will have a 16-bit size field. + slb.String(test_data); + // This one will have an 8-bit size field. + slb.String("hello"); + // We're asking this to be serialized as a typed vector (true), but not + // fixed size (false). The type will be FBT_VECTOR_STRING with a bit-width + // of whatever the offsets in the vector need, the bit-widths of the strings + // are not stored(!) <- the actual design flaw. + // Note that even in the fixed code, we continue to serialize the elements of + // FBT_VECTOR_STRING as FBT_STRING, since there may be old code out there + // reading new data that we want to continue to function. + // Thus, FBT_VECTOR_STRING, while deprecated, will always be represented the + // same way, the fix lies on the reading side. + slb.EndVector(start, true, false); + slb.Finish(); + // Verify because why not. + TEST_EQ(flexbuffers::VerifyBuffer(slb.GetBuffer().data(), + slb.GetBuffer().size(), nullptr), + true); + // So now lets read this data back. + // For existing data, since we have no way of knowing what the actual + // bit-width of the size field of the string is, we are going to ignore this + // field, and instead treat these strings as FBT_KEY (null-terminated), so we + // can deal with strings of arbitrary length. This of course truncates strings + // with embedded nulls, but we think that that is preferrable over truncating + // strings >= 256 bytes. + auto vec = flexbuffers::GetRoot(slb.GetBuffer()).AsTypedVector(); + // Even though this was serialized as FBT_VECTOR_STRING, it is read as + // FBT_VECTOR_KEY: + TEST_EQ(vec.ElementType(), flexbuffers::FBT_KEY); + // Access the long string. Previously, this would return a string of size 1, + // since it would read the high-byte of the 16-bit length. + // This should now correctly test the full 300 bytes, using AsKey(): + TEST_EQ_STR(vec[0].AsKey(), test_data.c_str()); + // Old code that called AsString will continue to work, as the String + // accessor objects now use a cached size that can come from a key as well. + TEST_EQ_STR(vec[0].AsString().c_str(), test_data.c_str()); + // Short strings work as before: + TEST_EQ_STR(vec[1].AsKey(), "hello"); + TEST_EQ_STR(vec[1].AsString().c_str(), "hello"); + // So, while existing code and data mostly "just work" with the fixes applied + // to AsTypedVector and AsString, what do you do going forward? + // Code accessing existing data doesn't necessarily need to change, though + // you could consider using AsKey instead of AsString for a) documenting + // that you are accessing keys, or b) a speedup if you don't actually use + // the string size. + // For new data, or data that doesn't need to be backwards compatible, + // instead serialize as FBT_VECTOR (call EndVector with typed = false, then + // read elements with AsString), or, for maximum compactness, use + // FBT_VECTOR_KEY (call slb.Key above instead, read with AsKey or AsString). +} + +void ParseFlexbuffersFromJsonWithNullTest() { + // Test nulls are handled appropriately through flexbuffers to exercise other + // code paths of ParseSingleValue in the optional scalars change. + // TODO(cneo): Json -> Flatbuffers test once some language can generate code + // with optional scalars. + { + char json[] = "{\"opt_field\": 123 }"; + flatbuffers::Parser parser; + flexbuffers::Builder flexbuild; + parser.ParseFlexBuffer(json, nullptr, &flexbuild); + auto root = flexbuffers::GetRoot(flexbuild.GetBuffer()); + TEST_EQ(root.AsMap()["opt_field"].AsInt64(), 123); + } + { + char json[] = "{\"opt_field\": 123.4 }"; + flatbuffers::Parser parser; + flexbuffers::Builder flexbuild; + parser.ParseFlexBuffer(json, nullptr, &flexbuild); + auto root = flexbuffers::GetRoot(flexbuild.GetBuffer()); + TEST_EQ(root.AsMap()["opt_field"].AsDouble(), 123.4); + } + { + char json[] = "{\"opt_field\": null }"; + flatbuffers::Parser parser; + flexbuffers::Builder flexbuild; + parser.ParseFlexBuffer(json, nullptr, &flexbuild); + auto root = flexbuffers::GetRoot(flexbuild.GetBuffer()); + TEST_ASSERT(!root.AsMap().IsTheEmptyMap()); + TEST_ASSERT(root.AsMap()["opt_field"].IsNull()); + TEST_EQ(root.ToString(), std::string("{ opt_field: null }")); + } +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/flexbuffers_test.h b/third_party/flatbuffers/tests/flexbuffers_test.h new file mode 100644 index 00000000000..132098fb37e --- /dev/null +++ b/third_party/flatbuffers/tests/flexbuffers_test.h @@ -0,0 +1,16 @@ +#ifndef TESTS_FLEXBUFFERS_TEST_H +#define TESTS_FLEXBUFFERS_TEST_H + +namespace flatbuffers { +namespace tests { + +void FlexBuffersTest(); +void FlexBuffersReuseBugTest(); +void FlexBuffersFloatingPointTest(); +void FlexBuffersDeprecatedTest(); +void ParseFlexbuffersFromJsonWithNullTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif // TESTS_FLEXBUFFERS_TEST_H diff --git a/third_party/flatbuffers/tests/fuzz_test.cpp b/third_party/flatbuffers/tests/fuzz_test.cpp new file mode 100644 index 00000000000..1c9adbc577e --- /dev/null +++ b/third_party/flatbuffers/tests/fuzz_test.cpp @@ -0,0 +1,306 @@ +#include "fuzz_test.h" + +#include + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/idl.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { +namespace { + +// Include simple random number generator to ensure results will be the +// same cross platform. +// http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator +uint32_t lcg_seed = 48271; +uint32_t lcg_rand() { + return lcg_seed = + (static_cast(lcg_seed) * 279470273UL) % 4294967291UL; +} +void lcg_reset() { lcg_seed = 48271; } + +template +static void CompareTableFieldValue(flatbuffers::Table *table, + flatbuffers::voffset_t voffset, T val) { + T read = table->GetField(voffset, static_cast(0)); + TEST_EQ(read, val); +} + +} // namespace + +// Low level stress/fuzz test: serialize/deserialize a variety of +// different kinds of data in different combinations +void FuzzTest1() { + // Values we're testing against: chosen to ensure no bits get chopped + // off anywhere, and also be different from eachother. + const uint8_t bool_val = true; + const int8_t char_val = -127; // 0x81 + const uint8_t uchar_val = 0xFF; + const int16_t short_val = -32222; // 0x8222; + const uint16_t ushort_val = 0xFEEE; + const int32_t int_val = 0x83333333; + const uint32_t uint_val = 0xFDDDDDDD; + const int64_t long_val = 0x8444444444444444LL; + const uint64_t ulong_val = 0xFCCCCCCCCCCCCCCCULL; + const float float_val = 3.14159f; + const double double_val = 3.14159265359; + + const int test_values_max = 11; + const flatbuffers::voffset_t fields_per_object = 4; + const int num_fuzz_objects = 10000; // The higher, the more thorough :) + + flatbuffers::FlatBufferBuilder builder; + + lcg_reset(); // Keep it deterministic. + + flatbuffers::uoffset_t objects[num_fuzz_objects]; + + // Generate num_fuzz_objects random objects each consisting of + // fields_per_object fields, each of a random type. + for (int i = 0; i < num_fuzz_objects; i++) { + auto start = builder.StartTable(); + for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) { + int choice = lcg_rand() % test_values_max; + auto off = flatbuffers::FieldIndexToOffset(f); + switch (choice) { + case 0: builder.AddElement(off, bool_val, 0); break; + case 1: builder.AddElement(off, char_val, 0); break; + case 2: builder.AddElement(off, uchar_val, 0); break; + case 3: builder.AddElement(off, short_val, 0); break; + case 4: builder.AddElement(off, ushort_val, 0); break; + case 5: builder.AddElement(off, int_val, 0); break; + case 6: builder.AddElement(off, uint_val, 0); break; + case 7: builder.AddElement(off, long_val, 0); break; + case 8: builder.AddElement(off, ulong_val, 0); break; + case 9: builder.AddElement(off, float_val, 0); break; + case 10: builder.AddElement(off, double_val, 0); break; + } + } + objects[i] = builder.EndTable(start); + } + builder.PreAlign(0); // Align whole buffer. + + lcg_reset(); // Reset. + + uint8_t *eob = builder.GetCurrentBufferPointer() + builder.GetSize(); + + // Test that all objects we generated are readable and return the + // expected values. We generate random objects in the same order + // so this is deterministic. + for (int i = 0; i < num_fuzz_objects; i++) { + auto table = reinterpret_cast(eob - objects[i]); + for (flatbuffers::voffset_t f = 0; f < fields_per_object; f++) { + int choice = lcg_rand() % test_values_max; + flatbuffers::voffset_t off = flatbuffers::FieldIndexToOffset(f); + switch (choice) { + case 0: CompareTableFieldValue(table, off, bool_val); break; + case 1: CompareTableFieldValue(table, off, char_val); break; + case 2: CompareTableFieldValue(table, off, uchar_val); break; + case 3: CompareTableFieldValue(table, off, short_val); break; + case 4: CompareTableFieldValue(table, off, ushort_val); break; + case 5: CompareTableFieldValue(table, off, int_val); break; + case 6: CompareTableFieldValue(table, off, uint_val); break; + case 7: CompareTableFieldValue(table, off, long_val); break; + case 8: CompareTableFieldValue(table, off, ulong_val); break; + case 9: CompareTableFieldValue(table, off, float_val); break; + case 10: CompareTableFieldValue(table, off, double_val); break; + } + } + } +} + +// High level stress/fuzz test: generate a big schema and +// matching json data in random combinations, then parse both, +// generate json back from the binary, and compare with the original. +void FuzzTest2() { + lcg_reset(); // Keep it deterministic. + + const int num_definitions = 30; + const int num_struct_definitions = 5; // Subset of num_definitions. + const int fields_per_definition = 15; + const int instances_per_definition = 5; + const int deprecation_rate = 10; // 1 in deprecation_rate fields will + // be deprecated. + + std::string schema = "namespace test;\n\n"; + + struct RndDef { + std::string instances[instances_per_definition]; + + // Since we're generating schema and corresponding data in tandem, + // this convenience function adds strings to both at once. + static void Add(RndDef (&definitions_l)[num_definitions], + std::string &schema_l, const int instances_per_definition_l, + const char *schema_add, const char *instance_add, + int definition) { + schema_l += schema_add; + for (int i = 0; i < instances_per_definition_l; i++) + definitions_l[definition].instances[i] += instance_add; + } + }; + + // clang-format off + #define AddToSchemaAndInstances(schema_add, instance_add) \ + RndDef::Add(definitions, schema, instances_per_definition, \ + schema_add, instance_add, definition) + + #define Dummy() \ + RndDef::Add(definitions, schema, instances_per_definition, \ + "byte", "1", definition) + // clang-format on + + RndDef definitions[num_definitions]; + + // We are going to generate num_definitions, the first + // num_struct_definitions will be structs, the rest tables. For each + // generate random fields, some of which may be struct/table types + // referring to previously generated structs/tables. + // Simultanenously, we generate instances_per_definition JSON data + // definitions, which will have identical structure to the schema + // being generated. We generate multiple instances such that when creating + // hierarchy, we get some variety by picking one randomly. + for (int definition = 0; definition < num_definitions; definition++) { + std::string definition_name = "D" + flatbuffers::NumToString(definition); + + bool is_struct = definition < num_struct_definitions; + + AddToSchemaAndInstances( + ((is_struct ? "struct " : "table ") + definition_name + " {\n").c_str(), + "{\n"); + + for (int field = 0; field < fields_per_definition; field++) { + const bool is_last_field = field == fields_per_definition - 1; + + // Deprecate 1 in deprecation_rate fields. Only table fields can be + // deprecated. + // Don't deprecate the last field to avoid dangling commas in JSON. + const bool deprecated = + !is_struct && !is_last_field && (lcg_rand() % deprecation_rate == 0); + + std::string field_name = "f" + flatbuffers::NumToString(field); + AddToSchemaAndInstances((" " + field_name + ":").c_str(), + deprecated ? "" : (field_name + ": ").c_str()); + // Pick random type: + auto base_type = static_cast( + lcg_rand() % (flatbuffers::BASE_TYPE_UNION + 1)); + switch (base_type) { + case flatbuffers::BASE_TYPE_STRING: + if (is_struct) { + Dummy(); // No strings in structs. + } else { + AddToSchemaAndInstances("string", deprecated ? "" : "\"hi\""); + } + break; + case flatbuffers::BASE_TYPE_VECTOR: + if (is_struct) { + Dummy(); // No vectors in structs. + } else { + AddToSchemaAndInstances("[ubyte]", + deprecated ? "" : "[\n0,\n1,\n255\n]"); + } + break; + case flatbuffers::BASE_TYPE_NONE: + case flatbuffers::BASE_TYPE_UTYPE: + case flatbuffers::BASE_TYPE_STRUCT: + case flatbuffers::BASE_TYPE_UNION: + if (definition) { + // Pick a random previous definition and random data instance of + // that definition. + int defref = lcg_rand() % definition; + int instance = lcg_rand() % instances_per_definition; + AddToSchemaAndInstances( + ("D" + flatbuffers::NumToString(defref)).c_str(), + deprecated ? "" + : definitions[defref].instances[instance].c_str()); + } else { + // If this is the first definition, we have no definition we can + // refer to. + Dummy(); + } + break; + case flatbuffers::BASE_TYPE_BOOL: + AddToSchemaAndInstances( + "bool", deprecated ? "" : (lcg_rand() % 2 ? "true" : "false")); + break; + case flatbuffers::BASE_TYPE_ARRAY: + if (!is_struct) { + AddToSchemaAndInstances( + "ubyte", + deprecated ? "" : "255"); // No fixed-length arrays in tables. + } else { + AddToSchemaAndInstances("[int:3]", deprecated ? "" : "[\n,\n,\n]"); + } + break; + default: + // All the scalar types. + schema += flatbuffers::TypeName(base_type); + + if (!deprecated) { + // We want each instance to use its own random value. + for (int inst = 0; inst < instances_per_definition; inst++) + definitions[definition].instances[inst] += + flatbuffers::IsFloat(base_type) + ? flatbuffers::NumToString(lcg_rand() % 128) + .c_str() + : flatbuffers::NumToString(lcg_rand() % 128).c_str(); + } + } + AddToSchemaAndInstances(deprecated ? "(deprecated);\n" : ";\n", + deprecated ? "" + : is_last_field ? "\n" + : ",\n"); + } + AddToSchemaAndInstances("}\n\n", "}"); + } + + schema += "root_type D" + flatbuffers::NumToString(num_definitions - 1); + schema += ";\n"; + + flatbuffers::Parser parser; + + // Will not compare against the original if we don't write defaults + parser.builder_.ForceDefaults(true); + + // Parse the schema, parse the generated data, then generate text back + // from the binary and compare against the original. + TEST_EQ(parser.Parse(schema.c_str()), true); + + const std::string &json = + definitions[num_definitions - 1].instances[0] + "\n"; + + TEST_EQ(parser.Parse(json.c_str()), true); + + std::string jsongen; + parser.opts.indent_step = 0; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_NULL(result); + + if (jsongen != json) { + // These strings are larger than a megabyte, so we show the bytes around + // the first bytes that are different rather than the whole string. + size_t len = std::min(json.length(), jsongen.length()); + for (size_t i = 0; i < len; i++) { + if (json[i] != jsongen[i]) { + i -= std::min(static_cast(10), i); // show some context; + size_t end = std::min(len, i + 20); + for (; i < end; i++) + TEST_OUTPUT_LINE("at %d: found \"%c\", expected \"%c\"\n", + static_cast(i), jsongen[i], json[i]); + break; + } + } + TEST_NOTNULL(nullptr); //-V501 (this comment suppresses CWE-570 warning) + } + + // clang-format off + #ifdef FLATBUFFERS_TEST_VERBOSE + TEST_OUTPUT_LINE("%dk schema tested with %dk of json\n", + static_cast(schema.length() / 1024), + static_cast(json.length() / 1024)); + #endif + // clang-format on +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/fuzz_test.h b/third_party/flatbuffers/tests/fuzz_test.h new file mode 100644 index 00000000000..370812823cb --- /dev/null +++ b/third_party/flatbuffers/tests/fuzz_test.h @@ -0,0 +1,13 @@ +#ifndef TESTS_FUZZ_TEST_H +#define TESTS_FUZZ_TEST_H + +namespace flatbuffers { +namespace tests { + +void FuzzTest1(); +void FuzzTest2(); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/fuzzer/.gitignore b/third_party/flatbuffers/tests/fuzzer/.gitignore new file mode 100644 index 00000000000..720146cf4bf --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/.gitignore @@ -0,0 +1,20 @@ +# The generated fuzzers +*_fuzzer + +# Findings from the fuzzers +oom-* +slow-unit-* +crash-* + +# Individual fuzzer logs if job=N +fuzz-*.log + +.clangd/ + +# These are copied from tests/annotated_binary/ and should use the latest ones. +annotated_binary.bfbs +annotated_binary.bin + +test_64bit.bin + +monster_test.bfbs \ No newline at end of file diff --git a/third_party/flatbuffers/tests/fuzzer/CMakeLists.txt b/third_party/flatbuffers/tests/fuzzer/CMakeLists.txt new file mode 100644 index 00000000000..b0c4ae6d6be --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/CMakeLists.txt @@ -0,0 +1,234 @@ +cmake_minimum_required(VERSION 3.9) + +set(CMAKE_VERBOSE_MAKEFILE ON) +set(CMAKE_EXPORT_COMPILE_COMMANDS ON) +set(CMAKE_POSITION_INDEPENDENT_CODE ON) + +project(FlatBuffersFuzzerTests) + +option(BUILD_DEBUGGER "Compile a debugger with main() and without libFuzzer" OFF) + +if(NOT DEFINED FLATBUFFERS_MAX_PARSING_DEPTH) + # Force checking of RecursionError in the test + set(FLATBUFFERS_MAX_PARSING_DEPTH 24) +endif() +message(STATUS "FLATBUFFERS_MAX_PARSING_DEPTH: ${FLATBUFFERS_MAX_PARSING_DEPTH}") + +# Usage '-fsanitize=address' doesn't allowed with '-fsanitize=memory'. +# MemorySanitizer will not work out-of-the-box, and will instead report false +# positives coming from uninstrumented code. Need to re-build both C++ standard +# library: https://github.com/google/sanitizers/wiki/MemorySanitizerLibcxxHowTo +option(USE_ASAN "Use fuzzers with ASASN" OFF) +option(USE_MSAN "Use fuzzers with MSASN" OFF) +option(OSS_FUZZ "Set this option to use flags by oss-fuzz" OFF) + +# Use Clang linker. +set(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -fuse-ld=lld") + +# add_link_options(-stdlib=libc++) + +add_compile_options( + # -stdlib=libc++ # Use Clang libc++ instead of GNU. + -std=c++17 + -Wall + -pedantic + -Werror + -Wextra + -Wno-unused-parameter + -fsigned-char + -fno-omit-frame-pointer + -g # Generate source-level debug information + # -flto # enable link-time optimisation +) + +# https://llvm.org/docs/Passes.html save IR to see call graph make one bitcode +# file:> llvm-link *.bc -o out.bc print call-graph:> opt out.bc -analyze -print- +# callgraph &> callgraph.txt set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -save-temps +# -flto") + +# A special target with fuzzer+sanitizer flags. +add_library(fuzzer_config INTERFACE) + +target_compile_options( + fuzzer_config + INTERFACE + $<$>: + -fsanitize-coverage=trace-cmp + > + $<$: + -fsanitize=fuzzer,undefined,address + > + $<$: + -fsanitize=fuzzer,undefined,memory + -fsanitize-memory-track-origins=2 + > + $<$: + ${CXX} + ${CXXFLAGS} + > +) + +target_link_libraries( + fuzzer_config + INTERFACE + $<$: + -fsanitize=fuzzer,undefined,address + > + $<$: + -fsanitize=fuzzer,undefined,memory + > + $<$: + $ENV{LIB_FUZZING_ENGINE} + > +) + +set(FLATBUFFERS_DIR "${CMAKE_CURRENT_SOURCE_DIR}/../../") + +set(FlatBuffers_Library_SRCS + ${FLATBUFFERS_DIR}/include/flatbuffers/allocator.h + ${FLATBUFFERS_DIR}/include/flatbuffers/array.h + ${FLATBUFFERS_DIR}/include/flatbuffers/base.h + ${FLATBUFFERS_DIR}/include/flatbuffers/buffer.h + ${FLATBUFFERS_DIR}/include/flatbuffers/buffer_ref.h + ${FLATBUFFERS_DIR}/include/flatbuffers/default_allocator.h + ${FLATBUFFERS_DIR}/include/flatbuffers/detached_buffer.h + ${FLATBUFFERS_DIR}/include/flatbuffers/flatbuffer_builder.h + ${FLATBUFFERS_DIR}/include/flatbuffers/flatbuffers.h + ${FLATBUFFERS_DIR}/include/flatbuffers/flexbuffers.h + ${FLATBUFFERS_DIR}/include/flatbuffers/flex_flat_util.h + ${FLATBUFFERS_DIR}/include/flatbuffers/hash.h + ${FLATBUFFERS_DIR}/include/flatbuffers/idl.h + ${FLATBUFFERS_DIR}/include/flatbuffers/minireflect.h + ${FLATBUFFERS_DIR}/include/flatbuffers/reflection.h + ${FLATBUFFERS_DIR}/include/flatbuffers/reflection_generated.h + ${FLATBUFFERS_DIR}/include/flatbuffers/registry.h + ${FLATBUFFERS_DIR}/include/flatbuffers/stl_emulation.h + ${FLATBUFFERS_DIR}/include/flatbuffers/string.h + ${FLATBUFFERS_DIR}/include/flatbuffers/struct.h + ${FLATBUFFERS_DIR}/include/flatbuffers/table.h + ${FLATBUFFERS_DIR}/include/flatbuffers/util.h + ${FLATBUFFERS_DIR}/include/flatbuffers/vector.h + ${FLATBUFFERS_DIR}/include/flatbuffers/vector_downward.h + ${FLATBUFFERS_DIR}/include/flatbuffers/verifier.h + ${FLATBUFFERS_DIR}/src/idl_parser.cpp + ${FLATBUFFERS_DIR}/src/idl_gen_text.cpp + ${FLATBUFFERS_DIR}/src/reflection.cpp + ${FLATBUFFERS_DIR}/src/binary_annotator.h + ${FLATBUFFERS_DIR}/src/binary_annotator.cpp + ${FLATBUFFERS_DIR}/src/util.cpp + ${FLATBUFFERS_DIR}/tests/test_assert.cpp + ${FLATBUFFERS_DIR}/tests/64bit/test_64bit_bfbs_generated.h +) + +include_directories(${FLATBUFFERS_DIR}/include) +include_directories(${FLATBUFFERS_DIR}/tests) +include_directories(${FLATBUFFERS_DIR}/src) + +add_library(flatbuffers_fuzzed STATIC ${FlatBuffers_Library_SRCS}) +# Use PUBLIC to force 'fuzzer_config' for all dependent targets +target_link_libraries(flatbuffers_fuzzed PUBLIC fuzzer_config) + +# FLATBUFFERS_ASSERT should assert in Release as well. Redefine +# FLATBUFFERS_ASSERT macro definition. Declare as PUBLIC to cover asserts in all +# included header files. +target_compile_definitions( + flatbuffers_fuzzed + PUBLIC + FLATBUFFERS_ASSERT=fuzzer_assert_impl + FLATBUFFERS_ASSERT_INCLUDE="${CMAKE_CURRENT_SOURCE_DIR}/fuzzer_assert.h" + PRIVATE + FLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH} +) + +# Setup fuzzer tests. + +add_executable(scalar_fuzzer flatbuffers_scalar_fuzzer.cc) +target_link_libraries(scalar_fuzzer PRIVATE flatbuffers_fuzzed) + +add_executable(parser_fuzzer flatbuffers_parser_fuzzer.cc) +target_link_libraries(parser_fuzzer PRIVATE flatbuffers_fuzzed) + +add_executable(verifier_fuzzer flatbuffers_verifier_fuzzer.cc) +target_link_libraries(verifier_fuzzer PRIVATE flatbuffers_fuzzed) + +add_executable(flexverifier_fuzzer flexbuffers_verifier_fuzzer.cc) +target_link_libraries(flexverifier_fuzzer PRIVATE flatbuffers_fuzzed) + +add_executable(monster_fuzzer flatbuffers_monster_fuzzer.cc) +target_link_libraries(monster_fuzzer PRIVATE flatbuffers_fuzzed) +add_custom_command( + TARGET monster_fuzzer PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_SOURCE_DIR}/../monster_test.bfbs + ${CMAKE_CURRENT_BINARY_DIR}/monster_test.bfbs) + +add_executable(annotator_fuzzer flatbuffers_annotator_fuzzer.cc) +target_link_libraries(annotator_fuzzer PRIVATE flatbuffers_fuzzed) +add_custom_command( + TARGET annotator_fuzzer PRE_BUILD + + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_SOURCE_DIR}/../annotated_binary/annotated_binary.bfbs + ${CMAKE_CURRENT_BINARY_DIR}/annotated_binary.bfbs + + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_SOURCE_DIR}/../annotated_binary/annotated_binary.bin + ${CMAKE_CURRENT_BINARY_DIR}/seed_annotator/annotated_binary.bin +) + +add_executable(64bit_fuzzer flatbuffers_64bit_fuzzer.cc) +target_link_libraries(64bit_fuzzer PRIVATE flatbuffers_fuzzed) +add_custom_command( + TARGET 64bit_fuzzer PRE_BUILD + + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_SOURCE_DIR}/../64bit/test_64bit.bin + ${CMAKE_CURRENT_BINARY_DIR}/seed_64bit/test_64bit.bin +) + +# Build debugger for weird cases found with fuzzer. +if(BUILD_DEBUGGER) + add_library(flatbuffers_nonfuzz STATIC ${FlatBuffers_Library_SRCS}) + target_compile_options( + flatbuffers_nonfuzz + PUBLIC + $<$: + -fsanitize=undefined,address + > + -fno-limit-debug-info + ) + + target_link_libraries( + flatbuffers_nonfuzz + PUBLIC + $<$: + -fsanitize=undefined,address + > + ) + + target_compile_definitions( + flatbuffers_nonfuzz + PUBLIC + FLATBUFFERS_ASSERT=fuzzer_assert_impl + FLATBUFFERS_ASSERT_INCLUDE="${CMAKE_CURRENT_SOURCE_DIR}/fuzzer_assert.h" + PRIVATE + FLATBUFFERS_MAX_PARSING_DEPTH=${FLATBUFFERS_MAX_PARSING_DEPTH} + ) + add_executable(scalar_debug + flatbuffers_scalar_fuzzer.cc + scalar_debug.cpp + ) + target_link_libraries(scalar_debug PRIVATE flatbuffers_nonfuzz) + + add_executable(monster_debug + flatbuffers_monster_fuzzer.cc + monster_debug.cpp + ) + target_link_libraries(monster_debug PRIVATE flatbuffers_nonfuzz) + add_custom_command( + TARGET monster_debug PRE_BUILD + COMMAND ${CMAKE_COMMAND} -E copy + ${CMAKE_SOURCE_DIR}/../monster_test.bfbs + ${CMAKE_CURRENT_BINARY_DIR}/monster_test.bfbs) + +endif(BUILD_DEBUGGER) diff --git a/third_party/flatbuffers/tests/fuzzer/flatbuffers_64bit_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flatbuffers_64bit_fuzzer.cc new file mode 100644 index 00000000000..efb629d3caf --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flatbuffers_64bit_fuzzer.cc @@ -0,0 +1,121 @@ +#include +#include +#include + +#include "64bit/test_64bit_bfbs_generated.h" +#include "64bit/test_64bit_generated.h" +#include "flatbuffers/base.h" +#include "flatbuffers/flatbuffer_builder.h" +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/reflection.h" +#include "flatbuffers/verifier.h" +#include "test_assert.h" +#include "test_init.h" + +OneTimeTestInit OneTimeTestInit::one_time_init_; + +static RootTableBinarySchema schema; + +static constexpr uint8_t flags_sized_prefixed = 0b00000001; + +static const uint64_t kFnvPrime = 0x00000100000001b3ULL; +static const uint64_t kOffsetBasis = 0xcbf29ce484222645ULL; + +namespace flatbuffers { + +template>> +uint64_t Hash(T value, uint64_t hash) { + return (hash * kFnvPrime) ^ value; +} + +uint64_t Hash(double value, uint64_t hash) { + static_assert(sizeof(double) == sizeof(uint64_t)); + return (hash * kFnvPrime) ^ static_cast(value); +} + +uint64_t Hash(const flatbuffers::String *value, uint64_t hash) { + if (value == nullptr) { return hash * kFnvPrime; } + for (auto &c : value->str()) { hash = Hash(static_cast(c), hash); } + return hash; +} + +uint64_t Hash(const LeafStruct *value, uint64_t hash) { + if (value == nullptr) { return hash * kFnvPrime; } + hash = Hash(value->a(), hash); + hash = Hash(value->b(), hash); + return hash; +} + +template uint64_t Hash(const Vector *value, uint64_t hash) { + if (value == nullptr) { return hash * kFnvPrime; } + for (const T c : *value) { hash = Hash(c, hash); } + return hash; +} + +template uint64_t Hash(const Vector64 *value, uint64_t hash) { + if (value == nullptr) { return hash * kFnvPrime; } + for (const T c : *value) { hash = Hash(c, hash); } + return hash; +} + +uint64_t Hash(const RootTable *value, uint64_t hash) { + if (value == nullptr) { return hash * kFnvPrime; } + // Hash all the fields so we can exercise all parts of the code. + hash = Hash(value->far_vector(), hash); + hash = Hash(value->a(), hash); + hash = Hash(value->far_string(), hash); + hash = Hash(value->big_vector(), hash); + hash = Hash(value->near_string(), hash); + hash = Hash(value->nested_root(), hash); + hash = Hash(value->far_struct_vector(), hash); + hash = Hash(value->big_struct_vector(), hash); + return hash; +} + +static int AccessBuffer(const uint8_t *data, size_t size, + bool is_size_prefixed) { + const RootTable *root_table = + is_size_prefixed ? GetSizePrefixedRootTable(data) : GetRootTable(data); + TEST_NOTNULL(root_table); + + uint64_t hash = kOffsetBasis; + hash = Hash(root_table, hash); + hash = Hash(root_table->nested_root_nested_root(), hash); + + return 0; +} + +extern "C" int LLVMFuzzerInitialize(int *, char ***argv) { + Verifier verifier(schema.begin(), schema.size()); + TEST_EQ(true, reflection::VerifySchemaBuffer(verifier)); + + return 0; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + if (size < FLATBUFFERS_MIN_BUFFER_SIZE) { return 0; } + + // Take the first bit of data as a flag to control things. + const uint8_t flags = data[0]; + data++; + size--; + + Verifier::Options options; + options.assert = true; + options.check_alignment = true; + options.check_nested_flatbuffers = true; + + Verifier verifier(data, size, options); + + const bool is_size_prefixed = flags & flags_sized_prefixed; + + // Filter out data that isn't valid. + if ((is_size_prefixed && !VerifySizePrefixedRootTableBuffer(verifier)) || + !VerifyRootTableBuffer(verifier)) { + return 0; + } + + return AccessBuffer(data, size, is_size_prefixed); +} + +} // namespace flatbuffers \ No newline at end of file diff --git a/third_party/flatbuffers/tests/fuzzer/flatbuffers_annotator_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flatbuffers_annotator_fuzzer.cc new file mode 100644 index 00000000000..08c1e0bcec9 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flatbuffers_annotator_fuzzer.cc @@ -0,0 +1,53 @@ + +#include +#include + +#include "binary_annotator.h" +#include "test_init.h" + +static std::filesystem::path exe_path_; +static const uint8_t *schema_bfbs_; +static size_t schema_bfbs_length_; + +bool TestFileExists(std::filesystem::path file_path) { + if (file_path.has_filename() && std::filesystem::exists(file_path)) + return true; + + TEST_OUTPUT_LINE("@DEBUG: file '%s' not found", file_path.string().c_str()); + for (const auto &entry : + std::filesystem::directory_iterator(file_path.parent_path())) { + TEST_OUTPUT_LINE("@DEBUG: parent path entry: '%s'", + entry.path().string().c_str()); + } + return false; +} + +std::string LoadBinarySchema(const char *file_name) { + const auto file_path = exe_path_.parent_path() / file_name; + TEST_EQ(true, TestFileExists(file_path)); + std::string schemafile; + TEST_EQ(true, + flatbuffers::LoadFile(file_path.string().c_str(), true, &schemafile)); + + flatbuffers::Verifier verifier( + reinterpret_cast(schemafile.c_str()), schemafile.size()); + TEST_EQ(true, reflection::VerifySchemaBuffer(verifier)); + return schemafile; +} + +extern "C" int LLVMFuzzerInitialize(int *, char ***argv) { + exe_path_ = (*argv)[0]; + static const std::string schema_file = + LoadBinarySchema("annotated_binary.bfbs"); + schema_bfbs_ = reinterpret_cast(schema_file.c_str()); + schema_bfbs_length_ = schema_file.size(); + return 0; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + flatbuffers::BinaryAnnotator annotator(schema_bfbs_, schema_bfbs_length_, + data, size, false); + + annotator.Annotate(); + return 0; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/fuzzer/flatbuffers_monster_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flatbuffers_monster_fuzzer.cc new file mode 100644 index 00000000000..71a6802789f --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flatbuffers_monster_fuzzer.cc @@ -0,0 +1,144 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include + +#include +#include +#include + +#include "cpp17/generated_cpp17/monster_test_generated.h" +#include "flatbuffers/idl.h" +#include "test_assert.h" +#include "test_init.h" + +namespace fs = std::filesystem; + +// Utility for test run. +OneTimeTestInit OneTimeTestInit::one_time_init_; +// The current executable path (see LLVMFuzzerInitialize). +static fs::path exe_path_; + +static flatbuffers::Parser parser_; + +namespace { + +static constexpr size_t kMinInputLength = 1; +static constexpr size_t kMaxInputLength = 16384; + +static constexpr uint8_t flags_strict_json = 0x80; +static constexpr uint8_t flags_skip_unexpected_fields_in_json = 0x40; +static constexpr uint8_t flags_allow_non_utf8 = 0x20; + +bool TestFileExists(fs::path file_path) { + if (file_path.has_filename() && fs::exists(file_path)) return true; + + TEST_OUTPUT_LINE("@DEBUG: file '%s' not found", file_path.string().c_str()); + for (const auto &entry : fs::directory_iterator(file_path.parent_path())) { + TEST_OUTPUT_LINE("@DEBUG: parent path entry: '%s'", + entry.path().string().c_str()); + } + return false; +} + +std::string LoadBinarySchema(const char *file_name) { + const auto file_path = exe_path_.parent_path() / file_name; + TEST_EQ(true, TestFileExists(file_path)); + std::string schemafile; + TEST_EQ(true, + flatbuffers::LoadFile(file_path.string().c_str(), true, &schemafile)); + + flatbuffers::Verifier verifier( + reinterpret_cast(schemafile.c_str()), schemafile.size()); + TEST_EQ(true, reflection::VerifySchemaBuffer(verifier)); + return schemafile; +} + +std::string do_test(const flatbuffers::IDLOptions &opts, + const std::string input_json, const bool check_parser) { + // (re)define parser options + parser_.opts = opts; + + std::string jsongen; + if (parser_.ParseJson(input_json.c_str())) { + flatbuffers::Verifier verifier(parser_.builder_.GetBufferPointer(), + parser_.builder_.GetSize()); + TEST_EQ(true, MyGame::Example::VerifyMonsterBuffer(verifier)); + TEST_NULL( + GenText(parser_, parser_.builder_.GetBufferPointer(), &jsongen)); + } else if (check_parser) { + TEST_OUTPUT_LINE("parser failed with JSON:\n%s", input_json.c_str()); + TEST_EQ_STR("", parser_.error_.c_str()); + TEST_ASSERT(false); + } + return jsongen; +}; +} // namespace + +// https://google.github.io/oss-fuzz/further-reading/fuzzer-environment/ +// Current working directory +// You should not make any assumptions about the current working directory of +// your fuzz target. If you need to load data files, please use argv[0] to get +// the directory where your fuzz target executable is located. +// You must not modify argv[0]. +extern "C" int LLVMFuzzerInitialize(int *argc, char ***argv) { + (void)argc; + exe_path_ = (*argv)[0]; + + static const std::string schemafile = LoadBinarySchema("monster_test.bfbs"); + // parse schema first, so we can use it to parse the data after + parser_.Deserialize(reinterpret_cast(schemafile.c_str()), + schemafile.size()); + return 0; +} + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + // Reserve one byte for Parser flags and one byte for repetition counter. + if (size < 3) return 0; + const uint8_t flags = data[0]; + (void)data[1]; // reserved + data += 2; + size -= 2; // bypass + + const std::string original(reinterpret_cast(data), size); + auto input = std::string(original.c_str()); // until '\0' + if (input.size() < kMinInputLength || input.size() > kMaxInputLength) + return 0; + + flatbuffers::IDLOptions opts; + opts.strict_json = (flags & flags_strict_json); + opts.skip_unexpected_fields_in_json = + (flags & flags_skip_unexpected_fields_in_json); + opts.allow_non_utf8 = (flags & flags_allow_non_utf8); + + do { + const std::string jsongen_1 = do_test(opts, input, false); + if (!jsongen_1.empty()) { + const std::string jsongen_2 = do_test(opts, jsongen_1, true); + if (jsongen_1 != jsongen_2 && !opts.output_default_scalars_in_json) { + // This gets tricky when the jsongen_1 includes a default-value, as the + // generated jsongen_2 doesn't emit default-values. So enable default + // scalars and re-run it. + opts.output_default_scalars_in_json = true; + continue; + } + TEST_EQ(jsongen_1, jsongen_2); + } + } while (0); + + return 0; +} diff --git a/third_party/flatbuffers/tests/fuzzer/flatbuffers_parser_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flatbuffers_parser_fuzzer.cc new file mode 100644 index 00000000000..0b74f2ceb14 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flatbuffers_parser_fuzzer.cc @@ -0,0 +1,55 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include +#include +#include +#include + +#include "flatbuffers/idl.h" +#include "test_init.h" + +static constexpr size_t kMinInputLength = 1; +static constexpr size_t kMaxInputLength = 16384; + +static constexpr uint8_t flags_strict_json = 0x80; +static constexpr uint8_t flags_skip_unexpected_fields_in_json = 0x40; +static constexpr uint8_t flags_allow_non_utf8 = 0x20; + +// Utility for test run. +OneTimeTestInit OneTimeTestInit::one_time_init_; + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + // Reserve one byte for Parser flags and one byte for repetition counter. + if (size < 3) return 0; + const uint8_t flags = data[0]; + (void)data[1]; // reserved + data += 2; + size -= 2; // bypass + + const std::string original(reinterpret_cast(data), size); + auto input = std::string(original.c_str()); // until '\0' + if (input.size() < kMinInputLength || input.size() > kMaxInputLength) + return 0; + + flatbuffers::IDLOptions opts; + opts.strict_json = (flags & flags_strict_json); + opts.skip_unexpected_fields_in_json = + (flags & flags_skip_unexpected_fields_in_json); + opts.allow_non_utf8 = (flags & flags_allow_non_utf8); + + flatbuffers::Parser parser(opts); + + // Guarantee 0-termination in the input. + auto parse_input = input.c_str(); + + // Check Parser. + parser.Parse(parse_input); + // TODO: + // Need to add additional checks for inputs passed Parse(parse_input) successfully: + // 1. Serialization to bfbs. + // 2. Generation of a default object. + // 3. Verification of the object using reflection. + // 3. Printing to json. + return 0; +} diff --git a/third_party/flatbuffers/tests/fuzzer/flatbuffers_scalar_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flatbuffers_scalar_fuzzer.cc new file mode 100644 index 00000000000..cd43506f511 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flatbuffers_scalar_fuzzer.cc @@ -0,0 +1,375 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include +#include +#include + +#include +#include +#include +#include +#include + +#include "flatbuffers/idl.h" +#include "test_init.h" + +static constexpr size_t kMinInputLength = 1; +static constexpr size_t kMaxInputLength = 3000; + +static constexpr uint8_t flags_scalar_type = 0x0F; // type of scalar value +static constexpr uint8_t flags_quotes_kind = 0x10; // quote " or ' +// reserved for future: json {named} or [unnamed] +// static constexpr uint8_t flags_json_bracer = 0x20; + +// Find all 'subj' sub-strings and replace first character of sub-string. +// BreakSequence("testest","tes", 'X') -> "XesXest". +// BreakSequence("xxx","xx", 'Y') -> "YYx". +static void BreakSequence(std::string &s, const char *subj, char repl) { + size_t pos = 0; + while (pos = s.find(subj, pos), pos != std::string::npos) { + s.at(pos) = repl; + pos++; + } +} + +// Remove all leading and trailing symbols matched with pattern set. +// StripString("xy{xy}y", "xy") -> "{xy}" +static std::string StripString(const std::string &s, const char *pattern, + size_t *pos = nullptr) { + if (pos) *pos = 0; + // leading + auto first = s.find_first_not_of(pattern); + if (std::string::npos == first) return ""; + if (pos) *pos = first; + // trailing + auto last = s.find_last_not_of(pattern); + assert(last < s.length()); + assert(first <= last); + return s.substr(first, last - first + 1); +} + +class RegexMatcher { + protected: + virtual bool MatchNumber(const std::string &input) const = 0; + + public: + virtual ~RegexMatcher() = default; + + struct MatchResult { + size_t pos{ 0 }; + size_t len{ 0 }; + bool res{ false }; + bool quoted{ false }; + }; + + MatchResult Match(const std::string &input) const { + MatchResult r; + // strip leading and trailing "spaces" accepted by flatbuffer + auto test = StripString(input, "\t\r\n ", &r.pos); + r.len = test.size(); + // check quotes + if (test.size() >= 2) { + auto fch = test.front(); + auto lch = test.back(); + r.quoted = (fch == lch) && (fch == '\'' || fch == '\"'); + if (r.quoted) { + // remove quotes for regex test + test = test.substr(1, test.size() - 2); + } + } + // Fast check: + if (test.empty()) return r; + // A string with a valid scalar shouldn't have non-ascii or non-printable + // symbols. + for (auto c : test) { + if ((c < ' ') || (c > '~')) return r; + } + // Check with regex + r.res = MatchNumber(test); + return r; + } + + bool MatchRegexList(const std::string &input, + const std::vector &re_list) const { + auto str = StripString(input, " "); + if (str.empty()) return false; + for (auto &re : re_list) { + std::smatch match; + if (std::regex_match(str, match, re)) return true; + } + return false; + } +}; + +class IntegerRegex : public RegexMatcher { + protected: + bool MatchNumber(const std::string &input) const override { + static const std::vector re_list = { + std::regex{ R"(^[-+]?[0-9]+$)", std::regex_constants::optimize }, + + std::regex{ R"(^[-+]?0[xX][0-9a-fA-F]+$)", + std::regex_constants::optimize } + }; + return MatchRegexList(input, re_list); + } + + public: + IntegerRegex() = default; + virtual ~IntegerRegex() = default; +}; + +class UIntegerRegex : public RegexMatcher { + protected: + bool MatchNumber(const std::string &input) const override { + static const std::vector re_list = { + std::regex{ R"(^[+]?[0-9]+$)", std::regex_constants::optimize }, + std::regex{ R"(^[+]?0[xX][0-9a-fA-F]+$)", + std::regex_constants::optimize }, + // accept -0 number + std::regex{ R"(^[-](?:0[xX])?0+$)", std::regex_constants::optimize } + }; + return MatchRegexList(input, re_list); + } + + public: + UIntegerRegex() = default; + virtual ~UIntegerRegex() = default; +}; + +class BooleanRegex : public IntegerRegex { + protected: + bool MatchNumber(const std::string &input) const override { + if (input == "true" || input == "false") return true; + return IntegerRegex::MatchNumber(input); + } + + public: + BooleanRegex() = default; + virtual ~BooleanRegex() = default; +}; + +class FloatRegex : public RegexMatcher { + protected: + bool MatchNumber(const std::string &input) const override { + static const std::vector re_list = { + // hex-float + std::regex{ + R"(^[-+]?0[xX](?:(?:[.][0-9a-fA-F]+)|(?:[0-9a-fA-F]+[.][0-9a-fA-F]*)|(?:[0-9a-fA-F]+))[pP][-+]?[0-9]+$)", + std::regex_constants::optimize }, + // dec-float + std::regex{ + R"(^[-+]?(?:(?:[.][0-9]+)|(?:[0-9]+[.][0-9]*)|(?:[0-9]+))(?:[eE][-+]?[0-9]+)?$)", + std::regex_constants::optimize }, + + std::regex{ R"(^[-+]?(?:nan|inf|infinity)$)", + std::regex_constants::optimize | std::regex_constants::icase } + }; + return MatchRegexList(input, re_list); + } + + public: + FloatRegex() = default; + virtual ~FloatRegex() = default; +}; + +class ScalarReferenceResult { + private: + ScalarReferenceResult(const char *_type, RegexMatcher::MatchResult _matched) + : type(_type), matched(_matched) {} + + public: + // Decode scalar type and check if the input string satisfies the scalar type. + static ScalarReferenceResult Check(uint8_t code, const std::string &input) { + switch (code) { + case 0x0: return { "double", FloatRegex().Match(input) }; + case 0x1: return { "float", FloatRegex().Match(input) }; + case 0x2: return { "int8", IntegerRegex().Match(input) }; + case 0x3: return { "int16", IntegerRegex().Match(input) }; + case 0x4: return { "int32", IntegerRegex().Match(input) }; + case 0x5: return { "int64", IntegerRegex().Match(input) }; + case 0x6: return { "uint8", UIntegerRegex().Match(input) }; + case 0x7: return { "uint16", UIntegerRegex().Match(input) }; + case 0x8: return { "uint32", UIntegerRegex().Match(input) }; + case 0x9: return { "uint64", UIntegerRegex().Match(input) }; + case 0xA: return { "bool", BooleanRegex().Match(input) }; + default: return { "float", FloatRegex().Match(input) }; + }; + } + + const char *type; + const RegexMatcher::MatchResult matched; +}; + +bool Parse(flatbuffers::Parser &parser, const std::string &json, + std::string *_text) { + auto done = parser.ParseJson(json.c_str()); + if (done) { + TEST_NULL(GenText(parser, parser.builder_.GetBufferPointer(), _text)); + } else { + *_text = parser.error_; + } + return done; +} + +// Utility for test run. +OneTimeTestInit OneTimeTestInit::one_time_init_; + +// llvm std::regex have problem with stack overflow, limit maximum length. +// ./scalar_fuzzer -max_len=3000 +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size) { + // Reserve one byte for Parser flags and one byte for repetition counter. + if (size < 3) return 0; + const uint8_t flags = data[0]; + // normalize to ascii alphabet + const int extra_rep_number = + std::max(5, (data[1] > '0' ? (data[1] - '0') : 0)); + data += 2; + size -= 2; // bypass + + // Guarantee 0-termination. + const std::string original(reinterpret_cast(data), size); + auto input = std::string(original.c_str()); // until '\0' + if (input.size() < kMinInputLength || input.size() > kMaxInputLength) + return 0; + + // Break comments in json to avoid complexity with regex matcher. + // The string " 12345 /* text */" will be accepted if insert it to string + // expression: "table X { Y: " + " 12345 /* text */" + "; }. + // But strings like this will complicate regex matcher. + // We reject this by transform "/* text */ 12345" to "@* text */ 12345". + BreakSequence(input, "//", '@'); // "//" -> "@/" + BreakSequence(input, "/*", '@'); // "/*" -> "@*" + // { "$schema: "text" } is exceptional case. + // This key:value ignored by the parser. Numbers can not have $. + BreakSequence(input, "$schema", '@'); // "$schema" -> "@schema" + // Break all known scalar functions (todo: add them to regex?): + for (auto f : { "deg", "rad", "sin", "cos", "tan", "asin", "acos", "atan" }) { + BreakSequence(input, f, '_'); // ident -> ident + } + + // Extract type of scalar from 'flags' and check if the input string satisfies + // the scalar type. + const auto ref_res = + ScalarReferenceResult::Check(flags & flags_scalar_type, input); + auto &recheck = ref_res.matched; + + // Create parser + flatbuffers::IDLOptions opts; + opts.force_defaults = true; + opts.output_default_scalars_in_json = true; + opts.indent_step = -1; + opts.strict_json = true; + + flatbuffers::Parser parser(opts); + auto schema = + "table X { Y: " + std::string(ref_res.type) + "; } root_type X;"; + TEST_EQ_FUNC(parser.Parse(schema.c_str()), true); + + // The fuzzer can adjust the number repetition if a side-effects have found. + // Each test should pass at least two times to ensure that the parser doesn't + // have any hidden-states or locale-depended effects. + for (auto cnt = 0; cnt < (extra_rep_number + 2); cnt++) { + // Each even run (0,2,4..) will test locale independed code. + auto use_locale = !!OneTimeTestInit::test_locale() && (0 == (cnt % 2)); + // Set new locale. + if (use_locale) { + FLATBUFFERS_ASSERT(setlocale(LC_ALL, OneTimeTestInit::test_locale())); + } + + // Parse original input as-is. + auto orig_scalar = "{\"Y\" : " + input + "}"; + std::string orig_back; + auto orig_done = Parse(parser, orig_scalar, &orig_back); + + if (recheck.res != orig_done) { + // look for "does not fit" or "doesn't fit" or "out of range" + auto not_fit = + (true == recheck.res) + ? ((orig_back.find("does not fit") != std::string::npos) || + (orig_back.find("out of range") != std::string::npos)) + : false; + + if (false == not_fit) { + TEST_OUTPUT_LINE("Stage 1 failed: Parser(%d) != Regex(%d)", orig_done, + recheck.res); + TEST_EQ_STR(orig_back.c_str(), + input.substr(recheck.pos, recheck.len).c_str()); + TEST_EQ_FUNC(orig_done, recheck.res); + } + } + + // Try to make quoted string and test it. + std::string qouted_input; + if (true == recheck.quoted) { + // we can't simply remove quotes, they may be nested "'12'". + // Original string "\'12\'" converted to "'12'". + // The string can be an invalid string by JSON rules, but after quotes + // removed can transform to valid. + assert(recheck.len >= 2); + } else { + const auto quote = (flags & flags_quotes_kind) ? '\"' : '\''; + qouted_input = input; // copy + qouted_input.insert(recheck.pos + recheck.len, 1, quote); + qouted_input.insert(recheck.pos, 1, quote); + } + + // Test quoted version of the string + if (!qouted_input.empty()) { + auto fix_scalar = "{\"Y\" : " + qouted_input + "}"; + std::string fix_back; + auto fix_done = Parse(parser, fix_scalar, &fix_back); + + if (orig_done != fix_done) { + TEST_OUTPUT_LINE("Stage 2 failed: Parser(%d) != Regex(%d)", fix_done, + orig_done); + TEST_EQ_STR(fix_back.c_str(), orig_back.c_str()); + } + if (orig_done) { TEST_EQ_STR(fix_back.c_str(), orig_back.c_str()); } + TEST_EQ_FUNC(fix_done, orig_done); + } + + // Create new parser and test default value + if (true == orig_done) { + flatbuffers::Parser def_parser(opts); // re-use options + auto def_schema = "table X { Y: " + std::string(ref_res.type) + " = " + + input + "; } root_type X;" + + "{}"; // <- with empty json {}! + + auto def_done = def_parser.Parse(def_schema.c_str()); + if (false == def_done) { + TEST_OUTPUT_LINE("Stage 3.1 failed with _error = %s", + def_parser.error_.c_str()); + FLATBUFFERS_ASSERT(false); + } + // Compare with print. + std::string ref_string, def_string; + FLATBUFFERS_ASSERT(!GenText( + parser, parser.builder_.GetBufferPointer(), &ref_string)); + FLATBUFFERS_ASSERT(!GenText( + def_parser, def_parser.builder_.GetBufferPointer(), &def_string)); + if (ref_string != def_string) { + TEST_OUTPUT_LINE("Stage 3.2 failed: '%s' != '%s'", def_string.c_str(), + ref_string.c_str()); + FLATBUFFERS_ASSERT(false); + } + } + + // Restore locale. + if (use_locale) { FLATBUFFERS_ASSERT(setlocale(LC_ALL, "C")); } + } + return 0; +} diff --git a/third_party/flatbuffers/tests/fuzzer/flatbuffers_verifier_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flatbuffers_verifier_fuzzer.cc new file mode 100644 index 00000000000..cb32a85f258 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flatbuffers_verifier_fuzzer.cc @@ -0,0 +1,14 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include +#include +#include + +#include "cpp17/generated_cpp17/monster_test_generated.h" + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + flatbuffers::Verifier verifier(data, size); + MyGame::Example::VerifyMonsterBuffer(verifier); + return 0; +} diff --git a/third_party/flatbuffers/tests/fuzzer/flexbuffers_verifier_fuzzer.cc b/third_party/flatbuffers/tests/fuzzer/flexbuffers_verifier_fuzzer.cc new file mode 100644 index 00000000000..ad374b3121e --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/flexbuffers_verifier_fuzzer.cc @@ -0,0 +1,19 @@ +// Copyright 2015 The Chromium Authors. All rights reserved. +// Use of this source code is governed by a BSD-style license that can be +// found in the LICENSE file. +#include +#include +#include + +#include "flatbuffers/flexbuffers.h" + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t* data, size_t size) { + std::vector reuse_tracker; + // Check both with and without reuse tracker paths. + flexbuffers::VerifyBuffer(data, size, &reuse_tracker); + // FIXME: we can't really verify this path, because the fuzzer will + // construct buffers that time out. + // Add a simple #define to bound the number of steps just for the fuzzer? + //flexbuffers::VerifyBuffer(data, size, nullptr); + return 0; +} diff --git a/third_party/flatbuffers/tests/fuzzer/fuzzer_assert.h b/third_party/flatbuffers/tests/fuzzer/fuzzer_assert.h new file mode 100644 index 00000000000..41a4164e937 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/fuzzer_assert.h @@ -0,0 +1,14 @@ +#ifndef FUZZER_ASSERT_IMPL_H_ +#define FUZZER_ASSERT_IMPL_H_ + +#if defined(_MSC_VER) +extern "C" void __debugbreak(); +#define __builtin_trap __debugbreak +#else // Clang +extern "C" void __builtin_trap(void); +#endif + +// Declare Debug/Release independed assert macro. +#define fuzzer_assert_impl(x) (!!(x) ? static_cast(0) : __builtin_trap()) + +#endif // !FUZZER_ASSERT_IMPL_H_ diff --git a/third_party/flatbuffers/tests/fuzzer/monster_debug.cpp b/third_party/flatbuffers/tests/fuzzer/monster_debug.cpp new file mode 100644 index 00000000000..c7a02e128f9 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/monster_debug.cpp @@ -0,0 +1,30 @@ +#include +#include + +#include "flatbuffers/util.h" + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); + +int main(int argc, char *argv[]) { + if (argc < 2) { + std::cerr << "Usage: monster_debug \n"; + return 0; + } + std::string crash_file_name(argv[1]); + std::string crash_file_data; + auto done = + flatbuffers::LoadFile(crash_file_name.c_str(), true, &crash_file_data); + if (!done) { + std::cerr << "Can not load file: '" << crash_file_name << "'"; + return -1; + } + if (crash_file_data.size() < 3) { + std::cerr << "Invalid file data: '" << crash_file_data << "'"; + return -2; + } + auto rc = LLVMFuzzerTestOneInput( + reinterpret_cast(crash_file_data.data()), + crash_file_data.size()); + std::cout << "LLVMFuzzerTestOneInput finished with code " << rc << "\n\n"; + return rc; +} diff --git a/third_party/flatbuffers/tests/fuzzer/monster_fuzzer.dict b/third_party/flatbuffers/tests/fuzzer/monster_fuzzer.dict new file mode 100644 index 00000000000..a06e1e063e1 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/monster_fuzzer.dict @@ -0,0 +1,60 @@ +"{" +"}" +"[" +"]" +"\"" +"'" +"\\" +"//" +":" +"," +" " +"\\n" +"\\r" +"/*" +"*/" +"true" +"false" +"null" +"\\u" +"\\b" +"\\f" +"\\t" +"." +"e" +"e+" +"e-" +"E" +"E+" +"E-" +"0x" +"p" +"a" +"b" +"Monster" +"pos" +"hp" +"name" +"weapons" +"damage" +"equipped_type" +"equipped" +"inventory" +"vector_of_longs" +"vector_of_doubles" +"test_type" +"test" +"test1" +"test2" +"test4" +"test3" +"test5" +"enemy" +"Weapon" +"Green" +"Red" +"Blue" +"testarrayofstring" +"testarrayofbools" +"testbool" +"flex" diff --git a/third_party/flatbuffers/tests/fuzzer/parser_fuzzer.dict b/third_party/flatbuffers/tests/fuzzer/parser_fuzzer.dict new file mode 100644 index 00000000000..44c18da8096 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/parser_fuzzer.dict @@ -0,0 +1,101 @@ +"struct" +"table" +"enum" +"union" +"include" +"namespace" +"attribute" +"null" +"NULL" +"byte" +"int8" +"ubyte" +"uint8" +"bool" +"short" +"int16" +"ushort" +"uint16" +"int" +"int32" +"uint" +"uint32" +"float" +"float32" +"long" +"int64" +"ulong" +"uint64" +"double" +"float64" +"root_type" +"file_identifier" +"file_extension" +"{" +"}" +"[" +"]" +"\"" +"'" +"\\" +"//" +":" +"," +" " +"\\n" +"\\r" +"/*" +"*/" +"true" +"false" +"null" +"\\u" +"\\b" +"\\f" +"\\t" +"." +"e" +"e+" +"e-" +"E" +"E+" +"E-" +"0x" +"p" +"a" +"b" +"Monster" +"pos" +"hp" +"name" +"weapons" +"damage" +"equipped_type" +"equipped" +"inventory" +"vector_of_longs" +"vector_of_doubles" +"test_type" +"test" +"test1" +"test2" +"test4" +"test3" +"test5" +"enemy" +"Weapon" +"Green" +"Red" +"Blue" +"testarrayofstring" +"testarrayofbools" +"testbool" +"testhashs32_fnv1" +"testhashu32_fnv1" +"testhashs64_fnv1" +"testhashu64_fnv1" +"testhashs32_fnv1a" +"testhashu32_fnv1a" +"testhashs64_fnv1a" +"testhashu64_fnv1a" +"flex" diff --git a/third_party/flatbuffers/tests/fuzzer/readme.md b/third_party/flatbuffers/tests/fuzzer/readme.md new file mode 100644 index 00000000000..c4513012085 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/readme.md @@ -0,0 +1,79 @@ +# Test Flatbuffers library with help of libFuzzer +Test suite of Flatbuffers library has fuzzer section with tests are based on libFuzzer library. + +> LibFuzzer is in-process, coverage-guided, evolutionary fuzzing engine. +LibFuzzer is linked with the library under test, and feeds fuzzed inputs to the library via a specific fuzzing entrypoint (aka “target function”); +the fuzzer then tracks which areas of the code are reached, and generates mutations on the corpus of input data in order to maximize the code coverage. +The code coverage information for libFuzzer is provided by LLVM’s SanitizerCoverage instrumentation. + +For details about **libFuzzer** see: https://llvm.org/docs/LibFuzzer.html + +To build and run these tests LLVM compiler (with clang frontend) and CMake should be installed before. + +The fuzzer section include four tests: +- `annotator_fuzzer` checks that inputs given to the flatc --annotate are always parsable; +- `verifier_fuzzer` checks stability of deserialization engine for `Monster` schema; +- `parser_fuzzer` checks stability of schema and json parser under various inputs; +- `scalar_parser` focused on validation of the parser while parse numeric scalars in schema and/or json files; +- `flexverifier_fuzzer` checks stability of deserialization engine for FlexBuffers only; + +## Build +```sh +cd tests/fuzzer +CC=clang CXX=clang++ cmake . -DCMAKE_BUILD_TYPE=Debug -DUSE_ASAN=ON +``` + +## Run tests with a specific locale +The grammar of the Flatbuffers library is based on printable-ASCII characters. +By design, the Flatbuffers library should be independent of the global or thread locales used by an end-user application. +Set environment variable `FLATBUFFERS_TEST_LOCALE` to run a fuzzer with a specific C-locale: +```sh +>FLATBUFFERS_TEST_LOCALE="" ./scalar_parser +>FLATBUFFERS_TEST_LOCALE="ru_RU.CP1251" ./parser_fuzzer +``` + +## Run fuzzer +These are examples of running a fuzzer. +Flags may vary and depend on a version of the libFuzzer library. +For details, run a fuzzer with `-help` flag: `./parser_fuzzer -help=1` + +`./verifier_fuzzer ../.corpus_verifier/ ../.seed_verifier/` + +`./parser_fuzzer -only_ascii=1 -max_len=500 -dict=../parser_fbs.dict ../.corpus_parser/ ../.seed_parser/` + +`./monster_fuzzer -only_ascii=1 -max_len=500 -dict=../monster_json.dict ../.corpus_monster/ ../.seed_monster/` + +`./scalar_fuzzer -use_value_profile=1 -max_len=500 -dict=../scalar_json.dict ../.corpus_scalar/ ../.seed_scalar/` + +Flag `-only_ascii=1` is useful for fast number-compatibility checking while run `scalar_fuzzer`. + +Run with a specific C-locale: +`FLATBUFFERS_TEST_LOCALE="ru_RU.CP1251" ./scalar_fuzzer -reduce_depth=1 -use_value_profile=1 -shrink=1 -max_len=3000 -timeout=10 -rss_limit_mb=2048 ../.corpus_parser/ ../.seed_parser/` + + +## Merge (minimize) corpus +The **libFuzzer** allow to filter (minimize) corpus with help of `-merge` flag: +> -merge + If set to 1, any corpus inputs from the 2nd, 3rd etc. corpus directories that trigger new code coverage will be merged into the first corpus directory. + Defaults to 0. This flag can be used to minimize a corpus. + +Merge several corpuses to a seed directory (a new collected corpus to the seed collection, for example): +`./verifier_fuzzer -merge=1 ../.seed_verifier/ ../.corpus_verifier/` +`./parser_fuzzer -merge=1 ../.seed_parser/ ../.corpus_parser/` +`./monster_fuzzer -merge=1 ../.seed_monster/ ../.corpus_monster/` +`./scalar_fuzzer -merge=1 ../.seed_scalar/ ../.corpus_scalar/` + +## Know limitations +- LLVM 7.0 std::regex library has problem with stack overflow, maximum length of input for `scalar_fuzzer` run should be limited to 3000. + Example: `./scalar_fuzzer -max_len=3000` + +# Fuzzing control + +## Set timeout or memory limit + +`-timeout=10 -rss_limit_mb=2048 -jobs=4 -workers=4`. + +## Force stop on first UBSAN error + +- `export UBSAN_OPTIONS=halt_on_error=1` +- `export ASAN_OPTIONS=halt_on_error=1` diff --git a/third_party/flatbuffers/tests/fuzzer/scalar_debug.cpp b/third_party/flatbuffers/tests/fuzzer/scalar_debug.cpp new file mode 100644 index 00000000000..d0c9b40782b --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/scalar_debug.cpp @@ -0,0 +1,28 @@ +#include +#include "flatbuffers/util.h" + +extern "C" int LLVMFuzzerTestOneInput(const uint8_t *data, size_t size); + +int main(int argc, char *argv[]) { + if (argc < 2) { + std::cerr << "Usage: scalar_debug \n"; + return 0; + } + std::string crash_file_name(argv[1]); + std::string crash_file_data; + auto done = + flatbuffers::LoadFile(crash_file_name.c_str(), true, &crash_file_data); + if (!done) { + std::cerr << "Can not load file: '" << crash_file_name << "'"; + return -1; + } + if (crash_file_data.size() < 3) { + std::cerr << "Invalid file data: '" << crash_file_data << "'"; + return -2; + } + auto rc = LLVMFuzzerTestOneInput( + reinterpret_cast(crash_file_data.data()), + crash_file_data.size()); + std::cout << "LLVMFuzzerTestOneInput finished with code " << rc << "\n\n"; + return rc; +} diff --git a/third_party/flatbuffers/tests/fuzzer/scalar_fuzzer.dict b/third_party/flatbuffers/tests/fuzzer/scalar_fuzzer.dict new file mode 100644 index 00000000000..3b2fbc84640 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/scalar_fuzzer.dict @@ -0,0 +1,37 @@ +"-" +"+" +"." +"e" +"e+" +"e-" +"E" +"E+" +"E-" +"0x" +"-0x" +"p" +"0" +"1" +"2" +"3" +"4" +"5" +"6" +"7" +"8" +"9" +"a" +"b" +"c" +"d" +"e" +"f" +"nan" +"-nan" +"+nan" +"inf" +"+inf" +"-inf" +"infinity" +"+infinity" +"-infinity" diff --git a/third_party/flatbuffers/tests/fuzzer/test_init.h b/third_party/flatbuffers/tests/fuzzer/test_init.h new file mode 100644 index 00000000000..6cb58d3f855 --- /dev/null +++ b/third_party/flatbuffers/tests/fuzzer/test_init.h @@ -0,0 +1,52 @@ + +#ifndef FUZZER_TEST_INIT_H_ +#define FUZZER_TEST_INIT_H_ + +#include "fuzzer_assert.h" +#include "test_assert.h" + +// Utility for test run. +struct OneTimeTestInit { + // Declare trap for the Flatbuffers test engine. + // This hook terminate program both in Debug and Release. + static bool TestFailListener(const char *expval, const char *val, + const char *exp, const char *file, int line, + const char *func = nullptr) { + (void)expval; + (void)val; + (void)exp; + (void)file; + (void)line; + (void)func; + // FLATBUFFERS_ASSERT redefined to be fully independent of the Flatbuffers + // library implementation (see test_assert.h for details). + fuzzer_assert_impl(false); // terminate + return false; + } + + OneTimeTestInit() : has_locale_(false) { + // Fuzzer test should be independent of the test engine implementation. + // This hook will terminate test if TEST_EQ/TEST_ASSERT asserted. + InitTestEngine(OneTimeTestInit::TestFailListener); + + // Read a locale for the test. + if (flatbuffers::ReadEnvironmentVariable("FLATBUFFERS_TEST_LOCALE", + &test_locale_)) { + TEST_OUTPUT_LINE("The environment variable FLATBUFFERS_TEST_LOCALE=%s", + test_locale_.c_str()); + test_locale_ = flatbuffers::RemoveStringQuotes(test_locale_); + has_locale_ = true; + } + } + + static const char *test_locale() { + return one_time_init_.has_locale_ ? nullptr + : one_time_init_.test_locale_.c_str(); + } + + bool has_locale_; + std::string test_locale_; + static OneTimeTestInit one_time_init_; +}; + +#endif // !FUZZER_TEST_INIT_H_ diff --git a/third_party/flatbuffers/tests/go_test.go b/third_party/flatbuffers/tests/go_test.go new file mode 100644 index 00000000000..f230060a66f --- /dev/null +++ b/third_party/flatbuffers/tests/go_test.go @@ -0,0 +1,2575 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +package main + +import ( + mygame "MyGame" // refers to generated code + example "MyGame/Example" // refers to generated code + pizza "Pizza" + "encoding/json" + optional_scalars "optional_scalars" // refers to generated code + order "order" + + "bytes" + "flag" + "fmt" + "os" + "reflect" + "sort" + "testing" + "testing/quick" + + flatbuffers "github.com/google/flatbuffers/go" +) + +var ( + cppData, javaData, outData string + fuzz bool + fuzzFields, fuzzObjects int +) + +func init() { + flag.StringVar(&cppData, "cpp_data", "", + "location of monsterdata_test.mon to verify against (required)") + flag.StringVar(&javaData, "java_data", "", + "location of monsterdata_java_wire.mon to verify against (optional)") + flag.StringVar(&outData, "out_data", "", + "location to write generated Go data") + flag.BoolVar(&fuzz, "fuzz", false, "perform fuzzing") + flag.IntVar(&fuzzFields, "fuzz_fields", 4, "fields per fuzzer object") + flag.IntVar(&fuzzObjects, "fuzz_objects", 10000, + "number of fuzzer objects (higher is slower and more thorough") +} + +// Store specific byte patterns in these variables for the fuzzer. These +// values are taken verbatim from the C++ function FuzzTest1. +var ( + overflowingInt32Val = flatbuffers.GetInt32([]byte{0x83, 0x33, 0x33, 0x33}) + overflowingInt64Val = flatbuffers.GetInt64([]byte{0x84, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44, 0x44}) +) + +func TestMain(m *testing.M) { + flag.Parse() + if cppData == "" { + fmt.Fprintf(os.Stderr, "cpp_data argument is required\n") + os.Exit(1) + } + os.Exit(m.Run()) +} + +// TestTextParsing test if text parsing works with object API. +func TestTextParsing(t *testing.T) { + expectedMonster := example.MonsterT{ + Mana: 42, + Name: "foo", + LongEnumNormalDefault: example.LongEnumLongTwo, + } + + buf := new(bytes.Buffer) + if err := json.NewEncoder(buf).Encode(expectedMonster); err != nil { + t.Fatal(err) + } + + var monster example.MonsterT + if err := json.NewDecoder(buf).Decode(&monster); err != nil { + t.Fatal(err) + } + + if monster.Mana != expectedMonster.Mana { + t.Fatal("wrong mana:", monster.Mana) + } + if monster.Name != expectedMonster.Name { + t.Fatal("wrong name:", monster.Name) + } + if monster.LongEnumNormalDefault != expectedMonster.LongEnumNormalDefault { + t.Fatal("wrong enum:", monster.LongEnumNormalDefault) + } +} + +func CheckNoNamespaceImport(fail func(string, ...interface{})) { + const size = 13 + // Order a pizza with specific size + builder := flatbuffers.NewBuilder(0) + ordered_pizza := pizza.PizzaT{Size: size} + food := order.FoodT{Pizza: &ordered_pizza} + builder.Finish(food.Pack(builder)) + + // Receive order + received_food := order.GetRootAsFood(builder.FinishedBytes(), 0) + received_pizza := received_food.Pizza(nil).UnPack() + + // Check if received pizza is equal to ordered pizza + if !reflect.DeepEqual(ordered_pizza, *received_pizza) { + fail(FailString("no namespace import", ordered_pizza, received_pizza)) + } +} + +// TestAll runs all checks, failing if any errors occur. +func TestAll(t *testing.T) { + // Verify that the Go FlatBuffers runtime library generates the + // expected bytes (does not use any schema): + CheckByteLayout(t.Fatalf) + CheckMutateMethods(t.Fatalf) + + // Verify that panics are raised during exceptional conditions: + CheckNotInObjectError(t.Fatalf) + CheckStringIsNestedError(t.Fatalf) + CheckByteStringIsNestedError(t.Fatalf) + CheckStructIsNotInlineError(t.Fatalf) + CheckFinishedBytesError(t.Fatalf) + CheckSharedStrings(t.Fatalf) + CheckEmptiedBuilder(t.Fatalf) + + // Verify that GetRootAs works for non-root tables + CheckGetRootAsForNonRootTable(t.Fatalf) + CheckTableAccessors(t.Fatalf) + + // Verify that using the generated Go code builds a buffer without + // returning errors: + generated, off := CheckGeneratedBuild(false, false, t.Fatalf) + + // Verify that the buffer generated by Go code is readable by the + // generated Go code: + CheckReadBuffer(generated, off, false, t.Fatalf) + CheckMutateBuffer(generated, off, false, t.Fatalf) + CheckObjectAPI(generated, off, false, t.Fatalf) + + // Generate the buffer again, with file identifier. + generated, off = CheckGeneratedBuild(false, true, t.Fatalf) + + // Check that this buffer with file identifier is usable + // and that the file identifier is correct. + CheckReadBuffer(generated, off, false, t.Fatalf) + CheckMutateBuffer(generated, off, false, t.Fatalf) + CheckObjectAPI(generated, off, false, t.Fatalf) + CheckFileIdentifier(generated, off, false, t.Fatalf) + + // Verify that the buffer generated by C++ code is readable by the + // generated Go code: + monsterDataCpp, err := os.ReadFile(cppData) + if err != nil { + t.Fatal(err) + } + CheckReadBuffer(monsterDataCpp, 0, false, t.Fatalf) + CheckMutateBuffer(monsterDataCpp, 0, false, t.Fatalf) + CheckObjectAPI(monsterDataCpp, 0, false, t.Fatalf) + CheckFileIdentifier(monsterDataCpp, 0, false, t.Fatalf) + + // Verify that vtables are deduplicated when written: + CheckVtableDeduplication(t.Fatalf) + + // Verify the enum names + CheckEnumNames(t.Fatalf) + + // Verify enum String methods + CheckEnumString(t.Fatalf) + + // Verify the enum values maps + CheckEnumValues(t.Fatalf) + + // Verify that the Go code used in FlatBuffers documentation passes + // some sanity checks: + CheckDocExample(generated, off, t.Fatalf) + + // Check Builder.CreateByteVector + CheckCreateByteVector(t.Fatalf) + + // Check a parent namespace import + CheckParentNamespace(t.Fatalf) + + // Check a no namespace import + CheckNoNamespaceImport(t.Fatalf) + + // Check size-prefixed flatbuffers + CheckSizePrefixedBuffer(t.Fatalf) + + // Check that optional scalars works + CheckOptionalScalars(t.Fatalf) + + // Check that getting vector element by key works + CheckByKey(t.Fatalf) + + // If the filename of the FlatBuffers file generated by the Java test + // is given, check that Go code can read it, and that Go code + // generates an identical buffer when used to create the example data: + if javaData != "" { + monsterDataJava, err := os.ReadFile(javaData) + if err != nil { + t.Fatal(err) + } + CheckReadBuffer(monsterDataJava, 0, false, t.Fatalf) + CheckByteEquality(generated[off:], monsterDataJava, t.Fatalf) + } + + // Verify that various fuzzing scenarios produce a valid FlatBuffer. + if fuzz { + checkFuzz(fuzzFields, fuzzObjects, t.Fatalf) + } + + // Write the generated buffer out to a file: + err = os.WriteFile(outData, generated[off:], os.FileMode(0644)) + if err != nil { + t.Fatal(err) + } +} + +// CheckReadBuffer checks that the given buffer is evaluated correctly +// as the example Monster. +func CheckReadBuffer(buf []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) { + // try the two ways of generating a monster + var monster1 *example.Monster + monster2 := &example.Monster{} + + if sizePrefix { + monster1 = example.GetSizePrefixedRootAsMonster(buf, offset) + flatbuffers.GetSizePrefixedRootAs(buf, offset, monster2) + } else { + monster1 = example.GetRootAsMonster(buf, offset) + flatbuffers.GetRootAs(buf, offset, monster2) + } + + for _, monster := range []*example.Monster{monster1, monster2} { + if got := monster.Hp(); 80 != got { + fail(FailString("hp", 80, got)) + } + + // default + if got := monster.Mana(); 150 != got { + fail(FailString("mana", 150, got)) + } + + if got := monster.Name(); !bytes.Equal([]byte("MyMonster"), got) { + fail(FailString("name", "MyMonster", got)) + } + + if got := monster.Color(); example.ColorBlue != got { + fail(FailString("color", example.ColorBlue, got)) + } + + if got := monster.Testbool(); true != got { + fail(FailString("testbool", true, got)) + } + + // initialize a Vec3 from Pos() + vec := new(example.Vec3) + vec = monster.Pos(vec) + if vec == nil { + fail("vec3 initialization failed") + } + + // check that new allocs equal given ones: + vec2 := monster.Pos(nil) + if !reflect.DeepEqual(vec, vec2) { + fail("fresh allocation failed") + } + + // verify the properties of the Vec3 + if got := vec.X(); float32(1.0) != got { + fail(FailString("Pos.X", float32(1.0), got)) + } + + if got := vec.Y(); float32(2.0) != got { + fail(FailString("Pos.Y", float32(2.0), got)) + } + + if got := vec.Z(); float32(3.0) != got { + fail(FailString("Pos.Z", float32(3.0), got)) + } + + if got := vec.Test1(); float64(3.0) != got { + fail(FailString("Pos.Test1", float64(3.0), got)) + } + + if got := vec.Test2(); example.ColorGreen != got { + fail(FailString("Pos.Test2", example.ColorGreen, got)) + } + + // initialize a Test from Test3(...) + t := new(example.Test) + t = vec.Test3(t) + if t == nil { + fail("vec.Test3(&t) failed") + } + + // check that new allocs equal given ones: + t2 := vec.Test3(nil) + if !reflect.DeepEqual(t, t2) { + fail("fresh allocation failed") + } + + // verify the properties of the Test + if got := t.A(); int16(5) != got { + fail(FailString("t.A()", int16(5), got)) + } + + if got := t.B(); int8(6) != got { + fail(FailString("t.B()", int8(6), got)) + } + + if got := monster.TestType(); example.AnyMonster != got { + fail(FailString("monster.TestType()", example.AnyMonster, got)) + } + + // initialize a Table from a union field Test(...) + var table2 flatbuffers.Table + if ok := monster.Test(&table2); !ok { + fail("monster.Test(&monster2) failed") + } + + // initialize a Monster from the Table from the union + var monster2 example.Monster + monster2.Init(table2.Bytes, table2.Pos) + + if got := monster2.Name(); !bytes.Equal([]byte("Fred"), got) { + fail(FailString("monster2.Name()", "Fred", got)) + } + + inventorySlice := monster.InventoryBytes() + if len(inventorySlice) != monster.InventoryLength() { + fail(FailString("len(monster.InventoryBytes) != monster.InventoryLength", len(inventorySlice), monster.InventoryLength())) + } + + if got := monster.InventoryLength(); 5 != got { + fail(FailString("monster.InventoryLength", 5, got)) + } + + invsum := 0 + l := monster.InventoryLength() + for i := 0; i < l; i++ { + v := monster.Inventory(i) + if v != inventorySlice[i] { + fail(FailString("monster inventory slice[i] != Inventory(i)", v, inventorySlice[i])) + } + invsum += int(v) + } + if invsum != 10 { + fail(FailString("monster inventory sum", 10, invsum)) + } + + if got := monster.Test4Length(); 2 != got { + fail(FailString("monster.Test4Length()", 2, got)) + } + + var test0 example.Test + ok := monster.Test4(&test0, 0) + if !ok { + fail(FailString("monster.Test4(&test0, 0)", true, ok)) + } + + var test1 example.Test + ok = monster.Test4(&test1, 1) + if !ok { + fail(FailString("monster.Test4(&test1, 1)", true, ok)) + } + + // the position of test0 and test1 are swapped in monsterdata_java_wire + // and monsterdata_test_wire, so ignore ordering + v0 := test0.A() + v1 := test0.B() + v2 := test1.A() + v3 := test1.B() + sum := int(v0) + int(v1) + int(v2) + int(v3) + + if 100 != sum { + fail(FailString("test0 and test1 sum", 100, sum)) + } + + if got := monster.TestarrayofstringLength(); 2 != got { + fail(FailString("Testarrayofstring length", 2, got)) + } + + if got := monster.Testarrayofstring(0); !bytes.Equal([]byte("test1"), got) { + fail(FailString("Testarrayofstring(0)", "test1", got)) + } + + if got := monster.Testarrayofstring(1); !bytes.Equal([]byte("test2"), got) { + fail(FailString("Testarrayofstring(1)", "test2", got)) + } + } +} + +// CheckFileIdentifier checks the "MONS" file identifier +func CheckFileIdentifier(buf []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) { + // Strip offset + buf = buf[offset:] + + var fileIdentifier string + var hasFileIdentifier bool + + if sizePrefix { + fileIdentifier = flatbuffers.GetSizePrefixedBufferIdentifier(buf) + hasFileIdentifier = example.SizePrefixedMonsterBufferHasIdentifier(buf) + } else { + fileIdentifier = flatbuffers.GetBufferIdentifier(buf) + hasFileIdentifier = example.MonsterBufferHasIdentifier(buf) + } + + expectedFileIdentifier := "MONS" + if fileIdentifier != expectedFileIdentifier { + fail("expected file identifier %q, got %q", expectedFileIdentifier, fileIdentifier) + } + if !hasFileIdentifier { + fail("did not find file identifier") + } +} + +// CheckMutateBuffer checks that the given buffer can be mutated correctly +// as the example Monster. Only available scalar values are mutated. +func CheckMutateBuffer(org []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) { + // make a copy to mutate + buf := make([]byte, len(org)) + copy(buf, org) + + // load monster data from the buffer + var monster *example.Monster + if sizePrefix { + monster = example.GetSizePrefixedRootAsMonster(buf, offset) + } else { + monster = example.GetRootAsMonster(buf, offset) + } + + // test case struct + type testcase struct { + field string + testfn func() bool + } + + testForOriginalValues := []testcase{ + testcase{"Hp", func() bool { return monster.Hp() == 80 }}, + testcase{"Mana", func() bool { return monster.Mana() == 150 }}, + testcase{"Testbool", func() bool { return monster.Testbool() == true }}, + testcase{"Pos.X'", func() bool { return monster.Pos(nil).X() == float32(1.0) }}, + testcase{"Pos.Y'", func() bool { return monster.Pos(nil).Y() == float32(2.0) }}, + testcase{"Pos.Z'", func() bool { return monster.Pos(nil).Z() == float32(3.0) }}, + testcase{"Pos.Test1'", func() bool { return monster.Pos(nil).Test1() == float64(3.0) }}, + testcase{"Pos.Test2'", func() bool { return monster.Pos(nil).Test2() == example.ColorGreen }}, + testcase{"Pos.Test3.A", func() bool { return monster.Pos(nil).Test3(nil).A() == int16(5) }}, + testcase{"Pos.Test3.B", func() bool { return monster.Pos(nil).Test3(nil).B() == int8(6) }}, + testcase{"Inventory[2]", func() bool { return monster.Inventory(2) == byte(2) }}, + } + + testMutability := []testcase{ + testcase{"Hp", func() bool { return monster.MutateHp(70) }}, + testcase{"Mana", func() bool { return !monster.MutateMana(140) }}, + testcase{"Testbool", func() bool { return monster.MutateTestbool(false) }}, + testcase{"Pos.X", func() bool { return monster.Pos(nil).MutateX(10.0) }}, + testcase{"Pos.Y", func() bool { return monster.Pos(nil).MutateY(20.0) }}, + testcase{"Pos.Z", func() bool { return monster.Pos(nil).MutateZ(30.0) }}, + testcase{"Pos.Test1", func() bool { return monster.Pos(nil).MutateTest1(30.0) }}, + testcase{"Pos.Test2", func() bool { return monster.Pos(nil).MutateTest2(example.ColorBlue) }}, + testcase{"Pos.Test3.A", func() bool { return monster.Pos(nil).Test3(nil).MutateA(50) }}, + testcase{"Pos.Test3.B", func() bool { return monster.Pos(nil).Test3(nil).MutateB(60) }}, + testcase{"Inventory[2]", func() bool { return monster.MutateInventory(2, 200) }}, + } + + testForMutatedValues := []testcase{ + testcase{"Hp", func() bool { return monster.Hp() == 70 }}, + testcase{"Mana", func() bool { return monster.Mana() == 150 }}, + testcase{"Testbool", func() bool { return monster.Testbool() == false }}, + testcase{"Pos.X'", func() bool { return monster.Pos(nil).X() == float32(10.0) }}, + testcase{"Pos.Y'", func() bool { return monster.Pos(nil).Y() == float32(20.0) }}, + testcase{"Pos.Z'", func() bool { return monster.Pos(nil).Z() == float32(30.0) }}, + testcase{"Pos.Test1'", func() bool { return monster.Pos(nil).Test1() == float64(30.0) }}, + testcase{"Pos.Test2'", func() bool { return monster.Pos(nil).Test2() == example.ColorBlue }}, + testcase{"Pos.Test3.A", func() bool { return monster.Pos(nil).Test3(nil).A() == int16(50) }}, + testcase{"Pos.Test3.B", func() bool { return monster.Pos(nil).Test3(nil).B() == int8(60) }}, + testcase{"Inventory[2]", func() bool { return monster.Inventory(2) == byte(200) }}, + } + + testInvalidEnumValues := []testcase{ + testcase{"Pos.Test2", func() bool { return monster.Pos(nil).MutateTest2(example.Color(20)) }}, + testcase{"Pos.Test2", func() bool { return monster.Pos(nil).Test2() == example.Color(20) }}, + } + + // make sure original values are okay + for _, t := range testForOriginalValues { + if !t.testfn() { + fail("field '" + t.field + "' doesn't have the expected original value") + } + } + + // try to mutate fields and check mutability + for _, t := range testMutability { + if !t.testfn() { + fail(FailString("field '"+t.field+"' failed mutability test", true, false)) + } + } + + // test whether values have changed + for _, t := range testForMutatedValues { + if !t.testfn() { + fail("field '" + t.field + "' doesn't have the expected mutated value") + } + } + + // make sure the buffer has changed + if reflect.DeepEqual(buf, org) { + fail("mutate buffer failed") + } + + // To make sure the buffer has changed accordingly + // Read data from the buffer and verify all fields + if sizePrefix { + monster = example.GetSizePrefixedRootAsMonster(buf, offset) + } else { + monster = example.GetRootAsMonster(buf, offset) + } + + for _, t := range testForMutatedValues { + if !t.testfn() { + fail("field '" + t.field + "' doesn't have the expected mutated value") + } + } + + // a couple extra tests for "invalid" enum values, which don't correspond to + // anything in the schema, but are allowed + for _, t := range testInvalidEnumValues { + if !t.testfn() { + fail("field '" + t.field + "' doesn't work with an invalid enum value") + } + } + + // reverting all fields to original values should + // re-create the original buffer. Mutate all fields + // back to their original values and compare buffers. + // This test is done to make sure mutations do not do + // any unnecessary changes to the buffer. + if sizePrefix { + monster = example.GetSizePrefixedRootAsMonster(buf, offset) + } else { + monster = example.GetRootAsMonster(buf, offset) + } + + monster.MutateHp(80) + monster.MutateTestbool(true) + monster.Pos(nil).MutateX(1.0) + monster.Pos(nil).MutateY(2.0) + monster.Pos(nil).MutateZ(3.0) + monster.Pos(nil).MutateTest1(3.0) + monster.Pos(nil).MutateTest2(example.ColorGreen) + monster.Pos(nil).Test3(nil).MutateA(5) + monster.Pos(nil).Test3(nil).MutateB(6) + monster.MutateInventory(2, 2) + + for _, t := range testForOriginalValues { + if !t.testfn() { + fail("field '" + t.field + "' doesn't have the expected original value") + } + } + + // buffer should have original values + if !reflect.DeepEqual(buf, org) { + fail("revert changes failed") + } +} + +func CheckObjectAPI(buf []byte, offset flatbuffers.UOffsetT, sizePrefix bool, fail func(string, ...interface{})) { + var monster *example.MonsterT + + if sizePrefix { + monster = example.GetSizePrefixedRootAsMonster(buf, offset).UnPack() + } else { + monster = example.GetRootAsMonster(buf, offset).UnPack() + } + + if got := monster.Hp; 80 != got { + fail(FailString("hp", 80, got)) + } + + // default + if got := monster.Mana; 150 != got { + fail(FailString("mana", 150, got)) + } + + if monster.Test != nil && monster.Test.Type == example.AnyMonster { + monster.Test.Value.(*example.MonsterT).NanDefault = 0.0 + } + if monster.Enemy != nil { + monster.Enemy.NanDefault = 0.0 + } + monster.NanDefault = 0.0 + + builder := flatbuffers.NewBuilder(0) + builder.Finish(monster.Pack(builder)) + monster2 := example.GetRootAsMonster(builder.FinishedBytes(), 0).UnPack() + if !reflect.DeepEqual(monster, monster2) { + fail(FailString("Pack/Unpack()", monster, monster2)) + } +} + +// Low level stress/fuzz test: serialize/deserialize a variety of +// different kinds of data in different combinations +func checkFuzz(fuzzFields, fuzzObjects int, fail func(string, ...interface{})) { + + // Values we're testing against: chosen to ensure no bits get chopped + // off anywhere, and also be different from eachother. + boolVal := true + int8Val := int8(-127) // 0x81 + uint8Val := uint8(0xFF) + int16Val := int16(-32222) // 0x8222 + uint16Val := uint16(0xFEEE) + int32Val := int32(overflowingInt32Val) + uint32Val := uint32(0xFDDDDDDD) + int64Val := int64(overflowingInt64Val) + uint64Val := uint64(0xFCCCCCCCCCCCCCCC) + float32Val := float32(3.14159) + float64Val := float64(3.14159265359) + + testValuesMax := 11 // hardcoded to the number of scalar types + + builder := flatbuffers.NewBuilder(0) + l := NewLCG() + + objects := make([]flatbuffers.UOffsetT, fuzzObjects) + + // Generate fuzzObjects random objects each consisting of + // fuzzFields fields, each of a random type. + for i := 0; i < fuzzObjects; i++ { + builder.StartObject(fuzzFields) + + for f := 0; f < fuzzFields; f++ { + choice := l.Next() % uint32(testValuesMax) + switch choice { + case 0: + builder.PrependBoolSlot(int(f), boolVal, false) + case 1: + builder.PrependInt8Slot(int(f), int8Val, 0) + case 2: + builder.PrependUint8Slot(int(f), uint8Val, 0) + case 3: + builder.PrependInt16Slot(int(f), int16Val, 0) + case 4: + builder.PrependUint16Slot(int(f), uint16Val, 0) + case 5: + builder.PrependInt32Slot(int(f), int32Val, 0) + case 6: + builder.PrependUint32Slot(int(f), uint32Val, 0) + case 7: + builder.PrependInt64Slot(int(f), int64Val, 0) + case 8: + builder.PrependUint64Slot(int(f), uint64Val, 0) + case 9: + builder.PrependFloat32Slot(int(f), float32Val, 0) + case 10: + builder.PrependFloat64Slot(int(f), float64Val, 0) + } + } + + off := builder.EndObject() + + // store the offset from the end of the builder buffer, + // since it will keep growing: + objects[i] = off + } + + // Do some bookkeeping to generate stats on fuzzes: + stats := map[string]int{} + check := func(desc string, want, got interface{}) { + stats[desc]++ + if want != got { + fail("%s want %v got %v", desc, want, got) + } + } + + l = NewLCG() // Reset. + + // Test that all objects we generated are readable and return the + // expected values. We generate random objects in the same order + // so this is deterministic. + for i := 0; i < fuzzObjects; i++ { + + table := &flatbuffers.Table{ + Bytes: builder.Bytes, + Pos: flatbuffers.UOffsetT(len(builder.Bytes)) - objects[i], + } + + for j := 0; j < fuzzFields; j++ { + f := flatbuffers.VOffsetT((flatbuffers.VtableMetadataFields + j) * flatbuffers.SizeVOffsetT) + choice := l.Next() % uint32(testValuesMax) + + switch choice { + case 0: + check("bool", boolVal, table.GetBoolSlot(f, false)) + case 1: + check("int8", int8Val, table.GetInt8Slot(f, 0)) + case 2: + check("uint8", uint8Val, table.GetUint8Slot(f, 0)) + case 3: + check("int16", int16Val, table.GetInt16Slot(f, 0)) + case 4: + check("uint16", uint16Val, table.GetUint16Slot(f, 0)) + case 5: + check("int32", int32Val, table.GetInt32Slot(f, 0)) + case 6: + check("uint32", uint32Val, table.GetUint32Slot(f, 0)) + case 7: + check("int64", int64Val, table.GetInt64Slot(f, 0)) + case 8: + check("uint64", uint64Val, table.GetUint64Slot(f, 0)) + case 9: + check("float32", float32Val, table.GetFloat32Slot(f, 0)) + case 10: + check("float64", float64Val, table.GetFloat64Slot(f, 0)) + } + } + } + + // If enough checks were made, verify that all scalar types were used: + if fuzzFields*fuzzObjects >= testValuesMax { + if len(stats) != testValuesMax { + fail("fuzzing failed to test all scalar types") + } + } + + // Print some counts, if needed: + if testing.Verbose() { + if fuzzFields == 0 || fuzzObjects == 0 { + fmt.Printf("fuzz\tfields: %d\tobjects: %d\t[none]\t%d\n", + fuzzFields, fuzzObjects, 0) + } else { + keys := make([]string, 0, len(stats)) + for k := range stats { + keys = append(keys, k) + } + sort.Strings(keys) + for _, k := range keys { + fmt.Printf("fuzz\tfields: %d\tobjects: %d\t%s\t%d\n", + fuzzFields, fuzzObjects, k, stats[k]) + } + } + } + + return +} + +// FailString makes a message for when expectations differ from reality. +func FailString(name string, want, got interface{}) string { + return fmt.Sprintf("bad %s: want %#v got %#v", name, want, got) +} + +// CheckByteLayout verifies the bytes of a Builder in various scenarios. +func CheckByteLayout(fail func(string, ...interface{})) { + var b *flatbuffers.Builder + + var i int + check := func(want []byte) { + i++ + got := b.Bytes[b.Head():] + if !bytes.Equal(want, got) { + fail("case %d: want\n%v\nbut got\n%v\n", i, want, got) + } + } + + // test 1: numbers + + b = flatbuffers.NewBuilder(0) + check([]byte{}) + b.PrependBool(true) + check([]byte{1}) + b.PrependInt8(-127) + check([]byte{129, 1}) + b.PrependUint8(255) + check([]byte{255, 129, 1}) + b.PrependInt16(-32222) + check([]byte{0x22, 0x82, 0, 255, 129, 1}) // first pad + b.PrependUint16(0xFEEE) + check([]byte{0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) // no pad this time + b.PrependInt32(-53687092) + check([]byte{204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) + b.PrependUint32(0x98765432) + check([]byte{0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1}) + + // test 1b: numbers 2 + + b = flatbuffers.NewBuilder(0) + b.PrependUint64(0x1122334455667788) + check([]byte{0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11}) + + // test 2: 1xbyte vector + + b = flatbuffers.NewBuilder(0) + check([]byte{}) + b.StartVector(flatbuffers.SizeByte, 1, 1) + check([]byte{0, 0, 0}) // align to 4bytes + b.PrependByte(1) + check([]byte{1, 0, 0, 0}) + b.EndVector(1) + check([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding + + // test 3: 2xbyte vector + + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeByte, 2, 1) + check([]byte{0, 0}) // align to 4bytes + b.PrependByte(1) + check([]byte{1, 0, 0}) + b.PrependByte(2) + check([]byte{2, 1, 0, 0}) + b.EndVector(2) + check([]byte{2, 0, 0, 0, 2, 1, 0, 0}) // padding + + // test 3b: 11xbyte vector matches builder size + + b = flatbuffers.NewBuilder(12) + b.StartVector(flatbuffers.SizeByte, 8, 1) + start := []byte{} + check(start) + for i := 1; i < 12; i++ { + b.PrependByte(byte(i)) + start = append([]byte{byte(i)}, start...) + check(start) + } + b.EndVector(8) + check(append([]byte{8, 0, 0, 0}, start...)) + + // test 4: 1xuint16 vector + + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeUint16, 1, 1) + check([]byte{0, 0}) // align to 4bytes + b.PrependUint16(1) + check([]byte{1, 0, 0, 0}) + b.EndVector(1) + check([]byte{1, 0, 0, 0, 1, 0, 0, 0}) // padding + + // test 5: 2xuint16 vector + + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeUint16, 2, 1) + check([]byte{}) // align to 4bytes + b.PrependUint16(0xABCD) + check([]byte{0xCD, 0xAB}) + b.PrependUint16(0xDCBA) + check([]byte{0xBA, 0xDC, 0xCD, 0xAB}) + b.EndVector(2) + check([]byte{2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB}) + + // test 6: CreateString + + b = flatbuffers.NewBuilder(0) + b.CreateString("foo") + check([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad + b.CreateString("moop") + check([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad + 3, 0, 0, 0, 'f', 'o', 'o', 0}) + + // test 6b: CreateString unicode + + b = flatbuffers.NewBuilder(0) + // These characters are chinese from blog.golang.org/strings + // We use escape codes here so that editors without unicode support + // aren't bothered: + uni_str := "\u65e5\u672c\u8a9e" + b.CreateString(uni_str) + check([]byte{9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, // null-terminated, 2-byte pad + 0, 0}) + + // test 6c: CreateByteString + + b = flatbuffers.NewBuilder(0) + b.CreateByteString([]byte("foo")) + check([]byte{3, 0, 0, 0, 'f', 'o', 'o', 0}) // 0-terminated, no pad + b.CreateByteString([]byte("moop")) + check([]byte{4, 0, 0, 0, 'm', 'o', 'o', 'p', 0, 0, 0, 0, // 0-terminated, 3-byte pad + 3, 0, 0, 0, 'f', 'o', 'o', 0}) + + // test 7: empty vtable + b = flatbuffers.NewBuilder(0) + b.StartObject(0) + check([]byte{}) + b.EndObject() + check([]byte{4, 0, 4, 0, 4, 0, 0, 0}) + + // test 8: vtable with one true bool + b = flatbuffers.NewBuilder(0) + check([]byte{}) + b.StartObject(1) + check([]byte{}) + b.PrependBoolSlot(0, true, false) + b.EndObject() + check([]byte{ + 6, 0, // vtable bytes + 8, 0, // length of object including vtable offset + 7, 0, // start of bool value + 6, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, 0, // padded to 4 bytes + 1, // bool value + }) + + // test 9: vtable with one default bool + b = flatbuffers.NewBuilder(0) + check([]byte{}) + b.StartObject(1) + check([]byte{}) + b.PrependBoolSlot(0, false, false) + b.EndObject() + check([]byte{ + 4, 0, // vtable bytes + 4, 0, // end of object from here + // entry 1 is zero and not stored. + 4, 0, 0, 0, // offset for start of vtable (int32) + }) + + // test 10: vtable with one int16 + b = flatbuffers.NewBuilder(0) + b.StartObject(1) + b.PrependInt16Slot(0, 0x789A, 0) + b.EndObject() + check([]byte{ + 6, 0, // vtable bytes + 8, 0, // end of object from here + 6, 0, // offset to value + 6, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, // padding to 4 bytes + 0x9A, 0x78, + }) + + // test 11: vtable with two int16 + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt16Slot(0, 0x3456, 0) + b.PrependInt16Slot(1, 0x789A, 0) + b.EndObject() + check([]byte{ + 8, 0, // vtable bytes + 8, 0, // end of object from here + 6, 0, // offset to value 0 + 4, 0, // offset to value 1 + 8, 0, 0, 0, // offset for start of vtable (int32) + 0x9A, 0x78, // value 1 + 0x56, 0x34, // value 0 + }) + + // test 12: vtable with int16 and bool + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt16Slot(0, 0x3456, 0) + b.PrependBoolSlot(1, true, false) + b.EndObject() + check([]byte{ + 8, 0, // vtable bytes + 8, 0, // end of object from here + 6, 0, // offset to value 0 + 5, 0, // offset to value 1 + 8, 0, 0, 0, // offset for start of vtable (int32) + 0, // padding + 1, // value 1 + 0x56, 0x34, // value 0 + }) + + // test 12: vtable with empty vector + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeByte, 0, 1) + vecend := b.EndVector(0) + b.StartObject(1) + b.PrependUOffsetTSlot(0, vecend, 0) + b.EndObject() + check([]byte{ + 6, 0, // vtable bytes + 8, 0, + 4, 0, // offset to vector offset + 6, 0, 0, 0, // offset for start of vtable (int32) + 4, 0, 0, 0, + 0, 0, 0, 0, // length of vector (not in struct) + }) + + // test 12b: vtable with empty vector of byte and some scalars + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeByte, 0, 1) + vecend = b.EndVector(0) + b.StartObject(2) + b.PrependInt16Slot(0, 55, 0) + b.PrependUOffsetTSlot(1, vecend, 0) + b.EndObject() + check([]byte{ + 8, 0, // vtable bytes + 12, 0, + 10, 0, // offset to value 0 + 4, 0, // offset to vector offset + 8, 0, 0, 0, // vtable loc + 8, 0, 0, 0, // value 1 + 0, 0, 55, 0, // value 0 + + 0, 0, 0, 0, // length of vector (not in struct) + }) + + // test 13: vtable with 1 int16 and 2-vector of int16 + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeInt16, 2, 1) + b.PrependInt16(0x1234) + b.PrependInt16(0x5678) + vecend = b.EndVector(2) + b.StartObject(2) + b.PrependUOffsetTSlot(1, vecend, 0) + b.PrependInt16Slot(0, 55, 0) + b.EndObject() + check([]byte{ + 8, 0, // vtable bytes + 12, 0, // length of object + 6, 0, // start of value 0 from end of vtable + 8, 0, // start of value 1 from end of buffer + 8, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, // padding + 55, 0, // value 0 + 4, 0, 0, 0, // vector position from here + 2, 0, 0, 0, // length of vector (uint32) + 0x78, 0x56, // vector value 1 + 0x34, 0x12, // vector value 0 + }) + + // test 14: vtable with 1 struct of 1 int8, 1 int16, 1 int32 + b = flatbuffers.NewBuilder(0) + b.StartObject(1) + b.Prep(4+4+4, 0) + b.PrependInt8(55) + b.Pad(3) + b.PrependInt16(0x1234) + b.Pad(2) + b.PrependInt32(0x12345678) + structStart := b.Offset() + b.PrependStructSlot(0, structStart, 0) + b.EndObject() + check([]byte{ + 6, 0, // vtable bytes + 16, 0, // end of object from here + 4, 0, // start of struct from here + 6, 0, 0, 0, // offset for start of vtable (int32) + 0x78, 0x56, 0x34, 0x12, // value 2 + 0, 0, // padding + 0x34, 0x12, // value 1 + 0, 0, 0, // padding + 55, // value 0 + }) + + // test 15: vtable with 1 vector of 2 struct of 2 int8 + b = flatbuffers.NewBuilder(0) + b.StartVector(flatbuffers.SizeInt8*2, 2, 1) + b.PrependInt8(33) + b.PrependInt8(44) + b.PrependInt8(55) + b.PrependInt8(66) + vecend = b.EndVector(2) + b.StartObject(1) + b.PrependUOffsetTSlot(0, vecend, 0) + b.EndObject() + check([]byte{ + 6, 0, // vtable bytes + 8, 0, + 4, 0, // offset of vector offset + 6, 0, 0, 0, // offset for start of vtable (int32) + 4, 0, 0, 0, // vector start offset + + 2, 0, 0, 0, // vector length + 66, // vector value 1,1 + 55, // vector value 1,0 + 44, // vector value 0,1 + 33, // vector value 0,0 + }) + + // test 16: table with some elements + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt8Slot(0, 33, 0) + b.PrependInt16Slot(1, 66, 0) + off := b.EndObject() + b.Finish(off) + + check([]byte{ + 12, 0, 0, 0, // root of table: points to vtable offset + + 8, 0, // vtable bytes + 8, 0, // end of object from here + 7, 0, // start of value 0 + 4, 0, // start of value 1 + + 8, 0, 0, 0, // offset for start of vtable (int32) + + 66, 0, // value 1 + 0, // padding + 33, // value 0 + }) + + // test 16b: same as test 16, size prefixed + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt8Slot(0, 33, 0) + b.PrependInt16Slot(1, 66, 0) + off = b.EndObject() + b.FinishSizePrefixed(off) + + check([]byte{ + 20, 0, 0, 0, // size prefix + 12, 0, 0, 0, // root of table: points to vtable offset + + 8, 0, // vtable bytes + 8, 0, // end of object from here + 7, 0, // start of value 0 + 4, 0, // start of value 1 + + 8, 0, 0, 0, // offset for start of vtable (int32) + + 66, 0, // value 1 + 0, // padding + 33, // value 0 + }) + + // test 16c: same as test 16, with file identifier + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt8Slot(0, 33, 0) + b.PrependInt16Slot(1, 66, 0) + off = b.EndObject() + b.FinishWithFileIdentifier(off, []byte("TEST")) + + check([]byte{ + 16, 0, 0, 0, // root of table: points to vtable offset + 'T', 'E', 'S', 'T', // file identifier + + 8, 0, // vtable bytes + 8, 0, // end of object from here + 7, 0, // start of value 0 + 4, 0, // start of value 1 + + 8, 0, 0, 0, // offset for start of vtable (int32) + + 66, 0, // value 1 + 0, // padding + 33, // value 0 + }) + + // test 16d: same as test 16, size prefixed with file identifier + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt8Slot(0, 33, 0) + b.PrependInt16Slot(1, 66, 0) + off = b.EndObject() + b.FinishSizePrefixedWithFileIdentifier(off, []byte("TEST")) + + check([]byte{ + 24, 0, 0, 0, // size prefix + 16, 0, 0, 0, // root of table: points to vtable offset + 'T', 'E', 'S', 'T', // file identifier + + 8, 0, // vtable bytes + 8, 0, // end of object from here + 7, 0, // start of value 0 + 4, 0, // start of value 1 + + 8, 0, 0, 0, // offset for start of vtable (int32) + + 66, 0, // value 1 + 0, // padding + 33, // value 0 + }) + + // test 17: one unfinished table and one finished table + b = flatbuffers.NewBuilder(0) + b.StartObject(2) + b.PrependInt8Slot(0, 33, 0) + b.PrependInt8Slot(1, 44, 0) + off = b.EndObject() + b.Finish(off) + + b.StartObject(3) + b.PrependInt8Slot(0, 55, 0) + b.PrependInt8Slot(1, 66, 0) + b.PrependInt8Slot(2, 77, 0) + off = b.EndObject() + b.Finish(off) + + check([]byte{ + 16, 0, 0, 0, // root of table: points to object + 0, 0, // padding + + 10, 0, // vtable bytes + 8, 0, // size of object + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 5, 0, // start of value 2 + 10, 0, 0, 0, // offset for start of vtable (int32) + 0, // padding + 77, // value 2 + 66, // value 1 + 55, // value 0 + + 12, 0, 0, 0, // root of table: points to object + + 8, 0, // vtable bytes + 8, 0, // size of object + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 8, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, // padding + 44, // value 1 + 33, // value 0 + }) + + // test 18: a bunch of bools + b = flatbuffers.NewBuilder(0) + b.StartObject(8) + b.PrependBoolSlot(0, true, false) + b.PrependBoolSlot(1, true, false) + b.PrependBoolSlot(2, true, false) + b.PrependBoolSlot(3, true, false) + b.PrependBoolSlot(4, true, false) + b.PrependBoolSlot(5, true, false) + b.PrependBoolSlot(6, true, false) + b.PrependBoolSlot(7, true, false) + off = b.EndObject() + b.Finish(off) + + check([]byte{ + 24, 0, 0, 0, // root of table: points to vtable offset + + 20, 0, // vtable bytes + 12, 0, // size of object + 11, 0, // start of value 0 + 10, 0, // start of value 1 + 9, 0, // start of value 2 + 8, 0, // start of value 3 + 7, 0, // start of value 4 + 6, 0, // start of value 5 + 5, 0, // start of value 6 + 4, 0, // start of value 7 + 20, 0, 0, 0, // vtable offset + + 1, // value 7 + 1, // value 6 + 1, // value 5 + 1, // value 4 + 1, // value 3 + 1, // value 2 + 1, // value 1 + 1, // value 0 + }) + + // test 19: three bools + b = flatbuffers.NewBuilder(0) + b.StartObject(3) + b.PrependBoolSlot(0, true, false) + b.PrependBoolSlot(1, true, false) + b.PrependBoolSlot(2, true, false) + off = b.EndObject() + b.Finish(off) + + check([]byte{ + 16, 0, 0, 0, // root of table: points to vtable offset + + 0, 0, // padding + + 10, 0, // vtable bytes + 8, 0, // size of object + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 5, 0, // start of value 2 + 10, 0, 0, 0, // vtable offset from here + + 0, // padding + 1, // value 2 + 1, // value 1 + 1, // value 0 + }) + + // test 20: some floats + b = flatbuffers.NewBuilder(0) + b.StartObject(1) + b.PrependFloat32Slot(0, 1.0, 0.0) + off = b.EndObject() + + check([]byte{ + 6, 0, // vtable bytes + 8, 0, // size of object + 4, 0, // start of value 0 + 6, 0, 0, 0, // vtable offset + + 0, 0, 128, 63, // value 0 + }) +} + +// CheckManualBuild builds a Monster manually. +func CheckManualBuild(fail func(string, ...interface{})) ([]byte, flatbuffers.UOffsetT) { + b := flatbuffers.NewBuilder(0) + str := b.CreateString("MyMonster") + + b.StartVector(1, 5, 1) + b.PrependByte(4) + b.PrependByte(3) + b.PrependByte(2) + b.PrependByte(1) + b.PrependByte(0) + inv := b.EndVector(5) + + b.StartObject(13) + b.PrependInt16Slot(2, 20, 100) + mon2 := b.EndObject() + + // Test4Vector + b.StartVector(4, 2, 1) + + // Test 0 + b.Prep(2, 4) + b.Pad(1) + b.PlaceInt8(20) + b.PlaceInt16(10) + + // Test 1 + b.Prep(2, 4) + b.Pad(1) + b.PlaceInt8(40) + b.PlaceInt16(30) + + // end testvector + test4 := b.EndVector(2) + + b.StartObject(13) + + // a vec3 + b.Prep(16, 32) + b.Pad(2) + b.Prep(2, 4) + b.Pad(1) + b.PlaceByte(6) + b.PlaceInt16(5) + b.Pad(1) + b.PlaceByte(4) + b.PlaceFloat64(3.0) + b.Pad(4) + b.PlaceFloat32(3.0) + b.PlaceFloat32(2.0) + b.PlaceFloat32(1.0) + vec3Loc := b.Offset() + // end vec3 + + b.PrependStructSlot(0, vec3Loc, 0) // vec3. noop + b.PrependInt16Slot(2, 80, 100) // hp + b.PrependUOffsetTSlot(3, str, 0) + b.PrependUOffsetTSlot(5, inv, 0) // inventory + b.PrependByteSlot(7, 1, 0) + b.PrependUOffsetTSlot(8, mon2, 0) + b.PrependUOffsetTSlot(9, test4, 0) + mon := b.EndObject() + + b.Finish(mon) + + return b.Bytes, b.Head() +} + +func CheckGetRootAsForNonRootTable(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + str := b.CreateString("MyStat") + example.StatStart(b) + example.StatAddId(b, str) + example.StatAddVal(b, 12345678) + example.StatAddCount(b, 12345) + stat_end := example.StatEnd(b) + b.Finish(stat_end) + + stat := example.GetRootAsStat(b.Bytes, b.Head()) + + if got := stat.Id(); !bytes.Equal([]byte("MyStat"), got) { + fail(FailString("stat.Id()", "MyStat", got)) + } + + if got := stat.Val(); 12345678 != got { + fail(FailString("stat.Val()", 12345678, got)) + } + + if got := stat.Count(); 12345 != got { + fail(FailString("stat.Count()", 12345, got)) + } +} + +// CheckGeneratedBuild uses generated code to build the example Monster. +func CheckGeneratedBuild(sizePrefix, fileIdentifier bool, fail func(string, ...interface{})) ([]byte, flatbuffers.UOffsetT) { + b := flatbuffers.NewBuilder(0) + str := b.CreateString("MyMonster") + test1 := b.CreateString("test1") + test2 := b.CreateString("test2") + fred := b.CreateString("Fred") + + example.MonsterStartInventoryVector(b, 5) + b.PrependByte(4) + b.PrependByte(3) + b.PrependByte(2) + b.PrependByte(1) + b.PrependByte(0) + inv := b.EndVector(5) + + example.MonsterStart(b) + example.MonsterAddName(b, fred) + mon2 := example.MonsterEnd(b) + + example.MonsterStartTest4Vector(b, 2) + example.CreateTest(b, 10, 20) + example.CreateTest(b, 30, 40) + test4 := b.EndVector(2) + + example.MonsterStartTestarrayofstringVector(b, 2) + b.PrependUOffsetT(test2) + b.PrependUOffsetT(test1) + testArrayOfString := b.EndVector(2) + + example.MonsterStart(b) + + pos := example.CreateVec3(b, 1.0, 2.0, 3.0, 3.0, example.ColorGreen, 5, 6) + example.MonsterAddPos(b, pos) + + example.MonsterAddHp(b, 80) + example.MonsterAddName(b, str) + example.MonsterAddTestbool(b, true) + example.MonsterAddInventory(b, inv) + example.MonsterAddTestType(b, 1) + example.MonsterAddTest(b, mon2) + example.MonsterAddTest4(b, test4) + example.MonsterAddTestarrayofstring(b, testArrayOfString) + mon := example.MonsterEnd(b) + + if fileIdentifier { + if sizePrefix { + example.FinishSizePrefixedMonsterBuffer(b, mon) + } else { + example.FinishMonsterBuffer(b, mon) + } + } else { + if sizePrefix { + b.FinishSizePrefixed(mon) + } else { + b.Finish(mon) + } + } + + return b.Bytes, b.Head() +} + +// CheckTableAccessors checks that the table accessors work as expected. +func CheckTableAccessors(fail func(string, ...interface{})) { + // test struct accessor + b := flatbuffers.NewBuilder(0) + pos := example.CreateVec3(b, 1.0, 2.0, 3.0, 3.0, 4, 5, 6) + b.Finish(pos) + vec3Bytes := b.FinishedBytes() + vec3 := &example.Vec3{} + flatbuffers.GetRootAs(vec3Bytes, 0, vec3) + + if bytes.Compare(vec3Bytes, vec3.Table().Bytes) != 0 { + fail("invalid vec3 table") + } + + // test table accessor + b = flatbuffers.NewBuilder(0) + str := b.CreateString("MyStat") + example.StatStart(b) + example.StatAddId(b, str) + example.StatAddVal(b, 12345678) + example.StatAddCount(b, 12345) + pos = example.StatEnd(b) + b.Finish(pos) + statBytes := b.FinishedBytes() + stat := &example.Stat{} + flatbuffers.GetRootAs(statBytes, 0, stat) + + if bytes.Compare(statBytes, stat.Table().Bytes) != 0 { + fail("invalid stat table") + } +} + +// CheckVtableDeduplication verifies that vtables are deduplicated. +func CheckVtableDeduplication(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + + b.StartObject(4) + b.PrependByteSlot(0, 0, 0) + b.PrependByteSlot(1, 11, 0) + b.PrependByteSlot(2, 22, 0) + b.PrependInt16Slot(3, 33, 0) + obj0 := b.EndObject() + + b.StartObject(4) + b.PrependByteSlot(0, 0, 0) + b.PrependByteSlot(1, 44, 0) + b.PrependByteSlot(2, 55, 0) + b.PrependInt16Slot(3, 66, 0) + obj1 := b.EndObject() + + b.StartObject(4) + b.PrependByteSlot(0, 0, 0) + b.PrependByteSlot(1, 77, 0) + b.PrependByteSlot(2, 88, 0) + b.PrependInt16Slot(3, 99, 0) + obj2 := b.EndObject() + + got := b.Bytes[b.Head():] + + want := []byte{ + 240, 255, 255, 255, // == -12. offset to dedupped vtable. + 99, 0, + 88, + 77, + 248, 255, 255, 255, // == -8. offset to dedupped vtable. + 66, 0, + 55, + 44, + 12, 0, + 8, 0, + 0, 0, + 7, 0, + 6, 0, + 4, 0, + 12, 0, 0, 0, + 33, 0, + 22, + 11, + } + + if !bytes.Equal(want, got) { + fail("testVtableDeduplication want:\n%d %v\nbut got:\n%d %v\n", + len(want), want, len(got), got) + } + + table0 := &flatbuffers.Table{Bytes: b.Bytes, Pos: flatbuffers.UOffsetT(len(b.Bytes)) - obj0} + table1 := &flatbuffers.Table{Bytes: b.Bytes, Pos: flatbuffers.UOffsetT(len(b.Bytes)) - obj1} + table2 := &flatbuffers.Table{Bytes: b.Bytes, Pos: flatbuffers.UOffsetT(len(b.Bytes)) - obj2} + + testTable := func(tab *flatbuffers.Table, a flatbuffers.VOffsetT, b, c, d byte) { + // vtable size + if got := tab.GetVOffsetTSlot(0, 0); 12 != got { + fail("failed 0, 0: %d", got) + } + // object size + if got := tab.GetVOffsetTSlot(2, 0); 8 != got { + fail("failed 2, 0: %d", got) + } + // default value + if got := tab.GetVOffsetTSlot(4, 0); a != got { + fail("failed 4, 0: %d", got) + } + if got := tab.GetByteSlot(6, 0); b != got { + fail("failed 6, 0: %d", got) + } + if val := tab.GetByteSlot(8, 0); c != val { + fail("failed 8, 0: %d", got) + } + if got := tab.GetByteSlot(10, 0); d != got { + fail("failed 10, 0: %d", got) + } + } + + testTable(table0, 0, 11, 22, 33) + testTable(table1, 0, 44, 55, 66) + testTable(table2, 0, 77, 88, 99) +} + +// CheckNotInObjectError verifies that `EndObject` fails if not inside an +// object. +func CheckNotInObjectError(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + + defer func() { + r := recover() + if r == nil { + fail("expected panic in CheckNotInObjectError") + } + }() + b.EndObject() +} + +// CheckStringIsNestedError verifies that a string can not be created inside +// another object. +func CheckStringIsNestedError(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + b.StartObject(0) + defer func() { + r := recover() + if r == nil { + fail("expected panic in CheckStringIsNestedError") + } + }() + b.CreateString("foo") +} + +func CheckEmptiedBuilder(fail func(string, ...interface{})) { + f := func(a, b string) bool { + if a == b { + return true + } + + builder := flatbuffers.NewBuilder(0) + + a1 := builder.CreateSharedString(a) + b1 := builder.CreateSharedString(b) + builder.Reset() + b2 := builder.CreateSharedString(b) + a2 := builder.CreateSharedString(a) + + return !(a1 == a2 || b1 == b2) + } + if err := quick.Check(f, nil); err != nil { + fail("expected different offset") + } +} + +func CheckSharedStrings(fail func(string, ...interface{})) { + f := func(strings []string) bool { + b := flatbuffers.NewBuilder(0) + for _, s1 := range strings { + for _, s2 := range strings { + off1 := b.CreateSharedString(s1) + off2 := b.CreateSharedString(s2) + + if (s1 == s2) && (off1 != off2) { + return false + } + if (s1 != s2) && (off1 == off2) { + return false + } + } + } + return true + } + if err := quick.Check(f, nil); err != nil { + fail("expected same offset") + } +} + +// CheckByteStringIsNestedError verifies that a bytestring can not be created +// inside another object. +func CheckByteStringIsNestedError(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + b.StartObject(0) + defer func() { + r := recover() + if r == nil { + fail("expected panic in CheckByteStringIsNestedError") + } + }() + b.CreateByteString([]byte("foo")) +} + +// CheckStructIsNotInlineError verifies that writing a struct in a location +// away from where it is used will cause a panic. +func CheckStructIsNotInlineError(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + b.StartObject(0) + defer func() { + r := recover() + if r == nil { + fail("expected panic in CheckStructIsNotInlineError") + } + }() + b.PrependStructSlot(0, 1, 0) +} + +// CheckFinishedBytesError verifies that `FinishedBytes` panics if the table +// is not finished. +func CheckFinishedBytesError(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + + defer func() { + r := recover() + if r == nil { + fail("expected panic in CheckFinishedBytesError") + } + }() + b.FinishedBytes() +} + +// CheckEnumNames checks that the generated enum names are correct. +func CheckEnumNames(fail func(string, ...interface{})) { + { + want := map[example.Any]string{ + example.AnyNONE: "NONE", + example.AnyMonster: "Monster", + example.AnyTestSimpleTableWithEnum: "TestSimpleTableWithEnum", + example.AnyMyGame_Example2_Monster: "MyGame_Example2_Monster", + } + got := example.EnumNamesAny + if !reflect.DeepEqual(got, want) { + fail("enum name is not equal") + } + } + { + want := map[example.Color]string{ + example.ColorRed: "Red", + example.ColorGreen: "Green", + example.ColorBlue: "Blue", + } + got := example.EnumNamesColor + if !reflect.DeepEqual(got, want) { + fail("enum name is not equal") + } + } +} + +// CheckEnumString checks the String method on generated enum types. +func CheckEnumString(fail func(string, ...interface{})) { + if got := example.AnyMonster.String(); got != "Monster" { + fail("Monster.String: %q != %q", got, "Monster") + } + if got := fmt.Sprintf("color: %s", example.ColorGreen); got != "color: Green" { + fail("color.String: %q != %q", got, "color: Green") + } +} + +// CheckEnumValues checks that the generated enum values maps are correct. +func CheckEnumValues(fail func(string, ...interface{})) { + { + want := map[string]example.Any{ + "NONE": example.AnyNONE, + "Monster": example.AnyMonster, + "TestSimpleTableWithEnum": example.AnyTestSimpleTableWithEnum, + "MyGame_Example2_Monster": example.AnyMyGame_Example2_Monster, + } + got := example.EnumValuesAny + if !reflect.DeepEqual(got, want) { + fail("enum name is not equal") + } + } + { + want := map[string]example.Color{ + "Red": example.ColorRed, + "Green": example.ColorGreen, + "Blue": example.ColorBlue, + } + got := example.EnumValuesColor + if !reflect.DeepEqual(got, want) { + fail("enum name is not equal") + } + } +} + +// CheckDocExample checks that the code given in FlatBuffers documentation +// is syntactically correct. +func CheckDocExample(buf []byte, off flatbuffers.UOffsetT, fail func(string, ...interface{})) { + monster := example.GetRootAsMonster(buf, off) + _ = monster.Hp() + _ = monster.Pos(nil) + for i := 0; i < monster.InventoryLength(); i++ { + _ = monster.Inventory(i) // do something here + } + + builder := flatbuffers.NewBuilder(0) + + example.MonsterStartInventoryVector(builder, 5) + for i := 4; i >= 0; i-- { + builder.PrependByte(byte(i)) + } + inv := builder.EndVector(5) + + str := builder.CreateString("MyMonster") + example.MonsterStart(builder) + example.MonsterAddPos(builder, example.CreateVec3(builder, 1.0, 2.0, 3.0, 3.0, example.Color(4), 5, 6)) + example.MonsterAddHp(builder, 80) + example.MonsterAddName(builder, str) + example.MonsterAddInventory(builder, inv) + example.MonsterAddTestType(builder, 1) + example.MonsterAddColor(builder, example.ColorRed) + // example.MonsterAddTest(builder, mon2) + // example.MonsterAddTest4(builder, test4s) + _ = example.MonsterEnd(builder) +} + +func CheckCreateByteVector(fail func(string, ...interface{})) { + raw := [30]byte{} + for i := 0; i < len(raw); i++ { + raw[i] = byte(i) + } + + for size := 0; size < len(raw); size++ { + b1 := flatbuffers.NewBuilder(0) + b2 := flatbuffers.NewBuilder(0) + b1.StartVector(1, size, 1) + for i := size - 1; i >= 0; i-- { + b1.PrependByte(raw[i]) + } + b1.EndVector(size) + b2.CreateByteVector(raw[:size]) + CheckByteEquality(b1.Bytes, b2.Bytes, fail) + } +} + +func CheckParentNamespace(fail func(string, ...interface{})) { + var empty, nonempty []byte + + // create monster with an empty parent namespace field + { + builder := flatbuffers.NewBuilder(0) + + example.MonsterStart(builder) + m := example.MonsterEnd(builder) + builder.Finish(m) + + empty = make([]byte, len(builder.FinishedBytes())) + copy(empty, builder.FinishedBytes()) + } + + // create monster with a non-empty parent namespace field + { + builder := flatbuffers.NewBuilder(0) + mygame.InParentNamespaceStart(builder) + pn := mygame.InParentNamespaceEnd(builder) + + example.MonsterStart(builder) + example.MonsterAddParentNamespaceTest(builder, pn) + m := example.MonsterEnd(builder) + + builder.Finish(m) + + nonempty = make([]byte, len(builder.FinishedBytes())) + copy(nonempty, builder.FinishedBytes()) + } + + // read monster with empty parent namespace field + { + m := example.GetRootAsMonster(empty, 0) + if m.ParentNamespaceTest(nil) != nil { + fail("expected nil ParentNamespaceTest for empty field") + } + } + + // read monster with non-empty parent namespace field + { + m := example.GetRootAsMonster(nonempty, 0) + if m.ParentNamespaceTest(nil) == nil { + fail("expected non-nil ParentNamespaceTest for non-empty field") + } + } +} + +func CheckSizePrefixedBuffer(fail func(string, ...interface{})) { + // Generate a size-prefixed flatbuffer, first without file identifier + generated, off := CheckGeneratedBuild(true, false, fail) + + // Check that the buffer can be used as expected + CheckReadBuffer(generated, off, true, fail) + CheckMutateBuffer(generated, off, true, fail) + CheckObjectAPI(generated, off, true, fail) + + // Now generate a size-prefixed flatbuffer with file identifier + generated, off = CheckGeneratedBuild(true, true, fail) + + // Check that the size prefix is the size of monsterdata_go_wire.mon, + // plus 4 bytes for padding + size := flatbuffers.GetSizePrefix(generated, off) + expectedSize := uint32(228) + if size != expectedSize { + fail("mismatch between size prefix (%d) and expected size (%d)", size, expectedSize) + } + + // Check that the buffer can be used as expected + CheckReadBuffer(generated, off, true, fail) + CheckMutateBuffer(generated, off, true, fail) + CheckObjectAPI(generated, off, true, fail) + CheckFileIdentifier(generated, off, true, fail) + + // Write generated buffer out to a file + if err := os.WriteFile(outData+".sp", generated[off:], os.FileMode(0644)); err != nil { + fail("failed to write file: %s", err) + } +} + +// Include simple random number generator to ensure results will be the +// same cross platform. +// http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator +type LCG uint32 + +const InitialLCGSeed = 48271 + +func NewLCG() *LCG { + n := uint32(InitialLCGSeed) + l := LCG(n) + return &l +} + +func (lcg *LCG) Reset() { + *lcg = InitialLCGSeed +} + +func (lcg *LCG) Next() uint32 { + n := uint32((uint64(*lcg) * uint64(279470273)) % uint64(4294967291)) + *lcg = LCG(n) + return n +} + +// CheckByteEquality verifies that two byte buffers are the same. +func CheckByteEquality(a, b []byte, fail func(string, ...interface{})) { + if !bytes.Equal(a, b) { + fail("objects are not byte-wise equal") + } +} + +// CheckMutateMethods checks all mutate methods one by one +func CheckMutateMethods(fail func(string, ...interface{})) { + b := flatbuffers.NewBuilder(0) + b.StartObject(15) + b.PrependBoolSlot(0, true, false) + b.PrependByteSlot(1, 1, 0) + b.PrependUint8Slot(2, 2, 0) + b.PrependUint16Slot(3, 3, 0) + b.PrependUint32Slot(4, 4, 0) + b.PrependUint64Slot(5, 5, 0) + b.PrependInt8Slot(6, 6, 0) + b.PrependInt16Slot(7, 7, 0) + b.PrependInt32Slot(8, 8, 0) + b.PrependInt64Slot(9, 9, 0) + b.PrependFloat32Slot(10, 10, 0) + b.PrependFloat64Slot(11, 11, 0) + + b.PrependUOffsetTSlot(12, 12, 0) + uoVal := b.Offset() - 12 + + b.PrependVOffsetT(13) + b.Slot(13) + + b.PrependSOffsetT(14) + b.Slot(14) + soVal := flatbuffers.SOffsetT(b.Offset() - 14) + + offset := b.EndObject() + + t := &flatbuffers.Table{ + Bytes: b.Bytes, + Pos: flatbuffers.UOffsetT(len(b.Bytes)) - offset, + } + + calcVOffsetT := func(slot int) (vtableOffset flatbuffers.VOffsetT) { + return flatbuffers.VOffsetT((flatbuffers.VtableMetadataFields + slot) * flatbuffers.SizeVOffsetT) + } + calcUOffsetT := func(vtableOffset flatbuffers.VOffsetT) (valueOffset flatbuffers.UOffsetT) { + return t.Pos + flatbuffers.UOffsetT(t.Offset(vtableOffset)) + } + + type testcase struct { + field string + testfn func() bool + } + + testForOriginalValues := []testcase{ + testcase{"BoolSlot", func() bool { return t.GetBoolSlot(calcVOffsetT(0), true) == true }}, + testcase{"ByteSlot", func() bool { return t.GetByteSlot(calcVOffsetT(1), 1) == 1 }}, + testcase{"Uint8Slot", func() bool { return t.GetUint8Slot(calcVOffsetT(2), 2) == 2 }}, + testcase{"Uint16Slot", func() bool { return t.GetUint16Slot(calcVOffsetT(3), 3) == 3 }}, + testcase{"Uint32Slot", func() bool { return t.GetUint32Slot(calcVOffsetT(4), 4) == 4 }}, + testcase{"Uint64Slot", func() bool { return t.GetUint64Slot(calcVOffsetT(5), 5) == 5 }}, + testcase{"Int8Slot", func() bool { return t.GetInt8Slot(calcVOffsetT(6), 6) == 6 }}, + testcase{"Int16Slot", func() bool { return t.GetInt16Slot(calcVOffsetT(7), 7) == 7 }}, + testcase{"Int32Slot", func() bool { return t.GetInt32Slot(calcVOffsetT(8), 8) == 8 }}, + testcase{"Int64Slot", func() bool { return t.GetInt64Slot(calcVOffsetT(9), 9) == 9 }}, + testcase{"Float32Slot", func() bool { return t.GetFloat32Slot(calcVOffsetT(10), 10) == 10 }}, + testcase{"Float64Slot", func() bool { return t.GetFloat64Slot(calcVOffsetT(11), 11) == 11 }}, + testcase{"UOffsetTSlot", func() bool { return t.GetUOffsetT(calcUOffsetT(calcVOffsetT(12))) == uoVal }}, + testcase{"VOffsetTSlot", func() bool { return t.GetVOffsetT(calcUOffsetT(calcVOffsetT(13))) == 13 }}, + testcase{"SOffsetTSlot", func() bool { return t.GetSOffsetT(calcUOffsetT(calcVOffsetT(14))) == soVal }}, + } + + testMutability := []testcase{ + testcase{"BoolSlot", func() bool { return t.MutateBoolSlot(calcVOffsetT(0), false) }}, + testcase{"ByteSlot", func() bool { return t.MutateByteSlot(calcVOffsetT(1), 2) }}, + testcase{"Uint8Slot", func() bool { return t.MutateUint8Slot(calcVOffsetT(2), 4) }}, + testcase{"Uint16Slot", func() bool { return t.MutateUint16Slot(calcVOffsetT(3), 6) }}, + testcase{"Uint32Slot", func() bool { return t.MutateUint32Slot(calcVOffsetT(4), 8) }}, + testcase{"Uint64Slot", func() bool { return t.MutateUint64Slot(calcVOffsetT(5), 10) }}, + testcase{"Int8Slot", func() bool { return t.MutateInt8Slot(calcVOffsetT(6), 12) }}, + testcase{"Int16Slot", func() bool { return t.MutateInt16Slot(calcVOffsetT(7), 14) }}, + testcase{"Int32Slot", func() bool { return t.MutateInt32Slot(calcVOffsetT(8), 16) }}, + testcase{"Int64Slot", func() bool { return t.MutateInt64Slot(calcVOffsetT(9), 18) }}, + testcase{"Float32Slot", func() bool { return t.MutateFloat32Slot(calcVOffsetT(10), 20) }}, + testcase{"Float64Slot", func() bool { return t.MutateFloat64Slot(calcVOffsetT(11), 22) }}, + testcase{"UOffsetTSlot", func() bool { return t.MutateUOffsetT(calcUOffsetT(calcVOffsetT(12)), 24) }}, + testcase{"VOffsetTSlot", func() bool { return t.MutateVOffsetT(calcUOffsetT(calcVOffsetT(13)), 26) }}, + testcase{"SOffsetTSlot", func() bool { return t.MutateSOffsetT(calcUOffsetT(calcVOffsetT(14)), 28) }}, + } + + testMutabilityWithoutSlot := []testcase{ + testcase{"BoolSlot", func() bool { return t.MutateBoolSlot(calcVOffsetT(16), false) }}, + testcase{"ByteSlot", func() bool { return t.MutateByteSlot(calcVOffsetT(16), 2) }}, + testcase{"Uint8Slot", func() bool { return t.MutateUint8Slot(calcVOffsetT(16), 2) }}, + testcase{"Uint16Slot", func() bool { return t.MutateUint16Slot(calcVOffsetT(16), 2) }}, + testcase{"Uint32Slot", func() bool { return t.MutateUint32Slot(calcVOffsetT(16), 2) }}, + testcase{"Uint64Slot", func() bool { return t.MutateUint64Slot(calcVOffsetT(16), 2) }}, + testcase{"Int8Slot", func() bool { return t.MutateInt8Slot(calcVOffsetT(16), 2) }}, + testcase{"Int16Slot", func() bool { return t.MutateInt16Slot(calcVOffsetT(16), 2) }}, + testcase{"Int32Slot", func() bool { return t.MutateInt32Slot(calcVOffsetT(16), 2) }}, + testcase{"Int64Slot", func() bool { return t.MutateInt64Slot(calcVOffsetT(16), 2) }}, + testcase{"Float32Slot", func() bool { return t.MutateFloat32Slot(calcVOffsetT(16), 2) }}, + testcase{"Float64Slot", func() bool { return t.MutateFloat64Slot(calcVOffsetT(16), 2) }}, + } + + testForMutatedValues := []testcase{ + testcase{"BoolSlot", func() bool { return t.GetBoolSlot(calcVOffsetT(0), true) == false }}, + testcase{"ByteSlot", func() bool { return t.GetByteSlot(calcVOffsetT(1), 1) == 2 }}, + testcase{"Uint8Slot", func() bool { return t.GetUint8Slot(calcVOffsetT(2), 1) == 4 }}, + testcase{"Uint16Slot", func() bool { return t.GetUint16Slot(calcVOffsetT(3), 1) == 6 }}, + testcase{"Uint32Slot", func() bool { return t.GetUint32Slot(calcVOffsetT(4), 1) == 8 }}, + testcase{"Uint64Slot", func() bool { return t.GetUint64Slot(calcVOffsetT(5), 1) == 10 }}, + testcase{"Int8Slot", func() bool { return t.GetInt8Slot(calcVOffsetT(6), 1) == 12 }}, + testcase{"Int16Slot", func() bool { return t.GetInt16Slot(calcVOffsetT(7), 1) == 14 }}, + testcase{"Int32Slot", func() bool { return t.GetInt32Slot(calcVOffsetT(8), 1) == 16 }}, + testcase{"Int64Slot", func() bool { return t.GetInt64Slot(calcVOffsetT(9), 1) == 18 }}, + testcase{"Float32Slot", func() bool { return t.GetFloat32Slot(calcVOffsetT(10), 1) == 20 }}, + testcase{"Float64Slot", func() bool { return t.GetFloat64Slot(calcVOffsetT(11), 1) == 22 }}, + testcase{"UOffsetTSlot", func() bool { return t.GetUOffsetT(calcUOffsetT(calcVOffsetT(12))) == 24 }}, + testcase{"VOffsetTSlot", func() bool { return t.GetVOffsetT(calcUOffsetT(calcVOffsetT(13))) == 26 }}, + testcase{"SOffsetTSlot", func() bool { return t.GetSOffsetT(calcUOffsetT(calcVOffsetT(14))) == 28 }}, + } + + // make sure original values are okay + for _, t := range testForOriginalValues { + if !t.testfn() { + fail(t.field + "' field doesn't have the expected original value") + } + } + + // try to mutate fields and check mutability + for _, t := range testMutability { + if !t.testfn() { + fail(FailString(t.field+"' field failed mutability test", "passed", "failed")) + } + } + + // try to mutate fields and check mutability + // these have wrong slots so should fail + for _, t := range testMutabilityWithoutSlot { + if t.testfn() { + fail(FailString(t.field+"' field failed no slot mutability test", "failed", "passed")) + } + } + + // test whether values have changed + for _, t := range testForMutatedValues { + if !t.testfn() { + fail(t.field + "' field doesn't have the expected mutated value") + } + } +} + +// CheckOptionalScalars verifies against the ScalarStuff schema. +func CheckOptionalScalars(fail func(string, ...interface{})) { + type testCase struct { + what string + result, expect interface{} + } + + makeDefaultTestCases := func(s *optional_scalars.ScalarStuff) []testCase { + return []testCase{ + {"justI8", s.JustI8(), int8(0)}, + {"maybeI8", s.MaybeI8(), (*int8)(nil)}, + {"defaultI8", s.DefaultI8(), int8(42)}, + {"justU8", s.JustU8(), byte(0)}, + {"maybeU8", s.MaybeU8(), (*byte)(nil)}, + {"defaultU8", s.DefaultU8(), byte(42)}, + {"justI16", s.JustI16(), int16(0)}, + {"maybeI16", s.MaybeI16(), (*int16)(nil)}, + {"defaultI16", s.DefaultI16(), int16(42)}, + {"justU16", s.JustU16(), uint16(0)}, + {"maybeU16", s.MaybeU16(), (*uint16)(nil)}, + {"defaultU16", s.DefaultU16(), uint16(42)}, + {"justI32", s.JustI32(), int32(0)}, + {"maybeI32", s.MaybeI32(), (*int32)(nil)}, + {"defaultI32", s.DefaultI32(), int32(42)}, + {"justU32", s.JustU32(), uint32(0)}, + {"maybeU32", s.MaybeU32(), (*uint32)(nil)}, + {"defaultU32", s.DefaultU32(), uint32(42)}, + {"justI64", s.JustI64(), int64(0)}, + {"maybeI64", s.MaybeI64(), (*int64)(nil)}, + {"defaultI64", s.DefaultI64(), int64(42)}, + {"justU64", s.JustU64(), uint64(0)}, + {"maybeU64", s.MaybeU64(), (*uint64)(nil)}, + {"defaultU64", s.DefaultU64(), uint64(42)}, + {"justF32", s.JustF32(), float32(0)}, + {"maybeF32", s.MaybeF32(), (*float32)(nil)}, + {"defaultF32", s.DefaultF32(), float32(42)}, + {"justF64", s.JustF64(), float64(0)}, + {"maybeF64", s.MaybeF64(), (*float64)(nil)}, + {"defaultF64", s.DefaultF64(), float64(42)}, + {"justBool", s.JustBool(), false}, + {"maybeBool", s.MaybeBool(), (*bool)(nil)}, + {"defaultBool", s.DefaultBool(), true}, + {"justEnum", s.JustEnum(), optional_scalars.OptionalByte(0)}, + {"maybeEnum", s.MaybeEnum(), (*optional_scalars.OptionalByte)(nil)}, + {"defaultEnum", s.DefaultEnum(), optional_scalars.OptionalByteOne}, + } + } + + makeAssignedTestCases := func(s *optional_scalars.ScalarStuff) []testCase { + return []testCase{ + {"justI8", s.JustI8(), int8(5)}, + {"maybeI8", s.MaybeI8(), int8(5)}, + {"defaultI8", s.DefaultI8(), int8(5)}, + {"justU8", s.JustU8(), byte(6)}, + {"maybeU8", s.MaybeU8(), byte(6)}, + {"defaultU8", s.DefaultU8(), byte(6)}, + {"justI16", s.JustI16(), int16(7)}, + {"maybeI16", s.MaybeI16(), int16(7)}, + {"defaultI16", s.DefaultI16(), int16(7)}, + {"justU16", s.JustU16(), uint16(8)}, + {"maybeU16", s.MaybeU16(), uint16(8)}, + {"defaultU16", s.DefaultU16(), uint16(8)}, + {"justI32", s.JustI32(), int32(9)}, + {"maybeI32", s.MaybeI32(), int32(9)}, + {"defaultI32", s.DefaultI32(), int32(9)}, + {"justU32", s.JustU32(), uint32(10)}, + {"maybeU32", s.MaybeU32(), uint32(10)}, + {"defaultU32", s.DefaultU32(), uint32(10)}, + {"justI64", s.JustI64(), int64(11)}, + {"maybeI64", s.MaybeI64(), int64(11)}, + {"defaultI64", s.DefaultI64(), int64(11)}, + {"justU64", s.JustU64(), uint64(12)}, + {"maybeU64", s.MaybeU64(), uint64(12)}, + {"defaultU64", s.DefaultU64(), uint64(12)}, + {"justF32", s.JustF32(), float32(13)}, + {"maybeF32", s.MaybeF32(), float32(13)}, + {"defaultF32", s.DefaultF32(), float32(13)}, + {"justF64", s.JustF64(), float64(14)}, + {"maybeF64", s.MaybeF64(), float64(14)}, + {"defaultF64", s.DefaultF64(), float64(14)}, + {"justBool", s.JustBool(), true}, + {"maybeBool", s.MaybeBool(), true}, + {"defaultBool", s.DefaultBool(), false}, + {"justEnum", s.JustEnum(), optional_scalars.OptionalByteTwo}, + {"maybeEnum", s.MaybeEnum(), optional_scalars.OptionalByteTwo}, + {"defaultEnum", s.DefaultEnum(), optional_scalars.OptionalByteTwo}, + } + } + + resolvePointer := func(v interface{}) interface{} { + switch v := v.(type) { + case *int8: + return *v + case *byte: + return *v + case *int16: + return *v + case *uint16: + return *v + case *int32: + return *v + case *uint32: + return *v + case *int64: + return *v + case *uint64: + return *v + case *float32: + return *v + case *float64: + return *v + case *bool: + return *v + case *optional_scalars.OptionalByte: + return *v + default: + return v + } + } + + buildAssignedTable := func(b *flatbuffers.Builder) *optional_scalars.ScalarStuff { + optional_scalars.ScalarStuffStart(b) + optional_scalars.ScalarStuffAddJustI8(b, int8(5)) + optional_scalars.ScalarStuffAddMaybeI8(b, int8(5)) + optional_scalars.ScalarStuffAddDefaultI8(b, int8(5)) + optional_scalars.ScalarStuffAddJustU8(b, byte(6)) + optional_scalars.ScalarStuffAddMaybeU8(b, byte(6)) + optional_scalars.ScalarStuffAddDefaultU8(b, byte(6)) + optional_scalars.ScalarStuffAddJustI16(b, int16(7)) + optional_scalars.ScalarStuffAddMaybeI16(b, int16(7)) + optional_scalars.ScalarStuffAddDefaultI16(b, int16(7)) + optional_scalars.ScalarStuffAddJustU16(b, uint16(8)) + optional_scalars.ScalarStuffAddMaybeU16(b, uint16(8)) + optional_scalars.ScalarStuffAddDefaultU16(b, uint16(8)) + optional_scalars.ScalarStuffAddJustI32(b, int32(9)) + optional_scalars.ScalarStuffAddMaybeI32(b, int32(9)) + optional_scalars.ScalarStuffAddDefaultI32(b, int32(9)) + optional_scalars.ScalarStuffAddJustU32(b, uint32(10)) + optional_scalars.ScalarStuffAddMaybeU32(b, uint32(10)) + optional_scalars.ScalarStuffAddDefaultU32(b, uint32(10)) + optional_scalars.ScalarStuffAddJustI64(b, int64(11)) + optional_scalars.ScalarStuffAddMaybeI64(b, int64(11)) + optional_scalars.ScalarStuffAddDefaultI64(b, int64(11)) + optional_scalars.ScalarStuffAddJustU64(b, uint64(12)) + optional_scalars.ScalarStuffAddMaybeU64(b, uint64(12)) + optional_scalars.ScalarStuffAddDefaultU64(b, uint64(12)) + optional_scalars.ScalarStuffAddJustF32(b, float32(13)) + optional_scalars.ScalarStuffAddMaybeF32(b, float32(13)) + optional_scalars.ScalarStuffAddDefaultF32(b, float32(13)) + optional_scalars.ScalarStuffAddJustF64(b, float64(14)) + optional_scalars.ScalarStuffAddMaybeF64(b, float64(14)) + optional_scalars.ScalarStuffAddDefaultF64(b, float64(14)) + optional_scalars.ScalarStuffAddJustBool(b, true) + optional_scalars.ScalarStuffAddMaybeBool(b, true) + optional_scalars.ScalarStuffAddDefaultBool(b, false) + optional_scalars.ScalarStuffAddJustEnum(b, optional_scalars.OptionalByteTwo) + optional_scalars.ScalarStuffAddMaybeEnum(b, optional_scalars.OptionalByteTwo) + optional_scalars.ScalarStuffAddDefaultEnum(b, optional_scalars.OptionalByteTwo) + b.Finish(optional_scalars.ScalarStuffEnd(b)) + return optional_scalars.GetRootAsScalarStuff(b.FinishedBytes(), 0) + } + + // test default values + + fbb := flatbuffers.NewBuilder(1) + optional_scalars.ScalarStuffStart(fbb) + fbb.Finish(optional_scalars.ScalarStuffEnd(fbb)) + ss := optional_scalars.GetRootAsScalarStuff(fbb.FinishedBytes(), 0) + for _, tc := range makeDefaultTestCases(ss) { + if tc.result != tc.expect { + fail(FailString("Default ScalarStuff: "+tc.what, tc.expect, tc.result)) + } + } + + // test assigned values + fbb.Reset() + ss = buildAssignedTable(fbb) + for _, tc := range makeAssignedTestCases(ss) { + if resolvePointer(tc.result) != tc.expect { + fail(FailString("Assigned ScalarStuff: "+tc.what, tc.expect, tc.result)) + } + } + + // test native object pack + fbb.Reset() + i8 := int8(5) + u8 := byte(6) + i16 := int16(7) + u16 := uint16(8) + i32 := int32(9) + u32 := uint32(10) + i64 := int64(11) + u64 := uint64(12) + f32 := float32(13) + f64 := float64(14) + b := true + enum := optional_scalars.OptionalByteTwo + obj := optional_scalars.ScalarStuffT{ + JustI8: 5, + MaybeI8: &i8, + DefaultI8: 5, + JustU8: 6, + MaybeU8: &u8, + DefaultU8: 6, + JustI16: 7, + MaybeI16: &i16, + DefaultI16: 7, + JustU16: 8, + MaybeU16: &u16, + DefaultU16: 8, + JustI32: 9, + MaybeI32: &i32, + DefaultI32: 9, + JustU32: 10, + MaybeU32: &u32, + DefaultU32: 10, + JustI64: 11, + MaybeI64: &i64, + DefaultI64: 11, + JustU64: 12, + MaybeU64: &u64, + DefaultU64: 12, + JustF32: 13, + MaybeF32: &f32, + DefaultF32: 13, + JustF64: 14, + MaybeF64: &f64, + DefaultF64: 14, + JustBool: true, + MaybeBool: &b, + DefaultBool: false, + JustEnum: optional_scalars.OptionalByteTwo, + MaybeEnum: &enum, + DefaultEnum: optional_scalars.OptionalByteTwo, + } + fbb.Finish(obj.Pack(fbb)) + ss = optional_scalars.GetRootAsScalarStuff(fbb.FinishedBytes(), 0) + for _, tc := range makeAssignedTestCases(ss) { + if resolvePointer(tc.result) != tc.expect { + fail(FailString("Native Object ScalarStuff: "+tc.what, tc.expect, tc.result)) + } + } + + // test native object unpack + fbb.Reset() + ss = buildAssignedTable(fbb) + ss.UnPackTo(&obj) + expectEq := func(what string, a, b interface{}) { + if resolvePointer(a) != b { + fail(FailString("Native Object Unpack ScalarStuff: "+what, b, a)) + } + } + expectEq("justI8", obj.JustI8, int8(5)) + expectEq("maybeI8", obj.MaybeI8, int8(5)) + expectEq("defaultI8", obj.DefaultI8, int8(5)) + expectEq("justU8", obj.JustU8, byte(6)) + expectEq("maybeU8", obj.MaybeU8, byte(6)) + expectEq("defaultU8", obj.DefaultU8, byte(6)) + expectEq("justI16", obj.JustI16, int16(7)) + expectEq("maybeI16", obj.MaybeI16, int16(7)) + expectEq("defaultI16", obj.DefaultI16, int16(7)) + expectEq("justU16", obj.JustU16, uint16(8)) + expectEq("maybeU16", obj.MaybeU16, uint16(8)) + expectEq("defaultU16", obj.DefaultU16, uint16(8)) + expectEq("justI32", obj.JustI32, int32(9)) + expectEq("maybeI32", obj.MaybeI32, int32(9)) + expectEq("defaultI32", obj.DefaultI32, int32(9)) + expectEq("justU32", obj.JustU32, uint32(10)) + expectEq("maybeU32", obj.MaybeU32, uint32(10)) + expectEq("defaultU32", obj.DefaultU32, uint32(10)) + expectEq("justI64", obj.JustI64, int64(11)) + expectEq("maybeI64", obj.MaybeI64, int64(11)) + expectEq("defaultI64", obj.DefaultI64, int64(11)) + expectEq("justU64", obj.JustU64, uint64(12)) + expectEq("maybeU64", obj.MaybeU64, uint64(12)) + expectEq("defaultU64", obj.DefaultU64, uint64(12)) + expectEq("justF32", obj.JustF32, float32(13)) + expectEq("maybeF32", obj.MaybeF32, float32(13)) + expectEq("defaultF32", obj.DefaultF32, float32(13)) + expectEq("justF64", obj.JustF64, float64(14)) + expectEq("maybeF64", obj.MaybeF64, float64(14)) + expectEq("defaultF64", obj.DefaultF64, float64(14)) + expectEq("justBool", obj.JustBool, true) + expectEq("maybeBool", obj.MaybeBool, true) + expectEq("defaultBool", obj.DefaultBool, false) + expectEq("justEnum", obj.JustEnum, optional_scalars.OptionalByteTwo) + expectEq("maybeEnum", obj.MaybeEnum, optional_scalars.OptionalByteTwo) + expectEq("defaultEnum", obj.DefaultEnum, optional_scalars.OptionalByteTwo) +} + +func CheckByKey(fail func(string, ...interface{})) { + expectEq := func(what string, a, b interface{}) { + if a != b { + fail(FailString("Lookup by key: "+what, b, a)) + } + } + + b := flatbuffers.NewBuilder(0) + name := b.CreateString("Boss") + + slime := &example.MonsterT{Name: "Slime"} + pig := &example.MonsterT{Name: "Pig"} + slimeBoss := &example.MonsterT{Name: "SlimeBoss"} + mushroom := &example.MonsterT{Name: "Mushroom"} + ironPig := &example.MonsterT{Name: "Iron Pig"} + + monsterOffsets := make([]flatbuffers.UOffsetT, 5) + monsterOffsets[0] = slime.Pack(b) + monsterOffsets[1] = pig.Pack(b) + monsterOffsets[2] = slimeBoss.Pack(b) + monsterOffsets[3] = mushroom.Pack(b) + monsterOffsets[4] = ironPig.Pack(b) + testarrayoftables := b.CreateVectorOfSortedTables(monsterOffsets, example.MonsterKeyCompare) + + str := &example.StatT{Id: "Strength", Count: 42} + luk := &example.StatT{Id: "Luck", Count: 51} + hp := &example.StatT{Id: "Health", Count: 12} + // Test default count value of 0 + mp := &example.StatT{Id: "Mana"} + + statOffsets := make([]flatbuffers.UOffsetT, 4) + statOffsets[0] = str.Pack(b) + statOffsets[1] = luk.Pack(b) + statOffsets[2] = hp.Pack(b) + statOffsets[3] = mp.Pack(b) + scalarKeySortedTablesOffset := b.CreateVectorOfSortedTables(statOffsets, example.StatKeyCompare) + + example.MonsterStart(b) + example.MonsterAddName(b, name) + example.MonsterAddTestarrayoftables(b, testarrayoftables) + example.MonsterAddScalarKeySortedTables(b, scalarKeySortedTablesOffset) + moff := example.MonsterEnd(b) + b.Finish(moff) + + monster := example.GetRootAsMonster(b.Bytes, b.Head()) + slimeMon := &example.Monster{} + monster.TestarrayoftablesByKey(slimeMon, slime.Name) + mushroomMon := &example.Monster{} + monster.TestarrayoftablesByKey(mushroomMon, mushroom.Name) + slimeBossMon := &example.Monster{} + monster.TestarrayoftablesByKey(slimeBossMon, slimeBoss.Name) + + strStat := &example.Stat{} + monster.ScalarKeySortedTablesByKey(strStat, str.Count) + lukStat := &example.Stat{} + monster.ScalarKeySortedTablesByKey(lukStat, luk.Count) + mpStat := &example.Stat{} + monster.ScalarKeySortedTablesByKey(mpStat, mp.Count) + + expectEq("Boss name", string(monster.Name()), "Boss") + expectEq("Slime name", string(slimeMon.Name()), slime.Name) + expectEq("Mushroom name", string(mushroomMon.Name()), mushroom.Name) + expectEq("SlimeBoss name", string(slimeBossMon.Name()), slimeBoss.Name) + expectEq("Strength Id", string(strStat.Id()), str.Id) + expectEq("Strength Count", strStat.Count(), str.Count) + expectEq("Luck Id", string(lukStat.Id()), luk.Id) + expectEq("Luck Count", lukStat.Count(), luk.Count) + expectEq("Mana Id", string(mpStat.Id()), mp.Id) + // Use default count value as key + expectEq("Mana Count", mpStat.Count(), uint16(0)) +} + +// BenchmarkVtableDeduplication measures the speed of vtable deduplication +// by creating prePop vtables, then populating b.N objects with a +// different single vtable. +// +// When b.N is large (as in long benchmarks), memory usage may be high. +func BenchmarkVtableDeduplication(b *testing.B) { + prePop := 10 + builder := flatbuffers.NewBuilder(0) + + // pre-populate some vtables: + for i := 0; i < prePop; i++ { + builder.StartObject(i) + for j := 0; j < i; j++ { + builder.PrependInt16Slot(j, int16(j), 0) + } + builder.EndObject() + } + + // benchmark deduplication of a new vtable: + b.ResetTimer() + for i := 0; i < b.N; i++ { + lim := prePop + + builder.StartObject(lim) + for j := 0; j < lim; j++ { + builder.PrependInt16Slot(j, int16(j), 0) + } + builder.EndObject() + } +} + +// BenchmarkParseGold measures the speed of parsing the 'gold' data +// used throughout this test suite. +func BenchmarkParseGold(b *testing.B) { + buf, offset := CheckGeneratedBuild(false, false, b.Fatalf) + monster := example.GetRootAsMonster(buf, offset) + + // use these to prevent allocations: + reuse_pos := example.Vec3{} + reuse_test3 := example.Test{} + reuse_table2 := flatbuffers.Table{} + reuse_monster2 := example.Monster{} + reuse_test4_0 := example.Test{} + reuse_test4_1 := example.Test{} + + b.SetBytes(int64(len(buf[offset:]))) + b.ReportAllocs() + b.ResetTimer() + for i := 0; i < b.N; i++ { + monster.Hp() + monster.Mana() + name := monster.Name() + _ = name[0] + _ = name[len(name)-1] + + monster.Pos(&reuse_pos) + reuse_pos.X() + reuse_pos.Y() + reuse_pos.Z() + reuse_pos.Test1() + reuse_pos.Test2() + reuse_pos.Test3(&reuse_test3) + reuse_test3.A() + reuse_test3.B() + monster.TestType() + monster.Test(&reuse_table2) + reuse_monster2.Init(reuse_table2.Bytes, reuse_table2.Pos) + name2 := reuse_monster2.Name() + _ = name2[0] + _ = name2[len(name2)-1] + monster.InventoryLength() + l := monster.InventoryLength() + for i := 0; i < l; i++ { + monster.Inventory(i) + } + monster.Test4Length() + monster.Test4(&reuse_test4_0, 0) + monster.Test4(&reuse_test4_1, 1) + + reuse_test4_0.A() + reuse_test4_0.B() + reuse_test4_1.A() + reuse_test4_1.B() + + monster.TestarrayofstringLength() + str0 := monster.Testarrayofstring(0) + _ = str0[0] + _ = str0[len(str0)-1] + str1 := monster.Testarrayofstring(1) + _ = str1[0] + _ = str1[len(str1)-1] + } +} + +// BenchmarkBuildGold uses generated code to build the example Monster. +func BenchmarkBuildGold(b *testing.B) { + buf, offset := CheckGeneratedBuild(false, false, b.Fatalf) + bytes_length := int64(len(buf[offset:])) + + reuse_str := "MyMonster" + reuse_test1 := "test1" + reuse_test2 := "test2" + reuse_fred := "Fred" + + b.SetBytes(bytes_length) + bldr := flatbuffers.NewBuilder(0) + b.ResetTimer() + b.ReportAllocs() + for i := 0; i < b.N; i++ { + bldr.Reset() + + str := bldr.CreateString(reuse_str) + test1 := bldr.CreateString(reuse_test1) + test2 := bldr.CreateString(reuse_test2) + fred := bldr.CreateString(reuse_fred) + + example.MonsterStartInventoryVector(bldr, 5) + bldr.PrependByte(4) + bldr.PrependByte(3) + bldr.PrependByte(2) + bldr.PrependByte(1) + bldr.PrependByte(0) + inv := bldr.EndVector(5) + + example.MonsterStart(bldr) + example.MonsterAddName(bldr, fred) + mon2 := example.MonsterEnd(bldr) + + example.MonsterStartTest4Vector(bldr, 2) + example.CreateTest(bldr, 10, 20) + example.CreateTest(bldr, 30, 40) + test4 := bldr.EndVector(2) + + example.MonsterStartTestarrayofstringVector(bldr, 2) + bldr.PrependUOffsetT(test2) + bldr.PrependUOffsetT(test1) + testArrayOfString := bldr.EndVector(2) + + example.MonsterStart(bldr) + + pos := example.CreateVec3(bldr, 1.0, 2.0, 3.0, 3.0, example.ColorGreen, 5, 6) + example.MonsterAddPos(bldr, pos) + + example.MonsterAddHp(bldr, 80) + example.MonsterAddName(bldr, str) + example.MonsterAddInventory(bldr, inv) + example.MonsterAddTestType(bldr, 1) + example.MonsterAddTest(bldr, mon2) + example.MonsterAddTest4(bldr, test4) + example.MonsterAddTestarrayofstring(bldr, testArrayOfString) + mon := example.MonsterEnd(bldr) + + bldr.Finish(mon) + } +} diff --git a/third_party/flatbuffers/tests/gold_flexbuffer_example.bin b/third_party/flatbuffers/tests/gold_flexbuffer_example.bin new file mode 100644 index 00000000000..f9d24b1e30f Binary files /dev/null and b/third_party/flatbuffers/tests/gold_flexbuffer_example.bin differ diff --git a/third_party/flatbuffers/tests/include_build_test.cc b/third_party/flatbuffers/tests/include_build_test.cc new file mode 100644 index 00000000000..a5282cc5618 --- /dev/null +++ b/third_party/flatbuffers/tests/include_build_test.cc @@ -0,0 +1 @@ +#include "tests/includer_test_generated.h" diff --git a/third_party/flatbuffers/tests/include_test/include_test1.fbs b/third_party/flatbuffers/tests/include_test/include_test1.fbs new file mode 100644 index 00000000000..804856a28df --- /dev/null +++ b/third_party/flatbuffers/tests/include_test/include_test1.fbs @@ -0,0 +1,7 @@ +include "sub/include_test2.fbs"; +include "sub/include_test2.fbs"; // should be skipped +include "include_test1.fbs"; // should be skipped + +table TableA { + b:MyGame.OtherNameSpace.TableB; +} diff --git a/third_party/flatbuffers/tests/include_test/order.fbs b/third_party/flatbuffers/tests/include_test/order.fbs new file mode 100644 index 00000000000..4588d5fd1b3 --- /dev/null +++ b/third_party/flatbuffers/tests/include_test/order.fbs @@ -0,0 +1,8 @@ +include "no_namespace.fbs"; + +namespace order; + +table Food { + pizza: Pizza (id: 0); + pizza_test:Pizza(id:1); +} diff --git a/third_party/flatbuffers/tests/include_test/sub/include_test2.fbs b/third_party/flatbuffers/tests/include_test/sub/include_test2.fbs new file mode 100644 index 00000000000..7225735cbfe --- /dev/null +++ b/third_party/flatbuffers/tests/include_test/sub/include_test2.fbs @@ -0,0 +1,12 @@ +include "include_test1.fbs"; +include "sub/include_test2.fbs"; // should be skipped + +namespace MyGame.OtherNameSpace; + +enum FromInclude:long { IncludeVal } + +struct Unused { a:int; } + +table TableB { + a:TableA; +} diff --git a/third_party/flatbuffers/tests/include_test/sub/no_namespace.fbs b/third_party/flatbuffers/tests/include_test/sub/no_namespace.fbs new file mode 100644 index 00000000000..5f1052d1795 --- /dev/null +++ b/third_party/flatbuffers/tests/include_test/sub/no_namespace.fbs @@ -0,0 +1,3 @@ +table Pizza { + size: int; +} diff --git a/third_party/flatbuffers/tests/include_test1/mod.rs b/third_party/flatbuffers/tests/include_test1/mod.rs new file mode 100644 index 00000000000..ca4894dc32c --- /dev/null +++ b/third_party/flatbuffers/tests/include_test1/mod.rs @@ -0,0 +1,16 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod my_game { + use super::*; + pub mod other_name_space { + use super::*; + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space +} // my_game +mod table_a_generated; +pub use self::table_a_generated::*; diff --git a/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/from_include_generated.rs b/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/from_include_generated.rs new file mode 100644 index 00000000000..70cb407c1ea --- /dev/null +++ b/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/from_include_generated.rs @@ -0,0 +1,92 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ + FromInclude::IncludeVal, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FromInclude(pub i64); +#[allow(non_upper_case_globals)] +impl FromInclude { + pub const IncludeVal: Self = Self(0); + + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, + } + } +} +impl core::fmt::Debug for FromInclude { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for FromInclude { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for FromInclude { + type Output = FromInclude; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for FromInclude { + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for FromInclude { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/table_b_generated.rs b/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/table_b_generated.rs new file mode 100644 index 00000000000..84932cbc5ad --- /dev/null +++ b/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/table_b_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableBOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableB<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableB<'a> { + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableB<'a> { + pub const VT_A: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + Box::new(x.unpack()) + }); + TableBT { + a, + } + } + + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableB::VT_A, None)} + } +} + +impl flatbuffers::Verifiable for TableB<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct TableBArgs<'a> { + pub a: Option>>, +} +impl<'a> Default for TableBArgs<'a> { + #[inline] + fn default() -> Self { + TableBArgs { + a: None, + } + } +} + +pub struct TableBBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableB<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableBT { + pub a: Option>, +} +impl Default for TableBT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl TableBT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } +} diff --git a/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/unused_generated.rs b/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/unused_generated.rs new file mode 100644 index 00000000000..11af62f073b --- /dev/null +++ b/third_party/flatbuffers/tests/include_test1/my_game/other_name_space/unused_generated.rs @@ -0,0 +1,128 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Unused, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Unused(pub [u8; 4]); +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Unused { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Unused {} +impl<'a> flatbuffers::Follow<'a> for Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Unused>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Unused { + type Output = Unused; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Unused { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Unused { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } + + pub fn a(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct UnusedT { + pub a: i32, +} +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } +} + diff --git a/third_party/flatbuffers/tests/include_test1/table_a_generated.rs b/third_party/flatbuffers/tests/include_test1/table_a_generated.rs new file mode 100644 index 00000000000..781a6c469db --- /dev/null +++ b/third_party/flatbuffers/tests/include_test1/table_a_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableAOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableA<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableA<'a> { + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableA<'a> { + pub const VT_B: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + Box::new(x.unpack()) + }); + TableAT { + b, + } + } + + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableA::VT_B, None)} + } +} + +impl flatbuffers::Verifiable for TableA<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } +} +pub struct TableAArgs<'a> { + pub b: Option>>, +} +impl<'a> Default for TableAArgs<'a> { + #[inline] + fn default() -> Self { + TableAArgs { + b: None, + } + } +} + +pub struct TableABuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { + #[inline] + pub fn add_b(&mut self, b: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableA<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableAT { + pub b: Option>, +} +impl Default for TableAT { + fn default() -> Self { + Self { + b: None, + } + } +} +impl TableAT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } +} diff --git a/third_party/flatbuffers/tests/include_test1_generated.dart b/third_party/flatbuffers/tests/include_test1_generated.dart new file mode 100644 index 00000000000..c04bf6b2d22 --- /dev/null +++ b/third_party/flatbuffers/tests/include_test1_generated.dart @@ -0,0 +1,109 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +import './include_test2_my_game.other_name_space_generated.dart' as my_game_other_name_space; + +class TableA { + TableA._(this._bc, this._bcOffset); + factory TableA(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableAReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + my_game_other_name_space.TableB? get b => my_game_other_name_space.TableB.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'TableA{b: ${b}}'; + } + + TableAT unpack() => TableAT( + b: b?.unpack()); + + static int pack(fb.Builder fbBuilder, TableAT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableAT implements fb.Packable { + my_game_other_name_space.TableBT? b; + + TableAT({ + this.b}); + + @override + int pack(fb.Builder fbBuilder) { + final int? bOffset = b?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, bOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableAT{b: ${b}}'; + } +} + +class _TableAReader extends fb.TableReader { + const _TableAReader(); + + @override + TableA createObject(fb.BufferContext bc, int offset) => + TableA._(bc, offset); +} + +class TableABuilder { + TableABuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addBOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableAObjectBuilder extends fb.ObjectBuilder { + final my_game_other_name_space.TableBObjectBuilder? _b; + + TableAObjectBuilder({ + my_game_other_name_space.TableBObjectBuilder? b, + }) + : _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? bOffset = _b?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, bOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/include_test2/mod.rs b/third_party/flatbuffers/tests/include_test2/mod.rs new file mode 100644 index 00000000000..ca4894dc32c --- /dev/null +++ b/third_party/flatbuffers/tests/include_test2/mod.rs @@ -0,0 +1,16 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod my_game { + use super::*; + pub mod other_name_space { + use super::*; + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space +} // my_game +mod table_a_generated; +pub use self::table_a_generated::*; diff --git a/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/from_include_generated.rs b/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/from_include_generated.rs new file mode 100644 index 00000000000..70cb407c1ea --- /dev/null +++ b/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/from_include_generated.rs @@ -0,0 +1,92 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ + FromInclude::IncludeVal, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FromInclude(pub i64); +#[allow(non_upper_case_globals)] +impl FromInclude { + pub const IncludeVal: Self = Self(0); + + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, + } + } +} +impl core::fmt::Debug for FromInclude { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for FromInclude { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for FromInclude { + type Output = FromInclude; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for FromInclude { + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for FromInclude { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/table_b_generated.rs b/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/table_b_generated.rs new file mode 100644 index 00000000000..84932cbc5ad --- /dev/null +++ b/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/table_b_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableBOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableB<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableB<'a> { + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableB<'a> { + pub const VT_A: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + Box::new(x.unpack()) + }); + TableBT { + a, + } + } + + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableB::VT_A, None)} + } +} + +impl flatbuffers::Verifiable for TableB<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct TableBArgs<'a> { + pub a: Option>>, +} +impl<'a> Default for TableBArgs<'a> { + #[inline] + fn default() -> Self { + TableBArgs { + a: None, + } + } +} + +pub struct TableBBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableB<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableBT { + pub a: Option>, +} +impl Default for TableBT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl TableBT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } +} diff --git a/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/unused_generated.rs b/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/unused_generated.rs new file mode 100644 index 00000000000..11af62f073b --- /dev/null +++ b/third_party/flatbuffers/tests/include_test2/my_game/other_name_space/unused_generated.rs @@ -0,0 +1,128 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Unused, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Unused(pub [u8; 4]); +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Unused { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Unused {} +impl<'a> flatbuffers::Follow<'a> for Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Unused>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Unused { + type Output = Unused; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Unused { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Unused { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } + + pub fn a(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct UnusedT { + pub a: i32, +} +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } +} + diff --git a/third_party/flatbuffers/tests/include_test2/table_a_generated.rs b/third_party/flatbuffers/tests/include_test2/table_a_generated.rs new file mode 100644 index 00000000000..781a6c469db --- /dev/null +++ b/third_party/flatbuffers/tests/include_test2/table_a_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableAOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableA<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableA<'a> { + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableA<'a> { + pub const VT_B: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + Box::new(x.unpack()) + }); + TableAT { + b, + } + } + + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableA::VT_B, None)} + } +} + +impl flatbuffers::Verifiable for TableA<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } +} +pub struct TableAArgs<'a> { + pub b: Option>>, +} +impl<'a> Default for TableAArgs<'a> { + #[inline] + fn default() -> Self { + TableAArgs { + b: None, + } + } +} + +pub struct TableABuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { + #[inline] + pub fn add_b(&mut self, b: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableA<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableAT { + pub b: Option>, +} +impl Default for TableAT { + fn default() -> Self { + Self { + b: None, + } + } +} +impl TableAT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } +} diff --git a/third_party/flatbuffers/tests/include_test2_my_game.other_name_space_generated.dart b/third_party/flatbuffers/tests/include_test2_my_game.other_name_space_generated.dart new file mode 100644 index 00000000000..365ed3ceb5d --- /dev/null +++ b/third_party/flatbuffers/tests/include_test2_my_game.other_name_space_generated.dart @@ -0,0 +1,231 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.other_name_space; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +import './include_test1_generated.dart'; + +enum FromInclude { + IncludeVal(0); + + final int value; + const FromInclude(this.value); + + factory FromInclude.fromValue(int value) { + switch (value) { + case 0: return FromInclude.IncludeVal; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static FromInclude? _createOrNull(int? value) => + value == null ? null : FromInclude.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 0; + static const fb.Reader reader = _FromIncludeReader(); +} + +class _FromIncludeReader extends fb.Reader { + const _FromIncludeReader(); + + @override + int get size => 8; + + @override + FromInclude read(fb.BufferContext bc, int offset) => + FromInclude.fromValue(const fb.Int64Reader().read(bc, offset)); +} + +class Unused { + Unused._(this._bc, this._bcOffset); + + static const fb.Reader reader = _UnusedReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get a => const fb.Int32Reader().read(_bc, _bcOffset + 0); + + @override + String toString() { + return 'Unused{a: ${a}}'; + } + + UnusedT unpack() => UnusedT( + a: a); + + static int pack(fb.Builder fbBuilder, UnusedT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class UnusedT implements fb.Packable { + int a; + + UnusedT({ + required this.a}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'UnusedT{a: ${a}}'; + } +} + +class _UnusedReader extends fb.StructReader { + const _UnusedReader(); + + @override + int get size => 4; + + @override + Unused createObject(fb.BufferContext bc, int offset) => + Unused._(bc, offset); +} + +class UnusedBuilder { + UnusedBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int a) { + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + +} + +class UnusedObjectBuilder extends fb.ObjectBuilder { + final int _a; + + UnusedObjectBuilder({ + required int a, + }) + : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putInt32(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class TableB { + TableB._(this._bc, this._bcOffset); + factory TableB(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableBReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + TableA? get a => TableA.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'TableB{a: ${a}}'; + } + + TableBT unpack() => TableBT( + a: a?.unpack()); + + static int pack(fb.Builder fbBuilder, TableBT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableBT implements fb.Packable { + TableAT? a; + + TableBT({ + this.a}); + + @override + int pack(fb.Builder fbBuilder) { + final int? aOffset = a?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, aOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableBT{a: ${a}}'; + } +} + +class _TableBReader extends fb.TableReader { + const _TableBReader(); + + @override + TableB createObject(fb.BufferContext bc, int offset) => + TableB._(bc, offset); +} + +class TableBBuilder { + TableBBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addAOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableBObjectBuilder extends fb.ObjectBuilder { + final TableAObjectBuilder? _a; + + TableBObjectBuilder({ + TableAObjectBuilder? a, + }) + : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? aOffset = _a?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, aOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/included_test.fbs b/third_party/flatbuffers/tests/included_test.fbs new file mode 100644 index 00000000000..59c4a85f09f --- /dev/null +++ b/third_party/flatbuffers/tests/included_test.fbs @@ -0,0 +1,3 @@ +table Wrapped { + a:double; +} diff --git a/third_party/flatbuffers/tests/includer_test.fbs b/third_party/flatbuffers/tests/includer_test.fbs new file mode 100644 index 00000000000..890fa70e149 --- /dev/null +++ b/third_party/flatbuffers/tests/includer_test.fbs @@ -0,0 +1,5 @@ +include "tests/included_test.fbs"; + +table Wrapper { + a:Wrapped; +} diff --git a/third_party/flatbuffers/tests/is_quiet_nan.h b/third_party/flatbuffers/tests/is_quiet_nan.h new file mode 100644 index 00000000000..6d31c3dedda --- /dev/null +++ b/third_party/flatbuffers/tests/is_quiet_nan.h @@ -0,0 +1,41 @@ +#ifndef TESTS_IS_QUIET_NAN_H +#define TESTS_IS_QUIET_NAN_H + +namespace flatbuffers { +namespace tests { + +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) +// The IEEE-754 quiet_NaN is not simple binary constant. +// All binary NaN bit strings have all the bits of the biased exponent field E +// set to 1. A quiet NaN bit string should be encoded with the first bit d[1] +// of the trailing significand field T being 1 (d[0] is implicit bit). +// It is assumed that endianness of floating-point is same as integer. +template bool is_quiet_nan_impl(T v) { + static_assert(sizeof(T) == sizeof(U), "unexpected"); + U b = 0; + std::memcpy(&b, &v, sizeof(T)); + return ((b & qnan_base) == qnan_base); +} +# if defined(__mips__) || defined(__hppa__) +inline bool is_quiet_nan(float v) { + return is_quiet_nan_impl(v) || + is_quiet_nan_impl(v); +} +inline bool is_quiet_nan(double v) { + return is_quiet_nan_impl(v) || + is_quiet_nan_impl(v); +} +# else +inline bool is_quiet_nan(float v) { + return is_quiet_nan_impl(v); +} +inline bool is_quiet_nan(double v) { + return is_quiet_nan_impl(v); +} +# endif +#endif + +} // namespace tests +} // namespace flatbuffers + +#endif // TESTS_IS_QUIET_NAN_H diff --git a/third_party/flatbuffers/tests/javatest.bin b/third_party/flatbuffers/tests/javatest.bin new file mode 100644 index 00000000000..804dbba6fdb Binary files /dev/null and b/third_party/flatbuffers/tests/javatest.bin differ diff --git a/third_party/flatbuffers/tests/json_test.cpp b/third_party/flatbuffers/tests/json_test.cpp new file mode 100644 index 00000000000..2a328638abb --- /dev/null +++ b/third_party/flatbuffers/tests/json_test.cpp @@ -0,0 +1,207 @@ +#include "json_test.h" + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/idl.h" +#include "monster_test_bfbs_generated.h" +#include "monster_test_generated.h" +#include "optional_scalars_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +using namespace MyGame::Example; + +// Check stringify of an default enum value to json +void JsonDefaultTest(const std::string &tests_data_path) { + // load FlatBuffer schema (.fbs) from disk + std::string schemafile; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(), + false, &schemafile), + true); + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parser; + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + + TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); + // create incomplete monster and store to json + parser.opts.output_default_scalars_in_json = true; + parser.opts.output_enum_identifiers = true; + flatbuffers::FlatBufferBuilder builder; + auto name = builder.CreateString("default_enum"); + MonsterBuilder color_monster(builder); + color_monster.add_name(name); + FinishMonsterBuffer(builder, color_monster.Finish()); + std::string jsongen; + auto result = GenText(parser, builder.GetBufferPointer(), &jsongen); + TEST_NULL(result); + // default value of the "color" field is Blue + TEST_EQ(std::string::npos != jsongen.find("color: \"Blue\""), true); + // default value of the "testf" field is 3.14159 + TEST_EQ(std::string::npos != jsongen.find("testf: 3.14159"), true); +} + +void JsonEnumsTest(const std::string &tests_data_path) { + // load FlatBuffer schema (.fbs) from disk + std::string schemafile; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(), + false, &schemafile), + true); + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parser; + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + parser.opts.output_enum_identifiers = true; + TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); + flatbuffers::FlatBufferBuilder builder; + auto name = builder.CreateString("bitflag_enum"); + MonsterBuilder color_monster(builder); + color_monster.add_name(name); + color_monster.add_color(Color(Color_Blue | Color_Red)); + FinishMonsterBuffer(builder, color_monster.Finish()); + std::string jsongen; + auto result = GenText(parser, builder.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ(std::string::npos != jsongen.find("color: \"Red Blue\""), true); + // Test forward compatibility with 'output_enum_identifiers = true'. + // Current Color doesn't have '(1u << 2)' field, let's add it. + builder.Clear(); + std::string future_json; + auto future_name = builder.CreateString("future bitflag_enum"); + MonsterBuilder future_color(builder); + future_color.add_name(future_name); + future_color.add_color( + static_cast((1u << 2) | Color_Blue | Color_Red)); + FinishMonsterBuffer(builder, future_color.Finish()); + result = GenText(parser, builder.GetBufferPointer(), &future_json); + TEST_NULL(result); + TEST_EQ(std::string::npos != future_json.find("color: 13"), true); +} + +void JsonOptionalTest(const std::string &tests_data_path, + bool default_scalars) { + // load FlatBuffer schema (.fbs) and JSON from disk + std::string schemafile; + std::string jsonfile; + TEST_EQ( + flatbuffers::LoadFile((tests_data_path + "optional_scalars.fbs").c_str(), + false, &schemafile), + true); + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "optional_scalars" + + (default_scalars ? "_defaults" : "") + ".json") + .c_str(), + false, &jsonfile), + true); + + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parser; + parser.opts.output_default_scalars_in_json = default_scalars; + TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); + TEST_EQ(parser.ParseJson(jsonfile.c_str()), true); + + // here, parser.builder_ contains a binary buffer that is the parsed data. + + // First, verify it, just in case: + flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(), + parser.builder_.GetSize()); + TEST_EQ(optional_scalars::VerifyScalarStuffBuffer(verifier), true); + + // to ensure it is correct, we now generate text back from the binary, + // and compare the two: + std::string jsongen; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str()); +} + +void ParseIncorrectMonsterJsonTest(const std::string &tests_data_path) { + std::string schemafile; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.bfbs").c_str(), + true, &schemafile), + true); + flatbuffers::Parser parser; + flatbuffers::Verifier verifier( + reinterpret_cast(schemafile.c_str()), schemafile.size()); + TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); + TEST_EQ( + parser.Deserialize(reinterpret_cast(schemafile.c_str()), + schemafile.size()), + true); + TEST_EQ(parser.ParseJson("{name:\"monster\"}"), true); + TEST_EQ(parser.ParseJson(""), false); + TEST_EQ(parser.ParseJson("{name: 1}"), false); + TEST_EQ(parser.ParseJson("{name:+1}"), false); + TEST_EQ(parser.ParseJson("{name:-1}"), false); + TEST_EQ(parser.ParseJson("{name:-f}"), false); + TEST_EQ(parser.ParseJson("{name:+f}"), false); +} + +void JsonUnsortedArrayTest() { + flatbuffers::Parser parser; + TEST_EQ(parser.Deserialize(MyGame::Example::MonsterBinarySchema::data(), + MyGame::Example::MonsterBinarySchema::size()), + true); + auto jsonStr = R"( + { + "name": "lookupTest", + "testarrayoftables": [ + { "name": "aaa" }, + { "name": "ccc" }, + { "name": "bbb" } + ] + } + )"; + TEST_EQ(parser.ParseJson(jsonStr), true); + auto monster = flatbuffers::GetRoot( + parser.builder_.GetBufferPointer()); + + TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("aaa")); + TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("bbb")); + TEST_NOTNULL(monster->testarrayoftables()->LookupByKey("ccc")); +} + +void JsonUnionStructTest() { + // schema to parse data + auto schema = R"( +struct MyStruct { field: int; } +union UnionWithStruct { MyStruct } +table JsonUnionStructTest { union_with_struct: UnionWithStruct; } +root_type JsonUnionStructTest; +)"; + // source text to parse and expected result of generation text back + auto json_source = R"({ + union_with_struct_type: "MyStruct", + union_with_struct: { + field: 12345 + } +} +)"; + + flatbuffers::Parser parser; + // set output language to JSON, so we assure that is supported + parser.opts.lang_to_generate = IDLOptions::kJson; + // parse schema first, so we assure that output language is supported + // and can use it to parse the data after + TEST_EQ(true, parser.Parse(schema)); + TEST_EQ(true, parser.ParseJson(json_source)); + + // now generate text back from the binary, and compare the two: + std::string json_generated; + auto generate_result = + GenText(parser, parser.builder_.GetBufferPointer(), &json_generated); + TEST_NULL(generate_result); + TEST_EQ_STR(json_source, json_generated.c_str()); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/json_test.h b/third_party/flatbuffers/tests/json_test.h new file mode 100644 index 00000000000..1c8e8093f62 --- /dev/null +++ b/third_party/flatbuffers/tests/json_test.h @@ -0,0 +1,19 @@ +#ifndef TESTS_JSON_TEST_H +#define TESTS_JSON_TEST_H + +#include + +namespace flatbuffers { +namespace tests { + +void JsonDefaultTest(const std::string& tests_data_path); +void JsonEnumsTest(const std::string& tests_data_path); +void JsonOptionalTest(const std::string& tests_data_path, bool default_scalars); +void ParseIncorrectMonsterJsonTest(const std::string& tests_data_path); +void JsonUnsortedArrayTest(); +void JsonUnionStructTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/key_field/key_field_sample.fbs b/third_party/flatbuffers/tests/key_field/key_field_sample.fbs new file mode 100644 index 00000000000..e19969bb179 --- /dev/null +++ b/third_party/flatbuffers/tests/key_field/key_field_sample.fbs @@ -0,0 +1,49 @@ +namespace keyfield.sample; + +struct Baz { + a: [uint8:4] (key); // A fixed-sized array of uint8 as a Key + b: uint8 ; +} + +struct Bar { + a: [float:3] (key); // A fixed-sized array of float as a Key + b: uint8; +} + +struct Color { + rgb: [float:3] (key); + tag: uint8; +} + +struct Apple { + tag: uint8; + color: Color(key); +} + +struct Fruit { + a: Apple (key); + b: uint8; +} + +struct Rice { + origin: [uint8:3]; + quantity: uint32; +} + +struct Grain { + a: [Rice:3] (key); + tag: uint8; +} + +table FooTable { + a: int; + b: int; + c: string (key); + d: [Baz]; + e: [Bar]; + f: [Apple]; + g: [Fruit]; + h: [Grain]; +} +root_type FooTable; + diff --git a/third_party/flatbuffers/tests/key_field/key_field_sample_generated.h b/third_party/flatbuffers/tests/key_field/key_field_sample_generated.h new file mode 100644 index 00000000000..d36d35c6d2e --- /dev/null +++ b/third_party/flatbuffers/tests/key_field/key_field_sample_generated.h @@ -0,0 +1,1030 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_KEYFIELDSAMPLE_KEYFIELD_SAMPLE_H_ +#define FLATBUFFERS_GENERATED_KEYFIELDSAMPLE_KEYFIELD_SAMPLE_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace keyfield { +namespace sample { + +struct Baz; + +struct Bar; + +struct Color; + +struct Apple; + +struct Fruit; + +struct Rice; + +struct Grain; + +struct FooTable; +struct FooTableBuilder; +struct FooTableT; + +bool operator==(const Baz &lhs, const Baz &rhs); +bool operator!=(const Baz &lhs, const Baz &rhs); +bool operator==(const Bar &lhs, const Bar &rhs); +bool operator!=(const Bar &lhs, const Bar &rhs); +bool operator==(const Color &lhs, const Color &rhs); +bool operator!=(const Color &lhs, const Color &rhs); +bool operator==(const Apple &lhs, const Apple &rhs); +bool operator!=(const Apple &lhs, const Apple &rhs); +bool operator==(const Fruit &lhs, const Fruit &rhs); +bool operator!=(const Fruit &lhs, const Fruit &rhs); +bool operator==(const Rice &lhs, const Rice &rhs); +bool operator!=(const Rice &lhs, const Rice &rhs); +bool operator==(const Grain &lhs, const Grain &rhs); +bool operator!=(const Grain &lhs, const Grain &rhs); +bool operator==(const FooTableT &lhs, const FooTableT &rhs); +bool operator!=(const FooTableT &lhs, const FooTableT &rhs); + +inline const ::flatbuffers::TypeTable *BazTypeTable(); + +inline const ::flatbuffers::TypeTable *BarTypeTable(); + +inline const ::flatbuffers::TypeTable *ColorTypeTable(); + +inline const ::flatbuffers::TypeTable *AppleTypeTable(); + +inline const ::flatbuffers::TypeTable *FruitTypeTable(); + +inline const ::flatbuffers::TypeTable *RiceTypeTable(); + +inline const ::flatbuffers::TypeTable *GrainTypeTable(); + +inline const ::flatbuffers::TypeTable *FooTableTypeTable(); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(1) Baz FLATBUFFERS_FINAL_CLASS { + private: + uint8_t a_[4]; + uint8_t b_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return BazTypeTable(); + } + Baz() + : a_(), + b_(0) { + } + Baz(uint8_t _b) + : a_(), + b_(::flatbuffers::EndianScalar(_b)) { + } + Baz(::flatbuffers::span _a, uint8_t _b) + : b_(::flatbuffers::EndianScalar(_b)) { + ::flatbuffers::CastToArray(a_).CopyFromSpan(_a); + } + const ::flatbuffers::Array *a() const { + return &::flatbuffers::CastToArray(a_); + } + ::flatbuffers::Array *mutable_a() { + return &::flatbuffers::CastToArray(a_); + } + bool KeyCompareLessThan(const Baz * const o) const { + return KeyCompareWithValue(o->a()) < 0; + } + int KeyCompareWithValue(const ::flatbuffers::Array *_a) const { + const ::flatbuffers::Array *curr_a = a(); + for (::flatbuffers::uoffset_t i = 0; i < curr_a->size(); i++) { + const auto lhs = curr_a->Get(i); + const auto rhs = _a->Get(i); + if (lhs != rhs) + return static_cast(lhs > rhs) - static_cast(lhs < rhs); + } + return 0; + } + uint8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(uint8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Baz, 5); + +inline bool operator==(const Baz &lhs, const Baz &rhs) { + return + (*lhs.a() == *rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Baz &lhs, const Baz &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Bar FLATBUFFERS_FINAL_CLASS { + private: + float a_[3]; + uint8_t b_; + int8_t padding0__; int16_t padding1__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return BarTypeTable(); + } + Bar() + : a_(), + b_(0), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Bar(uint8_t _b) + : a_(), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Bar(::flatbuffers::span _a, uint8_t _b) + : b_(::flatbuffers::EndianScalar(_b)), + padding0__(0), + padding1__(0) { + ::flatbuffers::CastToArray(a_).CopyFromSpan(_a); + (void)padding0__; + (void)padding1__; + } + const ::flatbuffers::Array *a() const { + return &::flatbuffers::CastToArray(a_); + } + ::flatbuffers::Array *mutable_a() { + return &::flatbuffers::CastToArray(a_); + } + bool KeyCompareLessThan(const Bar * const o) const { + return KeyCompareWithValue(o->a()) < 0; + } + int KeyCompareWithValue(const ::flatbuffers::Array *_a) const { + const ::flatbuffers::Array *curr_a = a(); + for (::flatbuffers::uoffset_t i = 0; i < curr_a->size(); i++) { + const auto lhs = curr_a->Get(i); + const auto rhs = _a->Get(i); + if (lhs != rhs) + return static_cast(lhs > rhs) - static_cast(lhs < rhs); + } + return 0; + } + uint8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(uint8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Bar, 16); + +inline bool operator==(const Bar &lhs, const Bar &rhs) { + return + (*lhs.a() == *rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Bar &lhs, const Bar &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Color FLATBUFFERS_FINAL_CLASS { + private: + float rgb_[3]; + uint8_t tag_; + int8_t padding0__; int16_t padding1__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ColorTypeTable(); + } + Color() + : rgb_(), + tag_(0), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Color(uint8_t _tag) + : rgb_(), + tag_(::flatbuffers::EndianScalar(_tag)), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Color(::flatbuffers::span _rgb, uint8_t _tag) + : tag_(::flatbuffers::EndianScalar(_tag)), + padding0__(0), + padding1__(0) { + ::flatbuffers::CastToArray(rgb_).CopyFromSpan(_rgb); + (void)padding0__; + (void)padding1__; + } + const ::flatbuffers::Array *rgb() const { + return &::flatbuffers::CastToArray(rgb_); + } + ::flatbuffers::Array *mutable_rgb() { + return &::flatbuffers::CastToArray(rgb_); + } + bool KeyCompareLessThan(const Color * const o) const { + return KeyCompareWithValue(o->rgb()) < 0; + } + int KeyCompareWithValue(const ::flatbuffers::Array *_rgb) const { + const ::flatbuffers::Array *curr_rgb = rgb(); + for (::flatbuffers::uoffset_t i = 0; i < curr_rgb->size(); i++) { + const auto lhs = curr_rgb->Get(i); + const auto rhs = _rgb->Get(i); + if (lhs != rhs) + return static_cast(lhs > rhs) - static_cast(lhs < rhs); + } + return 0; + } + uint8_t tag() const { + return ::flatbuffers::EndianScalar(tag_); + } + void mutate_tag(uint8_t _tag) { + ::flatbuffers::WriteScalar(&tag_, _tag); + } +}; +FLATBUFFERS_STRUCT_END(Color, 16); + +inline bool operator==(const Color &lhs, const Color &rhs) { + return + (*lhs.rgb() == *rhs.rgb()) && + (lhs.tag() == rhs.tag()); +} + +inline bool operator!=(const Color &lhs, const Color &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Apple FLATBUFFERS_FINAL_CLASS { + private: + uint8_t tag_; + int8_t padding0__; int16_t padding1__; + keyfield::sample::Color color_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AppleTypeTable(); + } + Apple() + : tag_(0), + padding0__(0), + padding1__(0), + color_() { + (void)padding0__; + (void)padding1__; + } + Apple(uint8_t _tag, const keyfield::sample::Color &_color) + : tag_(::flatbuffers::EndianScalar(_tag)), + padding0__(0), + padding1__(0), + color_(_color) { + (void)padding0__; + (void)padding1__; + } + uint8_t tag() const { + return ::flatbuffers::EndianScalar(tag_); + } + void mutate_tag(uint8_t _tag) { + ::flatbuffers::WriteScalar(&tag_, _tag); + } + const keyfield::sample::Color &color() const { + return color_; + } + keyfield::sample::Color &mutable_color() { + return color_; + } + bool KeyCompareLessThan(const Apple * const o) const { + return KeyCompareWithValue(o->color()) < 0; + } + int KeyCompareWithValue(const keyfield::sample::Color &_color) const { + const auto &lhs_color = color(); + const auto &rhs_color = _color; + const auto rhs_color_rgb = rhs_color.rgb(); + const auto rgb_compare_result = lhs_color.KeyCompareWithValue(rhs_color_rgb); + if (rgb_compare_result != 0) + return rgb_compare_result; + const auto lhs_color_tag = lhs_color.tag(); + const auto rhs_color_tag = rhs_color.tag(); + if (lhs_color_tag != rhs_color_tag) + return static_cast(lhs_color_tag > rhs_color_tag) - static_cast(lhs_color_tag < rhs_color_tag); + return 0; + } +}; +FLATBUFFERS_STRUCT_END(Apple, 20); + +inline bool operator==(const Apple &lhs, const Apple &rhs) { + return + (lhs.tag() == rhs.tag()) && + (lhs.color() == rhs.color()); +} + +inline bool operator!=(const Apple &lhs, const Apple &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Fruit FLATBUFFERS_FINAL_CLASS { + private: + keyfield::sample::Apple a_; + uint8_t b_; + int8_t padding0__; int16_t padding1__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return FruitTypeTable(); + } + Fruit() + : a_(), + b_(0), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Fruit(const keyfield::sample::Apple &_a, uint8_t _b) + : a_(_a), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + const keyfield::sample::Apple &a() const { + return a_; + } + keyfield::sample::Apple &mutable_a() { + return a_; + } + bool KeyCompareLessThan(const Fruit * const o) const { + return KeyCompareWithValue(o->a()) < 0; + } + int KeyCompareWithValue(const keyfield::sample::Apple &_a) const { + const auto &lhs_a = a(); + const auto &rhs_a = _a; + const auto lhs_a_tag = lhs_a.tag(); + const auto rhs_a_tag = rhs_a.tag(); + if (lhs_a_tag != rhs_a_tag) + return static_cast(lhs_a_tag > rhs_a_tag) - static_cast(lhs_a_tag < rhs_a_tag); + const auto rhs_a_color = rhs_a.color(); + const auto color_compare_result = lhs_a.KeyCompareWithValue(rhs_a_color); + if (color_compare_result != 0) + return color_compare_result; + return 0; + } + uint8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(uint8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Fruit, 24); + +inline bool operator==(const Fruit &lhs, const Fruit &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Fruit &lhs, const Fruit &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Rice FLATBUFFERS_FINAL_CLASS { + private: + uint8_t origin_[3]; + int8_t padding0__; + uint32_t quantity_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RiceTypeTable(); + } + Rice() + : origin_(), + padding0__(0), + quantity_(0) { + (void)padding0__; + } + Rice(uint32_t _quantity) + : origin_(), + padding0__(0), + quantity_(::flatbuffers::EndianScalar(_quantity)) { + (void)padding0__; + } + Rice(::flatbuffers::span _origin, uint32_t _quantity) + : padding0__(0), + quantity_(::flatbuffers::EndianScalar(_quantity)) { + ::flatbuffers::CastToArray(origin_).CopyFromSpan(_origin); + (void)padding0__; + } + const ::flatbuffers::Array *origin() const { + return &::flatbuffers::CastToArray(origin_); + } + ::flatbuffers::Array *mutable_origin() { + return &::flatbuffers::CastToArray(origin_); + } + uint32_t quantity() const { + return ::flatbuffers::EndianScalar(quantity_); + } + void mutate_quantity(uint32_t _quantity) { + ::flatbuffers::WriteScalar(&quantity_, _quantity); + } +}; +FLATBUFFERS_STRUCT_END(Rice, 8); + +inline bool operator==(const Rice &lhs, const Rice &rhs) { + return + (*lhs.origin() == *rhs.origin()) && + (lhs.quantity() == rhs.quantity()); +} + +inline bool operator!=(const Rice &lhs, const Rice &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Grain FLATBUFFERS_FINAL_CLASS { + private: + keyfield::sample::Rice a_[3]; + uint8_t tag_; + int8_t padding0__; int16_t padding1__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return GrainTypeTable(); + } + Grain() + : a_(), + tag_(0), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Grain(uint8_t _tag) + : a_(), + tag_(::flatbuffers::EndianScalar(_tag)), + padding0__(0), + padding1__(0) { + (void)padding0__; + (void)padding1__; + } + Grain(::flatbuffers::span _a, uint8_t _tag) + : tag_(::flatbuffers::EndianScalar(_tag)), + padding0__(0), + padding1__(0) { + ::flatbuffers::CastToArray(a_).CopyFromSpan(_a); + (void)padding0__; + (void)padding1__; + } + const ::flatbuffers::Array *a() const { + return &::flatbuffers::CastToArray(a_); + } + ::flatbuffers::Array *mutable_a() { + return &::flatbuffers::CastToArray(a_); + } + bool KeyCompareLessThan(const Grain * const o) const { + return KeyCompareWithValue(o->a()) < 0; + } + int KeyCompareWithValue(const ::flatbuffers::Array *_a) const { + const ::flatbuffers::Array *curr_a = a(); + for (::flatbuffers::uoffset_t i = 0; i < curr_a->size(); i++) { + const auto &lhs_a = *(curr_a->Get(i)); + const auto &rhs_a = *(_a->Get(i)); + const auto lhs_a_origin = lhs_a.origin(); + const auto rhs_a_origin = rhs_a.origin(); + for (::flatbuffers::uoffset_t i = 0; i < lhs_a_origin->size(); i++) { + const auto lhs_a_origin_elem = lhs_a_origin->Get(i); + const auto rhs_a_origin_elem = rhs_a_origin->Get(i); + if (lhs_a_origin_elem != rhs_a_origin_elem) + return static_cast(lhs_a_origin_elem > rhs_a_origin_elem) - static_cast(lhs_a_origin_elem < rhs_a_origin_elem); + } + const auto lhs_a_quantity = lhs_a.quantity(); + const auto rhs_a_quantity = rhs_a.quantity(); + if (lhs_a_quantity != rhs_a_quantity) + return static_cast(lhs_a_quantity > rhs_a_quantity) - static_cast(lhs_a_quantity < rhs_a_quantity); + } + return 0; + } + uint8_t tag() const { + return ::flatbuffers::EndianScalar(tag_); + } + void mutate_tag(uint8_t _tag) { + ::flatbuffers::WriteScalar(&tag_, _tag); + } +}; +FLATBUFFERS_STRUCT_END(Grain, 28); + +inline bool operator==(const Grain &lhs, const Grain &rhs) { + return + (*lhs.a() == *rhs.a()) && + (lhs.tag() == rhs.tag()); +} + +inline bool operator!=(const Grain &lhs, const Grain &rhs) { + return !(lhs == rhs); +} + + +struct FooTableT : public ::flatbuffers::NativeTable { + typedef FooTable TableType; + int32_t a = 0; + int32_t b = 0; + std::string c{}; + std::vector d{}; + std::vector e{}; + std::vector f{}; + std::vector g{}; + std::vector h{}; +}; + +struct FooTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef FooTableT NativeTableType; + typedef FooTableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return FooTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4, + VT_B = 6, + VT_C = 8, + VT_D = 10, + VT_E = 12, + VT_F = 14, + VT_G = 16, + VT_H = 18 + }; + int32_t a() const { + return GetField(VT_A, 0); + } + bool mutate_a(int32_t _a = 0) { + return SetField(VT_A, _a, 0); + } + int32_t b() const { + return GetField(VT_B, 0); + } + bool mutate_b(int32_t _b = 0) { + return SetField(VT_B, _b, 0); + } + const ::flatbuffers::String *c() const { + return GetPointer(VT_C); + } + ::flatbuffers::String *mutable_c() { + return GetPointer<::flatbuffers::String *>(VT_C); + } + bool KeyCompareLessThan(const FooTable * const o) const { + return *c() < *o->c(); + } + int KeyCompareWithValue(const char *_c) const { + return strcmp(c()->c_str(), _c); + } + template + int KeyCompareWithValue(const StringType& _c) const { + if (c()->c_str() < _c) return -1; + if (_c < c()->c_str()) return 1; + return 0; + } + const ::flatbuffers::Vector *d() const { + return GetPointer *>(VT_D); + } + ::flatbuffers::Vector *mutable_d() { + return GetPointer<::flatbuffers::Vector *>(VT_D); + } + const ::flatbuffers::Vector *e() const { + return GetPointer *>(VT_E); + } + ::flatbuffers::Vector *mutable_e() { + return GetPointer<::flatbuffers::Vector *>(VT_E); + } + const ::flatbuffers::Vector *f() const { + return GetPointer *>(VT_F); + } + ::flatbuffers::Vector *mutable_f() { + return GetPointer<::flatbuffers::Vector *>(VT_F); + } + const ::flatbuffers::Vector *g() const { + return GetPointer *>(VT_G); + } + ::flatbuffers::Vector *mutable_g() { + return GetPointer<::flatbuffers::Vector *>(VT_G); + } + const ::flatbuffers::Vector *h() const { + return GetPointer *>(VT_H); + } + ::flatbuffers::Vector *mutable_h() { + return GetPointer<::flatbuffers::Vector *>(VT_H); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + VerifyField(verifier, VT_B, 4) && + VerifyOffsetRequired(verifier, VT_C) && + verifier.VerifyString(c()) && + VerifyOffset(verifier, VT_D) && + verifier.VerifyVector(d()) && + VerifyOffset(verifier, VT_E) && + verifier.VerifyVector(e()) && + VerifyOffset(verifier, VT_F) && + verifier.VerifyVector(f()) && + VerifyOffset(verifier, VT_G) && + verifier.VerifyVector(g()) && + VerifyOffset(verifier, VT_H) && + verifier.VerifyVector(h()) && + verifier.EndTable(); + } + FooTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(FooTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const FooTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct FooTableBuilder { + typedef FooTable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(int32_t a) { + fbb_.AddElement(FooTable::VT_A, a, 0); + } + void add_b(int32_t b) { + fbb_.AddElement(FooTable::VT_B, b, 0); + } + void add_c(::flatbuffers::Offset<::flatbuffers::String> c) { + fbb_.AddOffset(FooTable::VT_C, c); + } + void add_d(::flatbuffers::Offset<::flatbuffers::Vector> d) { + fbb_.AddOffset(FooTable::VT_D, d); + } + void add_e(::flatbuffers::Offset<::flatbuffers::Vector> e) { + fbb_.AddOffset(FooTable::VT_E, e); + } + void add_f(::flatbuffers::Offset<::flatbuffers::Vector> f) { + fbb_.AddOffset(FooTable::VT_F, f); + } + void add_g(::flatbuffers::Offset<::flatbuffers::Vector> g) { + fbb_.AddOffset(FooTable::VT_G, g); + } + void add_h(::flatbuffers::Offset<::flatbuffers::Vector> h) { + fbb_.AddOffset(FooTable::VT_H, h); + } + explicit FooTableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + fbb_.Required(o, FooTable::VT_C); + return o; + } +}; + +inline ::flatbuffers::Offset CreateFooTable( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0, + int32_t b = 0, + ::flatbuffers::Offset<::flatbuffers::String> c = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> d = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> e = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> f = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> g = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> h = 0) { + FooTableBuilder builder_(_fbb); + builder_.add_h(h); + builder_.add_g(g); + builder_.add_f(f); + builder_.add_e(e); + builder_.add_d(d); + builder_.add_c(c); + builder_.add_b(b); + builder_.add_a(a); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateFooTableDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0, + int32_t b = 0, + const char *c = nullptr, + std::vector *d = nullptr, + std::vector *e = nullptr, + std::vector *f = nullptr, + std::vector *g = nullptr, + std::vector *h = nullptr) { + auto c__ = c ? _fbb.CreateString(c) : 0; + auto d__ = d ? _fbb.CreateVectorOfSortedStructs(d) : 0; + auto e__ = e ? _fbb.CreateVectorOfSortedStructs(e) : 0; + auto f__ = f ? _fbb.CreateVectorOfSortedStructs(f) : 0; + auto g__ = g ? _fbb.CreateVectorOfSortedStructs(g) : 0; + auto h__ = h ? _fbb.CreateVectorOfSortedStructs(h) : 0; + return keyfield::sample::CreateFooTable( + _fbb, + a, + b, + c__, + d__, + e__, + f__, + g__, + h__); +} + +::flatbuffers::Offset CreateFooTable(::flatbuffers::FlatBufferBuilder &_fbb, const FooTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const FooTableT &lhs, const FooTableT &rhs) { + return + (lhs.a == rhs.a) && + (lhs.b == rhs.b) && + (lhs.c == rhs.c) && + (lhs.d == rhs.d) && + (lhs.e == rhs.e) && + (lhs.f == rhs.f) && + (lhs.g == rhs.g) && + (lhs.h == rhs.h); +} + +inline bool operator!=(const FooTableT &lhs, const FooTableT &rhs) { + return !(lhs == rhs); +} + + +inline FooTableT *FooTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new FooTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void FooTable::UnPackTo(FooTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = a(); _o->a = _e; } + { auto _e = b(); _o->b = _e; } + { auto _e = c(); if (_e) _o->c = _e->str(); } + { auto _e = d(); if (_e) { _o->d.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->d[_i] = *_e->Get(_i); } } else { _o->d.resize(0); } } + { auto _e = e(); if (_e) { _o->e.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->e[_i] = *_e->Get(_i); } } else { _o->e.resize(0); } } + { auto _e = f(); if (_e) { _o->f.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->f[_i] = *_e->Get(_i); } } else { _o->f.resize(0); } } + { auto _e = g(); if (_e) { _o->g.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->g[_i] = *_e->Get(_i); } } else { _o->g.resize(0); } } + { auto _e = h(); if (_e) { _o->h.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->h[_i] = *_e->Get(_i); } } else { _o->h.resize(0); } } +} + +inline ::flatbuffers::Offset FooTable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const FooTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateFooTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateFooTable(::flatbuffers::FlatBufferBuilder &_fbb, const FooTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const FooTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _a = _o->a; + auto _b = _o->b; + auto _c = _fbb.CreateString(_o->c); + auto _d = _o->d.size() ? _fbb.CreateVectorOfStructs(_o->d) : 0; + auto _e = _o->e.size() ? _fbb.CreateVectorOfStructs(_o->e) : 0; + auto _f = _o->f.size() ? _fbb.CreateVectorOfStructs(_o->f) : 0; + auto _g = _o->g.size() ? _fbb.CreateVectorOfStructs(_o->g) : 0; + auto _h = _o->h.size() ? _fbb.CreateVectorOfStructs(_o->h) : 0; + return keyfield::sample::CreateFooTable( + _fbb, + _a, + _b, + _c, + _d, + _e, + _f, + _g, + _h); +} + +inline const ::flatbuffers::TypeTable *BazTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 } + }; + static const int16_t array_sizes[] = { 4, }; + static const int64_t values[] = { 0, 4, 5 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, array_sizes, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *BarTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 } + }; + static const int16_t array_sizes[] = { 3, }; + static const int64_t values[] = { 0, 12, 16 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, array_sizes, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ColorTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 } + }; + static const int16_t array_sizes[] = { 3, }; + static const int64_t values[] = { 0, 12, 16 }; + static const char * const names[] = { + "rgb", + "tag" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, array_sizes, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AppleTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + keyfield::sample::ColorTypeTable + }; + static const int64_t values[] = { 0, 4, 20 }; + static const char * const names[] = { + "tag", + "color" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *FruitTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + keyfield::sample::AppleTypeTable + }; + static const int64_t values[] = { 0, 20, 24 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RiceTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 } + }; + static const int16_t array_sizes[] = { 3, }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "origin", + "quantity" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, array_sizes, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *GrainTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 1, 0 }, + { ::flatbuffers::ET_UCHAR, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + keyfield::sample::RiceTypeTable + }; + static const int16_t array_sizes[] = { 3, }; + static const int64_t values[] = { 0, 24, 28 }; + static const char * const names[] = { + "a", + "tag" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, type_refs, array_sizes, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *FooTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 2 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_SEQUENCE, 1, 4 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + keyfield::sample::BazTypeTable, + keyfield::sample::BarTypeTable, + keyfield::sample::AppleTypeTable, + keyfield::sample::FruitTypeTable, + keyfield::sample::GrainTypeTable + }; + static const char * const names[] = { + "a", + "b", + "c", + "d", + "e", + "f", + "g", + "h" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 8, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const keyfield::sample::FooTable *GetFooTable(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const keyfield::sample::FooTable *GetSizePrefixedFooTable(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline FooTable *GetMutableFooTable(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline keyfield::sample::FooTable *GetMutableSizePrefixedFooTable(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline bool VerifyFooTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedFooTableBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishFooTableBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedFooTableBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +inline std::unique_ptr UnPackFooTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetFooTable(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedFooTable( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedFooTable(buf)->UnPack(res)); +} + +} // namespace sample +} // namespace keyfield + +#endif // FLATBUFFERS_GENERATED_KEYFIELDSAMPLE_KEYFIELD_SAMPLE_H_ diff --git a/third_party/flatbuffers/tests/key_field_test.cpp b/third_party/flatbuffers/tests/key_field_test.cpp new file mode 100644 index 00000000000..20eb2094c18 --- /dev/null +++ b/third_party/flatbuffers/tests/key_field_test.cpp @@ -0,0 +1,224 @@ +#include "key_field_test.h" + +#include + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/idl.h" +#include "key_field/key_field_sample_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +using namespace keyfield::sample; + +void FixedSizedScalarKeyInStructTest() { + flatbuffers::FlatBufferBuilder fbb; + std::vector bazs; + uint8_t test_array1[4] = { 8, 2, 3, 0 }; + uint8_t test_array2[4] = { 1, 2, 3, 4 }; + uint8_t test_array3[4] = { 2, 2, 3, 4 }; + uint8_t test_array4[4] = { 3, 2, 3, 4 }; + bazs.push_back(Baz(flatbuffers::make_span(test_array1), 4)); + bazs.push_back(Baz(flatbuffers::make_span(test_array2), 1)); + bazs.push_back(Baz(flatbuffers::make_span(test_array3), 2)); + bazs.push_back(Baz(flatbuffers::make_span(test_array4), 3)); + auto baz_vec = fbb.CreateVectorOfSortedStructs(&bazs); + + auto test_string = fbb.CreateString("TEST"); + + float test_float_array1[3] = { 1.5, 2.5, 0 }; + float test_float_array2[3] = { 7.5, 2.5, 0 }; + float test_float_array3[3] = { 1.5, 2.5, -1 }; + float test_float_array4[3] = { -1.5, 2.5, 0 }; + std::vector bars; + bars.push_back(Bar(flatbuffers::make_span(test_float_array1), 3)); + bars.push_back(Bar(flatbuffers::make_span(test_float_array2), 4)); + bars.push_back(Bar(flatbuffers::make_span(test_float_array3), 2)); + bars.push_back(Bar(flatbuffers::make_span(test_float_array4), 1)); + auto bar_vec = fbb.CreateVectorOfSortedStructs(&bars); + + auto t = CreateFooTable(fbb, 1, 2, test_string, baz_vec, bar_vec); + + fbb.Finish(t); + + uint8_t *buf = fbb.GetBufferPointer(); + auto foo_table = GetFooTable(buf); + + auto sorted_baz_vec = foo_table->d(); + TEST_EQ(sorted_baz_vec->Get(0)->b(), 1); + TEST_EQ(sorted_baz_vec->Get(3)->b(), 4); + + uint8_t test_array[4]; + auto *key_array = &flatbuffers::CastToArray(test_array); + key_array->CopyFromSpan(flatbuffers::make_span(test_array1)); + + TEST_NOTNULL(sorted_baz_vec->LookupByKey(key_array)); + TEST_EQ(sorted_baz_vec->LookupByKey(key_array)->b(), 4); + uint8_t array_int[4] = { 7, 2, 3, 0 }; + key_array->CopyFromSpan(flatbuffers::make_span(array_int)); + TEST_EQ(sorted_baz_vec->LookupByKey(key_array), + static_cast(nullptr)); + + auto sorted_bar_vec = foo_table->e(); + TEST_EQ(sorted_bar_vec->Get(0)->b(), 1); + TEST_EQ(sorted_bar_vec->Get(3)->b(), 4); + + float test_float_array[3]; + auto *key_float_array = &flatbuffers::CastToArray(test_float_array); + key_float_array->CopyFromSpan(flatbuffers::make_span(test_float_array1)); + TEST_NOTNULL(sorted_bar_vec->LookupByKey(key_float_array)); + TEST_EQ(sorted_bar_vec->LookupByKey(key_float_array)->b(), 3); + float array_float[3] = { -1, -2, -3 }; + key_float_array->CopyFromSpan(flatbuffers::make_span(array_float)); + TEST_EQ(sorted_bar_vec->LookupByKey(key_float_array), + static_cast(nullptr)); +} + +void StructKeyInStructTest() { + flatbuffers::FlatBufferBuilder fbb; + std::vector apples; + float test_float_array1[3] = { 1.5, 2.5, 0 }; + float test_float_array2[3] = { 7.5, 2.5, 0 }; + float test_float_array3[3] = { 1.5, 2.5, -1 }; + apples.push_back( + Apple(2, Color(flatbuffers::make_span(test_float_array1), 3))); + apples.push_back( + Apple(3, Color(flatbuffers::make_span(test_float_array2), 3))); + apples.push_back( + Apple(1, Color(flatbuffers::make_span(test_float_array3), 1))); + + auto apples_vec = fbb.CreateVectorOfSortedStructs(&apples); + auto test_string = fbb.CreateString("TEST"); + + FooTableBuilder foo_builder(fbb); + foo_builder.add_a(1); + foo_builder.add_c(test_string); + + foo_builder.add_f(apples_vec); + + auto orc = foo_builder.Finish(); + fbb.Finish(orc); + + uint8_t *buf = fbb.GetBufferPointer(); + auto foo_table = GetFooTable(buf); + + auto sorted_apple_vec = foo_table->f(); + TEST_EQ(sorted_apple_vec->Get(0)->tag(), 1); + TEST_EQ(sorted_apple_vec->Get(1)->tag(), 2); + TEST_EQ(sorted_apple_vec->Get(2)->tag(), 3); + TEST_EQ(sorted_apple_vec + ->LookupByKey(Color(flatbuffers::make_span(test_float_array1), 3)) + ->tag(), + 2); + TEST_EQ(sorted_apple_vec->LookupByKey( + Color(flatbuffers::make_span(test_float_array1), 0)), + static_cast(nullptr)); +} + +void NestedStructKeyInStructTest() { + flatbuffers::FlatBufferBuilder fbb; + std::vector fruits; + float test_float_array1[3] = { 1.5, 2.5, 0 }; + float test_float_array2[3] = { 1.5, 2.5, 0 }; + float test_float_array3[3] = { 1.5, 2.5, -1 }; + + fruits.push_back( + Fruit(Apple(2, Color(flatbuffers::make_span(test_float_array1), 2)), 2)); + fruits.push_back( + Fruit(Apple(2, Color(flatbuffers::make_span(test_float_array2), 1)), 1)); + fruits.push_back( + Fruit(Apple(2, Color(flatbuffers::make_span(test_float_array3), 3)), 3)); + + auto test_string = fbb.CreateString("TEST"); + auto fruits_vec = fbb.CreateVectorOfSortedStructs(&fruits); + + FooTableBuilder foo_builder(fbb); + foo_builder.add_a(1); + foo_builder.add_c(test_string); + foo_builder.add_g(fruits_vec); + + auto orc = foo_builder.Finish(); + fbb.Finish(orc); + uint8_t *buf = fbb.GetBufferPointer(); + auto foo_table = GetFooTable(buf); + + auto sorted_fruit_vec = foo_table->g(); + TEST_EQ(sorted_fruit_vec->Get(0)->b(), 3); + TEST_EQ(sorted_fruit_vec->Get(1)->b(), 1); + TEST_EQ(sorted_fruit_vec->Get(2)->b(), 2); + TEST_EQ(sorted_fruit_vec + ->LookupByKey( + Apple(2, Color(flatbuffers::make_span(test_float_array2), 1))) + ->b(), + 1); + TEST_EQ(sorted_fruit_vec->LookupByKey( + Apple(1, Color(flatbuffers::make_span(test_float_array2), 1))), + static_cast(nullptr)); +} + +void FixedSizedStructArrayKeyInStructTest() { + flatbuffers::FlatBufferBuilder fbb; + std::vector grains; + uint8_t test_char_array1[3] = { 'u', 's', 'a' }; + uint8_t test_char_array2[3] = { 'c', 'h', 'n' }; + uint8_t test_char_array3[3] = { 'c', 'h', 'l' }; + uint8_t test_char_array4[3] = { 'f', 'r', 'a' }; + uint8_t test_char_array5[3] = { 'i', 'n', 'd' }; + uint8_t test_char_array6[3] = { 'i', 't', 'a' }; + + Rice test_rice_array1[3] = { + Rice(flatbuffers::make_span(test_char_array1), 2), + Rice(flatbuffers::make_span(test_char_array2), 1), + Rice(flatbuffers::make_span(test_char_array3), 2) + }; + Rice test_rice_array2[3] = { + Rice(flatbuffers::make_span(test_char_array4), 2), + Rice(flatbuffers::make_span(test_char_array5), 1), + Rice(flatbuffers::make_span(test_char_array6), 2) + }; + Rice test_rice_array3[3] = { + Rice(flatbuffers::make_span(test_char_array4), 2), + Rice(flatbuffers::make_span(test_char_array6), 1), + Rice(flatbuffers::make_span(test_char_array1), 2) + }; + + grains.push_back(Grain(flatbuffers::make_span(test_rice_array1), 3)); + grains.push_back(Grain(flatbuffers::make_span(test_rice_array2), 1)); + grains.push_back(Grain(flatbuffers::make_span(test_rice_array3), 2)); + + auto test_string = fbb.CreateString("TEST"); + auto grains_vec = fbb.CreateVectorOfSortedStructs(&grains); + FooTableBuilder foo_builder(fbb); + foo_builder.add_a(1); + foo_builder.add_c(test_string); + foo_builder.add_h(grains_vec); + + auto orc = foo_builder.Finish(); + fbb.Finish(orc); + uint8_t *buf = fbb.GetBufferPointer(); + auto foo_table = GetFooTable(buf); + + auto sorted_grain_vec = foo_table->h(); + TEST_EQ(sorted_grain_vec->Get(0)->tag(), 1); + TEST_EQ(sorted_grain_vec->Get(1)->tag(), 2); + TEST_EQ(sorted_grain_vec->Get(2)->tag(), 3); + TEST_EQ( + sorted_grain_vec->LookupByKey(&flatbuffers::CastToArray(test_rice_array1)) + ->tag(), + 3); + Rice test_rice_array[3] = { Rice(flatbuffers::make_span(test_char_array3), 2), + Rice(flatbuffers::make_span(test_char_array2), 1), + Rice(flatbuffers::make_span(test_char_array1), + 2) }; + TEST_EQ( + sorted_grain_vec->LookupByKey(&flatbuffers::CastToArray(test_rice_array)), + static_cast(nullptr)); + TEST_EQ( + sorted_grain_vec->LookupByKey(&flatbuffers::CastToArray(test_rice_array1)) + ->tag(), + 3); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/key_field_test.h b/third_party/flatbuffers/tests/key_field_test.h new file mode 100644 index 00000000000..bfced61a175 --- /dev/null +++ b/third_party/flatbuffers/tests/key_field_test.h @@ -0,0 +1,16 @@ +#ifndef TESTS_KEY_FIELD_TEST_H +#define TESTS_KEY_FIELD_TEST_H + +namespace flatbuffers { +namespace tests { + +void FixedSizedScalarKeyInStructTest(); +void StructKeyInStructTest(); +void NestedStructKeyInStructTest(); +void FixedSizedStructArrayKeyInStructTest(); + + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/keyword_test.fbs b/third_party/flatbuffers/tests/keyword_test.fbs new file mode 100644 index 00000000000..b5955cbfd20 --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test.fbs @@ -0,0 +1,21 @@ +namespace KeywordTest; + +enum ABC: int { void, where, stackalloc } + +enum public: int { } + +table KeywordsInTable { + is: ABC = void; + private: public; + type: int; + default: bool = false; +} + +union KeywordsInUnion { + static: KeywordsInTable, + internal: KeywordsInTable, +} + +table Table2 { + type: KeywordsInUnion; +} diff --git a/third_party/flatbuffers/tests/keyword_test/keyword_test/abc_generated.rs b/third_party/flatbuffers/tests/keyword_test/keyword_test/abc_generated.rs new file mode 100644 index 00000000000..5169ab13da5 --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test/keyword_test/abc_generated.rs @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ABC: i32 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ABC: i32 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ABC: [ABC; 3] = [ + ABC::void, + ABC::where_, + ABC::stackalloc, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct ABC(pub i32); +#[allow(non_upper_case_globals)] +impl ABC { + pub const void: Self = Self(0); + pub const where_: Self = Self(1); + pub const stackalloc: Self = Self(2); + + pub const ENUM_MIN: i32 = 0; + pub const ENUM_MAX: i32 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::void, + Self::where_, + Self::stackalloc, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::void => Some("void"), + Self::where_ => Some("where_"), + Self::stackalloc => Some("stackalloc"), + _ => None, + } + } +} +impl core::fmt::Debug for ABC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for ABC { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for ABC { + type Output = ABC; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for ABC { + type Scalar = i32; + #[inline] + fn to_little_endian(self) -> i32 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i32) -> Self { + let b = i32::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for ABC { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i32::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for ABC {} diff --git a/third_party/flatbuffers/tests/keyword_test/keyword_test/keywords_in_table_generated.rs b/third_party/flatbuffers/tests/keyword_test/keyword_test/keywords_in_table_generated.rs new file mode 100644 index 00000000000..737e88aa0be --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test/keyword_test/keywords_in_table_generated.rs @@ -0,0 +1,210 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum KeywordsInTableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct KeywordsInTable<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for KeywordsInTable<'a> { + type Inner = KeywordsInTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> KeywordsInTable<'a> { + pub const VT_IS: flatbuffers::VOffsetT = 4; + pub const VT_PRIVATE: flatbuffers::VOffsetT = 6; + pub const VT_TYPE_: flatbuffers::VOffsetT = 8; + pub const VT_DEFAULT: flatbuffers::VOffsetT = 10; + + pub const fn get_fully_qualified_name() -> &'static str { + "KeywordTest.KeywordsInTable" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + KeywordsInTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args KeywordsInTableArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = KeywordsInTableBuilder::new(_fbb); + builder.add_type_(args.type_); + builder.add_private(args.private); + builder.add_is(args.is); + builder.add_default(args.default); + builder.finish() + } + + pub fn unpack(&self) -> KeywordsInTableT { + let is = self.is(); + let private = self.private(); + let type_ = self.type_(); + let default = self.default(); + KeywordsInTableT { + is, + private, + type_, + default, + } + } + + #[inline] + pub fn is(&self) -> ABC { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_IS, Some(ABC::void)).unwrap()} + } + #[inline] + pub fn private(&self) -> public { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_PRIVATE, Some(public::NONE)).unwrap()} + } + #[inline] + pub fn type_(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_TYPE_, Some(0)).unwrap()} + } + #[inline] + pub fn default(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(KeywordsInTable::VT_DEFAULT, Some(false)).unwrap()} + } +} + +impl flatbuffers::Verifiable for KeywordsInTable<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("is", Self::VT_IS, false)? + .visit_field::("private", Self::VT_PRIVATE, false)? + .visit_field::("type_", Self::VT_TYPE_, false)? + .visit_field::("default", Self::VT_DEFAULT, false)? + .finish(); + Ok(()) + } +} +pub struct KeywordsInTableArgs { + pub is: ABC, + pub private: public, + pub type_: i32, + pub default: bool, +} +impl<'a> Default for KeywordsInTableArgs { + #[inline] + fn default() -> Self { + KeywordsInTableArgs { + is: ABC::void, + private: public::NONE, + type_: 0, + default: false, + } + } +} + +pub struct KeywordsInTableBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> KeywordsInTableBuilder<'a, 'b, A> { + #[inline] + pub fn add_is(&mut self, is: ABC) { + self.fbb_.push_slot::(KeywordsInTable::VT_IS, is, ABC::void); + } + #[inline] + pub fn add_private(&mut self, private: public) { + self.fbb_.push_slot::(KeywordsInTable::VT_PRIVATE, private, public::NONE); + } + #[inline] + pub fn add_type_(&mut self, type_: i32) { + self.fbb_.push_slot::(KeywordsInTable::VT_TYPE_, type_, 0); + } + #[inline] + pub fn add_default(&mut self, default: bool) { + self.fbb_.push_slot::(KeywordsInTable::VT_DEFAULT, default, false); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> KeywordsInTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + KeywordsInTableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for KeywordsInTable<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("KeywordsInTable"); + ds.field("is", &self.is()); + ds.field("private", &self.private()); + ds.field("type_", &self.type_()); + ds.field("default", &self.default()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct KeywordsInTableT { + pub is: ABC, + pub private: public, + pub type_: i32, + pub default: bool, +} +impl Default for KeywordsInTableT { + fn default() -> Self { + Self { + is: ABC::void, + private: public::NONE, + type_: 0, + default: false, + } + } +} +impl KeywordsInTableT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let is = self.is; + let private = self.private; + let type_ = self.type_; + let default = self.default; + KeywordsInTable::create(_fbb, &KeywordsInTableArgs{ + is, + private, + type_, + default, + }) + } +} diff --git a/third_party/flatbuffers/tests/keyword_test/keyword_test/keywords_in_union_generated.rs b/third_party/flatbuffers/tests/keyword_test/keyword_test/keywords_in_union_generated.rs new file mode 100644 index 00000000000..fa06597dddc --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test/keyword_test/keywords_in_union_generated.rs @@ -0,0 +1,173 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_KEYWORDS_IN_UNION: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_KEYWORDS_IN_UNION: u8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_KEYWORDS_IN_UNION: [KeywordsInUnion; 3] = [ + KeywordsInUnion::NONE, + KeywordsInUnion::static_, + KeywordsInUnion::internal, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct KeywordsInUnion(pub u8); +#[allow(non_upper_case_globals)] +impl KeywordsInUnion { + pub const NONE: Self = Self(0); + pub const static_: Self = Self(1); + pub const internal: Self = Self(2); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::static_, + Self::internal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::static_ => Some("static_"), + Self::internal => Some("internal"), + _ => None, + } + } +} +impl core::fmt::Debug for KeywordsInUnion { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for KeywordsInUnion { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for KeywordsInUnion { + type Output = KeywordsInUnion; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for KeywordsInUnion { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for KeywordsInUnion { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for KeywordsInUnion {} +pub struct KeywordsInUnionUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum KeywordsInUnionT { + NONE, + Static_(Box), + Internal(Box), +} +impl Default for KeywordsInUnionT { + fn default() -> Self { + Self::NONE + } +} +impl KeywordsInUnionT { + pub fn keywords_in_union_type(&self) -> KeywordsInUnion { + match self { + Self::NONE => KeywordsInUnion::NONE, + Self::Static_(_) => KeywordsInUnion::static_, + Self::Internal(_) => KeywordsInUnion::internal, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::Static_(v) => Some(v.pack(fbb).as_union_value()), + Self::Internal(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE. + pub fn take_static_(&mut self) -> Option> { + if let Self::Static_(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::Static_(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the KeywordsInTableT. + pub fn as_static_(&self) -> Option<&KeywordsInTableT> { + if let Self::Static_(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the KeywordsInTableT. + pub fn as_static__mut(&mut self) -> Option<&mut KeywordsInTableT> { + if let Self::Static_(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned KeywordsInTableT, setting the union to NONE. + pub fn take_internal(&mut self) -> Option> { + if let Self::Internal(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::Internal(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the KeywordsInTableT. + pub fn as_internal(&self) -> Option<&KeywordsInTableT> { + if let Self::Internal(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the KeywordsInTableT. + pub fn as_internal_mut(&mut self) -> Option<&mut KeywordsInTableT> { + if let Self::Internal(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/keyword_test/keyword_test/public_generated.rs b/third_party/flatbuffers/tests/keyword_test/keyword_test/public_generated.rs new file mode 100644 index 00000000000..12c3ff57935 --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test/keyword_test/public_generated.rs @@ -0,0 +1,92 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_PUBLIC: i32 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_PUBLIC: i32 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_PUBLIC: [public; 1] = [ + public::NONE, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct public(pub i32); +#[allow(non_upper_case_globals)] +impl public { + pub const NONE: Self = Self(0); + + pub const ENUM_MIN: i32 = 0; + pub const ENUM_MAX: i32 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + _ => None, + } + } +} +impl core::fmt::Debug for public { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for public { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for public { + type Output = public; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for public { + type Scalar = i32; + #[inline] + fn to_little_endian(self) -> i32 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i32) -> Self { + let b = i32::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for public { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i32::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for public {} diff --git a/third_party/flatbuffers/tests/keyword_test/keyword_test/table_2_generated.rs b/third_party/flatbuffers/tests/keyword_test/keyword_test/table_2_generated.rs new file mode 100644 index 00000000000..2af417680e8 --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test/keyword_test/table_2_generated.rs @@ -0,0 +1,227 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum Table2Offset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Table2<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Table2<'a> { + type Inner = Table2<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Table2<'a> { + pub const VT_TYPE_TYPE: flatbuffers::VOffsetT = 4; + pub const VT_TYPE_: flatbuffers::VOffsetT = 6; + + pub const fn get_fully_qualified_name() -> &'static str { + "KeywordTest.Table2" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Table2 { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args Table2Args + ) -> flatbuffers::WIPOffset> { + let mut builder = Table2Builder::new(_fbb); + if let Some(x) = args.type_ { builder.add_type_(x); } + builder.add_type_type(args.type_type); + builder.finish() + } + + pub fn unpack(&self) -> Table2T { + let type_ = match self.type_type() { + KeywordsInUnion::NONE => KeywordsInUnionT::NONE, + KeywordsInUnion::static_ => KeywordsInUnionT::Static_(Box::new( + self.type__as_static_() + .expect("Invalid union table, expected `KeywordsInUnion::static_`.") + .unpack() + )), + KeywordsInUnion::internal => KeywordsInUnionT::Internal(Box::new( + self.type__as_internal() + .expect("Invalid union table, expected `KeywordsInUnion::internal`.") + .unpack() + )), + _ => KeywordsInUnionT::NONE, + }; + Table2T { + type_, + } + } + + #[inline] + pub fn type_type(&self) -> KeywordsInUnion { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Table2::VT_TYPE_TYPE, Some(KeywordsInUnion::NONE)).unwrap()} + } + #[inline] + pub fn type_(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Table2::VT_TYPE_, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn type__as_static_(&self) -> Option> { + if self.type_type() == KeywordsInUnion::static_ { + self.type_().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { KeywordsInTable::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn type__as_internal(&self) -> Option> { + if self.type_type() == KeywordsInUnion::internal { + self.type_().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { KeywordsInTable::init_from_table(t) } + }) + } else { + None + } + } + +} + +impl flatbuffers::Verifiable for Table2<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_union::("type_type", Self::VT_TYPE_TYPE, "type_", Self::VT_TYPE_, false, |key, v, pos| { + match key { + KeywordsInUnion::static_ => v.verify_union_variant::>("KeywordsInUnion::static_", pos), + KeywordsInUnion::internal => v.verify_union_variant::>("KeywordsInUnion::internal", pos), + _ => Ok(()), + } + })? + .finish(); + Ok(()) + } +} +pub struct Table2Args { + pub type_type: KeywordsInUnion, + pub type_: Option>, +} +impl<'a> Default for Table2Args { + #[inline] + fn default() -> Self { + Table2Args { + type_type: KeywordsInUnion::NONE, + type_: None, + } + } +} + +pub struct Table2Builder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> Table2Builder<'a, 'b, A> { + #[inline] + pub fn add_type_type(&mut self, type_type: KeywordsInUnion) { + self.fbb_.push_slot::(Table2::VT_TYPE_TYPE, type_type, KeywordsInUnion::NONE); + } + #[inline] + pub fn add_type_(&mut self, type_: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Table2::VT_TYPE_, type_); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> Table2Builder<'a, 'b, A> { + let start = _fbb.start_table(); + Table2Builder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Table2<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Table2"); + ds.field("type_type", &self.type_type()); + match self.type_type() { + KeywordsInUnion::static_ => { + if let Some(x) = self.type__as_static_() { + ds.field("type_", &x) + } else { + ds.field("type_", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + KeywordsInUnion::internal => { + if let Some(x) = self.type__as_internal() { + ds.field("type_", &x) + } else { + ds.field("type_", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("type_", &x) + }, + }; + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct Table2T { + pub type_: KeywordsInUnionT, +} +impl Default for Table2T { + fn default() -> Self { + Self { + type_: KeywordsInUnionT::NONE, + } + } +} +impl Table2T { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let type_type = self.type_.keywords_in_union_type(); + let type_ = self.type_.pack(_fbb); + Table2::create(_fbb, &Table2Args{ + type_type, + type_, + }) + } +} diff --git a/third_party/flatbuffers/tests/keyword_test/mod.rs b/third_party/flatbuffers/tests/keyword_test/mod.rs new file mode 100644 index 00000000000..56f68c40d53 --- /dev/null +++ b/third_party/flatbuffers/tests/keyword_test/mod.rs @@ -0,0 +1,15 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod keyword_test { + use super::*; + mod abc_generated; + pub use self::abc_generated::*; + mod public_generated; + pub use self::public_generated::*; + mod keywords_in_union_generated; + pub use self::keywords_in_union_generated::*; + mod keywords_in_table_generated; + pub use self::keywords_in_table_generated::*; + mod table_2_generated; + pub use self::table_2_generated::*; +} // keyword_test diff --git a/third_party/flatbuffers/tests/lobstertest.lobster b/third_party/flatbuffers/tests/lobstertest.lobster new file mode 100644 index 00000000000..ab016c9ba8e --- /dev/null +++ b/third_party/flatbuffers/tests/lobstertest.lobster @@ -0,0 +1,202 @@ +// Copyright 2018 Google Inc. All rights reserved. +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import from "../lobster/" +import monster_test_generated +import optional_scalars_generated + +def check_read_buffer(buf): + // Check that the given buffer is evaluated correctly as the example Monster. + assert flatbuffers.has_identifier(buf, "MONS") + + let monster = MyGame.Example.GetRootAsMonster(buf) + + assert monster.hp == 80 + assert monster.mana == 150 + assert monster.name == "MyMonster" + + let vec = monster.pos + assert vec + assert vec.x == 1.0 + assert vec.y == 2.0 + assert vec.z == 3.0 + assert vec.test1 == 3.0 + assert vec.test2 == 2 + + let t = vec.test3 + assert t + assert t.a == 5 + assert t.b == 6 + + assert monster.test_type == MyGame.Example.Any_Monster + assert monster.test_as_Monster.name == "Fred" + + assert monster.inventory_length == 5 + assert sum(map(monster.inventory_length) i: monster.inventory(i)) == 10 + + for(5) i: + assert monster.vector_of_longs(i) == pow(10, i * 2) + + assert equal([-1.7976931348623157e+308, 0.0, 1.7976931348623157e+308], + (map(monster.vector_of_doubles_length) i: monster.vector_of_doubles(i))) + + assert monster.test4_length == 2 + let test0 = monster.test4(0) + let test1 = monster.test4(1) + assert test0.a + test0.b + test1.a + test1.b == 100 + + assert monster.testarrayofstring_length == 2 + assert monster.testarrayofstring(0) == "test1" + assert monster.testarrayofstring(1) == "test2" + + assert monster.testarrayoftables_length == 0 + assert monster.testnestedflatbuffer_length == 0 + assert not monster.testempty() + +def make_monster_from_generated_code(): + // Use generated code to build the example Monster. + let b = flatbuffers.builder {} + + let name = b.CreateString("MyMonster") + let fred = b.CreateString("Fred") + + let inv = b.MyGame.Example.MonsterCreateInventoryVector([ 0, 1, 2, 3, 4 ]) + + let mon2 = MyGame.Example.MonsterBuilder { b } + .start() + .add_name(fred) + .end() + + b.MyGame.Example.MonsterStartTest4Vector(2) + b.MyGame.Example.CreateTest(10, 20) + b.MyGame.Example.CreateTest(30, 40) + let test4 = b.EndVector(2) + + let test_array_of_string = b.MyGame.Example.MonsterCreateTestarrayofstringVector( + [ b.CreateString("test1"), b.CreateString("test2") ]) + + let vector_of_longs = b.MyGame.Example.MonsterCreateVectorOfLongsVector( + [ 1, 100, 10000, 1000000, 100000000 ]) + + let vector_of_doubles = b.MyGame.Example.MonsterCreateVectorOfDoublesVector( + [ -1.7976931348623157e+308, 0.0, 1.7976931348623157e+308 ]) + + let mon = MyGame.Example.MonsterBuilder { b } + .start() + .add_pos(b.MyGame.Example.CreateVec3(1.0, 2.0, 3.0, 3.0, + MyGame.Example.Color_Green, 5, 6)) + .add_hp(80) + .add_name(name) + .add_inventory(inv) + .add_test_type(MyGame.Example.Any_Monster) + .add_test(mon2) + .add_test4(test4) + .add_testarrayofstring(test_array_of_string) + .add_vector_of_longs(vector_of_longs) + .add_vector_of_doubles(vector_of_doubles) + .end() + + b.Finish(mon, "MONS") + + return b.SizedCopy() + +def test_optional_scalars(): + def build(add_fields): + let b = flatbuffers.builder {} + let ss = optional_scalars.ScalarStuffBuilder { b }.start() + if add_fields: + ss.add_just_i8(1) + ss.add_maybe_i8(1) + ss.add_default_i8(1) + ss.add_just_f64(1.0) + ss.add_maybe_f64(1.0) + ss.add_default_f64(1.0) + ss.add_just_bool(true) + ss.add_maybe_bool(true) + ss.add_default_bool(true) + ss.add_just_enum(optional_scalars.OptionalByte_Two) + ss.add_maybe_enum(optional_scalars.OptionalByte_Two) + ss.add_default_enum(optional_scalars.OptionalByte_Two) + b.Finish(ss.end(), "NULL") + let buf = b.SizedCopy() + assert flatbuffers.has_identifier(buf, "NULL") + return optional_scalars.GetRootAsScalarStuff(buf) + + var root = build(true) + + assert root.just_i8() == 1 and root.default_i8() == 1 + var maybe_val_i8, maybe_present_i8 = root.maybe_i8() + assert maybe_val_i8 == 1 and maybe_present_i8 == true + + assert root.just_f64() == 1.0 and root.default_f64() == 1.0 + var maybe_val_f64, maybe_present_f64 = root.maybe_f64() + assert maybe_val_f64 == 1.0 and maybe_present_f64 == true + + assert root.just_bool() == true and root.default_bool() == true + var maybe_val_bool, maybe_present_bool = root.maybe_bool() + assert maybe_val_bool == true and maybe_present_bool == true + + assert root.just_enum() == optional_scalars.OptionalByte_Two and root.default_enum() == optional_scalars.OptionalByte_Two + var maybe_val_enum, maybe_present_enum = root.maybe_enum() + assert maybe_val_enum == optional_scalars.OptionalByte_Two and maybe_present_enum == true + + root = build(false) + + assert root.just_i8() == 0 and root.default_i8() == 42 + maybe_val_i8, maybe_present_i8 = root.maybe_i8() + assert maybe_val_i8 == 0 and maybe_present_i8 == false + + assert root.just_f64() == 0.0 and root.default_f64() == 42.0 + maybe_val_f64, maybe_present_f64 = root.maybe_f64() + assert maybe_val_f64 == 0.0 and maybe_present_f64 == false + + assert root.just_bool() == false and root.default_bool() == true + maybe_val_bool, maybe_present_bool = root.maybe_bool() + assert maybe_val_bool == false and maybe_present_bool == false + + assert root.just_enum() == optional_scalars.OptionalByte_None and root.default_enum() == optional_scalars.OptionalByte_One + maybe_val_enum, maybe_present_enum = root.maybe_enum() + assert maybe_val_enum == optional_scalars.OptionalByte_None and maybe_present_enum == false + + +// Verify that the canonical flatbuffer file (produced by the C++ implementation) +// is readable by the generated Lobster code. +let fb2 = read_file("monsterdata_test.mon") +assert fb2 +check_read_buffer(fb2) + +// Verify that using the generated Lobster code builds a buffer without +// returning errors, and is interpreted correctly. +let fb1 = make_monster_from_generated_code() +check_read_buffer(fb1) +// Write the result to file for no good reason. +write_file("monsterdata_lobster_wire.mon", fb1) + +// Test converting the buffer to JSON and parsing the JSON back again. +let schema = read_file("monster_test.fbs") +assert schema +let includedirs = [ "include_test" ] +// Convert binary to JSON: +let json, err1 = flatbuffers.binary_to_json(schema, fb1, includedirs) +assert not err1 +// Parse JSON back to binary: +let fb3, err2 = flatbuffers.json_to_binary(schema, json, includedirs) +assert not err2 +// Check the resulting binary again (full roundtrip test): +check_read_buffer(fb3) + +// Additional tests. +test_optional_scalars() + +print "Lobster test successful!" diff --git a/third_party/flatbuffers/tests/luatest.lua b/third_party/flatbuffers/tests/luatest.lua new file mode 100644 index 00000000000..1a70f5ff42b --- /dev/null +++ b/third_party/flatbuffers/tests/luatest.lua @@ -0,0 +1,428 @@ +package.path = string.format("../lua/?.lua;./?.lua;%s",package.path) +local compat = require("flatbuffers.compat") + +local performBenchmarkTests = false + +if #arg > 1 then + print("usage: lua luatests [benchmark]"); + return +elseif #arg > 0 then + if(arg[1] == "benchmark") then + performBenchmarkTests = true + end +end + +local function checkReadBuffer(buf, offset, sizePrefix) + offset = offset or 0 + + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + + if sizePrefix then + local size = flatbuffers.N.Int32:Unpack(buf, offset) + assert(size == buf.size - offset - 4) + offset = offset + flatbuffers.N.Int32.bytewidth + end + + local mon = monster.GetRootAsMonster(buf, offset) + assert(mon:Hp() == 80, "Monster Hp is not 80") + assert(mon:Mana() == 150, "Monster Mana is not 150") + assert(mon:Name() == "MyMonster", "Monster Name is not MyMonster") + assert(mon:Testbool() == true) + + local vec = assert(mon:Pos(), "Monster Position is nil") + assert(vec:X() == 1.0) + assert(vec:Y() == 2.0) + assert(vec:Z() == 3.0) + assert(vec:Test1() == 3.0) + assert(vec:Test2() == 2) + + local t = require("MyGame.Example.Test").New() + t = assert(vec:Test3(t)) + + assert(t:A() == 5) + assert(t:B() == 6) + + local ut = require("MyGame.Example.Any") + assert(mon:TestType() == ut.Monster) + + local table2 = mon:Test() + assert(getmetatable(table2) == "flatbuffers.view.mt") + + local mon2 = monster.New() + mon2:Init(table2.bytes, table2.pos) + + assert(mon2:Name() == "Fred") + + assert(mon:InventoryLength() == 5) + local invsum = 0 + for i=1,mon:InventoryLength() do + local v = mon:Inventory(i) + invsum = invsum + v + end + assert(invsum == 10) + + for i=1,5 do + assert(mon:VectorOfLongs(i) == 10^((i-1)*2)) + end + + local dbls = { -1.7976931348623157e+308, 0, 1.7976931348623157e+308} + for i=1,mon:VectorOfDoublesLength() do + assert(mon:VectorOfDoubles(i) == dbls[i]) + end + + assert(mon:Test4Length() == 2) + + local test0 = mon:Test4(1) + local test1 = mon:Test4(2) + + local v0 = test0:A() + local v1 = test0:B() + local v2 = test1:A() + local v3 = test1:B() + + local sumtest12 = v0 + v1 + v2 + v3 + assert(sumtest12 == 100) + + assert(mon:TestarrayofstringLength() == 2) + assert(mon:Testarrayofstring(1) == "test1") + assert(mon:Testarrayofstring(2) == "test2") + + assert(mon:TestarrayoftablesLength() == 0) + assert(mon:TestnestedflatbufferLength() == 0) + assert(mon:Testempty() == nil) +end + +local function generateMonster(sizePrefix, b) + if b then b:Clear() end + b = b or flatbuffers.Builder(0) + local str = b:CreateString("MyMonster") + local test1 = b:CreateString("test1") + local test2 = b:CreateString("test2") + local fred = b:CreateString("Fred") + + monster.StartInventoryVector(b, 5) + b:PrependByte(4) + b:PrependByte(3) + b:PrependByte(2) + b:PrependByte(1) + b:PrependByte(0) + local inv = b:EndVector(5) + + monster.Start(b) + monster.AddName(b, fred) + local mon2 = monster.End(b) + + monster.StartTest4Vector(b, 2) + test.CreateTest(b, 10, 20) + test.CreateTest(b, 30, 40) + local test4 = b:EndVector(2) + + monster.StartTestarrayofstringVector(b, 2) + b:PrependUOffsetTRelative(test2) + b:PrependUOffsetTRelative(test1) + local testArrayOfString = b:EndVector(2) + + monster.StartVectorOfLongsVector(b, 5) + b:PrependInt64(100000000) + b:PrependInt64(1000000) + b:PrependInt64(10000) + b:PrependInt64(100) + b:PrependInt64(1) + local vectorOfLongs = b:EndVector(5) + + monster.StartVectorOfDoublesVector(b, 3) + b:PrependFloat64(1.7976931348623157e+308) + b:PrependFloat64(0) + b:PrependFloat64(-1.7976931348623157e+308) + local vectorOfDoubles = b:EndVector(3) + + monster.Start(b) + local pos = vec3.CreateVec3(b, 1.0, 2.0, 3.0, 3.0, 2, 5, 6) + monster.AddPos(b, pos) + + monster.AddHp(b, 80) + monster.AddName(b, str) + monster.AddInventory(b, inv) + monster.AddTestType(b, 1) + monster.AddTest(b, mon2) + monster.AddTest4(b, test4) + monster.AddTestbool(b, true) + monster.AddTestbool(b, false) + monster.AddTestbool(b, null) + monster.AddTestbool(b,"true") + monster.AddTestarrayofstring(b, testArrayOfString) + monster.AddVectorOfLongs(b, vectorOfLongs) + monster.AddVectorOfDoubles(b, vectorOfDoubles) + local mon = monster.End(b) + + if sizePrefix then + b:FinishSizePrefixed(mon) + else + b:Finish(mon) + end + return b:Output(true), b:Head() +end + +local function sizePrefix(sizePrefix) + local buf,offset = generateMonster(sizePrefix) + checkReadBuffer(buf, offset, sizePrefix) +end + +local function fbbClear() + -- Generate a builder that will be 'cleared' and reused to create two different objects. + local fbb = flatbuffers.Builder(0) + + -- First use the builder to read the normal monster data and verify it works + local buf, offset = generateMonster(false, fbb) + checkReadBuffer(buf, offset, false) + + -- Then clear the builder to be used again + fbb:Clear() + + -- Storage for the built monsters + local monsters = {} + local lastBuf + + -- Make another builder that will be use identically to the 'cleared' one so outputs can be compared. Build both the + -- Cleared builder and new builder in the exact same way, so we can compare their results + for i, builder in ipairs({fbb, flatbuffers.Builder(0)}) do + local strOffset = builder:CreateString("Hi there") + monster.Start(builder) + monster.AddPos(builder, vec3.CreateVec3(builder, 3.0, 2.0, 1.0, 17.0, 3, 100, 123)) + monster.AddName(builder, strOffset) + monster.AddMana(builder, 123) + builder:Finish(monster.End(builder)) + local buf = builder:Output(false) + if not lastBuf then + lastBuf = buf + else + -- the output, sized-buffer should be identical + assert(lastBuf == buf, "Monster output buffers are not identical") + end + monsters[i] = monster.GetRootAsMonster(flatbuffers.binaryArray.New(buf), 0) + end + + -- Check that all the fields for the generated monsters are as we expect + for i, monster in ipairs(monsters) do + assert(monster:Name() == "Hi there", "Monster Name is not 'Hi There' for monster "..i) + -- HP is default to 100 in the schema, but we change it in generateMonster to 80, so this is a good test to + -- see if the cleared builder really clears the data. + assert(monster:Hp() == 100, "HP doesn't equal the default value for monster "..i) + assert(monster:Mana() == 123, "Monster Mana is not '123' for monster "..i) + assert(monster:Pos():X() == 3.0, "Monster vec3.X is not '3' for monster "..i) + end +end + +local function testCanonicalData() + local f = assert(io.open('monsterdata_test.mon', 'rb')) + local wireData = f:read("*a") + f:close() + checkReadBuffer(wireData) +end + +local function testCreateEmptyString() + local b = flatbuffers.Builder(0) + local str = b:CreateString("") + monster.Start(b) + monster.AddName(b, str) + b:Finish(monster.End(b)) + local s = b:Output() + local data = flatbuffers.binaryArray.New(s) + local mon = monster.GetRootAsMonster(data, 0) + assert(mon:Name() == "") +end + +local function benchmarkMakeMonster(count, reuseBuilder) + local fbb = reuseBuilder and flatbuffers.Builder(0) + local length = #(generateMonster(false, fbb)) + + local s = os.clock() + for i=1,count do + generateMonster(false, fbb) + end + local e = os.clock() + + local dur = (e - s) + local rate = count / (dur * 1000) + local data = (length * count) / (1024 * 1024) + local dataRate = data / dur + + print(string.format('built %d %d-byte flatbuffers in %.2fsec: %.2f/msec, %.2fMB/sec', + count, length, dur, rate, dataRate)) +end + +local function benchmarkReadBuffer(count) + local f = assert(io.open('monsterdata_test.mon', 'rb')) + local buf = f:read("*a") + f:close() + + local s = os.clock() + for i=1,count do + checkReadBuffer(buf) + end + local e = os.clock() + + local dur = (e - s) + local rate = count / (dur * 1000) + local data = (#buf * count) / (1024 * 1024) + local dataRate = data / dur + + print(string.format('traversed %d %d-byte flatbuffers in %.2fsec: %.2f/msec, %.2fMB/sec', + count, #buf, dur, rate, dataRate)) +end + +local function getRootAs_canAcceptString() + local f = assert(io.open('monsterdata_test.mon', 'rb')) + local wireData = f:read("*a") + f:close() + assert(type(wireData) == "string", "Data is not a string"); + local mon = monster.GetRootAsMonster(wireData, 0) + assert(mon:Hp() == 80, "Monster Hp is not 80") +end + +local function testAccessByteVectorAsString() + local f = assert(io.open('monsterdata_test.mon', 'rb')) + local wireData = f:read("*a") + f:close() + local mon = monster.GetRootAsMonster(wireData, 0) + -- the data of byte array Inventory is [0, 1, 2, 3, 4] + local s = mon:InventoryAsString(1, 3) + assert(#s == 3) + for i = 1, #s do + assert(string.byte(s, i) == i - 1) + end + + local s = mon:InventoryAsString(2, 5) + assert(#s == 4) + for i = 1, #s do + assert(string.byte(s, i) == i) + end + + local s = mon:InventoryAsString(5, 5) + assert(#s == 1) + assert(string.byte(s, 1) == 4) + + local s = mon:InventoryAsString(2) + assert(#s == 4) + for i = 1, #s do + assert(string.byte(s, i) == i) + end + + local s = mon:InventoryAsString() + assert(#s == 5) + for i = 1, #s do + assert(string.byte(s, i) == i - 1) + end +end + +local tests = +{ + { + f = sizePrefix, + d = "Test size prefix", + args = {{true}, {false}} + }, + { + f = fbbClear, + d = "FlatBufferBuilder Clear", + }, + { + f = testCanonicalData, + d = "Tests Canonical flatbuffer file included in repo" + }, + { + f = testCreateEmptyString, + d = "Avoid infinite loop when creating empty string" + }, + { + f = getRootAs_canAcceptString, + d = "Tests that GetRootAs() generated methods accept strings" + }, + { + f = testAccessByteVectorAsString, + d = "Access byte vector as string" + }, +} + +local benchmarks = +{ + { + f = benchmarkMakeMonster, + d = "Benchmark making monsters", + args = { + {100}, + {1000}, + {10000}, + {10000, true} + } + }, + { + f = benchmarkReadBuffer, + d = "Benchmark reading monsters", + args = { + {100}, + {1000}, + {10000}, + -- uncomment following to run 1 million to compare. + -- Took ~141 seconds on my machine + --{1000000}, + } + }, +} + +local result, err = xpcall(function() + flatbuffers = assert(require("flatbuffers")) + monster = assert(require("MyGame.Example.Monster")) + test = assert(require("MyGame.Example.Test")) + vec3 = assert(require("MyGame.Example.Vec3")) + + local function buildArgList(tbl) + local s = "" + for _,item in ipairs(tbl) do + s = s .. tostring(item) .. "," + end + return s:sub(1,-2) + end + + if performBenchmarkTests then + for _,benchmark in ipairs(benchmarks) do + table.insert(tests, benchmark) + end + end + + local testsPassed, testsFailed = 0,0 + for _,test in ipairs(tests) do + local allargs = test.args or {{}} + for _,args in ipairs(allargs) do + local results, err = xpcall(test.f,debug.traceback, table.unpack(args)) + if results then + testsPassed = testsPassed + 1 + else + testsFailed = testsFailed + 1 + print(string.format(" Test [%s](%s) failed: \n\t%s", + test.d or "", + buildArgList(args), + err)) + end + end + end + + local totalTests = testsPassed + testsFailed + print(string.format("# of test passed: %d / %d (%.2f%%)", + testsPassed, + totalTests, + totalTests ~= 0 + and 100 * (testsPassed / totalTests) + or 0) + ) + + return 0 +end, debug.traceback) + +if not result then + print("Unable to run tests due to test framework error: ",err) +end + +os.exit(result and 0 or -1) diff --git a/third_party/flatbuffers/tests/minified_enums/enums.fbs b/third_party/flatbuffers/tests/minified_enums/enums.fbs new file mode 100644 index 00000000000..0e0211aa1cd --- /dev/null +++ b/third_party/flatbuffers/tests/minified_enums/enums.fbs @@ -0,0 +1,3 @@ +enum Color : int {Red = 1, Blue, Orange} + +enum Size: int {Small = 10, Large = 100, Medium = 1000} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/minified_enums/enums_generated.h b/third_party/flatbuffers/tests/minified_enums/enums_generated.h new file mode 100644 index 00000000000..cee73174a25 --- /dev/null +++ b/third_party/flatbuffers/tests/minified_enums/enums_generated.h @@ -0,0 +1,26 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_ENUMS_H_ +#define FLATBUFFERS_GENERATED_ENUMS_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +enum Color : int32_t { + Color_Red = 1, + Color_Blue = 2, + Color_Orange = 3 +}; +enum Size : int32_t { + Size_Small = 10, + Size_Large = 100, + Size_Medium = 1000 +}; +#endif // FLATBUFFERS_GENERATED_ENUMS_H_ diff --git a/third_party/flatbuffers/tests/monster_extra.fbs b/third_party/flatbuffers/tests/monster_extra.fbs new file mode 100644 index 00000000000..7cadf457aa7 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_extra.fbs @@ -0,0 +1,22 @@ +namespace MyGame; + +// Not all programming languages support this extra table. +table MonsterExtra { + // Float-point values with NaN and Inf defaults. + d0:double = nan; + d1:double = -nan; // parser must ignore sign of NaN + d2:double = +inf; + d3:double = -inf; + f0:float = -nan; // parser must ignore sign of NaN + f1:float = +nan; + f2:float = +inf; + f3:float = -inf; + dvec : [double]; + fvec : [float]; + deprec:int (deprecated); +} + +root_type MonsterExtra; + +file_identifier "MONE"; +file_extension "mon"; diff --git a/third_party/flatbuffers/tests/monster_extra_generated.h b/third_party/flatbuffers/tests/monster_extra_generated.h new file mode 100644 index 00000000000..e50796749df --- /dev/null +++ b/third_party/flatbuffers/tests/monster_extra_generated.h @@ -0,0 +1,417 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTEREXTRA_MYGAME_H_ +#define FLATBUFFERS_GENERATED_MONSTEREXTRA_MYGAME_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace MyGame { + +struct MonsterExtra; +struct MonsterExtraBuilder; +struct MonsterExtraT; + +bool operator==(const MonsterExtraT &lhs, const MonsterExtraT &rhs); +bool operator!=(const MonsterExtraT &lhs, const MonsterExtraT &rhs); + +inline const ::flatbuffers::TypeTable *MonsterExtraTypeTable(); + +struct MonsterExtraT : public ::flatbuffers::NativeTable { + typedef MonsterExtra TableType; + double d0 = std::numeric_limits::quiet_NaN(); + double d1 = std::numeric_limits::quiet_NaN(); + double d2 = std::numeric_limits::infinity(); + double d3 = -std::numeric_limits::infinity(); + float f0 = std::numeric_limits::quiet_NaN(); + float f1 = std::numeric_limits::quiet_NaN(); + float f2 = std::numeric_limits::infinity(); + float f3 = -std::numeric_limits::infinity(); + std::vector dvec{}; + std::vector fvec{}; +}; + +struct MonsterExtra FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterExtraT NativeTableType; + typedef MonsterExtraBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterExtraTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_D0 = 4, + VT_D1 = 6, + VT_D2 = 8, + VT_D3 = 10, + VT_F0 = 12, + VT_F1 = 14, + VT_F2 = 16, + VT_F3 = 18, + VT_DVEC = 20, + VT_FVEC = 22 + }; + double d0() const { + return GetField(VT_D0, std::numeric_limits::quiet_NaN()); + } + bool mutate_d0(double _d0 = std::numeric_limits::quiet_NaN()) { + return SetField(VT_D0, _d0, std::numeric_limits::quiet_NaN()); + } + double d1() const { + return GetField(VT_D1, std::numeric_limits::quiet_NaN()); + } + bool mutate_d1(double _d1 = std::numeric_limits::quiet_NaN()) { + return SetField(VT_D1, _d1, std::numeric_limits::quiet_NaN()); + } + double d2() const { + return GetField(VT_D2, std::numeric_limits::infinity()); + } + bool mutate_d2(double _d2 = std::numeric_limits::infinity()) { + return SetField(VT_D2, _d2, std::numeric_limits::infinity()); + } + double d3() const { + return GetField(VT_D3, -std::numeric_limits::infinity()); + } + bool mutate_d3(double _d3 = -std::numeric_limits::infinity()) { + return SetField(VT_D3, _d3, -std::numeric_limits::infinity()); + } + float f0() const { + return GetField(VT_F0, std::numeric_limits::quiet_NaN()); + } + bool mutate_f0(float _f0 = std::numeric_limits::quiet_NaN()) { + return SetField(VT_F0, _f0, std::numeric_limits::quiet_NaN()); + } + float f1() const { + return GetField(VT_F1, std::numeric_limits::quiet_NaN()); + } + bool mutate_f1(float _f1 = std::numeric_limits::quiet_NaN()) { + return SetField(VT_F1, _f1, std::numeric_limits::quiet_NaN()); + } + float f2() const { + return GetField(VT_F2, std::numeric_limits::infinity()); + } + bool mutate_f2(float _f2 = std::numeric_limits::infinity()) { + return SetField(VT_F2, _f2, std::numeric_limits::infinity()); + } + float f3() const { + return GetField(VT_F3, -std::numeric_limits::infinity()); + } + bool mutate_f3(float _f3 = -std::numeric_limits::infinity()) { + return SetField(VT_F3, _f3, -std::numeric_limits::infinity()); + } + const ::flatbuffers::Vector *dvec() const { + return GetPointer *>(VT_DVEC); + } + ::flatbuffers::Vector *mutable_dvec() { + return GetPointer<::flatbuffers::Vector *>(VT_DVEC); + } + const ::flatbuffers::Vector *fvec() const { + return GetPointer *>(VT_FVEC); + } + ::flatbuffers::Vector *mutable_fvec() { + return GetPointer<::flatbuffers::Vector *>(VT_FVEC); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_D0, 8) && + VerifyField(verifier, VT_D1, 8) && + VerifyField(verifier, VT_D2, 8) && + VerifyField(verifier, VT_D3, 8) && + VerifyField(verifier, VT_F0, 4) && + VerifyField(verifier, VT_F1, 4) && + VerifyField(verifier, VT_F2, 4) && + VerifyField(verifier, VT_F3, 4) && + VerifyOffset(verifier, VT_DVEC) && + verifier.VerifyVector(dvec()) && + VerifyOffset(verifier, VT_FVEC) && + verifier.VerifyVector(fvec()) && + verifier.EndTable(); + } + MonsterExtraT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterExtraT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterExtraT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MonsterExtraBuilder { + typedef MonsterExtra Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_d0(double d0) { + fbb_.AddElement(MonsterExtra::VT_D0, d0, std::numeric_limits::quiet_NaN()); + } + void add_d1(double d1) { + fbb_.AddElement(MonsterExtra::VT_D1, d1, std::numeric_limits::quiet_NaN()); + } + void add_d2(double d2) { + fbb_.AddElement(MonsterExtra::VT_D2, d2, std::numeric_limits::infinity()); + } + void add_d3(double d3) { + fbb_.AddElement(MonsterExtra::VT_D3, d3, -std::numeric_limits::infinity()); + } + void add_f0(float f0) { + fbb_.AddElement(MonsterExtra::VT_F0, f0, std::numeric_limits::quiet_NaN()); + } + void add_f1(float f1) { + fbb_.AddElement(MonsterExtra::VT_F1, f1, std::numeric_limits::quiet_NaN()); + } + void add_f2(float f2) { + fbb_.AddElement(MonsterExtra::VT_F2, f2, std::numeric_limits::infinity()); + } + void add_f3(float f3) { + fbb_.AddElement(MonsterExtra::VT_F3, f3, -std::numeric_limits::infinity()); + } + void add_dvec(::flatbuffers::Offset<::flatbuffers::Vector> dvec) { + fbb_.AddOffset(MonsterExtra::VT_DVEC, dvec); + } + void add_fvec(::flatbuffers::Offset<::flatbuffers::Vector> fvec) { + fbb_.AddOffset(MonsterExtra::VT_FVEC, fvec); + } + explicit MonsterExtraBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonsterExtra( + ::flatbuffers::FlatBufferBuilder &_fbb, + double d0 = std::numeric_limits::quiet_NaN(), + double d1 = std::numeric_limits::quiet_NaN(), + double d2 = std::numeric_limits::infinity(), + double d3 = -std::numeric_limits::infinity(), + float f0 = std::numeric_limits::quiet_NaN(), + float f1 = std::numeric_limits::quiet_NaN(), + float f2 = std::numeric_limits::infinity(), + float f3 = -std::numeric_limits::infinity(), + ::flatbuffers::Offset<::flatbuffers::Vector> dvec = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> fvec = 0) { + MonsterExtraBuilder builder_(_fbb); + builder_.add_d3(d3); + builder_.add_d2(d2); + builder_.add_d1(d1); + builder_.add_d0(d0); + builder_.add_fvec(fvec); + builder_.add_dvec(dvec); + builder_.add_f3(f3); + builder_.add_f2(f2); + builder_.add_f1(f1); + builder_.add_f0(f0); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMonsterExtraDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + double d0 = std::numeric_limits::quiet_NaN(), + double d1 = std::numeric_limits::quiet_NaN(), + double d2 = std::numeric_limits::infinity(), + double d3 = -std::numeric_limits::infinity(), + float f0 = std::numeric_limits::quiet_NaN(), + float f1 = std::numeric_limits::quiet_NaN(), + float f2 = std::numeric_limits::infinity(), + float f3 = -std::numeric_limits::infinity(), + const std::vector *dvec = nullptr, + const std::vector *fvec = nullptr) { + auto dvec__ = dvec ? _fbb.CreateVector(*dvec) : 0; + auto fvec__ = fvec ? _fbb.CreateVector(*fvec) : 0; + return MyGame::CreateMonsterExtra( + _fbb, + d0, + d1, + d2, + d3, + f0, + f1, + f2, + f3, + dvec__, + fvec__); +} + +::flatbuffers::Offset CreateMonsterExtra(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterExtraT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const MonsterExtraT &lhs, const MonsterExtraT &rhs) { + return + (lhs.d0 == rhs.d0) && + (lhs.d1 == rhs.d1) && + (lhs.d2 == rhs.d2) && + (lhs.d3 == rhs.d3) && + (lhs.f0 == rhs.f0) && + (lhs.f1 == rhs.f1) && + (lhs.f2 == rhs.f2) && + (lhs.f3 == rhs.f3) && + (lhs.dvec == rhs.dvec) && + (lhs.fvec == rhs.fvec); +} + +inline bool operator!=(const MonsterExtraT &lhs, const MonsterExtraT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterExtraT *MonsterExtra::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterExtraT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void MonsterExtra::UnPackTo(MonsterExtraT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = d0(); _o->d0 = _e; } + { auto _e = d1(); _o->d1 = _e; } + { auto _e = d2(); _o->d2 = _e; } + { auto _e = d3(); _o->d3 = _e; } + { auto _e = f0(); _o->f0 = _e; } + { auto _e = f1(); _o->f1 = _e; } + { auto _e = f2(); _o->f2 = _e; } + { auto _e = f3(); _o->f3 = _e; } + { auto _e = dvec(); if (_e) { _o->dvec.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->dvec[_i] = _e->Get(_i); } } else { _o->dvec.resize(0); } } + { auto _e = fvec(); if (_e) { _o->fvec.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->fvec[_i] = _e->Get(_i); } } else { _o->fvec.resize(0); } } +} + +inline ::flatbuffers::Offset MonsterExtra::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterExtraT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonsterExtra(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonsterExtra(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterExtraT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterExtraT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _d0 = _o->d0; + auto _d1 = _o->d1; + auto _d2 = _o->d2; + auto _d3 = _o->d3; + auto _f0 = _o->f0; + auto _f1 = _o->f1; + auto _f2 = _o->f2; + auto _f3 = _o->f3; + auto _dvec = _o->dvec.size() ? _fbb.CreateVector(_o->dvec) : 0; + auto _fvec = _o->fvec.size() ? _fbb.CreateVector(_o->fvec) : 0; + return MyGame::CreateMonsterExtra( + _fbb, + _d0, + _d1, + _d2, + _d3, + _f0, + _f1, + _f2, + _f3, + _dvec, + _fvec); +} + +inline const ::flatbuffers::TypeTable *MonsterExtraTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 }, + { ::flatbuffers::ET_FLOAT, 1, -1 }, + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "d0", + "d1", + "d2", + "d3", + "f0", + "f1", + "f2", + "f3", + "dvec", + "fvec", + "deprec" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 11, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const MyGame::MonsterExtra *GetMonsterExtra(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const MyGame::MonsterExtra *GetSizePrefixedMonsterExtra(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline MonsterExtra *GetMutableMonsterExtra(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline MyGame::MonsterExtra *GetMutableSizePrefixedMonsterExtra(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MonsterExtraIdentifier() { + return "MONE"; +} + +inline bool MonsterExtraBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterExtraIdentifier()); +} + +inline bool SizePrefixedMonsterExtraBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterExtraIdentifier(), true); +} + +inline bool VerifyMonsterExtraBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MonsterExtraIdentifier()); +} + +inline bool VerifySizePrefixedMonsterExtraBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MonsterExtraIdentifier()); +} + +inline const char *MonsterExtraExtension() { + return "mon"; +} + +inline void FinishMonsterExtraBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MonsterExtraIdentifier()); +} + +inline void FinishSizePrefixedMonsterExtraBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MonsterExtraIdentifier()); +} + +inline std::unique_ptr UnPackMonsterExtra( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMonsterExtra(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMonsterExtra( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMonsterExtra(buf)->UnPack(res)); +} + +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTEREXTRA_MYGAME_H_ diff --git a/third_party/flatbuffers/tests/monster_extra_my_game_generated.dart b/third_party/flatbuffers/tests/monster_extra_my_game_generated.dart new file mode 100644 index 00000000000..462d5ac2087 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_extra_my_game_generated.dart @@ -0,0 +1,232 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +class MonsterExtra { + MonsterExtra._(this._bc, this._bcOffset); + factory MonsterExtra(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MonsterExtraReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + double get d0 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 4, double.nan); + double get d1 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 6, double.nan); + double get d2 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 8, double.infinity); + double get d3 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 10, double.negativeInfinity); + double get f0 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 12, double.nan); + double get f1 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 14, double.nan); + double get f2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 16, double.infinity); + double get f3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 18, double.negativeInfinity); + List? get dvec => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 20); + List? get fvec => const fb.ListReader(fb.Float32Reader()).vTableGetNullable(_bc, _bcOffset, 22); + + @override + String toString() { + return 'MonsterExtra{d0: ${d0}, d1: ${d1}, d2: ${d2}, d3: ${d3}, f0: ${f0}, f1: ${f1}, f2: ${f2}, f3: ${f3}, dvec: ${dvec}, fvec: ${fvec}}'; + } + + MonsterExtraT unpack() => MonsterExtraT( + d0: d0, + d1: d1, + d2: d2, + d3: d3, + f0: f0, + f1: f1, + f2: f2, + f3: f3, + dvec: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 20), + fvec: const fb.ListReader(fb.Float32Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 22)); + + static int pack(fb.Builder fbBuilder, MonsterExtraT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class MonsterExtraT implements fb.Packable { + double d0; + double d1; + double d2; + double d3; + double f0; + double f1; + double f2; + double f3; + List? dvec; + List? fvec; + + MonsterExtraT({ + this.d0 = double.nan, + this.d1 = double.nan, + this.d2 = double.infinity, + this.d3 = double.negativeInfinity, + this.f0 = double.nan, + this.f1 = double.nan, + this.f2 = double.infinity, + this.f3 = double.negativeInfinity, + this.dvec, + this.fvec}); + + @override + int pack(fb.Builder fbBuilder) { + final int? dvecOffset = dvec == null ? null + : fbBuilder.writeListFloat64(dvec!); + final int? fvecOffset = fvec == null ? null + : fbBuilder.writeListFloat32(fvec!); + fbBuilder.startTable(11); + fbBuilder.addFloat64(0, d0); + fbBuilder.addFloat64(1, d1); + fbBuilder.addFloat64(2, d2); + fbBuilder.addFloat64(3, d3); + fbBuilder.addFloat32(4, f0); + fbBuilder.addFloat32(5, f1); + fbBuilder.addFloat32(6, f2); + fbBuilder.addFloat32(7, f3); + fbBuilder.addOffset(8, dvecOffset); + fbBuilder.addOffset(9, fvecOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'MonsterExtraT{d0: ${d0}, d1: ${d1}, d2: ${d2}, d3: ${d3}, f0: ${f0}, f1: ${f1}, f2: ${f2}, f3: ${f3}, dvec: ${dvec}, fvec: ${fvec}}'; + } +} + +class _MonsterExtraReader extends fb.TableReader { + const _MonsterExtraReader(); + + @override + MonsterExtra createObject(fb.BufferContext bc, int offset) => + MonsterExtra._(bc, offset); +} + +class MonsterExtraBuilder { + MonsterExtraBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(11); + } + + int addD0(double? d0) { + fbBuilder.addFloat64(0, d0); + return fbBuilder.offset; + } + int addD1(double? d1) { + fbBuilder.addFloat64(1, d1); + return fbBuilder.offset; + } + int addD2(double? d2) { + fbBuilder.addFloat64(2, d2); + return fbBuilder.offset; + } + int addD3(double? d3) { + fbBuilder.addFloat64(3, d3); + return fbBuilder.offset; + } + int addF0(double? f0) { + fbBuilder.addFloat32(4, f0); + return fbBuilder.offset; + } + int addF1(double? f1) { + fbBuilder.addFloat32(5, f1); + return fbBuilder.offset; + } + int addF2(double? f2) { + fbBuilder.addFloat32(6, f2); + return fbBuilder.offset; + } + int addF3(double? f3) { + fbBuilder.addFloat32(7, f3); + return fbBuilder.offset; + } + int addDvecOffset(int? offset) { + fbBuilder.addOffset(8, offset); + return fbBuilder.offset; + } + int addFvecOffset(int? offset) { + fbBuilder.addOffset(9, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MonsterExtraObjectBuilder extends fb.ObjectBuilder { + final double? _d0; + final double? _d1; + final double? _d2; + final double? _d3; + final double? _f0; + final double? _f1; + final double? _f2; + final double? _f3; + final List? _dvec; + final List? _fvec; + + MonsterExtraObjectBuilder({ + double? d0, + double? d1, + double? d2, + double? d3, + double? f0, + double? f1, + double? f2, + double? f3, + List? dvec, + List? fvec, + }) + : _d0 = d0, + _d1 = d1, + _d2 = d2, + _d3 = d3, + _f0 = f0, + _f1 = f1, + _f2 = f2, + _f3 = f3, + _dvec = dvec, + _fvec = fvec; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? dvecOffset = _dvec == null ? null + : fbBuilder.writeListFloat64(_dvec!); + final int? fvecOffset = _fvec == null ? null + : fbBuilder.writeListFloat32(_fvec!); + fbBuilder.startTable(11); + fbBuilder.addFloat64(0, _d0); + fbBuilder.addFloat64(1, _d1); + fbBuilder.addFloat64(2, _d2); + fbBuilder.addFloat64(3, _d3); + fbBuilder.addFloat32(4, _f0); + fbBuilder.addFloat32(5, _f1); + fbBuilder.addFloat32(6, _f2); + fbBuilder.addFloat32(7, _f3); + fbBuilder.addOffset(8, dvecOffset); + fbBuilder.addOffset(9, fvecOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/monster_test.afb b/third_party/flatbuffers/tests/monster_test.afb new file mode 100644 index 00000000000..3a7f988d9f4 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.afb @@ -0,0 +1,6494 @@ +// Annotated Flatbuffer Binary +// +// Schema file: ../reflection/reflection.fbs +// Binary file: monster_test.bfbs + +header: + +0x0000 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0020 | offset to root table `reflection.Schema` + +0x0004 | 42 46 42 53 | char[4] | BFBS | File Identifier + +padding: + +0x0008 | 00 00 00 00 | uint8_t[4] | .... | padding + +vtable (reflection.Schema): + +0x000C | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x000E | 20 00 | uint16_t | 0x0020 (32) | size of referring table + +0x0010 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `objects` (id: 0) + +0x0012 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `enums` (id: 1) + +0x0014 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `file_ident` (id: 2) + +0x0016 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `file_ext` (id: 3) + +0x0018 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `root_table` (id: 4) + +0x001A | 18 00 | VOffset16 | 0x0018 (24) | offset to field `services` (id: 5) + +0x001C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `advanced_features` (id: 6) (ULong) + +0x001E | 1C 00 | VOffset16 | 0x001C (28) | offset to field `fbs_files` (id: 7) + +root_table (reflection.Schema): + +0x0020 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x000C | offset to vtable + +0x0024 | 58 00 00 00 | UOffset32 | 0x00000058 (88) Loc: 0x007C | offset to field `objects` (vector) + +0x0028 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x005C | offset to field `enums` (vector) + +0x002C | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x0050 | offset to field `file_ident` (string) + +0x0030 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0048 | offset to field `file_ext` (string) + +0x0034 | 50 0D 00 00 | UOffset32 | 0x00000D50 (3408) Loc: 0x0D84 | offset to field `root_table` (table) + +0x0038 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0040 | offset to field `services` (vector) + +0x003C | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x00BC | offset to field `fbs_files` (vector) + +vector (reflection.Schema.services): + +0x0040 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0044 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x0120 | offset to table[0] + +string (reflection.Schema.file_ext): + +0x0048 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x004C | 6D 6F 6E | char[3] | mon | string literal + +0x004F | 00 | char | 0x00 (0) | string terminator + +string (reflection.Schema.file_ident): + +0x0050 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0054 | 4D 4F 4E 53 | char[4] | MONS | string literal + +0x0058 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0059 | 00 00 00 | uint8_t[3] | ... | padding + +vector (reflection.Schema.enums): + +0x005C | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of vector (# items) + +0x0060 | D4 04 00 00 | UOffset32 | 0x000004D4 (1236) Loc: 0x0534 | offset to table[0] + +0x0064 | 90 02 00 00 | UOffset32 | 0x00000290 (656) Loc: 0x02F4 | offset to table[1] + +0x0068 | A8 03 00 00 | UOffset32 | 0x000003A8 (936) Loc: 0x0410 | offset to table[2] + +0x006C | 30 08 00 00 | UOffset32 | 0x00000830 (2096) Loc: 0x089C | offset to table[3] + +0x0070 | 00 06 00 00 | UOffset32 | 0x00000600 (1536) Loc: 0x0670 | offset to table[4] + +0x0074 | 0C 07 00 00 | UOffset32 | 0x0000070C (1804) Loc: 0x0780 | offset to table[5] + +0x0078 | 10 0A 00 00 | UOffset32 | 0x00000A10 (2576) Loc: 0x0A88 | offset to table[6] + +vector (reflection.Schema.objects): + +0x007C | 0F 00 00 00 | uint32_t | 0x0000000F (15) | length of vector (# items) + +0x0080 | BC 31 00 00 | UOffset32 | 0x000031BC (12732) Loc: 0x323C | offset to table[0] + +0x0084 | 00 0D 00 00 | UOffset32 | 0x00000D00 (3328) Loc: 0x0D84 | offset to table[1] + +0x0088 | 6C 2E 00 00 | UOffset32 | 0x00002E6C (11884) Loc: 0x2EF4 | offset to table[2] + +0x008C | 38 2F 00 00 | UOffset32 | 0x00002F38 (12088) Loc: 0x2FC4 | offset to table[3] + +0x0090 | A4 30 00 00 | UOffset32 | 0x000030A4 (12452) Loc: 0x3134 | offset to table[4] + +0x0094 | 28 30 00 00 | UOffset32 | 0x00003028 (12328) Loc: 0x30BC | offset to table[5] + +0x0098 | 44 35 00 00 | UOffset32 | 0x00003544 (13636) Loc: 0x35DC | offset to table[6] + +0x009C | 44 34 00 00 | UOffset32 | 0x00003444 (13380) Loc: 0x34E0 | offset to table[7] + +0x00A0 | 84 0A 00 00 | UOffset32 | 0x00000A84 (2692) Loc: 0x0B24 | offset to table[8] + +0x00A4 | 80 32 00 00 | UOffset32 | 0x00003280 (12928) Loc: 0x3324 | offset to table[9] + +0x00A8 | F4 35 00 00 | UOffset32 | 0x000035F4 (13812) Loc: 0x369C | offset to table[10] + +0x00AC | 24 36 00 00 | UOffset32 | 0x00003624 (13860) Loc: 0x36D0 | offset to table[11] + +0x00B0 | FC 36 00 00 | UOffset32 | 0x000036FC (14076) Loc: 0x37AC | offset to table[12] + +0x00B4 | A0 37 00 00 | UOffset32 | 0x000037A0 (14240) Loc: 0x3854 | offset to table[13] + +0x00B8 | 68 36 00 00 | UOffset32 | 0x00003668 (13928) Loc: 0x3720 | offset to table[14] + +vector (reflection.Schema.fbs_files): + +0x00BC | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x00C0 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x00F8 | offset to table[0] + +0x00C4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x00E0 | offset to table[1] + +0x00C8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00CC | offset to table[2] + +table (reflection.SchemaFile): + +0x00CC | 04 C8 FF FF | SOffset32 | 0xFFFFC804 (-14332) Loc: 0x38C8 | offset to vtable + +0x00D0 | 14 36 00 00 | UOffset32 | 0x00003614 (13844) Loc: 0x36E4 | offset to field `filename` (string) + +0x00D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00D8 | offset to field `included_filenames` (vector) + +vector (reflection.SchemaFile.included_filenames): + +0x00D8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x00DC | 58 36 00 00 | UOffset32 | 0x00003658 (13912) Loc: 0x3734 | offset to string[0] + +table (reflection.SchemaFile): + +0x00E0 | 18 C8 FF FF | SOffset32 | 0xFFFFC818 (-14312) Loc: 0x38C8 | offset to vtable + +0x00E4 | 8C 37 00 00 | UOffset32 | 0x0000378C (14220) Loc: 0x3870 | offset to field `filename` (string) + +0x00E8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x00EC | offset to field `included_filenames` (vector) + +vector (reflection.SchemaFile.included_filenames): + +0x00EC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x00F0 | 44 36 00 00 | UOffset32 | 0x00003644 (13892) Loc: 0x3734 | offset to string[0] + +0x00F4 | 7C 37 00 00 | UOffset32 | 0x0000377C (14204) Loc: 0x3870 | offset to string[1] + +table (reflection.SchemaFile): + +0x00F8 | 30 C8 FF FF | SOffset32 | 0xFFFFC830 (-14288) Loc: 0x38C8 | offset to vtable + +0x00FC | 38 36 00 00 | UOffset32 | 0x00003638 (13880) Loc: 0x3734 | offset to field `filename` (string) + +0x0100 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0104 | offset to field `included_filenames` (vector) + +vector (reflection.SchemaFile.included_filenames): + +0x0104 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x0108 | 2C 36 00 00 | UOffset32 | 0x0000362C (13868) Loc: 0x3734 | offset to string[0] + +0x010C | 64 37 00 00 | UOffset32 | 0x00003764 (14180) Loc: 0x3870 | offset to string[1] + +padding: + +0x0110 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Service): + +0x0112 | 0E 00 | uint16_t | 0x000E (14) | size of this vtable + +0x0114 | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x0116 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0118 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `calls` (id: 1) + +0x011A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 2) (Vector) + +0x011C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 3) (Vector) + +0x011E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `declaration_file` (id: 4) + +table (reflection.Service): + +0x0120 | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: 0x0112 | offset to vtable + +0x0124 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0144 | offset to field `name` (string) + +0x0128 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0130 | offset to field `calls` (vector) + +0x012C | B8 35 00 00 | UOffset32 | 0x000035B8 (13752) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Service.calls): + +0x0130 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x0134 | 70 01 00 00 | UOffset32 | 0x00000170 (368) Loc: 0x02A4 | offset to table[0] + +0x0138 | E4 00 00 00 | UOffset32 | 0x000000E4 (228) Loc: 0x021C | offset to table[1] + +0x013C | 88 00 00 00 | UOffset32 | 0x00000088 (136) Loc: 0x01C4 | offset to table[2] + +0x0140 | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x0168 | offset to table[3] + +string (reflection.Service.name): + +0x0144 | 1D 00 00 00 | uint32_t | 0x0000001D (29) | length of string + +0x0148 | 4D 79 47 61 6D 65 2E 45 | char[29] | MyGame.E | string literal + +0x0150 | 78 61 6D 70 6C 65 2E 4D | | xample.M + +0x0158 | 6F 6E 73 74 65 72 53 74 | | onsterSt + +0x0160 | 6F 72 61 67 65 | | orage + +0x0165 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0166 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.RPCCall): + +0x0168 | D0 FE FF FF | SOffset32 | 0xFFFFFED0 (-304) Loc: 0x0298 | offset to vtable + +0x016C | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x01AC | offset to field `name` (string) + +0x0170 | 14 0C 00 00 | UOffset32 | 0x00000C14 (3092) Loc: 0x0D84 | offset to field `request` (table) + +0x0174 | 50 2E 00 00 | UOffset32 | 0x00002E50 (11856) Loc: 0x2FC4 | offset to field `response` (table) + +0x0178 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x017C | offset to field `attributes` (vector) + +vector (reflection.RPCCall.attributes): + +0x017C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0180 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0184 | offset to table[0] + +table (reflection.KeyValue): + +0x0184 | BC C8 FF FF | SOffset32 | 0xFFFFC8BC (-14148) Loc: 0x38C8 | offset to vtable + +0x0188 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x019C | offset to field `key` (string) + +0x018C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0190 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0190 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0194 | 62 69 64 69 | char[4] | bidi | string literal + +0x0198 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0199 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x019C | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x01A0 | 73 74 72 65 61 6D 69 6E | char[9] | streamin | string literal + +0x01A8 | 67 | | g + +0x01A9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x01AA | 00 00 | uint8_t[2] | .. | padding + +string (reflection.RPCCall.name): + +0x01AC | 12 00 00 00 | uint32_t | 0x00000012 (18) | length of string + +0x01B0 | 47 65 74 4D 69 6E 4D 61 | char[18] | GetMinMa | string literal + +0x01B8 | 78 48 69 74 50 6F 69 6E | | xHitPoin + +0x01C0 | 74 73 | | ts + +0x01C2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.RPCCall): + +0x01C4 | 2C FF FF FF | SOffset32 | 0xFFFFFF2C (-212) Loc: 0x0298 | offset to vtable + +0x01C8 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x0208 | offset to field `name` (string) + +0x01CC | B8 0B 00 00 | UOffset32 | 0x00000BB8 (3000) Loc: 0x0D84 | offset to field `request` (table) + +0x01D0 | F4 2D 00 00 | UOffset32 | 0x00002DF4 (11764) Loc: 0x2FC4 | offset to field `response` (table) + +0x01D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x01D8 | offset to field `attributes` (vector) + +vector (reflection.RPCCall.attributes): + +0x01D8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x01DC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x01E0 | offset to table[0] + +table (reflection.KeyValue): + +0x01E0 | 18 C9 FF FF | SOffset32 | 0xFFFFC918 (-14056) Loc: 0x38C8 | offset to vtable + +0x01E4 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x01F8 | offset to field `key` (string) + +0x01E8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x01EC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x01EC | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of string + +0x01F0 | 63 6C 69 65 6E 74 | char[6] | client | string literal + +0x01F6 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x01F8 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x01FC | 73 74 72 65 61 6D 69 6E | char[9] | streamin | string literal + +0x0204 | 67 | | g + +0x0205 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0206 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.RPCCall.name): + +0x0208 | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of string + +0x020C | 47 65 74 4D 61 78 48 69 | char[14] | GetMaxHi | string literal + +0x0214 | 74 50 6F 69 6E 74 | | tPoint + +0x021A | 00 | char | 0x00 (0) | string terminator + +table (reflection.RPCCall): + +0x021C | 84 FF FF FF | SOffset32 | 0xFFFFFF84 (-124) Loc: 0x0298 | offset to vtable + +0x0220 | 68 00 00 00 | UOffset32 | 0x00000068 (104) Loc: 0x0288 | offset to field `name` (string) + +0x0224 | A0 2D 00 00 | UOffset32 | 0x00002DA0 (11680) Loc: 0x2FC4 | offset to field `request` (table) + +0x0228 | 5C 0B 00 00 | UOffset32 | 0x00000B5C (2908) Loc: 0x0D84 | offset to field `response` (table) + +0x022C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0230 | offset to field `attributes` (vector) + +vector (reflection.RPCCall.attributes): + +0x0230 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x0234 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: 0x0264 | offset to table[0] + +0x0238 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x023C | offset to table[1] + +table (reflection.KeyValue): + +0x023C | 74 C9 FF FF | SOffset32 | 0xFFFFC974 (-13964) Loc: 0x38C8 | offset to vtable + +0x0240 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0254 | offset to field `key` (string) + +0x0244 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0248 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0248 | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of string + +0x024C | 73 65 72 76 65 72 | char[6] | server | string literal + +0x0252 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x0254 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x0258 | 73 74 72 65 61 6D 69 6E | char[9] | streamin | string literal + +0x0260 | 67 | | g + +0x0261 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0262 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.KeyValue): + +0x0264 | 9C C9 FF FF | SOffset32 | 0xFFFFC99C (-13924) Loc: 0x38C8 | offset to vtable + +0x0268 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0278 | offset to field `key` (string) + +0x026C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0270 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0270 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x0274 | 30 | char[1] | 0 | string literal + +0x0275 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0276 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x0278 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | length of string + +0x027C | 69 64 65 6D 70 6F 74 65 | char[10] | idempote | string literal + +0x0284 | 6E 74 | | nt + +0x0286 | 00 | char | 0x00 (0) | string terminator + +string (reflection.RPCCall.name): + +0x0288 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x028C | 52 65 74 72 69 65 76 65 | char[8] | Retrieve | string literal + +0x0294 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0295 | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.RPCCall): + +0x0298 | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x029A | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x029C | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x029E | 08 00 | VOffset16 | 0x0008 (8) | offset to field `request` (id: 1) + +0x02A0 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `response` (id: 2) + +0x02A2 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 3) + +table (reflection.RPCCall): + +0x02A4 | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x0298 | offset to vtable + +0x02A8 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x02E8 | offset to field `name` (string) + +0x02AC | D8 0A 00 00 | UOffset32 | 0x00000AD8 (2776) Loc: 0x0D84 | offset to field `request` (table) + +0x02B0 | 14 2D 00 00 | UOffset32 | 0x00002D14 (11540) Loc: 0x2FC4 | offset to field `response` (table) + +0x02B4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x02B8 | offset to field `attributes` (vector) + +vector (reflection.RPCCall.attributes): + +0x02B8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x02BC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x02C0 | offset to table[0] + +table (reflection.KeyValue): + +0x02C0 | F8 C9 FF FF | SOffset32 | 0xFFFFC9F8 (-13832) Loc: 0x38C8 | offset to vtable + +0x02C4 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x02D8 | offset to field `key` (string) + +0x02C8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x02CC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x02CC | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x02D0 | 6E 6F 6E 65 | char[4] | none | string literal + +0x02D4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x02D5 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x02D8 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x02DC | 73 74 72 65 61 6D 69 6E | char[9] | streamin | string literal + +0x02E4 | 67 | | g + +0x02E5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x02E6 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.RPCCall.name): + +0x02E8 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x02EC | 53 74 6F 72 65 | char[5] | Store | string literal + +0x02F1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x02F2 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Enum): + +0x02F4 | D2 FD FF FF | SOffset32 | 0xFFFFFDD2 (-558) Loc: 0x0522 | offset to vtable + +0x02F8 | 00 00 00 | uint8_t[3] | ... | padding + +0x02FB | 01 | uint8_t | 0x01 (1) | table field `is_union` (Bool) + +0x02FC | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x0334 | offset to field `name` (string) + +0x0300 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0320 | offset to field `values` (vector) + +0x0304 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x030C | offset to field `underlying_type` (table) + +0x0308 | DC 33 00 00 | UOffset32 | 0x000033DC (13276) Loc: 0x36E4 | offset to field `declaration_file` (string) + +table (reflection.Type): + +0x030C | 60 CD FF FF | SOffset32 | 0xFFFFCD60 (-12960) Loc: 0x35AC | offset to vtable + +0x0310 | 00 00 00 | uint8_t[3] | ... | padding + +0x0313 | 01 | uint8_t | 0x01 (1) | table field `base_type` (Byte) + +0x0314 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x0318 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x031C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x0320 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x0324 | C8 00 00 00 | UOffset32 | 0x000000C8 (200) Loc: 0x03EC | offset to table[0] + +0x0328 | 94 00 00 00 | UOffset32 | 0x00000094 (148) Loc: 0x03BC | offset to table[1] + +0x032C | 60 00 00 00 | UOffset32 | 0x00000060 (96) Loc: 0x038C | offset to table[2] + +0x0330 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x035C | offset to table[3] + +string (reflection.Enum.name): + +0x0334 | 22 00 00 00 | uint32_t | 0x00000022 (34) | length of string + +0x0338 | 4D 79 47 61 6D 65 2E 45 | char[34] | MyGame.E | string literal + +0x0340 | 78 61 6D 70 6C 65 2E 41 | | xample.A + +0x0348 | 6E 79 41 6D 62 69 67 75 | | nyAmbigu + +0x0350 | 6F 75 73 41 6C 69 61 73 | | ousAlias + +0x0358 | 65 73 | | es + +0x035A | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x035C | 0C FB FF FF | SOffset32 | 0xFFFFFB0C (-1268) Loc: 0x0850 | offset to vtable + +0x0360 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x0384 | offset to field `name` (string) + +0x0364 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0374 | offset to field `union_type` (table) + +0x0368 | 03 00 00 00 00 00 00 00 | int64_t | 0x0000000000000003 (3) | table field `value` (Long) + +0x0370 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x0374 | 5C CB FF FF | SOffset32 | 0xFFFFCB5C (-13476) Loc: 0x3818 | offset to vtable + +0x0378 | 00 00 00 | uint8_t[3] | ... | padding + +0x037B | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x037C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x0380 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0384 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0388 | 4D 33 | char[2] | M3 | string literal + +0x038A | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x038C | 3C FB FF FF | SOffset32 | 0xFFFFFB3C (-1220) Loc: 0x0850 | offset to vtable + +0x0390 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x03B4 | offset to field `name` (string) + +0x0394 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x03A4 | offset to field `union_type` (table) + +0x0398 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `value` (Long) + +0x03A0 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x03A4 | 8C CB FF FF | SOffset32 | 0xFFFFCB8C (-13428) Loc: 0x3818 | offset to vtable + +0x03A8 | 00 00 00 | uint8_t[3] | ... | padding + +0x03AB | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x03AC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x03B0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x03B4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x03B8 | 4D 32 | char[2] | M2 | string literal + +0x03BA | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x03BC | 6C FB FF FF | SOffset32 | 0xFFFFFB6C (-1172) Loc: 0x0850 | offset to vtable + +0x03C0 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x03E4 | offset to field `name` (string) + +0x03C4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x03D4 | offset to field `union_type` (table) + +0x03C8 | 01 00 00 00 00 00 00 00 | int64_t | 0x0000000000000001 (1) | table field `value` (Long) + +0x03D0 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x03D4 | BC CB FF FF | SOffset32 | 0xFFFFCBBC (-13380) Loc: 0x3818 | offset to vtable + +0x03D8 | 00 00 00 | uint8_t[3] | ... | padding + +0x03DB | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x03DC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x03E0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x03E4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x03E8 | 4D 31 | char[2] | M1 | string literal + +0x03EA | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x03EC | 0C F9 FF FF | SOffset32 | 0xFFFFF90C (-1780) Loc: 0x0AE0 | offset to vtable + +0x03F0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0404 | offset to field `name` (string) + +0x03F4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x03F8 | offset to field `union_type` (table) + +table (reflection.Type): + +0x03F8 | 00 F9 FF FF | SOffset32 | 0xFFFFF900 (-1792) Loc: 0x0AF8 | offset to vtable + +0x03FC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0400 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0404 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0408 | 4E 4F 4E 45 | char[4] | NONE | string literal + +0x040C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x040D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Enum): + +0x0410 | EE FE FF FF | SOffset32 | 0xFFFFFEEE (-274) Loc: 0x0522 | offset to vtable + +0x0414 | 00 00 00 | uint8_t[3] | ... | padding + +0x0417 | 01 | uint8_t | 0x01 (1) | table field `is_union` (Bool) + +0x0418 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x0450 | offset to field `name` (string) + +0x041C | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x043C | offset to field `values` (vector) + +0x0420 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0428 | offset to field `underlying_type` (table) + +0x0424 | C0 32 00 00 | UOffset32 | 0x000032C0 (12992) Loc: 0x36E4 | offset to field `declaration_file` (string) + +table (reflection.Type): + +0x0428 | 7C CE FF FF | SOffset32 | 0xFFFFCE7C (-12676) Loc: 0x35AC | offset to vtable + +0x042C | 00 00 00 | uint8_t[3] | ... | padding + +0x042F | 01 | uint8_t | 0x01 (1) | table field `base_type` (Byte) + +0x0430 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `index` (Int) + +0x0434 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0438 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x043C | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x0440 | C0 00 00 00 | UOffset32 | 0x000000C0 (192) Loc: 0x0500 | offset to table[0] + +0x0444 | 90 00 00 00 | UOffset32 | 0x00000090 (144) Loc: 0x04D4 | offset to table[1] + +0x0448 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: 0x04A4 | offset to table[2] + +0x044C | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x0474 | offset to table[3] + +string (reflection.Enum.name): + +0x0450 | 1F 00 00 00 | uint32_t | 0x0000001F (31) | length of string + +0x0454 | 4D 79 47 61 6D 65 2E 45 | char[31] | MyGame.E | string literal + +0x045C | 78 61 6D 70 6C 65 2E 41 | | xample.A + +0x0464 | 6E 79 55 6E 69 71 75 65 | | nyUnique + +0x046C | 41 6C 69 61 73 65 73 | | Aliases + +0x0473 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x0474 | 24 FC FF FF | SOffset32 | 0xFFFFFC24 (-988) Loc: 0x0850 | offset to vtable + +0x0478 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x049C | offset to field `name` (string) + +0x047C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x048C | offset to field `union_type` (table) + +0x0480 | 03 00 00 00 00 00 00 00 | int64_t | 0x0000000000000003 (3) | table field `value` (Long) + +0x0488 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x048C | 74 CC FF FF | SOffset32 | 0xFFFFCC74 (-13196) Loc: 0x3818 | offset to vtable + +0x0490 | 00 00 00 | uint8_t[3] | ... | padding + +0x0493 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x0494 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | table field `index` (Int) + +0x0498 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x049C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x04A0 | 4D 32 | char[2] | M2 | string literal + +0x04A2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x04A4 | 54 FC FF FF | SOffset32 | 0xFFFFFC54 (-940) Loc: 0x0850 | offset to vtable + +0x04A8 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x04CC | offset to field `name` (string) + +0x04AC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x04BC | offset to field `union_type` (table) + +0x04B0 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `value` (Long) + +0x04B8 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x04BC | A4 CC FF FF | SOffset32 | 0xFFFFCCA4 (-13148) Loc: 0x3818 | offset to vtable + +0x04C0 | 00 00 00 | uint8_t[3] | ... | padding + +0x04C3 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x04C4 | 07 00 00 00 | uint32_t | 0x00000007 (7) | table field `index` (Int) + +0x04C8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x04CC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x04D0 | 54 53 | char[2] | TS | string literal + +0x04D2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x04D4 | 94 FA FF FF | SOffset32 | 0xFFFFFA94 (-1388) Loc: 0x0A40 | offset to vtable + +0x04D8 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x04F8 | offset to field `name` (string) + +0x04DC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x04E8 | offset to field `union_type` (table) + +0x04E0 | 01 00 00 00 00 00 00 00 | int64_t | 0x0000000000000001 (1) | table field `value` (Long) + +table (reflection.Type): + +0x04E8 | D0 CC FF FF | SOffset32 | 0xFFFFCCD0 (-13104) Loc: 0x3818 | offset to vtable + +0x04EC | 00 00 00 | uint8_t[3] | ... | padding + +0x04EF | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x04F0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x04F4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x04F8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x04FC | 4D | char[1] | M | string literal + +0x04FD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x04FE | 00 00 | uint8_t[2] | .. | padding + +table (reflection.EnumVal): + +0x0500 | 20 FA FF FF | SOffset32 | 0xFFFFFA20 (-1504) Loc: 0x0AE0 | offset to vtable + +0x0504 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0518 | offset to field `name` (string) + +0x0508 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x050C | offset to field `union_type` (table) + +table (reflection.Type): + +0x050C | 14 FA FF FF | SOffset32 | 0xFFFFFA14 (-1516) Loc: 0x0AF8 | offset to vtable + +0x0510 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0514 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0518 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x051C | 4E 4F 4E 45 | char[4] | NONE | string literal + +0x0520 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Enum): + +0x0522 | 12 00 | uint16_t | 0x0012 (18) | size of this vtable + +0x0524 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0526 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x0528 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `values` (id: 1) + +0x052A | 07 00 | VOffset16 | 0x0007 (7) | offset to field `is_union` (id: 2) + +0x052C | 10 00 | VOffset16 | 0x0010 (16) | offset to field `underlying_type` (id: 3) + +0x052E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 4) (Vector) + +0x0530 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 5) (Vector) + +0x0532 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `declaration_file` (id: 6) + +table (reflection.Enum): + +0x0534 | 12 00 00 00 | SOffset32 | 0x00000012 (18) Loc: 0x0522 | offset to vtable + +0x0538 | 00 00 00 | uint8_t[3] | ... | padding + +0x053B | 01 | uint8_t | 0x01 (1) | table field `is_union` (Bool) + +0x053C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x0574 | offset to field `name` (string) + +0x0540 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0560 | offset to field `values` (vector) + +0x0544 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x054C | offset to field `underlying_type` (table) + +0x0548 | 9C 31 00 00 | UOffset32 | 0x0000319C (12700) Loc: 0x36E4 | offset to field `declaration_file` (string) + +table (reflection.Type): + +0x054C | A0 CF FF FF | SOffset32 | 0xFFFFCFA0 (-12384) Loc: 0x35AC | offset to vtable + +0x0550 | 00 00 00 | uint8_t[3] | ... | padding + +0x0553 | 01 | uint8_t | 0x01 (1) | table field `base_type` (Byte) + +0x0554 | 00 00 00 00 | uint32_t | 0x00000000 (0) | table field `index` (Int) + +0x0558 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x055C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x0560 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x0564 | D8 00 00 00 | UOffset32 | 0x000000D8 (216) Loc: 0x063C | offset to table[0] + +0x0568 | A4 00 00 00 | UOffset32 | 0x000000A4 (164) Loc: 0x060C | offset to table[1] + +0x056C | 60 00 00 00 | UOffset32 | 0x00000060 (96) Loc: 0x05CC | offset to table[2] + +0x0570 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x058C | offset to table[3] + +string (reflection.Enum.name): + +0x0574 | 12 00 00 00 | uint32_t | 0x00000012 (18) | length of string + +0x0578 | 4D 79 47 61 6D 65 2E 45 | char[18] | MyGame.E | string literal + +0x0580 | 78 61 6D 70 6C 65 2E 41 | | xample.A + +0x0588 | 6E 79 | | ny + +0x058A | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x058C | 4C FB FF FF | SOffset32 | 0xFFFFFB4C (-1204) Loc: 0x0A40 | offset to vtable + +0x0590 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x05B0 | offset to field `name` (string) + +0x0594 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x05A0 | offset to field `union_type` (table) + +0x0598 | 03 00 00 00 00 00 00 00 | int64_t | 0x0000000000000003 (3) | table field `value` (Long) + +table (reflection.Type): + +0x05A0 | 88 CD FF FF | SOffset32 | 0xFFFFCD88 (-12920) Loc: 0x3818 | offset to vtable + +0x05A4 | 00 00 00 | uint8_t[3] | ... | padding + +0x05A7 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x05A8 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | table field `index` (Int) + +0x05AC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x05B0 | 17 00 00 00 | uint32_t | 0x00000017 (23) | length of string + +0x05B4 | 4D 79 47 61 6D 65 5F 45 | char[23] | MyGame_E | string literal + +0x05BC | 78 61 6D 70 6C 65 32 5F | | xample2_ + +0x05C4 | 4D 6F 6E 73 74 65 72 | | Monster + +0x05CB | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x05CC | 8C FB FF FF | SOffset32 | 0xFFFFFB8C (-1140) Loc: 0x0A40 | offset to vtable + +0x05D0 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x05F0 | offset to field `name` (string) + +0x05D4 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x05E0 | offset to field `union_type` (table) + +0x05D8 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `value` (Long) + +table (reflection.Type): + +0x05E0 | C8 CD FF FF | SOffset32 | 0xFFFFCDC8 (-12856) Loc: 0x3818 | offset to vtable + +0x05E4 | 00 00 00 | uint8_t[3] | ... | padding + +0x05E7 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x05E8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | table field `index` (Int) + +0x05EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x05F0 | 17 00 00 00 | uint32_t | 0x00000017 (23) | length of string + +0x05F4 | 54 65 73 74 53 69 6D 70 | char[23] | TestSimp | string literal + +0x05FC | 6C 65 54 61 62 6C 65 57 | | leTableW + +0x0604 | 69 74 68 45 6E 75 6D | | ithEnum + +0x060B | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x060C | CC FB FF FF | SOffset32 | 0xFFFFFBCC (-1076) Loc: 0x0A40 | offset to vtable + +0x0610 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0630 | offset to field `name` (string) + +0x0614 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0620 | offset to field `union_type` (table) + +0x0618 | 01 00 00 00 00 00 00 00 | int64_t | 0x0000000000000001 (1) | table field `value` (Long) + +table (reflection.Type): + +0x0620 | 08 CE FF FF | SOffset32 | 0xFFFFCE08 (-12792) Loc: 0x3818 | offset to vtable + +0x0624 | 00 00 00 | uint8_t[3] | ... | padding + +0x0627 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x0628 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x062C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0630 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0634 | 4D 6F 6E 73 74 65 72 | char[7] | Monster | string literal + +0x063B | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x063C | 5C FB FF FF | SOffset32 | 0xFFFFFB5C (-1188) Loc: 0x0AE0 | offset to vtable + +0x0640 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0654 | offset to field `name` (string) + +0x0644 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0648 | offset to field `union_type` (table) + +table (reflection.Type): + +0x0648 | 50 FB FF FF | SOffset32 | 0xFFFFFB50 (-1200) Loc: 0x0AF8 | offset to vtable + +0x064C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0650 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0654 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0658 | 4E 4F 4E 45 | char[4] | NONE | string literal + +0x065C | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Enum): + +0x065E | 12 00 | uint16_t | 0x0012 (18) | size of this vtable + +0x0660 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0662 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0664 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `values` (id: 1) + +0x0666 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `is_union` (id: 2) (Bool) + +0x0668 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `underlying_type` (id: 3) + +0x066A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 4) + +0x066C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 5) (Vector) + +0x066E | 14 00 | VOffset16 | 0x0014 (20) | offset to field `declaration_file` (id: 6) + +table (reflection.Enum): + +0x0670 | 12 00 00 00 | SOffset32 | 0x00000012 (18) Loc: 0x065E | offset to vtable + +0x0674 | 64 00 00 00 | UOffset32 | 0x00000064 (100) Loc: 0x06D8 | offset to field `name` (string) + +0x0678 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x06C8 | offset to field `values` (vector) + +0x067C | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x06B4 | offset to field `underlying_type` (table) + +0x0680 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0688 | offset to field `attributes` (vector) + +0x0684 | 60 30 00 00 | UOffset32 | 0x00003060 (12384) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Enum.attributes): + +0x0688 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x068C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0690 | offset to table[0] + +table (reflection.KeyValue): + +0x0690 | C8 CD FF FF | SOffset32 | 0xFFFFCDC8 (-12856) Loc: 0x38C8 | offset to vtable + +0x0694 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x06A4 | offset to field `key` (string) + +0x0698 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x069C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x069C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x06A0 | 30 | char[1] | 0 | string literal + +0x06A1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x06A2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x06A4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x06A8 | 62 69 74 5F 66 6C 61 67 | char[9] | bit_flag | string literal + +0x06B0 | 73 | | s + +0x06B1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x06B2 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Type): + +0x06B4 | 08 D1 FF FF | SOffset32 | 0xFFFFD108 (-12024) Loc: 0x35AC | offset to vtable + +0x06B8 | 00 00 00 | uint8_t[3] | ... | padding + +0x06BB | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x06BC | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `index` (Int) + +0x06C0 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x06C4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x06C8 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x06CC | 88 00 00 00 | UOffset32 | 0x00000088 (136) Loc: 0x0754 | offset to table[0] + +0x06D0 | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x0724 | offset to table[1] + +0x06D4 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x06F4 | offset to table[2] + +string (reflection.Enum.name): + +0x06D8 | 17 00 00 00 | uint32_t | 0x00000017 (23) | length of string + +0x06DC | 4D 79 47 61 6D 65 2E 45 | char[23] | MyGame.E | string literal + +0x06E4 | 78 61 6D 70 6C 65 2E 4C | | xample.L + +0x06EC | 6F 6E 67 45 6E 75 6D | | ongEnum + +0x06F3 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x06F4 | A4 FE FF FF | SOffset32 | 0xFFFFFEA4 (-348) Loc: 0x0850 | offset to vtable + +0x06F8 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0718 | offset to field `name` (string) + +0x06FC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x070C | offset to field `union_type` (table) + +0x0700 | 00 00 00 00 00 01 00 00 | int64_t | 0x0000010000000000 (1099511627776) | table field `value` (Long) + +0x0708 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x070C | 14 FC FF FF | SOffset32 | 0xFFFFFC14 (-1004) Loc: 0x0AF8 | offset to vtable + +0x0710 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0714 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0718 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x071C | 4C 6F 6E 67 42 69 67 | char[7] | LongBig | string literal + +0x0723 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x0724 | D4 FE FF FF | SOffset32 | 0xFFFFFED4 (-300) Loc: 0x0850 | offset to vtable + +0x0728 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0748 | offset to field `name` (string) + +0x072C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x073C | offset to field `union_type` (table) + +0x0730 | 04 00 00 00 00 00 00 00 | int64_t | 0x0000000000000004 (4) | table field `value` (Long) + +0x0738 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x073C | 44 FC FF FF | SOffset32 | 0xFFFFFC44 (-956) Loc: 0x0AF8 | offset to vtable + +0x0740 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0744 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0748 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x074C | 4C 6F 6E 67 54 77 6F | char[7] | LongTwo | string literal + +0x0753 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x0754 | 14 FD FF FF | SOffset32 | 0xFFFFFD14 (-748) Loc: 0x0A40 | offset to vtable + +0x0758 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x0774 | offset to field `name` (string) + +0x075C | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0768 | offset to field `union_type` (table) + +0x0760 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `value` (Long) + +table (reflection.Type): + +0x0768 | 70 FC FF FF | SOffset32 | 0xFFFFFC70 (-912) Loc: 0x0AF8 | offset to vtable + +0x076C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0770 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0774 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x0778 | 4C 6F 6E 67 4F 6E 65 | char[7] | LongOne | string literal + +0x077F | 00 | char | 0x00 (0) | string terminator + +table (reflection.Enum): + +0x0780 | 0A FD FF FF | SOffset32 | 0xFFFFFD0A (-758) Loc: 0x0A76 | offset to vtable + +0x0784 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x07BC | offset to field `name` (string) + +0x0788 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x07A8 | offset to field `values` (vector) + +0x078C | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0794 | offset to field `underlying_type` (table) + +0x0790 | 54 2F 00 00 | UOffset32 | 0x00002F54 (12116) Loc: 0x36E4 | offset to field `declaration_file` (string) + +table (reflection.Type): + +0x0794 | E8 D1 FF FF | SOffset32 | 0xFFFFD1E8 (-11800) Loc: 0x35AC | offset to vtable + +0x0798 | 00 00 00 | uint8_t[3] | ... | padding + +0x079B | 03 | uint8_t | 0x03 (3) | table field `base_type` (Byte) + +0x079C | 05 00 00 00 | uint32_t | 0x00000005 (5) | table field `index` (Int) + +0x07A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x07A4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x07A8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x07AC | B0 00 00 00 | UOffset32 | 0x000000B0 (176) Loc: 0x085C | offset to table[0] + +0x07B0 | 7C 00 00 00 | UOffset32 | 0x0000007C (124) Loc: 0x082C | offset to table[1] + +0x07B4 | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x07FC | offset to table[2] + +0x07B8 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x07D4 | offset to table[3] + +string (reflection.Enum.name): + +0x07BC | 13 00 00 00 | uint32_t | 0x00000013 (19) | length of string + +0x07C0 | 4D 79 47 61 6D 65 2E 45 | char[19] | MyGame.E | string literal + +0x07C8 | 78 61 6D 70 6C 65 2E 52 | | xample.R + +0x07D0 | 61 63 65 | | ace + +0x07D3 | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x07D4 | 94 FD FF FF | SOffset32 | 0xFFFFFD94 (-620) Loc: 0x0A40 | offset to vtable + +0x07D8 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x07F4 | offset to field `name` (string) + +0x07DC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x07E8 | offset to field `union_type` (table) + +0x07E0 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `value` (Long) + +table (reflection.Type): + +0x07E8 | F0 FC FF FF | SOffset32 | 0xFFFFFCF0 (-784) Loc: 0x0AF8 | offset to vtable + +0x07EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x07F0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x07F4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x07F8 | 45 6C 66 | char[3] | Elf | string literal + +0x07FB | 00 | char | 0x00 (0) | string terminator + +table (reflection.EnumVal): + +0x07FC | AC FF FF FF | SOffset32 | 0xFFFFFFAC (-84) Loc: 0x0850 | offset to vtable + +0x0800 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0820 | offset to field `name` (string) + +0x0804 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0814 | offset to field `union_type` (table) + +0x0808 | 01 00 00 00 00 00 00 00 | int64_t | 0x0000000000000001 (1) | table field `value` (Long) + +0x0810 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x0814 | 1C FD FF FF | SOffset32 | 0xFFFFFD1C (-740) Loc: 0x0AF8 | offset to vtable + +0x0818 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x081C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0820 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0824 | 44 77 61 72 66 | char[5] | Dwarf | string literal + +0x0829 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x082A | 00 00 | uint8_t[2] | .. | padding + +table (reflection.EnumVal): + +0x082C | 4C FD FF FF | SOffset32 | 0xFFFFFD4C (-692) Loc: 0x0AE0 | offset to vtable + +0x0830 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0844 | offset to field `name` (string) + +0x0834 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0838 | offset to field `union_type` (table) + +table (reflection.Type): + +0x0838 | 40 FD FF FF | SOffset32 | 0xFFFFFD40 (-704) Loc: 0x0AF8 | offset to vtable + +0x083C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0840 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0844 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0848 | 48 75 6D 61 6E | char[5] | Human | string literal + +0x084D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x084E | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.EnumVal): + +0x0850 | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x0852 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0854 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0856 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `value` (id: 1) + +0x0858 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `object` (id: 2) (Obj) + +0x085A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `union_type` (id: 3) + +table (reflection.EnumVal): + +0x085C | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x0850 | offset to vtable + +0x0860 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0880 | offset to field `name` (string) + +0x0864 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0874 | offset to field `union_type` (table) + +0x0868 | FF FF FF FF FF FF FF FF | int64_t | 0xFFFFFFFFFFFFFFFF (-1) | table field `value` (Long) + +0x0870 | 00 00 00 00 | uint8_t[4] | .... | padding + +table (reflection.Type): + +0x0874 | 7C FD FF FF | SOffset32 | 0xFFFFFD7C (-644) Loc: 0x0AF8 | offset to vtable + +0x0878 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x087C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0880 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0884 | 4E 6F 6E 65 | char[4] | None | string literal + +0x0888 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Enum): + +0x088A | 12 00 | uint16_t | 0x0012 (18) | size of this vtable + +0x088C | 1C 00 | uint16_t | 0x001C (28) | size of referring table + +0x088E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0890 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `values` (id: 1) + +0x0892 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `is_union` (id: 2) (Bool) + +0x0894 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `underlying_type` (id: 3) + +0x0896 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 4) + +0x0898 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `documentation` (id: 5) + +0x089A | 18 00 | VOffset16 | 0x0018 (24) | offset to field `declaration_file` (id: 6) + +table (reflection.Enum): + +0x089C | 12 00 00 00 | SOffset32 | 0x00000012 (18) Loc: 0x088A | offset to vtable + +0x08A0 | 9C 00 00 00 | UOffset32 | 0x0000009C (156) Loc: 0x093C | offset to field `name` (string) + +0x08A4 | 88 00 00 00 | UOffset32 | 0x00000088 (136) Loc: 0x092C | offset to field `values` (vector) + +0x08A8 | 70 00 00 00 | UOffset32 | 0x00000070 (112) Loc: 0x0918 | offset to field `underlying_type` (table) + +0x08AC | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x08EC | offset to field `attributes` (vector) + +0x08B0 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x08B8 | offset to field `documentation` (vector) + +0x08B4 | 30 2E 00 00 | UOffset32 | 0x00002E30 (11824) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Enum.documentation): + +0x08B8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x08BC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x08C0 | offset to string[0] + +string (reflection.Enum.documentation): + +0x08C0 | 27 00 00 00 | uint32_t | 0x00000027 (39) | length of string + +0x08C4 | 20 43 6F 6D 70 6F 73 69 | char[39] | Composi | string literal + +0x08CC | 74 65 20 63 6F 6D 70 6F | | te compo + +0x08D4 | 6E 65 6E 74 73 20 6F 66 | | nents of + +0x08DC | 20 4D 6F 6E 73 74 65 72 | | Monster + +0x08E4 | 20 63 6F 6C 6F 72 2E | | color. + +0x08EB | 00 | char | 0x00 (0) | string terminator + +vector (reflection.Enum.attributes): + +0x08EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x08F0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x08F4 | offset to table[0] + +table (reflection.KeyValue): + +0x08F4 | 2C D0 FF FF | SOffset32 | 0xFFFFD02C (-12244) Loc: 0x38C8 | offset to vtable + +0x08F8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0908 | offset to field `key` (string) + +0x08FC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0900 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0900 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x0904 | 30 | char[1] | 0 | string literal + +0x0905 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0906 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x0908 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x090C | 62 69 74 5F 66 6C 61 67 | char[9] | bit_flag | string literal + +0x0914 | 73 | | s + +0x0915 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0916 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Type): + +0x0918 | 6C D3 FF FF | SOffset32 | 0xFFFFD36C (-11412) Loc: 0x35AC | offset to vtable + +0x091C | 00 00 00 | uint8_t[3] | ... | padding + +0x091F | 04 | uint8_t | 0x04 (4) | table field `base_type` (Byte) + +0x0920 | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x0924 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0928 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x092C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0930 | 1C 01 00 00 | UOffset32 | 0x0000011C (284) Loc: 0x0A4C | offset to table[0] + +0x0934 | 8C 00 00 00 | UOffset32 | 0x0000008C (140) Loc: 0x09C0 | offset to table[1] + +0x0938 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0958 | offset to table[2] + +string (reflection.Enum.name): + +0x093C | 14 00 00 00 | uint32_t | 0x00000014 (20) | length of string + +0x0940 | 4D 79 47 61 6D 65 2E 45 | char[20] | MyGame.E | string literal + +0x0948 | 78 61 6D 70 6C 65 2E 43 | | xample.C + +0x0950 | 6F 6C 6F 72 | | olor + +0x0954 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0955 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.EnumVal): + +0x0958 | A6 FF FF FF | SOffset32 | 0xFFFFFFA6 (-90) Loc: 0x09B2 | offset to vtable + +0x095C | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: 0x09A8 | offset to field `name` (string) + +0x0960 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x099C | offset to field `union_type` (table) + +0x0964 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0970 | offset to field `documentation` (vector) + +0x0968 | 08 00 00 00 00 00 00 00 | int64_t | 0x0000000000000008 (8) | table field `value` (Long) + +vector (reflection.EnumVal.documentation): + +0x0970 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0974 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0978 | offset to string[0] + +string (reflection.EnumVal.documentation): + +0x0978 | 1C 00 00 00 | uint32_t | 0x0000001C (28) | length of string + +0x097C | 20 5C 62 72 69 65 66 20 | char[28] | \brief | string literal + +0x0984 | 63 6F 6C 6F 72 20 42 6C | | color Bl + +0x098C | 75 65 20 28 31 75 20 3C | | ue (1u < + +0x0994 | 3C 20 33 29 | | < 3) + +0x0998 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0999 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x099C | A4 FE FF FF | SOffset32 | 0xFFFFFEA4 (-348) Loc: 0x0AF8 | offset to vtable + +0x09A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x09A4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x09A8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x09AC | 42 6C 75 65 | char[4] | Blue | string literal + +0x09B0 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.EnumVal): + +0x09B2 | 0E 00 | uint16_t | 0x000E (14) | size of this vtable + +0x09B4 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x09B6 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x09B8 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `value` (id: 1) + +0x09BA | 00 00 | VOffset16 | 0x0000 (0) | offset to field `object` (id: 2) (Obj) + +0x09BC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `union_type` (id: 3) + +0x09BE | 0C 00 | VOffset16 | 0x000C (12) | offset to field `documentation` (id: 4) + +table (reflection.EnumVal): + +0x09C0 | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: 0x09B2 | offset to vtable + +0x09C4 | 70 00 00 00 | UOffset32 | 0x00000070 (112) Loc: 0x0A34 | offset to field `name` (string) + +0x09C8 | 60 00 00 00 | UOffset32 | 0x00000060 (96) Loc: 0x0A28 | offset to field `union_type` (table) + +0x09CC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x09D8 | offset to field `documentation` (vector) + +0x09D0 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `value` (Long) + +vector (reflection.EnumVal.documentation): + +0x09D8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x09DC | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x0A10 | offset to string[0] + +0x09E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x09E4 | offset to string[1] + +string (reflection.EnumVal.documentation): + +0x09E4 | 27 00 00 00 | uint32_t | 0x00000027 (39) | length of string + +0x09E8 | 20 47 72 65 65 6E 20 69 | char[39] | Green i | string literal + +0x09F0 | 73 20 62 69 74 5F 66 6C | | s bit_fl + +0x09F8 | 61 67 20 77 69 74 68 20 | | ag with + +0x0A00 | 76 61 6C 75 65 20 28 31 | | value (1 + +0x0A08 | 75 20 3C 3C 20 31 29 | | u << 1) + +0x0A0F | 00 | char | 0x00 (0) | string terminator + +string (reflection.EnumVal.documentation): + +0x0A10 | 13 00 00 00 | uint32_t | 0x00000013 (19) | length of string + +0x0A14 | 20 5C 62 72 69 65 66 20 | char[19] | \brief | string literal + +0x0A1C | 63 6F 6C 6F 72 20 47 72 | | color Gr + +0x0A24 | 65 65 6E | | een + +0x0A27 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x0A28 | 30 FF FF FF | SOffset32 | 0xFFFFFF30 (-208) Loc: 0x0AF8 | offset to vtable + +0x0A2C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0A30 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0A34 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x0A38 | 47 72 65 65 6E | char[5] | Green | string literal + +0x0A3D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0A3E | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.EnumVal): + +0x0A40 | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x0A42 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x0A44 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0A46 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `value` (id: 1) + +0x0A48 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `object` (id: 2) (Obj) + +0x0A4A | 08 00 | VOffset16 | 0x0008 (8) | offset to field `union_type` (id: 3) + +table (reflection.EnumVal): + +0x0A4C | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x0A40 | offset to vtable + +0x0A50 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x0A6C | offset to field `name` (string) + +0x0A54 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0A60 | offset to field `union_type` (table) + +0x0A58 | 01 00 00 00 00 00 00 00 | int64_t | 0x0000000000000001 (1) | table field `value` (Long) + +table (reflection.Type): + +0x0A60 | 68 FF FF FF | SOffset32 | 0xFFFFFF68 (-152) Loc: 0x0AF8 | offset to vtable + +0x0A64 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0A68 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0A6C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0A70 | 52 65 64 | char[3] | Red | string literal + +0x0A73 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0A74 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Enum): + +0x0A76 | 12 00 | uint16_t | 0x0012 (18) | size of this vtable + +0x0A78 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x0A7A | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0A7C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `values` (id: 1) + +0x0A7E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `is_union` (id: 2) (Bool) + +0x0A80 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `underlying_type` (id: 3) + +0x0A82 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 4) (Vector) + +0x0A84 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 5) (Vector) + +0x0A86 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `declaration_file` (id: 6) + +table (reflection.Enum): + +0x0A88 | 12 00 00 00 | SOffset32 | 0x00000012 (18) Loc: 0x0A76 | offset to vtable + +0x0A8C | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x0AB8 | offset to field `name` (string) + +0x0A90 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x0AB0 | offset to field `values` (vector) + +0x0A94 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0A9C | offset to field `underlying_type` (table) + +0x0A98 | D8 2D 00 00 | UOffset32 | 0x00002DD8 (11736) Loc: 0x3870 | offset to field `declaration_file` (string) + +table (reflection.Type): + +0x0A9C | F0 D4 FF FF | SOffset32 | 0xFFFFD4F0 (-11024) Loc: 0x35AC | offset to vtable + +0x0AA0 | 00 00 00 | uint8_t[3] | ... | padding + +0x0AA3 | 09 | uint8_t | 0x09 (9) | table field `base_type` (Byte) + +0x0AA4 | 06 00 00 00 | uint32_t | 0x00000006 (6) | table field `index` (Int) + +0x0AA8 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x0AAC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +vector (reflection.Enum.values): + +0x0AB0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0AB4 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x0AEC | offset to table[0] + +string (reflection.Enum.name): + +0x0AB8 | 21 00 00 00 | uint32_t | 0x00000021 (33) | length of string + +0x0ABC | 4D 79 47 61 6D 65 2E 4F | char[33] | MyGame.O | string literal + +0x0AC4 | 74 68 65 72 4E 61 6D 65 | | therName + +0x0ACC | 53 70 61 63 65 2E 46 72 | | Space.Fr + +0x0AD4 | 6F 6D 49 6E 63 6C 75 64 | | omInclud + +0x0ADC | 65 | | e + +0x0ADD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0ADE | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.EnumVal): + +0x0AE0 | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x0AE2 | 0C 00 | uint16_t | 0x000C (12) | size of referring table + +0x0AE4 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0AE6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `value` (id: 1) (Long) + +0x0AE8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `object` (id: 2) (Obj) + +0x0AEA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `union_type` (id: 3) + +table (reflection.EnumVal): + +0x0AEC | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x0AE0 | offset to vtable + +0x0AF0 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x0B14 | offset to field `name` (string) + +0x0AF4 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0B08 | offset to field `union_type` (table) + +vtable (reflection.Type): + +0x0AF8 | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x0AFA | 0C 00 | uint16_t | 0x000C (12) | size of referring table + +0x0AFC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `base_type` (id: 0) (Byte) + +0x0AFE | 00 00 | VOffset16 | 0x0000 (0) | offset to field `element` (id: 1) (Byte) + +0x0B00 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `index` (id: 2) (Int) + +0x0B02 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x0B04 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `base_size` (id: 4) + +0x0B06 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x0B08 | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x0AF8 | offset to vtable + +0x0B0C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0B10 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.EnumVal.name): + +0x0B14 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | length of string + +0x0B18 | 49 6E 63 6C 75 64 65 56 | char[10] | IncludeV | string literal + +0x0B20 | 61 6C | | al + +0x0B22 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Object): + +0x0B24 | 8C D3 FF FF | SOffset32 | 0xFFFFD38C (-11380) Loc: 0x3798 | offset to vtable + +0x0B28 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x0B6C | offset to field `name` (string) + +0x0B2C | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0B38 | offset to field `fields` (vector) + +0x0B30 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x0B34 | B0 2B 00 00 | UOffset32 | 0x00002BB0 (11184) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x0B38 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of vector (# items) + +0x0B3C | CC 00 00 00 | UOffset32 | 0x000000CC (204) Loc: 0x0C08 | offset to table[0] + +0x0B40 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x0BE0 | offset to table[1] + +0x0B44 | A8 01 00 00 | UOffset32 | 0x000001A8 (424) Loc: 0x0CEC | offset to table[2] + +0x0B48 | 58 01 00 00 | UOffset32 | 0x00000158 (344) Loc: 0x0CA0 | offset to table[3] + +0x0B4C | 08 01 00 00 | UOffset32 | 0x00000108 (264) Loc: 0x0C54 | offset to table[4] + +0x0B50 | F8 01 00 00 | UOffset32 | 0x000001F8 (504) Loc: 0x0D48 | offset to table[5] + +0x0B54 | 70 01 00 00 | UOffset32 | 0x00000170 (368) Loc: 0x0CC4 | offset to table[6] + +0x0B58 | 24 01 00 00 | UOffset32 | 0x00000124 (292) Loc: 0x0C7C | offset to table[7] + +0x0B5C | D0 00 00 00 | UOffset32 | 0x000000D0 (208) Loc: 0x0C2C | offset to table[8] + +0x0B60 | B4 01 00 00 | UOffset32 | 0x000001B4 (436) Loc: 0x0D14 | offset to table[9] + +0x0B64 | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x0BB8 | offset to table[10] + +0x0B68 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x0B8C | offset to table[11] + +string (reflection.Object.name): + +0x0B6C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of string + +0x0B70 | 4D 79 47 61 6D 65 2E 45 | char[26] | MyGame.E | string literal + +0x0B78 | 78 61 6D 70 6C 65 2E 54 | | xample.T + +0x0B80 | 79 70 65 41 6C 69 61 73 | | ypeAlias + +0x0B88 | 65 73 | | es + +0x0B8A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0B8C | DC D9 FF FF | SOffset32 | 0xFFFFD9DC (-9764) Loc: 0x31B0 | offset to vtable + +0x0B90 | 00 00 00 | uint8_t[3] | ... | padding + +0x0B93 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x0B94 | 0B 00 | uint16_t | 0x000B (11) | table field `id` (UShort) + +0x0B96 | 1A 00 | uint16_t | 0x001A (26) | table field `offset` (UShort) + +0x0B98 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0BAC | offset to field `name` (string) + +0x0B9C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0BA0 | offset to field `type` (table) + +table (reflection.Type): + +0x0BA0 | 60 DF FF FF | SOffset32 | 0xFFFFDF60 (-8352) Loc: 0x2C40 | offset to vtable + +0x0BA4 | 00 00 | uint8_t[2] | .. | padding + +0x0BA6 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x0BA7 | 0C | uint8_t | 0x0C (12) | table field `element` (Byte) + +0x0BA8 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0BAC | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0BB0 | 76 66 36 34 | char[4] | vf64 | string literal + +0x0BB4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0BB5 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x0BB8 | 08 DA FF FF | SOffset32 | 0xFFFFDA08 (-9720) Loc: 0x31B0 | offset to vtable + +0x0BBC | 00 00 00 | uint8_t[3] | ... | padding + +0x0BBF | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x0BC0 | 0A 00 | uint16_t | 0x000A (10) | table field `id` (UShort) + +0x0BC2 | 18 00 | uint16_t | 0x0018 (24) | table field `offset` (UShort) + +0x0BC4 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0BD8 | offset to field `name` (string) + +0x0BC8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0BCC | offset to field `type` (table) + +table (reflection.Type): + +0x0BCC | 8C DF FF FF | SOffset32 | 0xFFFFDF8C (-8308) Loc: 0x2C40 | offset to vtable + +0x0BD0 | 00 00 | uint8_t[2] | .. | padding + +0x0BD2 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x0BD3 | 03 | uint8_t | 0x03 (3) | table field `element` (Byte) + +0x0BD4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0BD8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0BDC | 76 38 | char[2] | v8 | string literal + +0x0BDE | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0BE0 | 64 D7 FF FF | SOffset32 | 0xFFFFD764 (-10396) Loc: 0x347C | offset to vtable + +0x0BE4 | 09 00 | uint16_t | 0x0009 (9) | table field `id` (UShort) + +0x0BE6 | 16 00 | uint16_t | 0x0016 (22) | table field `offset` (UShort) + +0x0BE8 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0C00 | offset to field `name` (string) + +0x0BEC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0BF0 | offset to field `type` (table) + +table (reflection.Type): + +0x0BF0 | 7C D5 FF FF | SOffset32 | 0xFFFFD57C (-10884) Loc: 0x3674 | offset to vtable + +0x0BF4 | 00 00 00 | uint8_t[3] | ... | padding + +0x0BF7 | 0C | uint8_t | 0x0C (12) | table field `base_type` (Byte) + +0x0BF8 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x0BFC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0C00 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0C04 | 66 36 34 | char[3] | f64 | string literal + +0x0C07 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0C08 | 8C D7 FF FF | SOffset32 | 0xFFFFD78C (-10356) Loc: 0x347C | offset to vtable + +0x0C0C | 08 00 | uint16_t | 0x0008 (8) | table field `id` (UShort) + +0x0C0E | 14 00 | uint16_t | 0x0014 (20) | table field `offset` (UShort) + +0x0C10 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0C24 | offset to field `name` (string) + +0x0C14 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0C18 | offset to field `type` (table) + +table (reflection.Type): + +0x0C18 | 3C D3 FF FF | SOffset32 | 0xFFFFD33C (-11460) Loc: 0x38DC | offset to vtable + +0x0C1C | 00 00 00 | uint8_t[3] | ... | padding + +0x0C1F | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x0C20 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0C24 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0C28 | 66 33 32 | char[3] | f32 | string literal + +0x0C2B | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0C2C | B0 D7 FF FF | SOffset32 | 0xFFFFD7B0 (-10320) Loc: 0x347C | offset to vtable + +0x0C30 | 07 00 | uint16_t | 0x0007 (7) | table field `id` (UShort) + +0x0C32 | 12 00 | uint16_t | 0x0012 (18) | table field `offset` (UShort) + +0x0C34 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0C4C | offset to field `name` (string) + +0x0C38 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0C3C | offset to field `type` (table) + +table (reflection.Type): + +0x0C3C | C8 D5 FF FF | SOffset32 | 0xFFFFD5C8 (-10808) Loc: 0x3674 | offset to vtable + +0x0C40 | 00 00 00 | uint8_t[3] | ... | padding + +0x0C43 | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x0C44 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x0C48 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0C4C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0C50 | 75 36 34 | char[3] | u64 | string literal + +0x0C53 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0C54 | D8 D7 FF FF | SOffset32 | 0xFFFFD7D8 (-10280) Loc: 0x347C | offset to vtable + +0x0C58 | 06 00 | uint16_t | 0x0006 (6) | table field `id` (UShort) + +0x0C5A | 10 00 | uint16_t | 0x0010 (16) | table field `offset` (UShort) + +0x0C5C | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0C74 | offset to field `name` (string) + +0x0C60 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0C64 | offset to field `type` (table) + +table (reflection.Type): + +0x0C64 | F0 D5 FF FF | SOffset32 | 0xFFFFD5F0 (-10768) Loc: 0x3674 | offset to vtable + +0x0C68 | 00 00 00 | uint8_t[3] | ... | padding + +0x0C6B | 09 | uint8_t | 0x09 (9) | table field `base_type` (Byte) + +0x0C6C | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x0C70 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0C74 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0C78 | 69 36 34 | char[3] | i64 | string literal + +0x0C7B | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0C7C | 00 D8 FF FF | SOffset32 | 0xFFFFD800 (-10240) Loc: 0x347C | offset to vtable + +0x0C80 | 05 00 | uint16_t | 0x0005 (5) | table field `id` (UShort) + +0x0C82 | 0E 00 | uint16_t | 0x000E (14) | table field `offset` (UShort) + +0x0C84 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0C98 | offset to field `name` (string) + +0x0C88 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0C8C | offset to field `type` (table) + +table (reflection.Type): + +0x0C8C | B0 D3 FF FF | SOffset32 | 0xFFFFD3B0 (-11344) Loc: 0x38DC | offset to vtable + +0x0C90 | 00 00 00 | uint8_t[3] | ... | padding + +0x0C93 | 08 | uint8_t | 0x08 (8) | table field `base_type` (Byte) + +0x0C94 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0C98 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0C9C | 75 33 32 | char[3] | u32 | string literal + +0x0C9F | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0CA0 | 24 D8 FF FF | SOffset32 | 0xFFFFD824 (-10204) Loc: 0x347C | offset to vtable + +0x0CA4 | 04 00 | uint16_t | 0x0004 (4) | table field `id` (UShort) + +0x0CA6 | 0C 00 | uint16_t | 0x000C (12) | table field `offset` (UShort) + +0x0CA8 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x0CBC | offset to field `name` (string) + +0x0CAC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0CB0 | offset to field `type` (table) + +table (reflection.Type): + +0x0CB0 | D4 D3 FF FF | SOffset32 | 0xFFFFD3D4 (-11308) Loc: 0x38DC | offset to vtable + +0x0CB4 | 00 00 00 | uint8_t[3] | ... | padding + +0x0CB7 | 07 | uint8_t | 0x07 (7) | table field `base_type` (Byte) + +0x0CB8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0CBC | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0CC0 | 69 33 32 | char[3] | i32 | string literal + +0x0CC3 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0CC4 | 48 D8 FF FF | SOffset32 | 0xFFFFD848 (-10168) Loc: 0x347C | offset to vtable + +0x0CC8 | 03 00 | uint16_t | 0x0003 (3) | table field `id` (UShort) + +0x0CCA | 0A 00 | uint16_t | 0x000A (10) | table field `offset` (UShort) + +0x0CCC | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0CE4 | offset to field `name` (string) + +0x0CD0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0CD4 | offset to field `type` (table) + +table (reflection.Type): + +0x0CD4 | 60 D6 FF FF | SOffset32 | 0xFFFFD660 (-10656) Loc: 0x3674 | offset to vtable + +0x0CD8 | 00 00 00 | uint8_t[3] | ... | padding + +0x0CDB | 06 | uint8_t | 0x06 (6) | table field `base_type` (Byte) + +0x0CDC | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `base_size` (UInt) + +0x0CE0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0CE4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0CE8 | 75 31 36 | char[3] | u16 | string literal + +0x0CEB | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0CEC | 70 D8 FF FF | SOffset32 | 0xFFFFD870 (-10128) Loc: 0x347C | offset to vtable + +0x0CF0 | 02 00 | uint16_t | 0x0002 (2) | table field `id` (UShort) + +0x0CF2 | 08 00 | uint16_t | 0x0008 (8) | table field `offset` (UShort) + +0x0CF4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0D0C | offset to field `name` (string) + +0x0CF8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0CFC | offset to field `type` (table) + +table (reflection.Type): + +0x0CFC | 88 D6 FF FF | SOffset32 | 0xFFFFD688 (-10616) Loc: 0x3674 | offset to vtable + +0x0D00 | 00 00 00 | uint8_t[3] | ... | padding + +0x0D03 | 05 | uint8_t | 0x05 (5) | table field `base_type` (Byte) + +0x0D04 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `base_size` (UInt) + +0x0D08 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0D0C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0D10 | 69 31 36 | char[3] | i16 | string literal + +0x0D13 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0D14 | 98 D8 FF FF | SOffset32 | 0xFFFFD898 (-10088) Loc: 0x347C | offset to vtable + +0x0D18 | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x0D1A | 06 00 | uint16_t | 0x0006 (6) | table field `offset` (UShort) + +0x0D1C | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0D34 | offset to field `name` (string) + +0x0D20 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0D24 | offset to field `type` (table) + +table (reflection.Type): + +0x0D24 | B0 D6 FF FF | SOffset32 | 0xFFFFD6B0 (-10576) Loc: 0x3674 | offset to vtable + +0x0D28 | 00 00 00 | uint8_t[3] | ... | padding + +0x0D2B | 04 | uint8_t | 0x04 (4) | table field `base_type` (Byte) + +0x0D2C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0D30 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0D34 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0D38 | 75 38 | char[2] | u8 | string literal + +0x0D3A | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Field): + +0x0D3C | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x0D3E | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x0D40 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x0D42 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x0D44 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x0D46 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +table (reflection.Field): + +0x0D48 | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x0D3C | offset to vtable + +0x0D4C | 00 00 | uint8_t[2] | .. | padding + +0x0D4E | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x0D50 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x0D68 | offset to field `name` (string) + +0x0D54 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0D58 | offset to field `type` (table) + +table (reflection.Type): + +0x0D58 | E4 D6 FF FF | SOffset32 | 0xFFFFD6E4 (-10524) Loc: 0x3674 | offset to vtable + +0x0D5C | 00 00 00 | uint8_t[3] | ... | padding + +0x0D5F | 03 | uint8_t | 0x03 (3) | table field `base_type` (Byte) + +0x0D60 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x0D64 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0D68 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0D6C | 69 38 | char[2] | i8 | string literal + +0x0D6E | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Object): + +0x0D70 | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x0D72 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x0D74 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x0D76 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `fields` (id: 1) + +0x0D78 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `is_struct` (id: 2) (Bool) + +0x0D7A | 0C 00 | VOffset16 | 0x000C (12) | offset to field `minalign` (id: 3) + +0x0D7C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `bytesize` (id: 4) (Int) + +0x0D7E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 5) (Vector) + +0x0D80 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `documentation` (id: 6) + +0x0D82 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `declaration_file` (id: 7) + +table (reflection.Object): + +0x0D84 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x0D70 | offset to vtable + +0x0D88 | 50 01 00 00 | UOffset32 | 0x00000150 (336) Loc: 0x0ED8 | offset to field `name` (string) + +0x0D8C | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x0DDC | offset to field `fields` (vector) + +0x0D90 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x0D94 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x0D9C | offset to field `documentation` (vector) + +0x0D98 | 4C 29 00 00 | UOffset32 | 0x0000294C (10572) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.documentation): + +0x0D9C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0DA0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0DA4 | offset to string[0] + +string (reflection.Object.documentation): + +0x0DA4 | 33 00 00 00 | uint32_t | 0x00000033 (51) | length of string + +0x0DA8 | 20 61 6E 20 65 78 61 6D | char[51] | an exam | string literal + +0x0DB0 | 70 6C 65 20 64 6F 63 75 | | ple docu + +0x0DB8 | 6D 65 6E 74 61 74 69 6F | | mentatio + +0x0DC0 | 6E 20 63 6F 6D 6D 65 6E | | n commen + +0x0DC8 | 74 3A 20 22 6D 6F 6E 73 | | t: "mons + +0x0DD0 | 74 65 72 20 6F 62 6A 65 | | ter obje + +0x0DD8 | 63 74 22 | | ct" + +0x0DDB | 00 | char | 0x00 (0) | string terminator + +vector (reflection.Object.fields): + +0x0DDC | 3E 00 00 00 | uint32_t | 0x0000003E (62) | length of vector (# items) + +0x0DE0 | A8 07 00 00 | UOffset32 | 0x000007A8 (1960) Loc: 0x1588 | offset to table[0] + +0x0DE4 | 04 08 00 00 | UOffset32 | 0x00000804 (2052) Loc: 0x15E8 | offset to table[1] + +0x0DE8 | 64 08 00 00 | UOffset32 | 0x00000864 (2148) Loc: 0x164C | offset to table[2] + +0x0DEC | BC 08 00 00 | UOffset32 | 0x000008BC (2236) Loc: 0x16A8 | offset to table[3] + +0x0DF0 | 98 0C 00 00 | UOffset32 | 0x00000C98 (3224) Loc: 0x1A88 | offset to table[4] + +0x0DF4 | 90 1D 00 00 | UOffset32 | 0x00001D90 (7568) Loc: 0x2B84 | offset to table[5] + +0x0DF8 | FC 00 00 00 | UOffset32 | 0x000000FC (252) Loc: 0x0EF4 | offset to table[6] + +0x0DFC | 90 1A 00 00 | UOffset32 | 0x00001A90 (6800) Loc: 0x288C | offset to table[7] + +0x0E00 | E8 11 00 00 | UOffset32 | 0x000011E8 (4584) Loc: 0x1FE8 | offset to table[8] + +0x0E04 | 80 1E 00 00 | UOffset32 | 0x00001E80 (7808) Loc: 0x2C84 | offset to table[9] + +0x0E08 | B4 1F 00 00 | UOffset32 | 0x00001FB4 (8116) Loc: 0x2DBC | offset to table[10] + +0x0E0C | 68 03 00 00 | UOffset32 | 0x00000368 (872) Loc: 0x1174 | offset to table[11] + +0x0E10 | 94 02 00 00 | UOffset32 | 0x00000294 (660) Loc: 0x10A4 | offset to table[12] + +0x0E14 | F0 1D 00 00 | UOffset32 | 0x00001DF0 (7664) Loc: 0x2C04 | offset to table[13] + +0x0E18 | A8 04 00 00 | UOffset32 | 0x000004A8 (1192) Loc: 0x12C0 | offset to table[14] + +0x0E1C | 30 04 00 00 | UOffset32 | 0x00000430 (1072) Loc: 0x124C | offset to table[15] + +0x0E20 | 0C 20 00 00 | UOffset32 | 0x0000200C (8204) Loc: 0x2E2C | offset to table[16] + +0x0E24 | 24 1F 00 00 | UOffset32 | 0x00001F24 (7972) Loc: 0x2D48 | offset to table[17] + +0x0E28 | C4 03 00 00 | UOffset32 | 0x000003C4 (964) Loc: 0x11EC | offset to table[18] + +0x0E2C | 00 05 00 00 | UOffset32 | 0x00000500 (1280) Loc: 0x132C | offset to table[19] + +0x0E30 | 9C 01 00 00 | UOffset32 | 0x0000019C (412) Loc: 0x0FCC | offset to table[20] + +0x0E34 | 28 01 00 00 | UOffset32 | 0x00000128 (296) Loc: 0x0F5C | offset to table[21] + +0x0E38 | F8 09 00 00 | UOffset32 | 0x000009F8 (2552) Loc: 0x1830 | offset to table[22] + +0x0E3C | 30 10 00 00 | UOffset32 | 0x00001030 (4144) Loc: 0x1E6C | offset to table[23] + +0x0E40 | 64 20 00 00 | UOffset32 | 0x00002064 (8292) Loc: 0x2EA4 | offset to table[24] + +0x0E44 | C8 02 00 00 | UOffset32 | 0x000002C8 (712) Loc: 0x110C | offset to table[25] + +0x0E48 | EC 01 00 00 | UOffset32 | 0x000001EC (492) Loc: 0x1034 | offset to table[26] + +0x0E4C | 6C 05 00 00 | UOffset32 | 0x0000056C (1388) Loc: 0x13B8 | offset to table[27] + +0x0E50 | 74 06 00 00 | UOffset32 | 0x00000674 (1652) Loc: 0x14C4 | offset to table[28] + +0x0E54 | C0 0E 00 00 | UOffset32 | 0x00000EC0 (3776) Loc: 0x1D14 | offset to table[29] + +0x0E58 | 48 1C 00 00 | UOffset32 | 0x00001C48 (7240) Loc: 0x2AA0 | offset to table[30] + +0x0E5C | DC 1B 00 00 | UOffset32 | 0x00001BDC (7132) Loc: 0x2A38 | offset to table[31] + +0x0E60 | 30 11 00 00 | UOffset32 | 0x00001130 (4400) Loc: 0x1F90 | offset to table[32] + +0x0E64 | AC 1C 00 00 | UOffset32 | 0x00001CAC (7340) Loc: 0x2B10 | offset to table[33] + +0x0E68 | DC 13 00 00 | UOffset32 | 0x000013DC (5084) Loc: 0x2244 | offset to table[34] + +0x0E6C | F8 11 00 00 | UOffset32 | 0x000011F8 (4600) Loc: 0x2064 | offset to table[35] + +0x0E70 | 68 1B 00 00 | UOffset32 | 0x00001B68 (7016) Loc: 0x29D8 | offset to table[36] + +0x0E74 | 58 12 00 00 | UOffset32 | 0x00001258 (4696) Loc: 0x20CC | offset to table[37] + +0x0E78 | 88 1A 00 00 | UOffset32 | 0x00001A88 (6792) Loc: 0x2900 | offset to table[38] + +0x0E7C | C4 18 00 00 | UOffset32 | 0x000018C4 (6340) Loc: 0x2740 | offset to table[39] + +0x0E80 | 18 19 00 00 | UOffset32 | 0x00001918 (6424) Loc: 0x2798 | offset to table[40] + +0x0E84 | 68 13 00 00 | UOffset32 | 0x00001368 (4968) Loc: 0x21EC | offset to table[41] + +0x0E88 | F4 12 00 00 | UOffset32 | 0x000012F4 (4852) Loc: 0x217C | offset to table[42] + +0x0E8C | A0 12 00 00 | UOffset32 | 0x000012A0 (4768) Loc: 0x212C | offset to table[43] + +0x0E90 | 2C 18 00 00 | UOffset32 | 0x0000182C (6188) Loc: 0x26BC | offset to table[44] + +0x0E94 | 0C 16 00 00 | UOffset32 | 0x0000160C (5644) Loc: 0x24A0 | offset to table[45] + +0x0E98 | 18 17 00 00 | UOffset32 | 0x00001718 (5912) Loc: 0x25B0 | offset to table[46] + +0x0E9C | 94 14 00 00 | UOffset32 | 0x00001494 (5268) Loc: 0x2330 | offset to table[47] + +0x0EA0 | 98 17 00 00 | UOffset32 | 0x00001798 (6040) Loc: 0x2638 | offset to table[48] + +0x0EA4 | 18 15 00 00 | UOffset32 | 0x00001518 (5400) Loc: 0x23BC | offset to table[49] + +0x0EA8 | 80 16 00 00 | UOffset32 | 0x00001680 (5760) Loc: 0x2528 | offset to table[50] + +0x0EAC | F8 13 00 00 | UOffset32 | 0x000013F8 (5112) Loc: 0x22A4 | offset to table[51] + +0x0EB0 | 44 19 00 00 | UOffset32 | 0x00001944 (6468) Loc: 0x27F4 | offset to table[52] + +0x0EB4 | 70 05 00 00 | UOffset32 | 0x00000570 (1392) Loc: 0x1424 | offset to table[53] + +0x0EB8 | 98 0A 00 00 | UOffset32 | 0x00000A98 (2712) Loc: 0x1950 | offset to table[54] + +0x0EBC | 18 10 00 00 | UOffset32 | 0x00001018 (4120) Loc: 0x1ED4 | offset to table[55] + +0x0EC0 | 68 06 00 00 | UOffset32 | 0x00000668 (1640) Loc: 0x1528 | offset to table[56] + +0x0EC4 | 70 10 00 00 | UOffset32 | 0x00001070 (4208) Loc: 0x1F34 | offset to table[57] + +0x0EC8 | 40 08 00 00 | UOffset32 | 0x00000840 (2112) Loc: 0x1708 | offset to table[58] + +0x0ECC | 38 0F 00 00 | UOffset32 | 0x00000F38 (3896) Loc: 0x1E04 | offset to table[59] + +0x0ED0 | A4 0C 00 00 | UOffset32 | 0x00000CA4 (3236) Loc: 0x1B74 | offset to table[60] + +0x0ED4 | 4C 0D 00 00 | UOffset32 | 0x00000D4C (3404) Loc: 0x1C20 | offset to table[61] + +string (reflection.Object.name): + +0x0ED8 | 16 00 00 00 | uint32_t | 0x00000016 (22) | length of string + +0x0EDC | 4D 79 47 61 6D 65 2E 45 | char[22] | MyGame.E | string literal + +0x0EE4 | 78 61 6D 70 6C 65 2E 4D | | xample.M + +0x0EEC | 6F 6E 73 74 65 72 | | onster + +0x0EF2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0EF4 | 20 ED FF FF | SOffset32 | 0xFFFFED20 (-4832) Loc: 0x21D4 | offset to vtable + +0x0EF8 | 3D 00 | uint16_t | 0x003D (61) | table field `id` (UShort) + +0x0EFA | 7E 00 | uint16_t | 0x007E (126) | table field `offset` (UShort) + +0x0EFC | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x0F44 | offset to field `name` (string) + +0x0F00 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x0F34 | offset to field `type` (table) + +0x0F04 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0F10 | offset to field `attributes` (vector) + +0x0F08 | 00 00 00 00 00 00 F0 7F | double | 0x7FF0000000000000 (inf) | table field `default_real` (Double) + +vector (reflection.Field.attributes): + +0x0F10 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0F14 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0F18 | offset to table[0] + +table (reflection.KeyValue): + +0x0F18 | 50 D6 FF FF | SOffset32 | 0xFFFFD650 (-10672) Loc: 0x38C8 | offset to vtable + +0x0F1C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0F2C | offset to field `key` (string) + +0x0F20 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0F24 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0F24 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0F28 | 36 31 | char[2] | 61 | string literal + +0x0F2A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x0F2C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0F30 | 69 64 | char[2] | id | string literal + +0x0F32 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x0F34 | C0 D8 FF FF | SOffset32 | 0xFFFFD8C0 (-10048) Loc: 0x3674 | offset to vtable + +0x0F38 | 00 00 00 | uint8_t[3] | ... | padding + +0x0F3B | 0C | uint8_t | 0x0C (12) | table field `base_type` (Byte) + +0x0F3C | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x0F40 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0F44 | 12 00 00 00 | uint32_t | 0x00000012 (18) | length of string + +0x0F48 | 64 6F 75 62 6C 65 5F 69 | char[18] | double_i | string literal + +0x0F50 | 6E 66 5F 64 65 66 61 75 | | nf_defau + +0x0F58 | 6C 74 | | lt + +0x0F5A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x0F5C | 88 FD FF FF | SOffset32 | 0xFFFFFD88 (-632) Loc: 0x11D4 | offset to vtable + +0x0F60 | 3C 00 | uint16_t | 0x003C (60) | table field `id` (UShort) + +0x0F62 | 7C 00 | uint16_t | 0x007C (124) | table field `offset` (UShort) + +0x0F64 | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x0FAC | offset to field `name` (string) + +0x0F68 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x0FA0 | offset to field `type` (table) + +0x0F6C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0F7C | offset to field `attributes` (vector) + +0x0F70 | 00 00 00 00 00 00 F0 FF | double | 0xFFF0000000000000 (-inf) | table field `default_real` (Double) + +0x0F78 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (reflection.Field.attributes): + +0x0F7C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0F80 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0F84 | offset to table[0] + +table (reflection.KeyValue): + +0x0F84 | BC D6 FF FF | SOffset32 | 0xFFFFD6BC (-10564) Loc: 0x38C8 | offset to vtable + +0x0F88 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0F98 | offset to field `key` (string) + +0x0F8C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0F90 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0F90 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0F94 | 36 30 | char[2] | 60 | string literal + +0x0F96 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x0F98 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x0F9C | 69 64 | char[2] | id | string literal + +0x0F9E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x0FA0 | C4 D6 FF FF | SOffset32 | 0xFFFFD6C4 (-10556) Loc: 0x38DC | offset to vtable + +0x0FA4 | 00 00 00 | uint8_t[3] | ... | padding + +0x0FA7 | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x0FA8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x0FAC | 19 00 00 00 | uint32_t | 0x00000019 (25) | length of string + +0x0FB0 | 6E 65 67 61 74 69 76 65 | char[25] | negative | string literal + +0x0FB8 | 5F 69 6E 66 69 6E 69 74 | | _infinit + +0x0FC0 | 79 5F 64 65 66 61 75 6C | | y_defaul + +0x0FC8 | 74 | | t + +0x0FC9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0FCA | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x0FCC | F8 ED FF FF | SOffset32 | 0xFFFFEDF8 (-4616) Loc: 0x21D4 | offset to vtable + +0x0FD0 | 3B 00 | uint16_t | 0x003B (59) | table field `id` (UShort) + +0x0FD2 | 7A 00 | uint16_t | 0x007A (122) | table field `offset` (UShort) + +0x0FD4 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x1018 | offset to field `name` (string) + +0x0FD8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x100C | offset to field `type` (table) + +0x0FDC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0FE8 | offset to field `attributes` (vector) + +0x0FE0 | 00 00 00 00 00 00 F0 FF | double | 0xFFF0000000000000 (-inf) | table field `default_real` (Double) + +vector (reflection.Field.attributes): + +0x0FE8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x0FEC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0FF0 | offset to table[0] + +table (reflection.KeyValue): + +0x0FF0 | 28 D7 FF FF | SOffset32 | 0xFFFFD728 (-10456) Loc: 0x38C8 | offset to vtable + +0x0FF4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1004 | offset to field `key` (string) + +0x0FF8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0FFC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x0FFC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1000 | 35 39 | char[2] | 59 | string literal + +0x1002 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1004 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1008 | 69 64 | char[2] | id | string literal + +0x100A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x100C | 30 D7 FF FF | SOffset32 | 0xFFFFD730 (-10448) Loc: 0x38DC | offset to vtable + +0x1010 | 00 00 00 | uint8_t[3] | ... | padding + +0x1013 | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x1014 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1018 | 14 00 00 00 | uint32_t | 0x00000014 (20) | length of string + +0x101C | 6E 65 67 61 74 69 76 65 | char[20] | negative | string literal + +0x1024 | 5F 69 6E 66 5F 64 65 66 | | _inf_def + +0x102C | 61 75 6C 74 | | ault + +0x1030 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1031 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x1034 | 60 FE FF FF | SOffset32 | 0xFFFFFE60 (-416) Loc: 0x11D4 | offset to vtable + +0x1038 | 3A 00 | uint16_t | 0x003A (58) | table field `id` (UShort) + +0x103A | 78 00 | uint16_t | 0x0078 (120) | table field `offset` (UShort) + +0x103C | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x1084 | offset to field `name` (string) + +0x1040 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x1078 | offset to field `type` (table) + +0x1044 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1054 | offset to field `attributes` (vector) + +0x1048 | 00 00 00 00 00 00 F0 7F | double | 0x7FF0000000000000 (inf) | table field `default_real` (Double) + +0x1050 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (reflection.Field.attributes): + +0x1054 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1058 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x105C | offset to table[0] + +table (reflection.KeyValue): + +0x105C | 94 D7 FF FF | SOffset32 | 0xFFFFD794 (-10348) Loc: 0x38C8 | offset to vtable + +0x1060 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1070 | offset to field `key` (string) + +0x1064 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1068 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1068 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x106C | 35 38 | char[2] | 58 | string literal + +0x106E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1070 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1074 | 69 64 | char[2] | id | string literal + +0x1076 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1078 | 9C D7 FF FF | SOffset32 | 0xFFFFD79C (-10340) Loc: 0x38DC | offset to vtable + +0x107C | 00 00 00 | uint8_t[3] | ... | padding + +0x107F | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x1080 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1084 | 19 00 00 00 | uint32_t | 0x00000019 (25) | length of string + +0x1088 | 70 6F 73 69 74 69 76 65 | char[25] | positive | string literal + +0x1090 | 5F 69 6E 66 69 6E 69 74 | | _infinit + +0x1098 | 79 5F 64 65 66 61 75 6C | | y_defaul + +0x10A0 | 74 | | t + +0x10A1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x10A2 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x10A4 | D0 FE FF FF | SOffset32 | 0xFFFFFED0 (-304) Loc: 0x11D4 | offset to vtable + +0x10A8 | 39 00 | uint16_t | 0x0039 (57) | table field `id` (UShort) + +0x10AA | 76 00 | uint16_t | 0x0076 (118) | table field `offset` (UShort) + +0x10AC | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x10F4 | offset to field `name` (string) + +0x10B0 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x10E8 | offset to field `type` (table) + +0x10B4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x10C4 | offset to field `attributes` (vector) + +0x10B8 | 00 00 00 00 00 00 F0 7F | double | 0x7FF0000000000000 (inf) | table field `default_real` (Double) + +0x10C0 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (reflection.Field.attributes): + +0x10C4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x10C8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x10CC | offset to table[0] + +table (reflection.KeyValue): + +0x10CC | 04 D8 FF FF | SOffset32 | 0xFFFFD804 (-10236) Loc: 0x38C8 | offset to vtable + +0x10D0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x10E0 | offset to field `key` (string) + +0x10D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x10D8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x10D8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x10DC | 35 37 | char[2] | 57 | string literal + +0x10DE | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x10E0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x10E4 | 69 64 | char[2] | id | string literal + +0x10E6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x10E8 | 0C D8 FF FF | SOffset32 | 0xFFFFD80C (-10228) Loc: 0x38DC | offset to vtable + +0x10EC | 00 00 00 | uint8_t[3] | ... | padding + +0x10EF | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x10F0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x10F4 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x10F8 | 69 6E 66 69 6E 69 74 79 | char[16] | infinity | string literal + +0x1100 | 5F 64 65 66 61 75 6C 74 | | _default + +0x1108 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1109 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x110C | 38 EF FF FF | SOffset32 | 0xFFFFEF38 (-4296) Loc: 0x21D4 | offset to vtable + +0x1110 | 38 00 | uint16_t | 0x0038 (56) | table field `id` (UShort) + +0x1112 | 74 00 | uint16_t | 0x0074 (116) | table field `offset` (UShort) + +0x1114 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x1158 | offset to field `name` (string) + +0x1118 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x114C | offset to field `type` (table) + +0x111C | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x1128 | offset to field `attributes` (vector) + +0x1120 | 00 00 00 00 00 00 F0 7F | double | 0x7FF0000000000000 (inf) | table field `default_real` (Double) + +vector (reflection.Field.attributes): + +0x1128 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x112C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1130 | offset to table[0] + +table (reflection.KeyValue): + +0x1130 | 68 D8 FF FF | SOffset32 | 0xFFFFD868 (-10136) Loc: 0x38C8 | offset to vtable + +0x1134 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1144 | offset to field `key` (string) + +0x1138 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x113C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x113C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1140 | 35 36 | char[2] | 56 | string literal + +0x1142 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1144 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1148 | 69 64 | char[2] | id | string literal + +0x114A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x114C | 70 D8 FF FF | SOffset32 | 0xFFFFD870 (-10128) Loc: 0x38DC | offset to vtable + +0x1150 | 00 00 00 | uint8_t[3] | ... | padding + +0x1153 | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x1154 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1158 | 14 00 00 00 | uint32_t | 0x00000014 (20) | length of string + +0x115C | 70 6F 73 69 74 69 76 65 | char[20] | positive | string literal + +0x1164 | 5F 69 6E 66 5F 64 65 66 | | _inf_def + +0x116C | 61 75 6C 74 | | ault + +0x1170 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1171 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x1174 | A0 FF FF FF | SOffset32 | 0xFFFFFFA0 (-96) Loc: 0x11D4 | offset to vtable + +0x1178 | 37 00 | uint16_t | 0x0037 (55) | table field `id` (UShort) + +0x117A | 72 00 | uint16_t | 0x0072 (114) | table field `offset` (UShort) + +0x117C | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x11C4 | offset to field `name` (string) + +0x1180 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x11B8 | offset to field `type` (table) + +0x1184 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1194 | offset to field `attributes` (vector) + +0x1188 | 00 00 00 00 00 00 F0 7F | double | 0x7FF0000000000000 (inf) | table field `default_real` (Double) + +0x1190 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (reflection.Field.attributes): + +0x1194 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1198 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x119C | offset to table[0] + +table (reflection.KeyValue): + +0x119C | D4 D8 FF FF | SOffset32 | 0xFFFFD8D4 (-10028) Loc: 0x38C8 | offset to vtable + +0x11A0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x11B0 | offset to field `key` (string) + +0x11A4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x11A8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x11A8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x11AC | 35 35 | char[2] | 55 | string literal + +0x11AE | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x11B0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x11B4 | 69 64 | char[2] | id | string literal + +0x11B6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x11B8 | DC D8 FF FF | SOffset32 | 0xFFFFD8DC (-10020) Loc: 0x38DC | offset to vtable + +0x11BC | 00 00 00 | uint8_t[3] | ... | padding + +0x11BF | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x11C0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x11C4 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x11C8 | 69 6E 66 5F 64 65 66 61 | char[11] | inf_defa | string literal + +0x11D0 | 75 6C 74 | | ult + +0x11D3 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Field): + +0x11D4 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x11D6 | 20 00 | uint16_t | 0x0020 (32) | size of referring table + +0x11D8 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x11DA | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x11DC | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 2) + +0x11DE | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x11E0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x11E2 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `default_real` (id: 5) + +0x11E4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x11E6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x11E8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x11EA | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x11EC | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x11D4 | offset to vtable + +0x11F0 | 36 00 | uint16_t | 0x0036 (54) | table field `id` (UShort) + +0x11F2 | 70 00 | uint16_t | 0x0070 (112) | table field `offset` (UShort) + +0x11F4 | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x123C | offset to field `name` (string) + +0x11F8 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x1230 | offset to field `type` (table) + +0x11FC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x120C | offset to field `attributes` (vector) + +0x1200 | 00 00 00 00 00 00 F8 7F | double | 0x7FF8000000000000 (nan) | table field `default_real` (Double) + +0x1208 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (reflection.Field.attributes): + +0x120C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1210 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1214 | offset to table[0] + +table (reflection.KeyValue): + +0x1214 | 4C D9 FF FF | SOffset32 | 0xFFFFD94C (-9908) Loc: 0x38C8 | offset to vtable + +0x1218 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1228 | offset to field `key` (string) + +0x121C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1220 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1220 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1224 | 35 34 | char[2] | 54 | string literal + +0x1226 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1228 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x122C | 69 64 | char[2] | id | string literal + +0x122E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1230 | 54 D9 FF FF | SOffset32 | 0xFFFFD954 (-9900) Loc: 0x38DC | offset to vtable + +0x1234 | 00 00 00 | uint8_t[3] | ... | padding + +0x1237 | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x1238 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x123C | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x1240 | 6E 61 6E 5F 64 65 66 61 | char[11] | nan_defa | string literal + +0x1248 | 75 6C 74 | | ult + +0x124B | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x124C | 38 E4 FF FF | SOffset32 | 0xFFFFE438 (-7112) Loc: 0x2E14 | offset to vtable + +0x1250 | 35 00 | uint16_t | 0x0035 (53) | table field `id` (UShort) + +0x1252 | 6E 00 | uint16_t | 0x006E (110) | table field `offset` (UShort) + +0x1254 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: 0x12A0 | offset to field `name` (string) + +0x1258 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x128C | offset to field `type` (table) + +0x125C | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x1268 | offset to field `attributes` (vector) + +0x1260 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `default_integer` (Long) + +vector (reflection.Field.attributes): + +0x1268 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x126C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1270 | offset to table[0] + +table (reflection.KeyValue): + +0x1270 | A8 D9 FF FF | SOffset32 | 0xFFFFD9A8 (-9816) Loc: 0x38C8 | offset to vtable + +0x1274 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1284 | offset to field `key` (string) + +0x1278 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x127C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x127C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1280 | 35 33 | char[2] | 53 | string literal + +0x1282 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1284 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1288 | 69 64 | char[2] | id | string literal + +0x128A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x128C | E0 DC FF FF | SOffset32 | 0xFFFFDCE0 (-8992) Loc: 0x35AC | offset to vtable + +0x1290 | 00 00 00 | uint8_t[3] | ... | padding + +0x1293 | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x1294 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `index` (Int) + +0x1298 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x129C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x12A0 | 18 00 00 00 | uint32_t | 0x00000018 (24) | length of string + +0x12A4 | 6C 6F 6E 67 5F 65 6E 75 | char[24] | long_enu | string literal + +0x12AC | 6D 5F 6E 6F 72 6D 61 6C | | m_normal + +0x12B4 | 5F 64 65 66 61 75 6C 74 | | _default + +0x12BC | 00 | char | 0x00 (0) | string terminator + +padding: + +0x12BD | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x12C0 | C8 E7 FF FF | SOffset32 | 0xFFFFE7C8 (-6200) Loc: 0x2AF8 | offset to vtable + +0x12C4 | 34 00 | uint16_t | 0x0034 (52) | table field `id` (UShort) + +0x12C6 | 6C 00 | uint16_t | 0x006C (108) | table field `offset` (UShort) + +0x12C8 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x130C | offset to field `name` (string) + +0x12CC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x12F8 | offset to field `type` (table) + +0x12D0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x12D4 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x12D4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x12D8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x12DC | offset to table[0] + +table (reflection.KeyValue): + +0x12DC | 14 DA FF FF | SOffset32 | 0xFFFFDA14 (-9708) Loc: 0x38C8 | offset to vtable + +0x12E0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x12F0 | offset to field `key` (string) + +0x12E4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x12E8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x12E8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x12EC | 35 32 | char[2] | 52 | string literal + +0x12EE | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x12F0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x12F4 | 69 64 | char[2] | id | string literal + +0x12F6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x12F8 | 4C DD FF FF | SOffset32 | 0xFFFFDD4C (-8884) Loc: 0x35AC | offset to vtable + +0x12FC | 00 00 00 | uint8_t[3] | ... | padding + +0x12FF | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x1300 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `index` (Int) + +0x1304 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x1308 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x130C | 1A 00 00 00 | uint32_t | 0x0000001A (26) | length of string + +0x1310 | 6C 6F 6E 67 5F 65 6E 75 | char[26] | long_enu | string literal + +0x1318 | 6D 5F 6E 6F 6E 5F 65 6E | | m_non_en + +0x1320 | 75 6D 5F 64 65 66 61 75 | | um_defau + +0x1328 | 6C 74 | | lt + +0x132A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x132C | 44 E7 FF FF | SOffset32 | 0xFFFFE744 (-6332) Loc: 0x2BE8 | offset to vtable + +0x1330 | 00 00 00 | uint8_t[3] | ... | padding + +0x1333 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1334 | 33 00 | uint16_t | 0x0033 (51) | table field `id` (UShort) + +0x1336 | 6A 00 | uint16_t | 0x006A (106) | table field `offset` (UShort) + +0x1338 | 6C 00 00 00 | UOffset32 | 0x0000006C (108) Loc: 0x13A4 | offset to field `name` (string) + +0x133C | 58 00 00 00 | UOffset32 | 0x00000058 (88) Loc: 0x1394 | offset to field `type` (table) + +0x1340 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1344 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1344 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x1348 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: 0x1378 | offset to table[0] + +0x134C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1350 | offset to table[1] + +table (reflection.KeyValue): + +0x1350 | 88 DA FF FF | SOffset32 | 0xFFFFDA88 (-9592) Loc: 0x38C8 | offset to vtable + +0x1354 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1364 | offset to field `key` (string) + +0x1358 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x135C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x135C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x1360 | 30 | char[1] | 0 | string literal + +0x1361 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1362 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x1364 | 0D 00 00 00 | uint32_t | 0x0000000D (13) | length of string + +0x1368 | 6E 61 74 69 76 65 5F 69 | char[13] | native_i | string literal + +0x1370 | 6E 6C 69 6E 65 | | nline + +0x1375 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1376 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.KeyValue): + +0x1378 | B0 DA FF FF | SOffset32 | 0xFFFFDAB0 (-9552) Loc: 0x38C8 | offset to vtable + +0x137C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x138C | offset to field `key` (string) + +0x1380 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1384 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1384 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1388 | 35 31 | char[2] | 51 | string literal + +0x138A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x138C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1390 | 69 64 | char[2] | id | string literal + +0x1392 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1394 | 7C DB FF FF | SOffset32 | 0xFFFFDB7C (-9348) Loc: 0x3818 | offset to vtable + +0x1398 | 00 00 00 | uint8_t[3] | ... | padding + +0x139B | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x139C | 06 00 00 00 | uint32_t | 0x00000006 (6) | table field `index` (Int) + +0x13A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x13A4 | 0D 00 00 00 | uint32_t | 0x0000000D (13) | length of string + +0x13A8 | 6E 61 74 69 76 65 5F 69 | char[13] | native_i | string literal + +0x13B0 | 6E 6C 69 6E 65 | | nline + +0x13B5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x13B6 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x13B8 | D0 E7 FF FF | SOffset32 | 0xFFFFE7D0 (-6192) Loc: 0x2BE8 | offset to vtable + +0x13BC | 00 00 00 | uint8_t[3] | ... | padding + +0x13BF | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x13C0 | 32 00 | uint16_t | 0x0032 (50) | table field `id` (UShort) + +0x13C2 | 68 00 | uint16_t | 0x0068 (104) | table field `offset` (UShort) + +0x13C4 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x1404 | offset to field `name` (string) + +0x13C8 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x13F4 | offset to field `type` (table) + +0x13CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x13D0 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x13D0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x13D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x13D8 | offset to table[0] + +table (reflection.KeyValue): + +0x13D8 | 10 DB FF FF | SOffset32 | 0xFFFFDB10 (-9456) Loc: 0x38C8 | offset to vtable + +0x13DC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x13EC | offset to field `key` (string) + +0x13E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x13E4 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x13E4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x13E8 | 35 30 | char[2] | 50 | string literal + +0x13EA | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x13EC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x13F0 | 69 64 | char[2] | id | string literal + +0x13F2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x13F4 | 80 E9 FF FF | SOffset32 | 0xFFFFE980 (-5760) Loc: 0x2A74 | offset to vtable + +0x13F8 | 00 00 | uint8_t[2] | .. | padding + +0x13FA | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x13FB | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x13FC | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x1400 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1404 | 18 00 00 00 | uint32_t | 0x00000018 (24) | length of string + +0x1408 | 73 63 61 6C 61 72 5F 6B | char[24] | scalar_k | string literal + +0x1410 | 65 79 5F 73 6F 72 74 65 | | ey_sorte + +0x1418 | 64 5F 74 61 62 6C 65 73 | | d_tables + +0x1420 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1421 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x1424 | 3C E8 FF FF | SOffset32 | 0xFFFFE83C (-6084) Loc: 0x2BE8 | offset to vtable + +0x1428 | 00 00 00 | uint8_t[3] | ... | padding + +0x142B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x142C | 31 00 | uint16_t | 0x0031 (49) | table field `id` (UShort) + +0x142E | 66 00 | uint16_t | 0x0066 (102) | table field `offset` (UShort) + +0x1430 | 70 00 00 00 | UOffset32 | 0x00000070 (112) Loc: 0x14A0 | offset to field `name` (string) + +0x1434 | 60 00 00 00 | UOffset32 | 0x00000060 (96) Loc: 0x1494 | offset to field `type` (table) + +0x1438 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x143C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x143C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x1440 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x1478 | offset to table[0] + +0x1444 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1448 | offset to table[1] + +table (reflection.KeyValue): + +0x1448 | 80 DB FF FF | SOffset32 | 0xFFFFDB80 (-9344) Loc: 0x38C8 | offset to vtable + +0x144C | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x1460 | offset to field `key` (string) + +0x1450 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1454 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1454 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x1458 | 4D 6F 6E 73 74 65 72 | char[7] | Monster | string literal + +0x145F | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1460 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x1464 | 6E 65 73 74 65 64 5F 66 | char[17] | nested_f | string literal + +0x146C | 6C 61 74 62 75 66 66 65 | | latbuffe + +0x1474 | 72 | | r + +0x1475 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1476 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.KeyValue): + +0x1478 | B0 DB FF FF | SOffset32 | 0xFFFFDBB0 (-9296) Loc: 0x38C8 | offset to vtable + +0x147C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x148C | offset to field `key` (string) + +0x1480 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1484 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1484 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1488 | 34 39 | char[2] | 49 | string literal + +0x148A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x148C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1490 | 69 64 | char[2] | id | string literal + +0x1492 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1494 | 54 E8 FF FF | SOffset32 | 0xFFFFE854 (-6060) Loc: 0x2C40 | offset to vtable + +0x1498 | 00 00 | uint8_t[2] | .. | padding + +0x149A | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x149B | 04 | uint8_t | 0x04 (4) | table field `element` (Byte) + +0x149C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x14A0 | 1C 00 00 00 | uint32_t | 0x0000001C (28) | length of string + +0x14A4 | 74 65 73 74 72 65 71 75 | char[28] | testrequ | string literal + +0x14AC | 69 72 65 64 6E 65 73 74 | | irednest + +0x14B4 | 65 64 66 6C 61 74 62 75 | | edflatbu + +0x14BC | 66 66 65 72 | | ffer + +0x14C0 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x14C1 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x14C4 | B0 E6 FF FF | SOffset32 | 0xFFFFE6B0 (-6480) Loc: 0x2E14 | offset to vtable + +0x14C8 | 30 00 | uint16_t | 0x0030 (48) | table field `id` (UShort) + +0x14CA | 64 00 | uint16_t | 0x0064 (100) | table field `offset` (UShort) + +0x14CC | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: 0x1518 | offset to field `name` (string) + +0x14D0 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x1504 | offset to field `type` (table) + +0x14D4 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x14E0 | offset to field `attributes` (vector) + +0x14D8 | FF FF FF FF FF FF FF FF | int64_t | 0xFFFFFFFFFFFFFFFF (-1) | table field `default_integer` (Long) + +vector (reflection.Field.attributes): + +0x14E0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x14E4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x14E8 | offset to table[0] + +table (reflection.KeyValue): + +0x14E8 | 20 DC FF FF | SOffset32 | 0xFFFFDC20 (-9184) Loc: 0x38C8 | offset to vtable + +0x14EC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x14FC | offset to field `key` (string) + +0x14F0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x14F4 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x14F4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x14F8 | 34 38 | char[2] | 48 | string literal + +0x14FA | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x14FC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1500 | 69 64 | char[2] | id | string literal + +0x1502 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1504 | 58 DF FF FF | SOffset32 | 0xFFFFDF58 (-8360) Loc: 0x35AC | offset to vtable + +0x1508 | 00 00 00 | uint8_t[3] | ... | padding + +0x150B | 03 | uint8_t | 0x03 (3) | table field `base_type` (Byte) + +0x150C | 05 00 00 00 | uint32_t | 0x00000005 (5) | table field `index` (Int) + +0x1510 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x1514 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1518 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x151C | 73 69 67 6E 65 64 5F 65 | char[11] | signed_e | string literal + +0x1524 | 6E 75 6D | | num + +0x1527 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1528 | 40 E9 FF FF | SOffset32 | 0xFFFFE940 (-5824) Loc: 0x2BE8 | offset to vtable + +0x152C | 00 00 00 | uint8_t[3] | ... | padding + +0x152F | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1530 | 2F 00 | uint16_t | 0x002F (47) | table field `id` (UShort) + +0x1532 | 62 00 | uint16_t | 0x0062 (98) | table field `offset` (UShort) + +0x1534 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x1574 | offset to field `name` (string) + +0x1538 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1564 | offset to field `type` (table) + +0x153C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1540 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1540 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1544 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1548 | offset to table[0] + +table (reflection.KeyValue): + +0x1548 | 80 DC FF FF | SOffset32 | 0xFFFFDC80 (-9088) Loc: 0x38C8 | offset to vtable + +0x154C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x155C | offset to field `key` (string) + +0x1550 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1554 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1554 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1558 | 34 37 | char[2] | 47 | string literal + +0x155A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x155C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1560 | 69 64 | char[2] | id | string literal + +0x1562 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1564 | F0 EA FF FF | SOffset32 | 0xFFFFEAF0 (-5392) Loc: 0x2A74 | offset to vtable + +0x1568 | 00 00 | uint8_t[2] | .. | padding + +0x156A | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x156B | 04 | uint8_t | 0x04 (4) | table field `element` (Byte) + +0x156C | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x1570 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1574 | 0F 00 00 00 | uint32_t | 0x0000000F (15) | length of string + +0x1578 | 76 65 63 74 6F 72 5F 6F | char[15] | vector_o | string literal + +0x1580 | 66 5F 65 6E 75 6D 73 | | f_enums + +0x1587 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1588 | A0 E9 FF FF | SOffset32 | 0xFFFFE9A0 (-5728) Loc: 0x2BE8 | offset to vtable + +0x158C | 00 00 00 | uint8_t[3] | ... | padding + +0x158F | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1590 | 2E 00 | uint16_t | 0x002E (46) | table field `id` (UShort) + +0x1592 | 60 00 | uint16_t | 0x0060 (96) | table field `offset` (UShort) + +0x1594 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x15D4 | offset to field `name` (string) + +0x1598 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x15C4 | offset to field `type` (table) + +0x159C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x15A0 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x15A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x15A4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x15A8 | offset to table[0] + +table (reflection.KeyValue): + +0x15A8 | E0 DC FF FF | SOffset32 | 0xFFFFDCE0 (-8992) Loc: 0x38C8 | offset to vtable + +0x15AC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x15BC | offset to field `key` (string) + +0x15B0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x15B4 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x15B4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x15B8 | 34 36 | char[2] | 46 | string literal + +0x15BA | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x15BC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x15C0 | 69 64 | char[2] | id | string literal + +0x15C2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x15C4 | AC DD FF FF | SOffset32 | 0xFFFFDDAC (-8788) Loc: 0x3818 | offset to vtable + +0x15C8 | 00 00 00 | uint8_t[3] | ... | padding + +0x15CB | 10 | uint8_t | 0x10 (16) | table field `base_type` (Byte) + +0x15CC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x15D0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x15D4 | 0D 00 00 00 | uint32_t | 0x0000000D (13) | length of string + +0x15D8 | 61 6E 79 5F 61 6D 62 69 | char[13] | any_ambi | string literal + +0x15E0 | 67 75 6F 75 73 | | guous + +0x15E5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x15E6 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x15E8 | F0 EA FF FF | SOffset32 | 0xFFFFEAF0 (-5392) Loc: 0x2AF8 | offset to vtable + +0x15EC | 2D 00 | uint16_t | 0x002D (45) | table field `id` (UShort) + +0x15EE | 5E 00 | uint16_t | 0x005E (94) | table field `offset` (UShort) + +0x15F0 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x1634 | offset to field `name` (string) + +0x15F4 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1620 | offset to field `type` (table) + +0x15F8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x15FC | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x15FC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1600 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1604 | offset to table[0] + +table (reflection.KeyValue): + +0x1604 | 3C DD FF FF | SOffset32 | 0xFFFFDD3C (-8900) Loc: 0x38C8 | offset to vtable + +0x1608 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1618 | offset to field `key` (string) + +0x160C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1610 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1610 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1614 | 34 35 | char[2] | 45 | string literal + +0x1616 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1618 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x161C | 69 64 | char[2] | id | string literal + +0x161E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1620 | 74 E0 FF FF | SOffset32 | 0xFFFFE074 (-8076) Loc: 0x35AC | offset to vtable + +0x1624 | 00 00 00 | uint8_t[3] | ... | padding + +0x1627 | 01 | uint8_t | 0x01 (1) | table field `base_type` (Byte) + +0x1628 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x162C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x1630 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1634 | 12 00 00 00 | uint32_t | 0x00000012 (18) | length of string + +0x1638 | 61 6E 79 5F 61 6D 62 69 | char[18] | any_ambi | string literal + +0x1640 | 67 75 6F 75 73 5F 74 79 | | guous_ty + +0x1648 | 70 65 | | pe + +0x164A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x164C | 64 EA FF FF | SOffset32 | 0xFFFFEA64 (-5532) Loc: 0x2BE8 | offset to vtable + +0x1650 | 00 00 00 | uint8_t[3] | ... | padding + +0x1653 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1654 | 2C 00 | uint16_t | 0x002C (44) | table field `id` (UShort) + +0x1656 | 5C 00 | uint16_t | 0x005C (92) | table field `offset` (UShort) + +0x1658 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x1698 | offset to field `name` (string) + +0x165C | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1688 | offset to field `type` (table) + +0x1660 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1664 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1664 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1668 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x166C | offset to table[0] + +table (reflection.KeyValue): + +0x166C | A4 DD FF FF | SOffset32 | 0xFFFFDDA4 (-8796) Loc: 0x38C8 | offset to vtable + +0x1670 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1680 | offset to field `key` (string) + +0x1674 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1678 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1678 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x167C | 34 34 | char[2] | 44 | string literal + +0x167E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1680 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1684 | 69 64 | char[2] | id | string literal + +0x1686 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1688 | 70 DE FF FF | SOffset32 | 0xFFFFDE70 (-8592) Loc: 0x3818 | offset to vtable + +0x168C | 00 00 00 | uint8_t[3] | ... | padding + +0x168F | 10 | uint8_t | 0x10 (16) | table field `base_type` (Byte) + +0x1690 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `index` (Int) + +0x1694 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1698 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | length of string + +0x169C | 61 6E 79 5F 75 6E 69 71 | char[10] | any_uniq | string literal + +0x16A4 | 75 65 | | ue + +0x16A6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x16A8 | B0 EB FF FF | SOffset32 | 0xFFFFEBB0 (-5200) Loc: 0x2AF8 | offset to vtable + +0x16AC | 2B 00 | uint16_t | 0x002B (43) | table field `id` (UShort) + +0x16AE | 5A 00 | uint16_t | 0x005A (90) | table field `offset` (UShort) + +0x16B0 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x16F4 | offset to field `name` (string) + +0x16B4 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x16E0 | offset to field `type` (table) + +0x16B8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x16BC | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x16BC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x16C0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x16C4 | offset to table[0] + +table (reflection.KeyValue): + +0x16C4 | FC DD FF FF | SOffset32 | 0xFFFFDDFC (-8708) Loc: 0x38C8 | offset to vtable + +0x16C8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x16D8 | offset to field `key` (string) + +0x16CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x16D0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x16D0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x16D4 | 34 33 | char[2] | 43 | string literal + +0x16D6 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x16D8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x16DC | 69 64 | char[2] | id | string literal + +0x16DE | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x16E0 | 34 E1 FF FF | SOffset32 | 0xFFFFE134 (-7884) Loc: 0x35AC | offset to vtable + +0x16E4 | 00 00 00 | uint8_t[3] | ... | padding + +0x16E7 | 01 | uint8_t | 0x01 (1) | table field `base_type` (Byte) + +0x16E8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `index` (Int) + +0x16EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x16F0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x16F4 | 0F 00 00 00 | uint32_t | 0x0000000F (15) | length of string + +0x16F8 | 61 6E 79 5F 75 6E 69 71 | char[15] | any_uniq | string literal + +0x1700 | 75 65 5F 74 79 70 65 | | ue_type + +0x1707 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1708 | 20 EB FF FF | SOffset32 | 0xFFFFEB20 (-5344) Loc: 0x2BE8 | offset to vtable + +0x170C | 00 00 00 | uint8_t[3] | ... | padding + +0x170F | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1710 | 2A 00 | uint16_t | 0x002A (42) | table field `id` (UShort) + +0x1712 | 58 00 | uint16_t | 0x0058 (88) | table field `offset` (UShort) + +0x1714 | F8 00 00 00 | UOffset32 | 0x000000F8 (248) Loc: 0x180C | offset to field `name` (string) + +0x1718 | E8 00 00 00 | UOffset32 | 0x000000E8 (232) Loc: 0x1800 | offset to field `type` (table) + +0x171C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1720 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1720 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of vector (# items) + +0x1724 | B0 00 00 00 | UOffset32 | 0x000000B0 (176) Loc: 0x17D4 | offset to table[0] + +0x1728 | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x17A8 | offset to table[1] + +0x172C | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x177C | offset to table[2] + +0x1730 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x1754 | offset to table[3] + +0x1734 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1738 | offset to table[4] + +table (reflection.KeyValue): + +0x1738 | 70 DE FF FF | SOffset32 | 0xFFFFDE70 (-8592) Loc: 0x38C8 | offset to vtable + +0x173C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x174C | offset to field `key` (string) + +0x1740 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1744 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1744 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1748 | 34 32 | char[2] | 42 | string literal + +0x174A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x174C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1750 | 69 64 | char[2] | id | string literal + +0x1752 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x1754 | 8C DE FF FF | SOffset32 | 0xFFFFDE8C (-8564) Loc: 0x38C8 | offset to vtable + +0x1758 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1770 | offset to field `key` (string) + +0x175C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1760 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1760 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1764 | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x176C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x176D | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1770 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x1774 | 68 61 73 68 | char[4] | hash | string literal + +0x1778 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1779 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x177C | B4 DE FF FF | SOffset32 | 0xFFFFDEB4 (-8524) Loc: 0x38C8 | offset to vtable + +0x1780 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1798 | offset to field `key` (string) + +0x1784 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1788 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1788 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x178C | 52 65 66 65 72 72 61 62 | char[11] | Referrab | string literal + +0x1794 | 6C 65 54 | | leT + +0x1797 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1798 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x179C | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x17A4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x17A5 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x17A8 | E0 DE FF FF | SOffset32 | 0xFFFFDEE0 (-8480) Loc: 0x38C8 | offset to vtable + +0x17AC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x17BC | offset to field `key` (string) + +0x17B0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x17B4 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x17B4 | 00 00 00 00 | uint32_t | 0x00000000 (0) | length of string + +0x17B8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x17B9 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x17BC | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x17C0 | 63 70 70 5F 70 74 72 5F | char[16] | cpp_ptr_ | string literal + +0x17C8 | 74 79 70 65 5F 67 65 74 | | type_get + +0x17D0 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x17D1 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x17D4 | 0C DF FF FF | SOffset32 | 0xFFFFDF0C (-8436) Loc: 0x38C8 | offset to vtable + +0x17D8 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x17EC | offset to field `key` (string) + +0x17DC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x17E0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x17E0 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x17E4 | 6E 61 6B 65 64 | char[5] | naked | string literal + +0x17E9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x17EA | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x17EC | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x17F0 | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x17F8 | 74 79 70 65 | | type + +0x17FC | 00 | char | 0x00 (0) | string terminator + +padding: + +0x17FD | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1800 | C0 EB FF FF | SOffset32 | 0xFFFFEBC0 (-5184) Loc: 0x2C40 | offset to vtable + +0x1804 | 00 00 | uint8_t[2] | .. | padding + +0x1806 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1807 | 0A | uint8_t | 0x0A (10) | table field `element` (Byte) + +0x1808 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x180C | 1F 00 00 00 | uint32_t | 0x0000001F (31) | length of string + +0x1810 | 76 65 63 74 6F 72 5F 6F | char[31] | vector_o | string literal + +0x1818 | 66 5F 6E 6F 6E 5F 6F 77 | | f_non_ow + +0x1820 | 6E 69 6E 67 5F 72 65 66 | | ning_ref + +0x1828 | 65 72 65 6E 63 65 73 | | erences + +0x182F | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1830 | 38 ED FF FF | SOffset32 | 0xFFFFED38 (-4808) Loc: 0x2AF8 | offset to vtable + +0x1834 | 29 00 | uint16_t | 0x0029 (41) | table field `id` (UShort) + +0x1836 | 56 00 | uint16_t | 0x0056 (86) | table field `offset` (UShort) + +0x1838 | FC 00 00 00 | UOffset32 | 0x000000FC (252) Loc: 0x1934 | offset to field `name` (string) + +0x183C | E8 00 00 00 | UOffset32 | 0x000000E8 (232) Loc: 0x1924 | offset to field `type` (table) + +0x1840 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1844 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1844 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of vector (# items) + +0x1848 | B0 00 00 00 | UOffset32 | 0x000000B0 (176) Loc: 0x18F8 | offset to table[0] + +0x184C | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x18CC | offset to table[1] + +0x1850 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x18A0 | offset to table[2] + +0x1854 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x1878 | offset to table[3] + +0x1858 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x185C | offset to table[4] + +table (reflection.KeyValue): + +0x185C | 94 DF FF FF | SOffset32 | 0xFFFFDF94 (-8300) Loc: 0x38C8 | offset to vtable + +0x1860 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1870 | offset to field `key` (string) + +0x1864 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1868 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1868 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x186C | 34 31 | char[2] | 41 | string literal + +0x186E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1870 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1874 | 69 64 | char[2] | id | string literal + +0x1876 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x1878 | B0 DF FF FF | SOffset32 | 0xFFFFDFB0 (-8272) Loc: 0x38C8 | offset to vtable + +0x187C | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1894 | offset to field `key` (string) + +0x1880 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1884 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1884 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1888 | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x1890 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1891 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1894 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x1898 | 68 61 73 68 | char[4] | hash | string literal + +0x189C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x189D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x18A0 | D8 DF FF FF | SOffset32 | 0xFFFFDFD8 (-8232) Loc: 0x38C8 | offset to vtable + +0x18A4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x18BC | offset to field `key` (string) + +0x18A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x18AC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x18AC | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x18B0 | 52 65 66 65 72 72 61 62 | char[11] | Referrab | string literal + +0x18B8 | 6C 65 54 | | leT + +0x18BB | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x18BC | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x18C0 | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x18C8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x18C9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x18CC | 04 E0 FF FF | SOffset32 | 0xFFFFE004 (-8188) Loc: 0x38C8 | offset to vtable + +0x18D0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x18E0 | offset to field `key` (string) + +0x18D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x18D8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x18D8 | 00 00 00 00 | uint32_t | 0x00000000 (0) | length of string + +0x18DC | 00 | char | 0x00 (0) | string terminator + +padding: + +0x18DD | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x18E0 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x18E4 | 63 70 70 5F 70 74 72 5F | char[16] | cpp_ptr_ | string literal + +0x18EC | 74 79 70 65 5F 67 65 74 | | type_get + +0x18F4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x18F5 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x18F8 | 30 E0 FF FF | SOffset32 | 0xFFFFE030 (-8144) Loc: 0x38C8 | offset to vtable + +0x18FC | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x1910 | offset to field `key` (string) + +0x1900 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1904 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1904 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x1908 | 6E 61 6B 65 64 | char[5] | naked | string literal + +0x190D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x190E | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x1910 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x1914 | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x191C | 74 79 70 65 | | type + +0x1920 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1921 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1924 | B0 E2 FF FF | SOffset32 | 0xFFFFE2B0 (-7504) Loc: 0x3674 | offset to vtable + +0x1928 | 00 00 00 | uint8_t[3] | ... | padding + +0x192B | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x192C | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x1930 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1934 | 14 00 00 00 | uint32_t | 0x00000014 (20) | length of string + +0x1938 | 6E 6F 6E 5F 6F 77 6E 69 | char[20] | non_owni | string literal + +0x1940 | 6E 67 5F 72 65 66 65 72 | | ng_refer + +0x1948 | 65 6E 63 65 | | ence + +0x194C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x194D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x1950 | 68 ED FF FF | SOffset32 | 0xFFFFED68 (-4760) Loc: 0x2BE8 | offset to vtable + +0x1954 | 00 00 00 | uint8_t[3] | ... | padding + +0x1957 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1958 | 28 00 | uint16_t | 0x0028 (40) | table field `id` (UShort) + +0x195A | 54 00 | uint16_t | 0x0054 (84) | table field `offset` (UShort) + +0x195C | 08 01 00 00 | UOffset32 | 0x00000108 (264) Loc: 0x1A64 | offset to field `name` (string) + +0x1960 | F8 00 00 00 | UOffset32 | 0x000000F8 (248) Loc: 0x1A58 | offset to field `type` (table) + +0x1964 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1968 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1968 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of vector (# items) + +0x196C | B4 00 00 00 | UOffset32 | 0x000000B4 (180) Loc: 0x1A20 | offset to table[0] + +0x1970 | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x19F0 | offset to table[1] + +0x1974 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x19C4 | offset to table[2] + +0x1978 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x199C | offset to table[3] + +0x197C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1980 | offset to table[4] + +table (reflection.KeyValue): + +0x1980 | B8 E0 FF FF | SOffset32 | 0xFFFFE0B8 (-8008) Loc: 0x38C8 | offset to vtable + +0x1984 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1994 | offset to field `key` (string) + +0x1988 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x198C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x198C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1990 | 34 30 | char[2] | 40 | string literal + +0x1992 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1994 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1998 | 69 64 | char[2] | id | string literal + +0x199A | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x199C | D4 E0 FF FF | SOffset32 | 0xFFFFE0D4 (-7980) Loc: 0x38C8 | offset to vtable + +0x19A0 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x19B8 | offset to field `key` (string) + +0x19A4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x19A8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x19A8 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x19AC | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x19B4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x19B5 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x19B8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x19BC | 68 61 73 68 | char[4] | hash | string literal + +0x19C0 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x19C1 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x19C4 | FC E0 FF FF | SOffset32 | 0xFFFFE0FC (-7940) Loc: 0x38C8 | offset to vtable + +0x19C8 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x19E0 | offset to field `key` (string) + +0x19CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x19D0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x19D0 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x19D4 | 52 65 66 65 72 72 61 62 | char[11] | Referrab | string literal + +0x19DC | 6C 65 54 | | leT + +0x19DF | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x19E0 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x19E4 | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x19EC | 00 | char | 0x00 (0) | string terminator + +padding: + +0x19ED | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x19F0 | 28 E1 FF FF | SOffset32 | 0xFFFFE128 (-7896) Loc: 0x38C8 | offset to vtable + +0x19F4 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x1A08 | offset to field `key` (string) + +0x19F8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x19FC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x19FC | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of string + +0x1A00 | 2E 67 65 74 28 29 | char[6] | .get() | string literal + +0x1A06 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1A08 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x1A0C | 63 70 70 5F 70 74 72 5F | char[16] | cpp_ptr_ | string literal + +0x1A14 | 74 79 70 65 5F 67 65 74 | | type_get + +0x1A1C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1A1D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1A20 | 58 E1 FF FF | SOffset32 | 0xFFFFE158 (-7848) Loc: 0x38C8 | offset to vtable + +0x1A24 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x1A44 | offset to field `key` (string) + +0x1A28 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1A2C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1A2C | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x1A30 | 64 65 66 61 75 6C 74 5F | char[16] | default_ | string literal + +0x1A38 | 70 74 72 5F 74 79 70 65 | | ptr_type + +0x1A40 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1A41 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1A44 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x1A48 | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x1A50 | 74 79 70 65 | | type + +0x1A54 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1A55 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1A58 | 18 EE FF FF | SOffset32 | 0xFFFFEE18 (-4584) Loc: 0x2C40 | offset to vtable + +0x1A5C | 00 00 | uint8_t[2] | .. | padding + +0x1A5E | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1A5F | 0A | uint8_t | 0x0A (10) | table field `element` (Byte) + +0x1A60 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1A64 | 1E 00 00 00 | uint32_t | 0x0000001E (30) | length of string + +0x1A68 | 76 65 63 74 6F 72 5F 6F | char[30] | vector_o | string literal + +0x1A70 | 66 5F 63 6F 5F 6F 77 6E | | f_co_own + +0x1A78 | 69 6E 67 5F 72 65 66 65 | | ing_refe + +0x1A80 | 72 65 6E 63 65 73 | | rences + +0x1A86 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1A88 | 90 EF FF FF | SOffset32 | 0xFFFFEF90 (-4208) Loc: 0x2AF8 | offset to vtable + +0x1A8C | 27 00 | uint16_t | 0x0027 (39) | table field `id` (UShort) + +0x1A8E | 52 00 | uint16_t | 0x0052 (82) | table field `offset` (UShort) + +0x1A90 | CC 00 00 00 | UOffset32 | 0x000000CC (204) Loc: 0x1B5C | offset to field `name` (string) + +0x1A94 | B8 00 00 00 | UOffset32 | 0x000000B8 (184) Loc: 0x1B4C | offset to field `type` (table) + +0x1A98 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1A9C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1A9C | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x1AA0 | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x1B20 | offset to table[0] + +0x1AA4 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x1AF4 | offset to table[1] + +0x1AA8 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x1ACC | offset to table[2] + +0x1AAC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1AB0 | offset to table[3] + +table (reflection.KeyValue): + +0x1AB0 | E8 E1 FF FF | SOffset32 | 0xFFFFE1E8 (-7704) Loc: 0x38C8 | offset to vtable + +0x1AB4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1AC4 | offset to field `key` (string) + +0x1AB8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1ABC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1ABC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1AC0 | 33 39 | char[2] | 39 | string literal + +0x1AC2 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1AC4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1AC8 | 69 64 | char[2] | id | string literal + +0x1ACA | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x1ACC | 04 E2 FF FF | SOffset32 | 0xFFFFE204 (-7676) Loc: 0x38C8 | offset to vtable + +0x1AD0 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1AE8 | offset to field `key` (string) + +0x1AD4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1AD8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1AD8 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1ADC | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x1AE4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1AE5 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1AE8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x1AEC | 68 61 73 68 | char[4] | hash | string literal + +0x1AF0 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1AF1 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1AF4 | 2C E2 FF FF | SOffset32 | 0xFFFFE22C (-7636) Loc: 0x38C8 | offset to vtable + +0x1AF8 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1B10 | offset to field `key` (string) + +0x1AFC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1B00 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1B00 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x1B04 | 52 65 66 65 72 72 61 62 | char[11] | Referrab | string literal + +0x1B0C | 6C 65 54 | | leT + +0x1B0F | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1B10 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1B14 | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x1B1C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1B1D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1B20 | 58 E2 FF FF | SOffset32 | 0xFFFFE258 (-7592) Loc: 0x38C8 | offset to vtable + +0x1B24 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x1B38 | offset to field `key` (string) + +0x1B28 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1B2C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1B2C | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x1B30 | 6E 61 6B 65 64 | char[5] | naked | string literal + +0x1B35 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1B36 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x1B38 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x1B3C | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x1B44 | 74 79 70 65 | | type + +0x1B48 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1B49 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1B4C | D8 E4 FF FF | SOffset32 | 0xFFFFE4D8 (-6952) Loc: 0x3674 | offset to vtable + +0x1B50 | 00 00 00 | uint8_t[3] | ... | padding + +0x1B53 | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x1B54 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x1B58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1B5C | 13 00 00 00 | uint32_t | 0x00000013 (19) | length of string + +0x1B60 | 63 6F 5F 6F 77 6E 69 6E | char[19] | co_ownin | string literal + +0x1B68 | 67 5F 72 65 66 65 72 65 | | g_refere + +0x1B70 | 6E 63 65 | | nce + +0x1B73 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1B74 | 8C EF FF FF | SOffset32 | 0xFFFFEF8C (-4212) Loc: 0x2BE8 | offset to vtable + +0x1B78 | 00 00 00 | uint8_t[3] | ... | padding + +0x1B7B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1B7C | 26 00 | uint16_t | 0x0026 (38) | table field `id` (UShort) + +0x1B7E | 50 00 | uint16_t | 0x0050 (80) | table field `offset` (UShort) + +0x1B80 | 7C 00 00 00 | UOffset32 | 0x0000007C (124) Loc: 0x1BFC | offset to field `name` (string) + +0x1B84 | 68 00 00 00 | UOffset32 | 0x00000068 (104) Loc: 0x1BEC | offset to field `type` (table) + +0x1B88 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1B8C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1B8C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x1B90 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x1BB4 | offset to table[0] + +0x1B94 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1B98 | offset to table[1] + +table (reflection.KeyValue): + +0x1B98 | D0 E2 FF FF | SOffset32 | 0xFFFFE2D0 (-7472) Loc: 0x38C8 | offset to vtable + +0x1B9C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1BAC | offset to field `key` (string) + +0x1BA0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1BA4 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1BA4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1BA8 | 33 38 | char[2] | 38 | string literal + +0x1BAA | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1BAC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1BB0 | 69 64 | char[2] | id | string literal + +0x1BB2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x1BB4 | EC E2 FF FF | SOffset32 | 0xFFFFE2EC (-7444) Loc: 0x38C8 | offset to vtable + +0x1BB8 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x1BD8 | offset to field `key` (string) + +0x1BBC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1BC0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1BC0 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x1BC4 | 64 65 66 61 75 6C 74 5F | char[16] | default_ | string literal + +0x1BCC | 70 74 72 5F 74 79 70 65 | | ptr_type + +0x1BD4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1BD5 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1BD8 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x1BDC | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x1BE4 | 74 79 70 65 | | type + +0x1BE8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1BE9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1BEC | 78 F1 FF FF | SOffset32 | 0xFFFFF178 (-3720) Loc: 0x2A74 | offset to vtable + +0x1BF0 | 00 00 | uint8_t[2] | .. | padding + +0x1BF2 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1BF3 | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x1BF4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `index` (Int) + +0x1BF8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1BFC | 1C 00 00 00 | uint32_t | 0x0000001C (28) | length of string + +0x1C00 | 76 65 63 74 6F 72 5F 6F | char[28] | vector_o | string literal + +0x1C08 | 66 5F 73 74 72 6F 6E 67 | | f_strong + +0x1C10 | 5F 72 65 66 65 72 72 61 | | _referra + +0x1C18 | 62 6C 65 73 | | bles + +0x1C1C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1C1D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x1C20 | 38 F0 FF FF | SOffset32 | 0xFFFFF038 (-4040) Loc: 0x2BE8 | offset to vtable + +0x1C24 | 00 00 00 | uint8_t[3] | ... | padding + +0x1C27 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1C28 | 25 00 | uint16_t | 0x0025 (37) | table field `id` (UShort) + +0x1C2A | 4E 00 | uint16_t | 0x004E (78) | table field `offset` (UShort) + +0x1C2C | C8 00 00 00 | UOffset32 | 0x000000C8 (200) Loc: 0x1CF4 | offset to field `name` (string) + +0x1C30 | B8 00 00 00 | UOffset32 | 0x000000B8 (184) Loc: 0x1CE8 | offset to field `type` (table) + +0x1C34 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1C38 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1C38 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x1C3C | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x1CBC | offset to table[0] + +0x1C40 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x1C90 | offset to table[1] + +0x1C44 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x1C68 | offset to table[2] + +0x1C48 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1C4C | offset to table[3] + +table (reflection.KeyValue): + +0x1C4C | 84 E3 FF FF | SOffset32 | 0xFFFFE384 (-7292) Loc: 0x38C8 | offset to vtable + +0x1C50 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1C60 | offset to field `key` (string) + +0x1C54 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1C58 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1C58 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1C5C | 33 37 | char[2] | 37 | string literal + +0x1C5E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1C60 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1C64 | 69 64 | char[2] | id | string literal + +0x1C66 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x1C68 | A0 E3 FF FF | SOffset32 | 0xFFFFE3A0 (-7264) Loc: 0x38C8 | offset to vtable + +0x1C6C | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1C84 | offset to field `key` (string) + +0x1C70 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1C74 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1C74 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1C78 | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x1C80 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1C81 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1C84 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x1C88 | 68 61 73 68 | char[4] | hash | string literal + +0x1C8C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1C8D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1C90 | C8 E3 FF FF | SOffset32 | 0xFFFFE3C8 (-7224) Loc: 0x38C8 | offset to vtable + +0x1C94 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1CAC | offset to field `key` (string) + +0x1C98 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1C9C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1C9C | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x1CA0 | 52 65 66 65 72 72 61 62 | char[11] | Referrab | string literal + +0x1CA8 | 6C 65 54 | | leT + +0x1CAB | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1CAC | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1CB0 | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x1CB8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1CB9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1CBC | F4 E3 FF FF | SOffset32 | 0xFFFFE3F4 (-7180) Loc: 0x38C8 | offset to vtable + +0x1CC0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x1CD4 | offset to field `key` (string) + +0x1CC4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1CC8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1CC8 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x1CCC | 6E 61 6B 65 64 | char[5] | naked | string literal + +0x1CD1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1CD2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x1CD4 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x1CD8 | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x1CE0 | 74 79 70 65 | | type + +0x1CE4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1CE5 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1CE8 | A8 F0 FF FF | SOffset32 | 0xFFFFF0A8 (-3928) Loc: 0x2C40 | offset to vtable + +0x1CEC | 00 00 | uint8_t[2] | .. | padding + +0x1CEE | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1CEF | 0A | uint8_t | 0x0A (10) | table field `element` (Byte) + +0x1CF0 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1CF4 | 19 00 00 00 | uint32_t | 0x00000019 (25) | length of string + +0x1CF8 | 76 65 63 74 6F 72 5F 6F | char[25] | vector_o | string literal + +0x1D00 | 66 5F 77 65 61 6B 5F 72 | | f_weak_r + +0x1D08 | 65 66 65 72 65 6E 63 65 | | eference + +0x1D10 | 73 | | s + +0x1D11 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1D12 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x1D14 | 1C F2 FF FF | SOffset32 | 0xFFFFF21C (-3556) Loc: 0x2AF8 | offset to vtable + +0x1D18 | 24 00 | uint16_t | 0x0024 (36) | table field `id` (UShort) + +0x1D1A | 4C 00 | uint16_t | 0x004C (76) | table field `offset` (UShort) + +0x1D1C | CC 00 00 00 | UOffset32 | 0x000000CC (204) Loc: 0x1DE8 | offset to field `name` (string) + +0x1D20 | B8 00 00 00 | UOffset32 | 0x000000B8 (184) Loc: 0x1DD8 | offset to field `type` (table) + +0x1D24 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1D28 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1D28 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x1D2C | 80 00 00 00 | UOffset32 | 0x00000080 (128) Loc: 0x1DAC | offset to table[0] + +0x1D30 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x1D80 | offset to table[1] + +0x1D34 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x1D58 | offset to table[2] + +0x1D38 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1D3C | offset to table[3] + +table (reflection.KeyValue): + +0x1D3C | 74 E4 FF FF | SOffset32 | 0xFFFFE474 (-7052) Loc: 0x38C8 | offset to vtable + +0x1D40 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1D50 | offset to field `key` (string) + +0x1D44 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1D48 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1D48 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1D4C | 33 36 | char[2] | 36 | string literal + +0x1D4E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1D50 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1D54 | 69 64 | char[2] | id | string literal + +0x1D56 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x1D58 | 90 E4 FF FF | SOffset32 | 0xFFFFE490 (-7024) Loc: 0x38C8 | offset to vtable + +0x1D5C | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1D74 | offset to field `key` (string) + +0x1D60 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1D64 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1D64 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1D68 | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x1D70 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1D71 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x1D74 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x1D78 | 68 61 73 68 | char[4] | hash | string literal + +0x1D7C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1D7D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1D80 | B8 E4 FF FF | SOffset32 | 0xFFFFE4B8 (-6984) Loc: 0x38C8 | offset to vtable + +0x1D84 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x1D9C | offset to field `key` (string) + +0x1D88 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1D8C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1D8C | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x1D90 | 52 65 66 65 72 72 61 62 | char[11] | Referrab | string literal + +0x1D98 | 6C 65 54 | | leT + +0x1D9B | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1D9C | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x1DA0 | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x1DA8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1DA9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x1DAC | E4 E4 FF FF | SOffset32 | 0xFFFFE4E4 (-6940) Loc: 0x38C8 | offset to vtable + +0x1DB0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x1DC4 | offset to field `key` (string) + +0x1DB4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1DB8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1DB8 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x1DBC | 6E 61 6B 65 64 | char[5] | naked | string literal + +0x1DC1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1DC2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x1DC4 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x1DC8 | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x1DD0 | 74 79 70 65 | | type + +0x1DD4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1DD5 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x1DD8 | 64 E7 FF FF | SOffset32 | 0xFFFFE764 (-6300) Loc: 0x3674 | offset to vtable + +0x1DDC | 00 00 00 | uint8_t[3] | ... | padding + +0x1DDF | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x1DE0 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x1DE4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1DE8 | 15 00 00 00 | uint32_t | 0x00000015 (21) | length of string + +0x1DEC | 73 69 6E 67 6C 65 5F 77 | char[21] | single_w | string literal + +0x1DF4 | 65 61 6B 5F 72 65 66 65 | | eak_refe + +0x1DFC | 72 65 6E 63 65 | | rence + +0x1E01 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1E02 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x1E04 | 1C F2 FF FF | SOffset32 | 0xFFFFF21C (-3556) Loc: 0x2BE8 | offset to vtable + +0x1E08 | 00 00 00 | uint8_t[3] | ... | padding + +0x1E0B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1E0C | 23 00 | uint16_t | 0x0023 (35) | table field `id` (UShort) + +0x1E0E | 4A 00 | uint16_t | 0x004A (74) | table field `offset` (UShort) + +0x1E10 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x1E50 | offset to field `name` (string) + +0x1E14 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1E40 | offset to field `type` (table) + +0x1E18 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1E1C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1E1C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1E20 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1E24 | offset to table[0] + +table (reflection.KeyValue): + +0x1E24 | 5C E5 FF FF | SOffset32 | 0xFFFFE55C (-6820) Loc: 0x38C8 | offset to vtable + +0x1E28 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1E38 | offset to field `key` (string) + +0x1E2C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1E30 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1E30 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1E34 | 33 35 | char[2] | 35 | string literal + +0x1E36 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1E38 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1E3C | 69 64 | char[2] | id | string literal + +0x1E3E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1E40 | CC F3 FF FF | SOffset32 | 0xFFFFF3CC (-3124) Loc: 0x2A74 | offset to vtable + +0x1E44 | 00 00 | uint8_t[2] | .. | padding + +0x1E46 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1E47 | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x1E48 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `index` (Int) + +0x1E4C | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1E50 | 15 00 00 00 | uint32_t | 0x00000015 (21) | length of string + +0x1E54 | 76 65 63 74 6F 72 5F 6F | char[21] | vector_o | string literal + +0x1E5C | 66 5F 72 65 66 65 72 72 | | f_referr + +0x1E64 | 61 62 6C 65 73 | | ables + +0x1E69 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1E6A | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x1E6C | 84 F2 FF FF | SOffset32 | 0xFFFFF284 (-3452) Loc: 0x2BE8 | offset to vtable + +0x1E70 | 00 00 00 | uint8_t[3] | ... | padding + +0x1E73 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1E74 | 22 00 | uint16_t | 0x0022 (34) | table field `id` (UShort) + +0x1E76 | 48 00 | uint16_t | 0x0048 (72) | table field `offset` (UShort) + +0x1E78 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x1EB8 | offset to field `name` (string) + +0x1E7C | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1EA8 | offset to field `type` (table) + +0x1E80 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1E84 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1E84 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1E88 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1E8C | offset to table[0] + +table (reflection.KeyValue): + +0x1E8C | C4 E5 FF FF | SOffset32 | 0xFFFFE5C4 (-6716) Loc: 0x38C8 | offset to vtable + +0x1E90 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1EA0 | offset to field `key` (string) + +0x1E94 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1E98 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1E98 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1E9C | 33 34 | char[2] | 34 | string literal + +0x1E9E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1EA0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1EA4 | 69 64 | char[2] | id | string literal + +0x1EA6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1EA8 | 90 E6 FF FF | SOffset32 | 0xFFFFE690 (-6512) Loc: 0x3818 | offset to vtable + +0x1EAC | 00 00 00 | uint8_t[3] | ... | padding + +0x1EAF | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x1EB0 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | table field `index` (Int) + +0x1EB4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1EB8 | 15 00 00 00 | uint32_t | 0x00000015 (21) | length of string + +0x1EBC | 70 61 72 65 6E 74 5F 6E | char[21] | parent_n | string literal + +0x1EC4 | 61 6D 65 73 70 61 63 65 | | amespace + +0x1ECC | 5F 74 65 73 74 | | _test + +0x1ED1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1ED2 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x1ED4 | EC F2 FF FF | SOffset32 | 0xFFFFF2EC (-3348) Loc: 0x2BE8 | offset to vtable + +0x1ED8 | 00 00 00 | uint8_t[3] | ... | padding + +0x1EDB | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1EDC | 21 00 | uint16_t | 0x0021 (33) | table field `id` (UShort) + +0x1EDE | 46 00 | uint16_t | 0x0046 (70) | table field `offset` (UShort) + +0x1EE0 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x1F1C | offset to field `name` (string) + +0x1EE4 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1F10 | offset to field `type` (table) + +0x1EE8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1EEC | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1EEC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1EF0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1EF4 | offset to table[0] + +table (reflection.KeyValue): + +0x1EF4 | 2C E6 FF FF | SOffset32 | 0xFFFFE62C (-6612) Loc: 0x38C8 | offset to vtable + +0x1EF8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1F08 | offset to field `key` (string) + +0x1EFC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1F00 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1F00 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1F04 | 33 33 | char[2] | 33 | string literal + +0x1F06 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1F08 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1F0C | 69 64 | char[2] | id | string literal + +0x1F0E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1F10 | D0 F2 FF FF | SOffset32 | 0xFFFFF2D0 (-3376) Loc: 0x2C40 | offset to vtable + +0x1F14 | 00 00 | uint8_t[2] | .. | padding + +0x1F16 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1F17 | 0C | uint8_t | 0x0C (12) | table field `element` (Byte) + +0x1F18 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1F1C | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x1F20 | 76 65 63 74 6F 72 5F 6F | char[17] | vector_o | string literal + +0x1F28 | 66 5F 64 6F 75 62 6C 65 | | f_double + +0x1F30 | 73 | | s + +0x1F31 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1F32 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x1F34 | 4C F3 FF FF | SOffset32 | 0xFFFFF34C (-3252) Loc: 0x2BE8 | offset to vtable + +0x1F38 | 00 00 00 | uint8_t[3] | ... | padding + +0x1F3B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1F3C | 20 00 | uint16_t | 0x0020 (32) | table field `id` (UShort) + +0x1F3E | 44 00 | uint16_t | 0x0044 (68) | table field `offset` (UShort) + +0x1F40 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x1F7C | offset to field `name` (string) + +0x1F44 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1F70 | offset to field `type` (table) + +0x1F48 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1F4C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1F4C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1F50 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1F54 | offset to table[0] + +table (reflection.KeyValue): + +0x1F54 | 8C E6 FF FF | SOffset32 | 0xFFFFE68C (-6516) Loc: 0x38C8 | offset to vtable + +0x1F58 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1F68 | offset to field `key` (string) + +0x1F5C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1F60 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1F60 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1F64 | 33 32 | char[2] | 32 | string literal + +0x1F66 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1F68 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1F6C | 69 64 | char[2] | id | string literal + +0x1F6E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1F70 | 30 F3 FF FF | SOffset32 | 0xFFFFF330 (-3280) Loc: 0x2C40 | offset to vtable + +0x1F74 | 00 00 | uint8_t[2] | .. | padding + +0x1F76 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1F77 | 09 | uint8_t | 0x09 (9) | table field `element` (Byte) + +0x1F78 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1F7C | 0F 00 00 00 | uint32_t | 0x0000000F (15) | length of string + +0x1F80 | 76 65 63 74 6F 72 5F 6F | char[15] | vector_o | string literal + +0x1F88 | 66 5F 6C 6F 6E 67 73 | | f_longs + +0x1F8F | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x1F90 | A8 F3 FF FF | SOffset32 | 0xFFFFF3A8 (-3160) Loc: 0x2BE8 | offset to vtable + +0x1F94 | 00 00 00 | uint8_t[3] | ... | padding + +0x1F97 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1F98 | 1F 00 | uint16_t | 0x001F (31) | table field `id` (UShort) + +0x1F9A | 42 00 | uint16_t | 0x0042 (66) | table field `offset` (UShort) + +0x1F9C | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x1FDC | offset to field `name` (string) + +0x1FA0 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x1FCC | offset to field `type` (table) + +0x1FA4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1FA8 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x1FA8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x1FAC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1FB0 | offset to table[0] + +table (reflection.KeyValue): + +0x1FB0 | E8 E6 FF FF | SOffset32 | 0xFFFFE6E8 (-6424) Loc: 0x38C8 | offset to vtable + +0x1FB4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x1FC4 | offset to field `key` (string) + +0x1FB8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x1FBC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x1FBC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1FC0 | 33 31 | char[2] | 31 | string literal + +0x1FC2 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x1FC4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x1FC8 | 69 64 | char[2] | id | string literal + +0x1FCA | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x1FCC | 58 F5 FF FF | SOffset32 | 0xFFFFF558 (-2728) Loc: 0x2A74 | offset to vtable + +0x1FD0 | 00 00 | uint8_t[2] | .. | padding + +0x1FD2 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x1FD3 | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x1FD4 | 06 00 00 00 | uint32_t | 0x00000006 (6) | table field `index` (Int) + +0x1FD8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x1FDC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x1FE0 | 74 65 73 74 35 | char[5] | test5 | string literal + +0x1FE5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x1FE6 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x1FE8 | 00 F4 FF FF | SOffset32 | 0xFFFFF400 (-3072) Loc: 0x2BE8 | offset to vtable + +0x1FEC | 00 00 00 | uint8_t[3] | ... | padding + +0x1FEF | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x1FF0 | 1E 00 | uint16_t | 0x001E (30) | table field `id` (UShort) + +0x1FF2 | 40 00 | uint16_t | 0x0040 (64) | table field `offset` (UShort) + +0x1FF4 | 64 00 00 00 | UOffset32 | 0x00000064 (100) Loc: 0x2058 | offset to field `name` (string) + +0x1FF8 | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x204C | offset to field `type` (table) + +0x1FFC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2000 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2000 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2004 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x2028 | offset to table[0] + +0x2008 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x200C | offset to table[1] + +table (reflection.KeyValue): + +0x200C | 44 E7 FF FF | SOffset32 | 0xFFFFE744 (-6332) Loc: 0x38C8 | offset to vtable + +0x2010 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2020 | offset to field `key` (string) + +0x2014 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2018 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2018 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x201C | 33 30 | char[2] | 30 | string literal + +0x201E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2020 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2024 | 69 64 | char[2] | id | string literal + +0x2026 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2028 | 60 E7 FF FF | SOffset32 | 0xFFFFE760 (-6304) Loc: 0x38C8 | offset to vtable + +0x202C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x203C | offset to field `key` (string) + +0x2030 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2034 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2034 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2038 | 30 | char[1] | 0 | string literal + +0x2039 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x203A | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x203C | 0A 00 00 00 | uint32_t | 0x0000000A (10) | length of string + +0x2040 | 66 6C 65 78 62 75 66 66 | char[10] | flexbuff | string literal + +0x2048 | 65 72 | | er + +0x204A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x204C | 0C F4 FF FF | SOffset32 | 0xFFFFF40C (-3060) Loc: 0x2C40 | offset to vtable + +0x2050 | 00 00 | uint8_t[2] | .. | padding + +0x2052 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x2053 | 04 | uint8_t | 0x04 (4) | table field `element` (Byte) + +0x2054 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2058 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x205C | 66 6C 65 78 | char[4] | flex | string literal + +0x2060 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2061 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x2064 | 7C F4 FF FF | SOffset32 | 0xFFFFF47C (-2948) Loc: 0x2BE8 | offset to vtable + +0x2068 | 00 00 00 | uint8_t[3] | ... | padding + +0x206B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x206C | 1D 00 | uint16_t | 0x001D (29) | table field `id` (UShort) + +0x206E | 3E 00 | uint16_t | 0x003E (62) | table field `offset` (UShort) + +0x2070 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x20B0 | offset to field `name` (string) + +0x2074 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x20A0 | offset to field `type` (table) + +0x2078 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x207C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x207C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2080 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2084 | offset to table[0] + +table (reflection.KeyValue): + +0x2084 | BC E7 FF FF | SOffset32 | 0xFFFFE7BC (-6212) Loc: 0x38C8 | offset to vtable + +0x2088 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2098 | offset to field `key` (string) + +0x208C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2090 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2090 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2094 | 32 39 | char[2] | 29 | string literal + +0x2096 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2098 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x209C | 69 64 | char[2] | id | string literal + +0x209E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x20A0 | 2C F6 FF FF | SOffset32 | 0xFFFFF62C (-2516) Loc: 0x2A74 | offset to vtable + +0x20A4 | 00 00 | uint8_t[2] | .. | padding + +0x20A6 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x20A7 | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x20A8 | 00 00 00 00 | uint32_t | 0x00000000 (0) | table field `index` (Int) + +0x20AC | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x20B0 | 17 00 00 00 | uint32_t | 0x00000017 (23) | length of string + +0x20B4 | 74 65 73 74 61 72 72 61 | char[23] | testarra | string literal + +0x20BC | 79 6F 66 73 6F 72 74 65 | | yofsorte + +0x20C4 | 64 73 74 72 75 63 74 | | dstruct + +0x20CB | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x20CC | E4 F4 FF FF | SOffset32 | 0xFFFFF4E4 (-2844) Loc: 0x2BE8 | offset to vtable + +0x20D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x20D3 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x20D4 | 1C 00 | uint16_t | 0x001C (28) | table field `id` (UShort) + +0x20D6 | 3C 00 | uint16_t | 0x003C (60) | table field `offset` (UShort) + +0x20D8 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x2114 | offset to field `name` (string) + +0x20DC | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2108 | offset to field `type` (table) + +0x20E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x20E4 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x20E4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x20E8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x20EC | offset to table[0] + +table (reflection.KeyValue): + +0x20EC | 24 E8 FF FF | SOffset32 | 0xFFFFE824 (-6108) Loc: 0x38C8 | offset to vtable + +0x20F0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2100 | offset to field `key` (string) + +0x20F4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x20F8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x20F8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x20FC | 32 38 | char[2] | 28 | string literal + +0x20FE | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2100 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2104 | 69 64 | char[2] | id | string literal + +0x2106 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2108 | C8 F4 FF FF | SOffset32 | 0xFFFFF4C8 (-2872) Loc: 0x2C40 | offset to vtable + +0x210C | 00 00 | uint8_t[2] | .. | padding + +0x210E | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x210F | 0D | uint8_t | 0x0D (13) | table field `element` (Byte) + +0x2110 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2114 | 12 00 00 00 | uint32_t | 0x00000012 (18) | length of string + +0x2118 | 74 65 73 74 61 72 72 61 | char[18] | testarra | string literal + +0x2120 | 79 6F 66 73 74 72 69 6E | | yofstrin + +0x2128 | 67 32 | | g2 + +0x212A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x212C | 34 F6 FF FF | SOffset32 | 0xFFFFF634 (-2508) Loc: 0x2AF8 | offset to vtable + +0x2130 | 1B 00 | uint16_t | 0x001B (27) | table field `id` (UShort) + +0x2132 | 3A 00 | uint16_t | 0x003A (58) | table field `offset` (UShort) + +0x2134 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x2170 | offset to field `name` (string) + +0x2138 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2164 | offset to field `type` (table) + +0x213C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2140 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2140 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2144 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2148 | offset to table[0] + +table (reflection.KeyValue): + +0x2148 | 80 E8 FF FF | SOffset32 | 0xFFFFE880 (-6016) Loc: 0x38C8 | offset to vtable + +0x214C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x215C | offset to field `key` (string) + +0x2150 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2154 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2154 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2158 | 32 37 | char[2] | 27 | string literal + +0x215A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x215C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2160 | 69 64 | char[2] | id | string literal + +0x2162 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2164 | 88 E8 FF FF | SOffset32 | 0xFFFFE888 (-6008) Loc: 0x38DC | offset to vtable + +0x2168 | 00 00 00 | uint8_t[3] | ... | padding + +0x216B | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x216C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2170 | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of string + +0x2174 | 74 65 73 74 66 33 | char[6] | testf3 | string literal + +0x217A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x217C | A8 FF FF FF | SOffset32 | 0xFFFFFFA8 (-88) Loc: 0x21D4 | offset to vtable + +0x2180 | 1A 00 | uint16_t | 0x001A (26) | table field `id` (UShort) + +0x2182 | 38 00 | uint16_t | 0x0038 (56) | table field `offset` (UShort) + +0x2184 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x21C8 | offset to field `name` (string) + +0x2188 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x21BC | offset to field `type` (table) + +0x218C | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x2198 | offset to field `attributes` (vector) + +0x2190 | 00 00 00 00 00 00 08 40 | double | 0x4008000000000000 (3) | table field `default_real` (Double) + +vector (reflection.Field.attributes): + +0x2198 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x219C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x21A0 | offset to table[0] + +table (reflection.KeyValue): + +0x21A0 | D8 E8 FF FF | SOffset32 | 0xFFFFE8D8 (-5928) Loc: 0x38C8 | offset to vtable + +0x21A4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x21B4 | offset to field `key` (string) + +0x21A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x21AC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x21AC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x21B0 | 32 36 | char[2] | 26 | string literal + +0x21B2 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x21B4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x21B8 | 69 64 | char[2] | id | string literal + +0x21BA | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x21BC | E0 E8 FF FF | SOffset32 | 0xFFFFE8E0 (-5920) Loc: 0x38DC | offset to vtable + +0x21C0 | 00 00 00 | uint8_t[3] | ... | padding + +0x21C3 | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x21C4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x21C8 | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of string + +0x21CC | 74 65 73 74 66 32 | char[6] | testf2 | string literal + +0x21D2 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Field): + +0x21D4 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x21D6 | 1C 00 | uint16_t | 0x001C (28) | size of referring table + +0x21D8 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x21DA | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x21DC | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 2) + +0x21DE | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x21E0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x21E2 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `default_real` (id: 5) + +0x21E4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x21E6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x21E8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x21EA | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x21EC | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x21D4 | offset to vtable + +0x21F0 | 19 00 | uint16_t | 0x0019 (25) | table field `id` (UShort) + +0x21F2 | 36 00 | uint16_t | 0x0036 (54) | table field `offset` (UShort) + +0x21F4 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x2238 | offset to field `name` (string) + +0x21F8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x222C | offset to field `type` (table) + +0x21FC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x2208 | offset to field `attributes` (vector) + +0x2200 | 6E 86 1B F0 F9 21 09 40 | double | 0x400921F9F01B866E (3.14159) | table field `default_real` (Double) + +vector (reflection.Field.attributes): + +0x2208 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x220C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2210 | offset to table[0] + +table (reflection.KeyValue): + +0x2210 | 48 E9 FF FF | SOffset32 | 0xFFFFE948 (-5816) Loc: 0x38C8 | offset to vtable + +0x2214 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2224 | offset to field `key` (string) + +0x2218 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x221C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x221C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2220 | 32 35 | char[2] | 25 | string literal + +0x2222 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2224 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2228 | 69 64 | char[2] | id | string literal + +0x222A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x222C | 50 E9 FF FF | SOffset32 | 0xFFFFE950 (-5808) Loc: 0x38DC | offset to vtable + +0x2230 | 00 00 00 | uint8_t[3] | ... | padding + +0x2233 | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x2234 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2238 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x223C | 74 65 73 74 66 | char[5] | testf | string literal + +0x2241 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2242 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x2244 | 5C F6 FF FF | SOffset32 | 0xFFFFF65C (-2468) Loc: 0x2BE8 | offset to vtable + +0x2248 | 00 00 00 | uint8_t[3] | ... | padding + +0x224B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x224C | 18 00 | uint16_t | 0x0018 (24) | table field `id` (UShort) + +0x224E | 34 00 | uint16_t | 0x0034 (52) | table field `offset` (UShort) + +0x2250 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x228C | offset to field `name` (string) + +0x2254 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2280 | offset to field `type` (table) + +0x2258 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x225C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x225C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2260 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2264 | offset to table[0] + +table (reflection.KeyValue): + +0x2264 | 9C E9 FF FF | SOffset32 | 0xFFFFE99C (-5732) Loc: 0x38C8 | offset to vtable + +0x2268 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2278 | offset to field `key` (string) + +0x226C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2270 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2270 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2274 | 32 34 | char[2] | 24 | string literal + +0x2276 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2278 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x227C | 69 64 | char[2] | id | string literal + +0x227E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2280 | 40 F6 FF FF | SOffset32 | 0xFFFFF640 (-2496) Loc: 0x2C40 | offset to vtable + +0x2284 | 00 00 | uint8_t[2] | .. | padding + +0x2286 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x2287 | 02 | uint8_t | 0x02 (2) | table field `element` (Byte) + +0x2288 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x228C | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x2290 | 74 65 73 74 61 72 72 61 | char[16] | testarra | string literal + +0x2298 | 79 6F 66 62 6F 6F 6C 73 | | yofbools + +0x22A0 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x22A1 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x22A4 | AC F7 FF FF | SOffset32 | 0xFFFFF7AC (-2132) Loc: 0x2AF8 | offset to vtable + +0x22A8 | 17 00 | uint16_t | 0x0017 (23) | table field `id` (UShort) + +0x22AA | 32 00 | uint16_t | 0x0032 (50) | table field `offset` (UShort) + +0x22AC | 6C 00 00 00 | UOffset32 | 0x0000006C (108) Loc: 0x2318 | offset to field `name` (string) + +0x22B0 | 58 00 00 00 | UOffset32 | 0x00000058 (88) Loc: 0x2308 | offset to field `type` (table) + +0x22B4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x22B8 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x22B8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x22BC | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x22E0 | offset to table[0] + +0x22C0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x22C4 | offset to table[1] + +table (reflection.KeyValue): + +0x22C4 | FC E9 FF FF | SOffset32 | 0xFFFFE9FC (-5636) Loc: 0x38C8 | offset to vtable + +0x22C8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x22D8 | offset to field `key` (string) + +0x22CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x22D0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x22D0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x22D4 | 32 33 | char[2] | 23 | string literal + +0x22D6 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x22D8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x22DC | 69 64 | char[2] | id | string literal + +0x22DE | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x22E0 | 18 EA FF FF | SOffset32 | 0xFFFFEA18 (-5608) Loc: 0x38C8 | offset to vtable + +0x22E4 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x22FC | offset to field `key` (string) + +0x22E8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x22EC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x22EC | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x22F0 | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x22F8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x22F9 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x22FC | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2300 | 68 61 73 68 | char[4] | hash | string literal + +0x2304 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2305 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2308 | 94 EC FF FF | SOffset32 | 0xFFFFEC94 (-4972) Loc: 0x3674 | offset to vtable + +0x230C | 00 00 00 | uint8_t[3] | ... | padding + +0x230F | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x2310 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x2314 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2318 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x231C | 74 65 73 74 68 61 73 68 | char[17] | testhash | string literal + +0x2324 | 75 36 34 5F 66 6E 76 31 | | u64_fnv1 + +0x232C | 61 | | a + +0x232D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x232E | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x2330 | 38 F8 FF FF | SOffset32 | 0xFFFFF838 (-1992) Loc: 0x2AF8 | offset to vtable + +0x2334 | 16 00 | uint16_t | 0x0016 (22) | table field `id` (UShort) + +0x2336 | 30 00 | uint16_t | 0x0030 (48) | table field `offset` (UShort) + +0x2338 | 6C 00 00 00 | UOffset32 | 0x0000006C (108) Loc: 0x23A4 | offset to field `name` (string) + +0x233C | 58 00 00 00 | UOffset32 | 0x00000058 (88) Loc: 0x2394 | offset to field `type` (table) + +0x2340 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2344 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2344 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2348 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x236C | offset to table[0] + +0x234C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2350 | offset to table[1] + +table (reflection.KeyValue): + +0x2350 | 88 EA FF FF | SOffset32 | 0xFFFFEA88 (-5496) Loc: 0x38C8 | offset to vtable + +0x2354 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2364 | offset to field `key` (string) + +0x2358 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x235C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x235C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2360 | 32 32 | char[2] | 22 | string literal + +0x2362 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2364 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2368 | 69 64 | char[2] | id | string literal + +0x236A | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x236C | A4 EA FF FF | SOffset32 | 0xFFFFEAA4 (-5468) Loc: 0x38C8 | offset to vtable + +0x2370 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x2388 | offset to field `key` (string) + +0x2374 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2378 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2378 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x237C | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x2384 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2385 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x2388 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x238C | 68 61 73 68 | char[4] | hash | string literal + +0x2390 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2391 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2394 | 20 ED FF FF | SOffset32 | 0xFFFFED20 (-4832) Loc: 0x3674 | offset to vtable + +0x2398 | 00 00 00 | uint8_t[3] | ... | padding + +0x239B | 09 | uint8_t | 0x09 (9) | table field `base_type` (Byte) + +0x239C | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x23A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x23A4 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x23A8 | 74 65 73 74 68 61 73 68 | char[17] | testhash | string literal + +0x23B0 | 73 36 34 5F 66 6E 76 31 | | s64_fnv1 + +0x23B8 | 61 | | a + +0x23B9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x23BA | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x23BC | C4 F8 FF FF | SOffset32 | 0xFFFFF8C4 (-1852) Loc: 0x2AF8 | offset to vtable + +0x23C0 | 15 00 | uint16_t | 0x0015 (21) | table field `id` (UShort) + +0x23C2 | 2E 00 | uint16_t | 0x002E (46) | table field `offset` (UShort) + +0x23C4 | C4 00 00 00 | UOffset32 | 0x000000C4 (196) Loc: 0x2488 | offset to field `name` (string) + +0x23C8 | B4 00 00 00 | UOffset32 | 0x000000B4 (180) Loc: 0x247C | offset to field `type` (table) + +0x23CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x23D0 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x23D0 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of vector (# items) + +0x23D4 | 7C 00 00 00 | UOffset32 | 0x0000007C (124) Loc: 0x2450 | offset to table[0] + +0x23D8 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x2428 | offset to table[1] + +0x23DC | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x2400 | offset to table[2] + +0x23E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x23E4 | offset to table[3] + +table (reflection.KeyValue): + +0x23E4 | 1C EB FF FF | SOffset32 | 0xFFFFEB1C (-5348) Loc: 0x38C8 | offset to vtable + +0x23E8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x23F8 | offset to field `key` (string) + +0x23EC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x23F0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x23F0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x23F4 | 32 31 | char[2] | 21 | string literal + +0x23F6 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x23F8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x23FC | 69 64 | char[2] | id | string literal + +0x23FE | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2400 | 38 EB FF FF | SOffset32 | 0xFFFFEB38 (-5320) Loc: 0x38C8 | offset to vtable + +0x2404 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x241C | offset to field `key` (string) + +0x2408 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x240C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x240C | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x2410 | 66 6E 76 31 61 5F 33 32 | char[8] | fnv1a_32 | string literal + +0x2418 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2419 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x241C | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2420 | 68 61 73 68 | char[4] | hash | string literal + +0x2424 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2425 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x2428 | 60 EB FF FF | SOffset32 | 0xFFFFEB60 (-5280) Loc: 0x38C8 | offset to vtable + +0x242C | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x2440 | offset to field `key` (string) + +0x2430 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2434 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2434 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2438 | 53 74 61 74 | char[4] | Stat | string literal + +0x243C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x243D | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x2440 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x2444 | 63 70 70 5F 74 79 70 65 | char[8] | cpp_type | string literal + +0x244C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x244D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x2450 | 88 EB FF FF | SOffset32 | 0xFFFFEB88 (-5240) Loc: 0x38C8 | offset to vtable + +0x2454 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x2468 | offset to field `key` (string) + +0x2458 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x245C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x245C | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x2460 | 6E 61 6B 65 64 | char[5] | naked | string literal + +0x2465 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2466 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2468 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | length of string + +0x246C | 63 70 70 5F 70 74 72 5F | char[12] | cpp_ptr_ | string literal + +0x2474 | 74 79 70 65 | | type + +0x2478 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2479 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x247C | A0 EB FF FF | SOffset32 | 0xFFFFEBA0 (-5216) Loc: 0x38DC | offset to vtable + +0x2480 | 00 00 00 | uint8_t[3] | ... | padding + +0x2483 | 08 | uint8_t | 0x08 (8) | table field `base_type` (Byte) + +0x2484 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2488 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x248C | 74 65 73 74 68 61 73 68 | char[17] | testhash | string literal + +0x2494 | 75 33 32 5F 66 6E 76 31 | | u32_fnv1 + +0x249C | 61 | | a + +0x249D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x249E | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x24A0 | A8 F9 FF FF | SOffset32 | 0xFFFFF9A8 (-1624) Loc: 0x2AF8 | offset to vtable + +0x24A4 | 14 00 | uint16_t | 0x0014 (20) | table field `id` (UShort) + +0x24A6 | 2C 00 | uint16_t | 0x002C (44) | table field `offset` (UShort) + +0x24A8 | 68 00 00 00 | UOffset32 | 0x00000068 (104) Loc: 0x2510 | offset to field `name` (string) + +0x24AC | 58 00 00 00 | UOffset32 | 0x00000058 (88) Loc: 0x2504 | offset to field `type` (table) + +0x24B0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x24B4 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x24B4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x24B8 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x24DC | offset to table[0] + +0x24BC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x24C0 | offset to table[1] + +table (reflection.KeyValue): + +0x24C0 | F8 EB FF FF | SOffset32 | 0xFFFFEBF8 (-5128) Loc: 0x38C8 | offset to vtable + +0x24C4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x24D4 | offset to field `key` (string) + +0x24C8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x24CC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x24CC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x24D0 | 32 30 | char[2] | 20 | string literal + +0x24D2 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x24D4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x24D8 | 69 64 | char[2] | id | string literal + +0x24DA | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x24DC | 14 EC FF FF | SOffset32 | 0xFFFFEC14 (-5100) Loc: 0x38C8 | offset to vtable + +0x24E0 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x24F8 | offset to field `key` (string) + +0x24E4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x24E8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x24E8 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x24EC | 66 6E 76 31 61 5F 33 32 | char[8] | fnv1a_32 | string literal + +0x24F4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x24F5 | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x24F8 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x24FC | 68 61 73 68 | char[4] | hash | string literal + +0x2500 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2501 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2504 | 28 EC FF FF | SOffset32 | 0xFFFFEC28 (-5080) Loc: 0x38DC | offset to vtable + +0x2508 | 00 00 00 | uint8_t[3] | ... | padding + +0x250B | 07 | uint8_t | 0x07 (7) | table field `base_type` (Byte) + +0x250C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2510 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x2514 | 74 65 73 74 68 61 73 68 | char[17] | testhash | string literal + +0x251C | 73 33 32 5F 66 6E 76 31 | | s32_fnv1 + +0x2524 | 61 | | a + +0x2525 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2526 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x2528 | 30 FA FF FF | SOffset32 | 0xFFFFFA30 (-1488) Loc: 0x2AF8 | offset to vtable + +0x252C | 13 00 | uint16_t | 0x0013 (19) | table field `id` (UShort) + +0x252E | 2A 00 | uint16_t | 0x002A (42) | table field `offset` (UShort) + +0x2530 | 68 00 00 00 | UOffset32 | 0x00000068 (104) Loc: 0x2598 | offset to field `name` (string) + +0x2534 | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x2588 | offset to field `type` (table) + +0x2538 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x253C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x253C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2540 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x2564 | offset to table[0] + +0x2544 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2548 | offset to table[1] + +table (reflection.KeyValue): + +0x2548 | 80 EC FF FF | SOffset32 | 0xFFFFEC80 (-4992) Loc: 0x38C8 | offset to vtable + +0x254C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x255C | offset to field `key` (string) + +0x2550 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2554 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2554 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2558 | 31 39 | char[2] | 19 | string literal + +0x255A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x255C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2560 | 69 64 | char[2] | id | string literal + +0x2562 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2564 | 9C EC FF FF | SOffset32 | 0xFFFFEC9C (-4964) Loc: 0x38C8 | offset to vtable + +0x2568 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x257C | offset to field `key` (string) + +0x256C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2570 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2570 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x2574 | 66 6E 76 31 5F 36 34 | char[7] | fnv1_64 | string literal + +0x257B | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x257C | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2580 | 68 61 73 68 | char[4] | hash | string literal + +0x2584 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2585 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2588 | 14 EF FF FF | SOffset32 | 0xFFFFEF14 (-4332) Loc: 0x3674 | offset to vtable + +0x258C | 00 00 00 | uint8_t[3] | ... | padding + +0x258F | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x2590 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x2594 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2598 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x259C | 74 65 73 74 68 61 73 68 | char[16] | testhash | string literal + +0x25A4 | 75 36 34 5F 66 6E 76 31 | | u64_fnv1 + +0x25AC | 00 | char | 0x00 (0) | string terminator + +padding: + +0x25AD | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x25B0 | B8 FA FF FF | SOffset32 | 0xFFFFFAB8 (-1352) Loc: 0x2AF8 | offset to vtable + +0x25B4 | 12 00 | uint16_t | 0x0012 (18) | table field `id` (UShort) + +0x25B6 | 28 00 | uint16_t | 0x0028 (40) | table field `offset` (UShort) + +0x25B8 | 68 00 00 00 | UOffset32 | 0x00000068 (104) Loc: 0x2620 | offset to field `name` (string) + +0x25BC | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x2610 | offset to field `type` (table) + +0x25C0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x25C4 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x25C4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x25C8 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x25EC | offset to table[0] + +0x25CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x25D0 | offset to table[1] + +table (reflection.KeyValue): + +0x25D0 | 08 ED FF FF | SOffset32 | 0xFFFFED08 (-4856) Loc: 0x38C8 | offset to vtable + +0x25D4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x25E4 | offset to field `key` (string) + +0x25D8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x25DC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x25DC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x25E0 | 31 38 | char[2] | 18 | string literal + +0x25E2 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x25E4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x25E8 | 69 64 | char[2] | id | string literal + +0x25EA | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x25EC | 24 ED FF FF | SOffset32 | 0xFFFFED24 (-4828) Loc: 0x38C8 | offset to vtable + +0x25F0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x2604 | offset to field `key` (string) + +0x25F4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x25F8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x25F8 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x25FC | 66 6E 76 31 5F 36 34 | char[7] | fnv1_64 | string literal + +0x2603 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2604 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2608 | 68 61 73 68 | char[4] | hash | string literal + +0x260C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x260D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2610 | 9C EF FF FF | SOffset32 | 0xFFFFEF9C (-4196) Loc: 0x3674 | offset to vtable + +0x2614 | 00 00 00 | uint8_t[3] | ... | padding + +0x2617 | 09 | uint8_t | 0x09 (9) | table field `base_type` (Byte) + +0x2618 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x261C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2620 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x2624 | 74 65 73 74 68 61 73 68 | char[16] | testhash | string literal + +0x262C | 73 36 34 5F 66 6E 76 31 | | s64_fnv1 + +0x2634 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2635 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x2638 | 40 FB FF FF | SOffset32 | 0xFFFFFB40 (-1216) Loc: 0x2AF8 | offset to vtable + +0x263C | 11 00 | uint16_t | 0x0011 (17) | table field `id` (UShort) + +0x263E | 26 00 | uint16_t | 0x0026 (38) | table field `offset` (UShort) + +0x2640 | 64 00 00 00 | UOffset32 | 0x00000064 (100) Loc: 0x26A4 | offset to field `name` (string) + +0x2644 | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x2698 | offset to field `type` (table) + +0x2648 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x264C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x264C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2650 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x2674 | offset to table[0] + +0x2654 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2658 | offset to table[1] + +table (reflection.KeyValue): + +0x2658 | 90 ED FF FF | SOffset32 | 0xFFFFED90 (-4720) Loc: 0x38C8 | offset to vtable + +0x265C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x266C | offset to field `key` (string) + +0x2660 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2664 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2664 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2668 | 31 37 | char[2] | 17 | string literal + +0x266A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x266C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2670 | 69 64 | char[2] | id | string literal + +0x2672 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2674 | AC ED FF FF | SOffset32 | 0xFFFFEDAC (-4692) Loc: 0x38C8 | offset to vtable + +0x2678 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x268C | offset to field `key` (string) + +0x267C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2680 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2680 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x2684 | 66 6E 76 31 5F 33 32 | char[7] | fnv1_32 | string literal + +0x268B | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x268C | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2690 | 68 61 73 68 | char[4] | hash | string literal + +0x2694 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2695 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2698 | BC ED FF FF | SOffset32 | 0xFFFFEDBC (-4676) Loc: 0x38DC | offset to vtable + +0x269C | 00 00 00 | uint8_t[3] | ... | padding + +0x269F | 08 | uint8_t | 0x08 (8) | table field `base_type` (Byte) + +0x26A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x26A4 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x26A8 | 74 65 73 74 68 61 73 68 | char[16] | testhash | string literal + +0x26B0 | 75 33 32 5F 66 6E 76 31 | | u32_fnv1 + +0x26B8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x26B9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x26BC | C4 FB FF FF | SOffset32 | 0xFFFFFBC4 (-1084) Loc: 0x2AF8 | offset to vtable + +0x26C0 | 10 00 | uint16_t | 0x0010 (16) | table field `id` (UShort) + +0x26C2 | 24 00 | uint16_t | 0x0024 (36) | table field `offset` (UShort) + +0x26C4 | 64 00 00 00 | UOffset32 | 0x00000064 (100) Loc: 0x2728 | offset to field `name` (string) + +0x26C8 | 54 00 00 00 | UOffset32 | 0x00000054 (84) Loc: 0x271C | offset to field `type` (table) + +0x26CC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x26D0 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x26D0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x26D4 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x26F8 | offset to table[0] + +0x26D8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x26DC | offset to table[1] + +table (reflection.KeyValue): + +0x26DC | 14 EE FF FF | SOffset32 | 0xFFFFEE14 (-4588) Loc: 0x38C8 | offset to vtable + +0x26E0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x26F0 | offset to field `key` (string) + +0x26E4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x26E8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x26E8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x26EC | 31 36 | char[2] | 16 | string literal + +0x26EE | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x26F0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x26F4 | 69 64 | char[2] | id | string literal + +0x26F6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x26F8 | 30 EE FF FF | SOffset32 | 0xFFFFEE30 (-4560) Loc: 0x38C8 | offset to vtable + +0x26FC | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x2710 | offset to field `key` (string) + +0x2700 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2704 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2704 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x2708 | 66 6E 76 31 5F 33 32 | char[7] | fnv1_32 | string literal + +0x270F | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2710 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2714 | 68 61 73 68 | char[4] | hash | string literal + +0x2718 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2719 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x271C | 40 EE FF FF | SOffset32 | 0xFFFFEE40 (-4544) Loc: 0x38DC | offset to vtable + +0x2720 | 00 00 00 | uint8_t[3] | ... | padding + +0x2723 | 07 | uint8_t | 0x07 (7) | table field `base_type` (Byte) + +0x2724 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2728 | 10 00 00 00 | uint32_t | 0x00000010 (16) | length of string + +0x272C | 74 65 73 74 68 61 73 68 | char[16] | testhash | string literal + +0x2734 | 73 33 32 5F 66 6E 76 31 | | s32_fnv1 + +0x273C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x273D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x2740 | 48 FC FF FF | SOffset32 | 0xFFFFFC48 (-952) Loc: 0x2AF8 | offset to vtable + +0x2744 | 0F 00 | uint16_t | 0x000F (15) | table field `id` (UShort) + +0x2746 | 22 00 | uint16_t | 0x0022 (34) | table field `offset` (UShort) + +0x2748 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x2788 | offset to field `name` (string) + +0x274C | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2778 | offset to field `type` (table) + +0x2750 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2754 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2754 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2758 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x275C | offset to table[0] + +table (reflection.KeyValue): + +0x275C | 94 EE FF FF | SOffset32 | 0xFFFFEE94 (-4460) Loc: 0x38C8 | offset to vtable + +0x2760 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2770 | offset to field `key` (string) + +0x2764 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2768 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2768 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x276C | 31 35 | char[2] | 15 | string literal + +0x276E | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2770 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2774 | 69 64 | char[2] | id | string literal + +0x2776 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2778 | 04 F1 FF FF | SOffset32 | 0xFFFFF104 (-3836) Loc: 0x3674 | offset to vtable + +0x277C | 00 00 00 | uint8_t[3] | ... | padding + +0x277F | 02 | uint8_t | 0x02 (2) | table field `base_type` (Byte) + +0x2780 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x2784 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2788 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x278C | 74 65 73 74 62 6F 6F 6C | char[8] | testbool | string literal + +0x2794 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2795 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x2798 | B0 FB FF FF | SOffset32 | 0xFFFFFBB0 (-1104) Loc: 0x2BE8 | offset to vtable + +0x279C | 00 00 00 | uint8_t[3] | ... | padding + +0x279F | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x27A0 | 0E 00 | uint16_t | 0x000E (14) | table field `id` (UShort) + +0x27A2 | 20 00 | uint16_t | 0x0020 (32) | table field `offset` (UShort) + +0x27A4 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x27E4 | offset to field `name` (string) + +0x27A8 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x27D4 | offset to field `type` (table) + +0x27AC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x27B0 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x27B0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x27B4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x27B8 | offset to table[0] + +table (reflection.KeyValue): + +0x27B8 | F0 EE FF FF | SOffset32 | 0xFFFFEEF0 (-4368) Loc: 0x38C8 | offset to vtable + +0x27BC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x27CC | offset to field `key` (string) + +0x27C0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x27C4 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x27C4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x27C8 | 31 34 | char[2] | 14 | string literal + +0x27CA | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x27CC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x27D0 | 69 64 | char[2] | id | string literal + +0x27D2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x27D4 | BC EF FF FF | SOffset32 | 0xFFFFEFBC (-4164) Loc: 0x3818 | offset to vtable + +0x27D8 | 00 00 00 | uint8_t[3] | ... | padding + +0x27DB | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x27DC | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x27E0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x27E4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x27E8 | 74 65 73 74 65 6D 70 74 | char[9] | testempt | string literal + +0x27F0 | 79 | | y + +0x27F1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x27F2 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x27F4 | 0C FC FF FF | SOffset32 | 0xFFFFFC0C (-1012) Loc: 0x2BE8 | offset to vtable + +0x27F8 | 00 00 00 | uint8_t[3] | ... | padding + +0x27FB | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x27FC | 0D 00 | uint16_t | 0x000D (13) | table field `id` (UShort) + +0x27FE | 1E 00 | uint16_t | 0x001E (30) | table field `offset` (UShort) + +0x2800 | 70 00 00 00 | UOffset32 | 0x00000070 (112) Loc: 0x2870 | offset to field `name` (string) + +0x2804 | 60 00 00 00 | UOffset32 | 0x00000060 (96) Loc: 0x2864 | offset to field `type` (table) + +0x2808 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x280C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x280C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2810 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x2848 | offset to table[0] + +0x2814 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2818 | offset to table[1] + +table (reflection.KeyValue): + +0x2818 | 50 EF FF FF | SOffset32 | 0xFFFFEF50 (-4272) Loc: 0x38C8 | offset to vtable + +0x281C | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x2830 | offset to field `key` (string) + +0x2820 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2824 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2824 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x2828 | 4D 6F 6E 73 74 65 72 | char[7] | Monster | string literal + +0x282F | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2830 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x2834 | 6E 65 73 74 65 64 5F 66 | char[17] | nested_f | string literal + +0x283C | 6C 61 74 62 75 66 66 65 | | latbuffe + +0x2844 | 72 | | r + +0x2845 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2846 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.KeyValue): + +0x2848 | 80 EF FF FF | SOffset32 | 0xFFFFEF80 (-4224) Loc: 0x38C8 | offset to vtable + +0x284C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x285C | offset to field `key` (string) + +0x2850 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2854 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2854 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2858 | 31 33 | char[2] | 13 | string literal + +0x285A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x285C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2860 | 69 64 | char[2] | id | string literal + +0x2862 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2864 | 24 FC FF FF | SOffset32 | 0xFFFFFC24 (-988) Loc: 0x2C40 | offset to vtable + +0x2868 | 00 00 | uint8_t[2] | .. | padding + +0x286A | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x286B | 04 | uint8_t | 0x04 (4) | table field `element` (Byte) + +0x286C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2870 | 14 00 00 00 | uint32_t | 0x00000014 (20) | length of string + +0x2874 | 74 65 73 74 6E 65 73 74 | char[20] | testnest | string literal + +0x287C | 65 64 66 6C 61 74 62 75 | | edflatbu + +0x2884 | 66 66 65 72 | | ffer + +0x2888 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2889 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x288C | A4 FC FF FF | SOffset32 | 0xFFFFFCA4 (-860) Loc: 0x2BE8 | offset to vtable + +0x2890 | 00 00 00 | uint8_t[3] | ... | padding + +0x2893 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x2894 | 0C 00 | uint16_t | 0x000C (12) | table field `id` (UShort) + +0x2896 | 1C 00 | uint16_t | 0x001C (28) | table field `offset` (UShort) + +0x2898 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x28D8 | offset to field `name` (string) + +0x289C | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x28C8 | offset to field `type` (table) + +0x28A0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x28A4 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x28A4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x28A8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x28AC | offset to table[0] + +table (reflection.KeyValue): + +0x28AC | E4 EF FF FF | SOffset32 | 0xFFFFEFE4 (-4124) Loc: 0x38C8 | offset to vtable + +0x28B0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x28C0 | offset to field `key` (string) + +0x28B4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x28B8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x28B8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x28BC | 31 32 | char[2] | 12 | string literal + +0x28BE | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x28C0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x28C4 | 69 64 | char[2] | id | string literal + +0x28C6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x28C8 | B0 F0 FF FF | SOffset32 | 0xFFFFF0B0 (-3920) Loc: 0x3818 | offset to vtable + +0x28CC | 00 00 00 | uint8_t[3] | ... | padding + +0x28CF | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x28D0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x28D4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x28D8 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x28DC | 65 6E 65 6D 79 | char[5] | enemy | string literal + +0x28E1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x28E2 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x28E4 | 1C 00 | uint16_t | 0x001C (28) | size of this vtable + +0x28E6 | 1C 00 | uint16_t | 0x001C (28) | size of referring table + +0x28E8 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x28EA | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x28EC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 2) + +0x28EE | 0A 00 | VOffset16 | 0x000A (10) | offset to field `offset` (id: 3) + +0x28F0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x28F2 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x28F4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x28F6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x28F8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x28FA | 14 00 | VOffset16 | 0x0014 (20) | offset to field `attributes` (id: 9) + +0x28FC | 18 00 | VOffset16 | 0x0018 (24) | offset to field `documentation` (id: 10) + +0x28FE | 07 00 | VOffset16 | 0x0007 (7) | offset to field `optional` (id: 11) + +table (reflection.Field): + +0x2900 | 1C 00 00 00 | SOffset32 | 0x0000001C (28) Loc: 0x28E4 | offset to vtable + +0x2904 | 00 00 00 | uint8_t[3] | ... | padding + +0x2907 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x2908 | 0B 00 | uint16_t | 0x000B (11) | table field `id` (UShort) + +0x290A | 1A 00 | uint16_t | 0x001A (26) | table field `offset` (UShort) + +0x290C | B4 00 00 00 | UOffset32 | 0x000000B4 (180) Loc: 0x29C0 | offset to field `name` (string) + +0x2910 | A0 00 00 00 | UOffset32 | 0x000000A0 (160) Loc: 0x29B0 | offset to field `type` (table) + +0x2914 | 78 00 00 00 | UOffset32 | 0x00000078 (120) Loc: 0x298C | offset to field `attributes` (vector) + +0x2918 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x291C | offset to field `documentation` (vector) + +vector (reflection.Field.documentation): + +0x291C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2920 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x293C | offset to string[0] + +0x2924 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2928 | offset to string[1] + +string (reflection.Field.documentation): + +0x2928 | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of string + +0x292C | 20 6D 75 6C 74 69 6C 69 | char[14] | multili | string literal + +0x2934 | 6E 65 20 74 6F 6F | | ne too + +0x293A | 00 | char | 0x00 (0) | string terminator + +string (reflection.Field.documentation): + +0x293C | 49 00 00 00 | uint32_t | 0x00000049 (73) | length of string + +0x2940 | 20 61 6E 20 65 78 61 6D | char[73] | an exam | string literal + +0x2948 | 70 6C 65 20 64 6F 63 75 | | ple docu + +0x2950 | 6D 65 6E 74 61 74 69 6F | | mentatio + +0x2958 | 6E 20 63 6F 6D 6D 65 6E | | n commen + +0x2960 | 74 3A 20 74 68 69 73 20 | | t: this + +0x2968 | 77 69 6C 6C 20 65 6E 64 | | will end + +0x2970 | 20 75 70 20 69 6E 20 74 | | up in t + +0x2978 | 68 65 20 67 65 6E 65 72 | | he gener + +0x2980 | 61 74 65 64 20 63 6F 64 | | ated cod + +0x2988 | 65 | | e + +0x2989 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x298A | 00 00 | uint8_t[2] | .. | padding + +vector (reflection.Field.attributes): + +0x298C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2990 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2994 | offset to table[0] + +table (reflection.KeyValue): + +0x2994 | CC F0 FF FF | SOffset32 | 0xFFFFF0CC (-3892) Loc: 0x38C8 | offset to vtable + +0x2998 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x29A8 | offset to field `key` (string) + +0x299C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x29A0 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x29A0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x29A4 | 31 31 | char[2] | 11 | string literal + +0x29A6 | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x29A8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x29AC | 69 64 | char[2] | id | string literal + +0x29AE | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x29B0 | 3C FF FF FF | SOffset32 | 0xFFFFFF3C (-196) Loc: 0x2A74 | offset to vtable + +0x29B4 | 00 00 | uint8_t[2] | .. | padding + +0x29B6 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x29B7 | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x29B8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `index` (Int) + +0x29BC | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x29C0 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x29C4 | 74 65 73 74 61 72 72 61 | char[17] | testarra | string literal + +0x29CC | 79 6F 66 74 61 62 6C 65 | | yoftable + +0x29D4 | 73 | | s + +0x29D5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x29D6 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x29D8 | F0 FD FF FF | SOffset32 | 0xFFFFFDF0 (-528) Loc: 0x2BE8 | offset to vtable + +0x29DC | 00 00 00 | uint8_t[3] | ... | padding + +0x29DF | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x29E0 | 0A 00 | uint16_t | 0x000A (10) | table field `id` (UShort) + +0x29E2 | 18 00 | uint16_t | 0x0018 (24) | table field `offset` (UShort) + +0x29E4 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x2A20 | offset to field `name` (string) + +0x29E8 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2A14 | offset to field `type` (table) + +0x29EC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x29F0 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x29F0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x29F4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x29F8 | offset to table[0] + +table (reflection.KeyValue): + +0x29F8 | 30 F1 FF FF | SOffset32 | 0xFFFFF130 (-3792) Loc: 0x38C8 | offset to vtable + +0x29FC | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2A0C | offset to field `key` (string) + +0x2A00 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2A04 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2A04 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2A08 | 31 30 | char[2] | 10 | string literal + +0x2A0A | 00 | char | 0x00 (0) | string terminator + +string (reflection.KeyValue.key): + +0x2A0C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2A10 | 69 64 | char[2] | id | string literal + +0x2A12 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2A14 | D4 FD FF FF | SOffset32 | 0xFFFFFDD4 (-556) Loc: 0x2C40 | offset to vtable + +0x2A18 | 00 00 | uint8_t[2] | .. | padding + +0x2A1A | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x2A1B | 0D | uint8_t | 0x0D (13) | table field `element` (Byte) + +0x2A1C | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2A20 | 11 00 00 00 | uint32_t | 0x00000011 (17) | length of string + +0x2A24 | 74 65 73 74 61 72 72 61 | char[17] | testarra | string literal + +0x2A2C | 79 6F 66 73 74 72 69 6E | | yofstrin + +0x2A34 | 67 | | g + +0x2A35 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2A36 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x2A38 | 50 FE FF FF | SOffset32 | 0xFFFFFE50 (-432) Loc: 0x2BE8 | offset to vtable + +0x2A3C | 00 00 00 | uint8_t[3] | ... | padding + +0x2A3F | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x2A40 | 09 00 | uint16_t | 0x0009 (9) | table field `id` (UShort) + +0x2A42 | 16 00 | uint16_t | 0x0016 (22) | table field `offset` (UShort) + +0x2A44 | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x2A94 | offset to field `name` (string) + +0x2A48 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x2A84 | offset to field `type` (table) + +0x2A4C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2A50 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2A50 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2A54 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2A58 | offset to table[0] + +table (reflection.KeyValue): + +0x2A58 | 90 F1 FF FF | SOffset32 | 0xFFFFF190 (-3696) Loc: 0x38C8 | offset to vtable + +0x2A5C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2A6C | offset to field `key` (string) + +0x2A60 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2A64 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2A64 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2A68 | 39 | char[1] | 9 | string literal + +0x2A69 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2A6A | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2A6C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2A70 | 69 64 | char[2] | id | string literal + +0x2A72 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Type): + +0x2A74 | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x2A76 | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x2A78 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `base_type` (id: 0) + +0x2A7A | 07 00 | VOffset16 | 0x0007 (7) | offset to field `element` (id: 1) + +0x2A7C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `index` (id: 2) + +0x2A7E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x2A80 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `base_size` (id: 4) (UInt) + +0x2A82 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x2A84 | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x2A74 | offset to vtable + +0x2A88 | 00 00 | uint8_t[2] | .. | padding + +0x2A8A | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x2A8B | 0F | uint8_t | 0x0F (15) | table field `element` (Byte) + +0x2A8C | 06 00 00 00 | uint32_t | 0x00000006 (6) | table field `index` (Int) + +0x2A90 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2A94 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x2A98 | 74 65 73 74 34 | char[5] | test4 | string literal + +0x2A9D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2A9E | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x2AA0 | B8 FE FF FF | SOffset32 | 0xFFFFFEB8 (-328) Loc: 0x2BE8 | offset to vtable + +0x2AA4 | 00 00 00 | uint8_t[3] | ... | padding + +0x2AA7 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x2AA8 | 08 00 | uint16_t | 0x0008 (8) | table field `id` (UShort) + +0x2AAA | 14 00 | uint16_t | 0x0014 (20) | table field `offset` (UShort) + +0x2AAC | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x2AEC | offset to field `name` (string) + +0x2AB0 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2ADC | offset to field `type` (table) + +0x2AB4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2AB8 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2AB8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2ABC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2AC0 | offset to table[0] + +table (reflection.KeyValue): + +0x2AC0 | F8 F1 FF FF | SOffset32 | 0xFFFFF1F8 (-3592) Loc: 0x38C8 | offset to vtable + +0x2AC4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2AD4 | offset to field `key` (string) + +0x2AC8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2ACC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2ACC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2AD0 | 38 | char[1] | 8 | string literal + +0x2AD1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2AD2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2AD4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2AD8 | 69 64 | char[2] | id | string literal + +0x2ADA | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2ADC | C4 F2 FF FF | SOffset32 | 0xFFFFF2C4 (-3388) Loc: 0x3818 | offset to vtable + +0x2AE0 | 00 00 00 | uint8_t[3] | ... | padding + +0x2AE3 | 10 | uint8_t | 0x10 (16) | table field `base_type` (Byte) + +0x2AE4 | 00 00 00 00 | uint32_t | 0x00000000 (0) | table field `index` (Int) + +0x2AE8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2AEC | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2AF0 | 74 65 73 74 | char[4] | test | string literal + +0x2AF4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2AF5 | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.Field): + +0x2AF8 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x2AFA | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x2AFC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x2AFE | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x2B00 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 2) + +0x2B02 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x2B04 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x2B06 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2B08 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2B0A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2B0C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x2B0E | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x2B10 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x2AF8 | offset to vtable + +0x2B14 | 07 00 | uint16_t | 0x0007 (7) | table field `id` (UShort) + +0x2B16 | 12 00 | uint16_t | 0x0012 (18) | table field `offset` (UShort) + +0x2B18 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x2B5C | offset to field `name` (string) + +0x2B1C | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2B48 | offset to field `type` (table) + +0x2B20 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2B24 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2B24 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2B28 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2B2C | offset to table[0] + +table (reflection.KeyValue): + +0x2B2C | 64 F2 FF FF | SOffset32 | 0xFFFFF264 (-3484) Loc: 0x38C8 | offset to vtable + +0x2B30 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2B40 | offset to field `key` (string) + +0x2B34 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2B38 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2B38 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2B3C | 37 | char[1] | 7 | string literal + +0x2B3D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2B3E | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2B40 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2B44 | 69 64 | char[2] | id | string literal + +0x2B46 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2B48 | 9C F5 FF FF | SOffset32 | 0xFFFFF59C (-2660) Loc: 0x35AC | offset to vtable + +0x2B4C | 00 00 00 | uint8_t[3] | ... | padding + +0x2B4F | 01 | uint8_t | 0x01 (1) | table field `base_type` (Byte) + +0x2B50 | 00 00 00 00 | uint32_t | 0x00000000 (0) | table field `index` (Int) + +0x2B54 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x2B58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2B5C | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x2B60 | 74 65 73 74 5F 74 79 70 | char[9] | test_typ | string literal + +0x2B68 | 65 | | e + +0x2B69 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2B6A | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x2B6C | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x2B6E | 20 00 | uint16_t | 0x0020 (32) | size of referring table + +0x2B70 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x2B72 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x2B74 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 2) + +0x2B76 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x2B78 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `default_integer` (id: 4) + +0x2B7A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2B7C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2B7E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2B80 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x2B82 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x2B84 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x2B6C | offset to vtable + +0x2B88 | 06 00 | uint16_t | 0x0006 (6) | table field `id` (UShort) + +0x2B8A | 10 00 | uint16_t | 0x0010 (16) | table field `offset` (UShort) + +0x2B8C | 50 00 00 00 | UOffset32 | 0x00000050 (80) Loc: 0x2BDC | offset to field `name` (string) + +0x2B90 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x2BC8 | offset to field `type` (table) + +0x2B94 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2BA4 | offset to field `attributes` (vector) + +0x2B98 | 08 00 00 00 00 00 00 00 | int64_t | 0x0000000000000008 (8) | table field `default_integer` (Long) + +0x2BA0 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (reflection.Field.attributes): + +0x2BA4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2BA8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2BAC | offset to table[0] + +table (reflection.KeyValue): + +0x2BAC | E4 F2 FF FF | SOffset32 | 0xFFFFF2E4 (-3356) Loc: 0x38C8 | offset to vtable + +0x2BB0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2BC0 | offset to field `key` (string) + +0x2BB4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2BB8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2BB8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2BBC | 36 | char[1] | 6 | string literal + +0x2BBD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2BBE | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2BC0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2BC4 | 69 64 | char[2] | id | string literal + +0x2BC6 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2BC8 | 1C F6 FF FF | SOffset32 | 0xFFFFF61C (-2532) Loc: 0x35AC | offset to vtable + +0x2BCC | 00 00 00 | uint8_t[3] | ... | padding + +0x2BCF | 04 | uint8_t | 0x04 (4) | table field `base_type` (Byte) + +0x2BD0 | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x2BD4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x2BD8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2BDC | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x2BE0 | 63 6F 6C 6F 72 | char[5] | color | string literal + +0x2BE5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2BE6 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x2BE8 | 1C 00 | uint16_t | 0x001C (28) | size of this vtable + +0x2BEA | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x2BEC | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x2BEE | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x2BF0 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 2) + +0x2BF2 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `offset` (id: 3) + +0x2BF4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x2BF6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2BF8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2BFA | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2BFC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x2BFE | 14 00 | VOffset16 | 0x0014 (20) | offset to field `attributes` (id: 9) + +0x2C00 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x2C02 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `optional` (id: 11) + +table (reflection.Field): + +0x2C04 | 1C 00 00 00 | SOffset32 | 0x0000001C (28) Loc: 0x2BE8 | offset to vtable + +0x2C08 | 00 00 00 | uint8_t[3] | ... | padding + +0x2C0B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x2C0C | 05 00 | uint16_t | 0x0005 (5) | table field `id` (UShort) + +0x2C0E | 0E 00 | uint16_t | 0x000E (14) | table field `offset` (UShort) + +0x2C10 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: 0x2C5C | offset to field `name` (string) + +0x2C14 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x2C50 | offset to field `type` (table) + +0x2C18 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2C1C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2C1C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2C20 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2C24 | offset to table[0] + +table (reflection.KeyValue): + +0x2C24 | 5C F3 FF FF | SOffset32 | 0xFFFFF35C (-3236) Loc: 0x38C8 | offset to vtable + +0x2C28 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2C38 | offset to field `key` (string) + +0x2C2C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2C30 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2C30 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2C34 | 35 | char[1] | 5 | string literal + +0x2C35 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2C36 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2C38 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2C3C | 69 64 | char[2] | id | string literal + +0x2C3E | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Type): + +0x2C40 | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x2C42 | 0C 00 | uint16_t | 0x000C (12) | size of referring table + +0x2C44 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `base_type` (id: 0) + +0x2C46 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `element` (id: 1) + +0x2C48 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `index` (id: 2) (Int) + +0x2C4A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x2C4C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `base_size` (id: 4) (UInt) + +0x2C4E | 08 00 | VOffset16 | 0x0008 (8) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x2C50 | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x2C40 | offset to vtable + +0x2C54 | 00 00 | uint8_t[2] | .. | padding + +0x2C56 | 0E | uint8_t | 0x0E (14) | table field `base_type` (Byte) + +0x2C57 | 04 | uint8_t | 0x04 (4) | table field `element` (Byte) + +0x2C58 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2C5C | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x2C60 | 69 6E 76 65 6E 74 6F 72 | char[9] | inventor | string literal + +0x2C68 | 79 | | y + +0x2C69 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2C6A | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x2C6C | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x2C6E | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x2C70 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x2C72 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x2C74 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 2) + +0x2C76 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `offset` (id: 3) + +0x2C78 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x2C7A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2C7C | 07 00 | VOffset16 | 0x0007 (7) | offset to field `deprecated` (id: 6) + +0x2C7E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2C80 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x2C82 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x2C84 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x2C6C | offset to vtable + +0x2C88 | 00 00 00 | uint8_t[3] | ... | padding + +0x2C8B | 01 | uint8_t | 0x01 (1) | table field `deprecated` (Bool) + +0x2C8C | 04 00 | uint16_t | 0x0004 (4) | table field `id` (UShort) + +0x2C8E | 0C 00 | uint16_t | 0x000C (12) | table field `offset` (UShort) + +0x2C90 | 90 00 00 00 | UOffset32 | 0x00000090 (144) Loc: 0x2D20 | offset to field `name` (string) + +0x2C94 | 7C 00 00 00 | UOffset32 | 0x0000007C (124) Loc: 0x2D10 | offset to field `type` (table) + +0x2C98 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2C9C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2C9C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x2CA0 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: 0x2CEC | offset to table[0] + +0x2CA4 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2CD0 | offset to table[1] + +0x2CA8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2CAC | offset to table[2] + +table (reflection.KeyValue): + +0x2CAC | E4 F3 FF FF | SOffset32 | 0xFFFFF3E4 (-3100) Loc: 0x38C8 | offset to vtable + +0x2CB0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2CC0 | offset to field `key` (string) + +0x2CB4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2CB8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2CB8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2CBC | 31 | char[1] | 1 | string literal + +0x2CBD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2CBE | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2CC0 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x2CC4 | 70 72 69 6F 72 69 74 79 | char[8] | priority | string literal + +0x2CCC | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2CCD | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.KeyValue): + +0x2CD0 | 08 F4 FF FF | SOffset32 | 0xFFFFF408 (-3064) Loc: 0x38C8 | offset to vtable + +0x2CD4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2CE4 | offset to field `key` (string) + +0x2CD8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2CDC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2CDC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2CE0 | 34 | char[1] | 4 | string literal + +0x2CE1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2CE2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2CE4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2CE8 | 69 64 | char[2] | id | string literal + +0x2CEA | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2CEC | 24 F4 FF FF | SOffset32 | 0xFFFFF424 (-3036) Loc: 0x38C8 | offset to vtable + +0x2CF0 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2D00 | offset to field `key` (string) + +0x2CF4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2CF8 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2CF8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2CFC | 30 | char[1] | 0 | string literal + +0x2CFD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2CFE | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2D00 | 0A 00 00 00 | uint32_t | 0x0000000A (10) | length of string + +0x2D04 | 64 65 70 72 65 63 61 74 | char[10] | deprecat | string literal + +0x2D0C | 65 64 | | ed + +0x2D0E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2D10 | 9C F6 FF FF | SOffset32 | 0xFFFFF69C (-2404) Loc: 0x3674 | offset to vtable + +0x2D14 | 00 00 00 | uint8_t[3] | ... | padding + +0x2D17 | 02 | uint8_t | 0x02 (2) | table field `base_type` (Byte) + +0x2D18 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x2D1C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2D20 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x2D24 | 66 72 69 65 6E 64 6C 79 | char[8] | friendly | string literal + +0x2D2C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2D2D | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.Field): + +0x2D30 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x2D32 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x2D34 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x2D36 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x2D38 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 2) + +0x2D3A | 0A 00 | VOffset16 | 0x000A (10) | offset to field `offset` (id: 3) + +0x2D3C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x2D3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2D40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2D42 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `required` (id: 7) + +0x2D44 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `key` (id: 8) + +0x2D46 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x2D48 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x2D30 | offset to vtable + +0x2D4C | 00 00 | uint8_t[2] | .. | padding + +0x2D4E | 01 | uint8_t | 0x01 (1) | table field `required` (Bool) + +0x2D4F | 01 | uint8_t | 0x01 (1) | table field `key` (Bool) + +0x2D50 | 03 00 | uint16_t | 0x0003 (3) | table field `id` (UShort) + +0x2D52 | 0A 00 | uint16_t | 0x000A (10) | table field `offset` (UShort) + +0x2D54 | 5C 00 00 00 | UOffset32 | 0x0000005C (92) Loc: 0x2DB0 | offset to field `name` (string) + +0x2D58 | 4C 00 00 00 | UOffset32 | 0x0000004C (76) Loc: 0x2DA4 | offset to field `type` (table) + +0x2D5C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2D60 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2D60 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2D64 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x2D88 | offset to table[0] + +0x2D68 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2D6C | offset to table[1] + +table (reflection.KeyValue): + +0x2D6C | A4 F4 FF FF | SOffset32 | 0xFFFFF4A4 (-2908) Loc: 0x38C8 | offset to vtable + +0x2D70 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2D80 | offset to field `key` (string) + +0x2D74 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2D78 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2D78 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2D7C | 30 | char[1] | 0 | string literal + +0x2D7D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2D7E | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2D80 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x2D84 | 6B 65 79 | char[3] | key | string literal + +0x2D87 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2D88 | C0 F4 FF FF | SOffset32 | 0xFFFFF4C0 (-2880) Loc: 0x38C8 | offset to vtable + +0x2D8C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2D9C | offset to field `key` (string) + +0x2D90 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2D94 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2D94 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2D98 | 33 | char[1] | 3 | string literal + +0x2D99 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2D9A | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2D9C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2DA0 | 69 64 | char[2] | id | string literal + +0x2DA2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2DA4 | C8 F4 FF FF | SOffset32 | 0xFFFFF4C8 (-2872) Loc: 0x38DC | offset to vtable + +0x2DA8 | 00 00 00 | uint8_t[3] | ... | padding + +0x2DAB | 0D | uint8_t | 0x0D (13) | table field `base_type` (Byte) + +0x2DAC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2DB0 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2DB4 | 6E 61 6D 65 | char[4] | name | string literal + +0x2DB8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2DB9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Field): + +0x2DBC | A8 FF FF FF | SOffset32 | 0xFFFFFFA8 (-88) Loc: 0x2E14 | offset to vtable + +0x2DC0 | 02 00 | uint16_t | 0x0002 (2) | table field `id` (UShort) + +0x2DC2 | 08 00 | uint16_t | 0x0008 (8) | table field `offset` (UShort) + +0x2DC4 | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x2E0C | offset to field `name` (string) + +0x2DC8 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x2DFC | offset to field `type` (table) + +0x2DCC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x2DD8 | offset to field `attributes` (vector) + +0x2DD0 | 64 00 00 00 00 00 00 00 | int64_t | 0x0000000000000064 (100) | table field `default_integer` (Long) + +vector (reflection.Field.attributes): + +0x2DD8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2DDC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2DE0 | offset to table[0] + +table (reflection.KeyValue): + +0x2DE0 | 18 F5 FF FF | SOffset32 | 0xFFFFF518 (-2792) Loc: 0x38C8 | offset to vtable + +0x2DE4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2DF4 | offset to field `key` (string) + +0x2DE8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2DEC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2DEC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2DF0 | 32 | char[1] | 2 | string literal + +0x2DF1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2DF2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2DF4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2DF8 | 69 64 | char[2] | id | string literal + +0x2DFA | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2DFC | 88 F7 FF FF | SOffset32 | 0xFFFFF788 (-2168) Loc: 0x3674 | offset to vtable + +0x2E00 | 00 00 00 | uint8_t[3] | ... | padding + +0x2E03 | 05 | uint8_t | 0x05 (5) | table field `base_type` (Byte) + +0x2E04 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `base_size` (UInt) + +0x2E08 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2E0C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2E10 | 68 70 | char[2] | hp | string literal + +0x2E12 | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Field): + +0x2E14 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x2E16 | 1C 00 | uint16_t | 0x001C (28) | size of referring table + +0x2E18 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x2E1A | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x2E1C | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 2) + +0x2E1E | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x2E20 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `default_integer` (id: 4) + +0x2E22 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2E24 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2E26 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2E28 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x2E2A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x2E2C | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x2E14 | offset to vtable + +0x2E30 | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x2E32 | 06 00 | uint16_t | 0x0006 (6) | table field `offset` (UShort) + +0x2E34 | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x2E7C | offset to field `name` (string) + +0x2E38 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x2E6C | offset to field `type` (table) + +0x2E3C | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x2E48 | offset to field `attributes` (vector) + +0x2E40 | 96 00 00 00 00 00 00 00 | int64_t | 0x0000000000000096 (150) | table field `default_integer` (Long) + +vector (reflection.Field.attributes): + +0x2E48 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2E4C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2E50 | offset to table[0] + +table (reflection.KeyValue): + +0x2E50 | 88 F5 FF FF | SOffset32 | 0xFFFFF588 (-2680) Loc: 0x38C8 | offset to vtable + +0x2E54 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2E64 | offset to field `key` (string) + +0x2E58 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2E5C | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2E5C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2E60 | 31 | char[1] | 1 | string literal + +0x2E61 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2E62 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2E64 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2E68 | 69 64 | char[2] | id | string literal + +0x2E6A | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2E6C | F8 F7 FF FF | SOffset32 | 0xFFFFF7F8 (-2056) Loc: 0x3674 | offset to vtable + +0x2E70 | 00 00 00 | uint8_t[3] | ... | padding + +0x2E73 | 05 | uint8_t | 0x05 (5) | table field `base_type` (Byte) + +0x2E74 | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `base_size` (UInt) + +0x2E78 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2E7C | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2E80 | 6D 61 6E 61 | char[4] | mana | string literal + +0x2E84 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2E85 | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.Field): + +0x2E88 | 1C 00 | uint16_t | 0x001C (28) | size of this vtable + +0x2E8A | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x2E8C | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x2E8E | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x2E90 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x2E92 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x2E94 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x2E96 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2E98 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2E9A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2E9C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x2E9E | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +0x2EA0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x2EA2 | 05 00 | VOffset16 | 0x0005 (5) | offset to field `optional` (id: 11) + +table (reflection.Field): + +0x2EA4 | 1C 00 00 00 | SOffset32 | 0x0000001C (28) Loc: 0x2E88 | offset to vtable + +0x2EA8 | 00 | uint8_t[1] | . | padding + +0x2EA9 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x2EAA | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x2EAC | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x2EEC | offset to field `name` (string) + +0x2EB0 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x2EDC | offset to field `type` (table) + +0x2EB4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2EB8 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2EB8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2EBC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2EC0 | offset to table[0] + +table (reflection.KeyValue): + +0x2EC0 | F8 F5 FF FF | SOffset32 | 0xFFFFF5F8 (-2568) Loc: 0x38C8 | offset to vtable + +0x2EC4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2ED4 | offset to field `key` (string) + +0x2EC8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2ECC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2ECC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2ED0 | 30 | char[1] | 0 | string literal + +0x2ED1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2ED2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2ED4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2ED8 | 69 64 | char[2] | id | string literal + +0x2EDA | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x2EDC | C4 F6 FF FF | SOffset32 | 0xFFFFF6C4 (-2364) Loc: 0x3818 | offset to vtable + +0x2EE0 | 00 00 00 | uint8_t[3] | ... | padding + +0x2EE3 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x2EE4 | 09 00 00 00 | uint32_t | 0x00000009 (9) | table field `index` (Int) + +0x2EE8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2EEC | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x2EF0 | 70 6F 73 | char[3] | pos | string literal + +0x2EF3 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Object): + +0x2EF4 | 5C F7 FF FF | SOffset32 | 0xFFFFF75C (-2212) Loc: 0x3798 | offset to vtable + +0x2EF8 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x2F10 | offset to field `name` (string) + +0x2EFC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x2F08 | offset to field `fields` (vector) + +0x2F00 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x2F04 | E0 07 00 00 | UOffset32 | 0x000007E0 (2016) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x2F08 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x2F0C | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x2F48 | offset to table[0] + +string (reflection.Object.name): + +0x2F10 | 19 00 00 00 | uint32_t | 0x00000019 (25) | length of string + +0x2F14 | 4D 79 47 61 6D 65 2E 45 | char[25] | MyGame.E | string literal + +0x2F1C | 78 61 6D 70 6C 65 2E 52 | | xample.R + +0x2F24 | 65 66 65 72 72 61 62 6C | | eferrabl + +0x2F2C | 65 | | e + +0x2F2D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2F2E | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x2F30 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x2F32 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x2F34 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x2F36 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x2F38 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x2F3A | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x2F3C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x2F3E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x2F40 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x2F42 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x2F44 | 05 00 | VOffset16 | 0x0005 (5) | offset to field `key` (id: 8) + +0x2F46 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x2F48 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x2F30 | offset to vtable + +0x2F4C | 00 | uint8_t[1] | . | padding + +0x2F4D | 01 | uint8_t | 0x01 (1) | table field `key` (Bool) + +0x2F4E | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x2F50 | 6C 00 00 00 | UOffset32 | 0x0000006C (108) Loc: 0x2FBC | offset to field `name` (string) + +0x2F54 | 58 00 00 00 | UOffset32 | 0x00000058 (88) Loc: 0x2FAC | offset to field `type` (table) + +0x2F58 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2F5C | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x2F5C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x2F60 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x2F84 | offset to table[0] + +0x2F64 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2F68 | offset to table[1] + +table (reflection.KeyValue): + +0x2F68 | A0 F6 FF FF | SOffset32 | 0xFFFFF6A0 (-2400) Loc: 0x38C8 | offset to vtable + +0x2F6C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x2F7C | offset to field `key` (string) + +0x2F70 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2F74 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2F74 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x2F78 | 30 | char[1] | 0 | string literal + +0x2F79 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2F7A | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x2F7C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x2F80 | 6B 65 79 | char[3] | key | string literal + +0x2F83 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x2F84 | BC F6 FF FF | SOffset32 | 0xFFFFF6BC (-2372) Loc: 0x38C8 | offset to vtable + +0x2F88 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x2FA0 | offset to field `key` (string) + +0x2F8C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x2F90 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x2F90 | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x2F94 | 66 6E 76 31 61 5F 36 34 | char[8] | fnv1a_64 | string literal + +0x2F9C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2F9D | 00 00 00 | uint8_t[3] | ... | padding + +string (reflection.KeyValue.key): + +0x2FA0 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x2FA4 | 68 61 73 68 | char[4] | hash | string literal + +0x2FA8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x2FA9 | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Type): + +0x2FAC | 38 F9 FF FF | SOffset32 | 0xFFFFF938 (-1736) Loc: 0x3674 | offset to vtable + +0x2FB0 | 00 00 00 | uint8_t[3] | ... | padding + +0x2FB3 | 0A | uint8_t | 0x0A (10) | table field `base_type` (Byte) + +0x2FB4 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x2FB8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x2FBC | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x2FC0 | 69 64 | char[2] | id | string literal + +0x2FC2 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Object): + +0x2FC4 | 2C F8 FF FF | SOffset32 | 0xFFFFF82C (-2004) Loc: 0x3798 | offset to vtable + +0x2FC8 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x2FE8 | offset to field `name` (string) + +0x2FCC | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x2FD8 | offset to field `fields` (vector) + +0x2FD0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x2FD4 | 10 07 00 00 | UOffset32 | 0x00000710 (1808) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x2FD8 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x2FDC | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x3018 | offset to table[0] + +0x2FE0 | B8 00 00 00 | UOffset32 | 0x000000B8 (184) Loc: 0x3098 | offset to table[1] + +0x2FE4 | 8C 00 00 00 | UOffset32 | 0x0000008C (140) Loc: 0x3070 | offset to table[2] + +string (reflection.Object.name): + +0x2FE8 | 13 00 00 00 | uint32_t | 0x00000013 (19) | length of string + +0x2FEC | 4D 79 47 61 6D 65 2E 45 | char[19] | MyGame.E | string literal + +0x2FF4 | 78 61 6D 70 6C 65 2E 53 | | xample.S + +0x2FFC | 74 61 74 | | tat + +0x2FFF | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Field): + +0x3000 | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x3002 | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x3004 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x3006 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x3008 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 2) + +0x300A | 0A 00 | VOffset16 | 0x000A (10) | offset to field `offset` (id: 3) + +0x300C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x300E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x3010 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x3012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x3014 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `key` (id: 8) + +0x3016 | 14 00 | VOffset16 | 0x0014 (20) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x3018 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x3000 | offset to vtable + +0x301C | 00 00 00 | uint8_t[3] | ... | padding + +0x301F | 01 | uint8_t | 0x01 (1) | table field `key` (Bool) + +0x3020 | 02 00 | uint16_t | 0x0002 (2) | table field `id` (UShort) + +0x3022 | 08 00 | uint16_t | 0x0008 (8) | table field `offset` (UShort) + +0x3024 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x3064 | offset to field `name` (string) + +0x3028 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x3054 | offset to field `type` (table) + +0x302C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3030 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x3030 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x3034 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3038 | offset to table[0] + +table (reflection.KeyValue): + +0x3038 | 70 F7 FF FF | SOffset32 | 0xFFFFF770 (-2192) Loc: 0x38C8 | offset to vtable + +0x303C | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x304C | offset to field `key` (string) + +0x3040 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3044 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x3044 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3048 | 30 | char[1] | 0 | string literal + +0x3049 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x304A | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x304C | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x3050 | 6B 65 79 | char[3] | key | string literal + +0x3053 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x3054 | E0 F9 FF FF | SOffset32 | 0xFFFFF9E0 (-1568) Loc: 0x3674 | offset to vtable + +0x3058 | 00 00 00 | uint8_t[3] | ... | padding + +0x305B | 06 | uint8_t | 0x06 (6) | table field `base_type` (Byte) + +0x305C | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `base_size` (UInt) + +0x3060 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3064 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x3068 | 63 6F 75 6E 74 | char[5] | count | string literal + +0x306D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x306E | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x3070 | F4 FB FF FF | SOffset32 | 0xFFFFFBF4 (-1036) Loc: 0x347C | offset to vtable + +0x3074 | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x3076 | 06 00 | uint16_t | 0x0006 (6) | table field `offset` (UShort) + +0x3078 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x3090 | offset to field `name` (string) + +0x307C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3080 | offset to field `type` (table) + +table (reflection.Type): + +0x3080 | 0C FA FF FF | SOffset32 | 0xFFFFFA0C (-1524) Loc: 0x3674 | offset to vtable + +0x3084 | 00 00 00 | uint8_t[3] | ... | padding + +0x3087 | 09 | uint8_t | 0x09 (9) | table field `base_type` (Byte) + +0x3088 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x308C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3090 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x3094 | 76 61 6C | char[3] | val | string literal + +0x3097 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x3098 | AC F8 FF FF | SOffset32 | 0xFFFFF8AC (-1876) Loc: 0x37EC | offset to vtable + +0x309C | 00 | uint8_t[1] | . | padding + +0x309D | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x309E | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x30A0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x30B4 | offset to field `name` (string) + +0x30A4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x30A8 | offset to field `type` (table) + +table (reflection.Type): + +0x30A8 | CC F7 FF FF | SOffset32 | 0xFFFFF7CC (-2100) Loc: 0x38DC | offset to vtable + +0x30AC | 00 00 00 | uint8_t[3] | ... | padding + +0x30AF | 0D | uint8_t | 0x0D (13) | table field `base_type` (Byte) + +0x30B0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x30B4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x30B8 | 69 64 | char[2] | id | string literal + +0x30BA | 00 | char | 0x00 (0) | string terminator + +table (reflection.Object): + +0x30BC | 7C F8 FF FF | SOffset32 | 0xFFFFF87C (-1924) Loc: 0x3840 | offset to vtable + +0x30C0 | 00 00 00 | uint8_t[3] | ... | padding + +0x30C3 | 01 | uint8_t | 0x01 (1) | table field `is_struct` (Bool) + +0x30C4 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x30E0 | offset to field `name` (string) + +0x30C8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x30D8 | offset to field `fields` (vector) + +0x30CC | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `minalign` (Int) + +0x30D0 | 14 00 00 00 | uint32_t | 0x00000014 (20) | table field `bytesize` (Int) + +0x30D4 | 10 06 00 00 | UOffset32 | 0x00000610 (1552) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x30D8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x30DC | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: 0x310C | offset to table[0] + +string (reflection.Object.name): + +0x30E0 | 27 00 00 00 | uint32_t | 0x00000027 (39) | length of string + +0x30E4 | 4D 79 47 61 6D 65 2E 45 | char[39] | MyGame.E | string literal + +0x30EC | 78 61 6D 70 6C 65 2E 53 | | xample.S + +0x30F4 | 74 72 75 63 74 4F 66 53 | | tructOfS + +0x30FC | 74 72 75 63 74 73 4F 66 | | tructsOf + +0x3104 | 53 74 72 75 63 74 73 | | Structs + +0x310B | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x310C | 14 FF FF FF | SOffset32 | 0xFFFFFF14 (-236) Loc: 0x31F8 | offset to vtable + +0x3110 | 00 00 00 | uint8_t[3] | ... | padding + +0x3113 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x3114 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x312C | offset to field `name` (string) + +0x3118 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x311C | offset to field `type` (table) + +table (reflection.Type): + +0x311C | 04 F9 FF FF | SOffset32 | 0xFFFFF904 (-1788) Loc: 0x3818 | offset to vtable + +0x3120 | 00 00 00 | uint8_t[3] | ... | padding + +0x3123 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x3124 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `index` (Int) + +0x3128 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x312C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3130 | 61 | char[1] | a | string literal + +0x3131 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3132 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Object): + +0x3134 | F4 F8 FF FF | SOffset32 | 0xFFFFF8F4 (-1804) Loc: 0x3840 | offset to vtable + +0x3138 | 00 00 00 | uint8_t[3] | ... | padding + +0x313B | 01 | uint8_t | 0x01 (1) | table field `is_struct` (Bool) + +0x313C | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x3160 | offset to field `name` (string) + +0x3140 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x3150 | offset to field `fields` (vector) + +0x3144 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `minalign` (Int) + +0x3148 | 14 00 00 00 | uint32_t | 0x00000014 (20) | table field `bytesize` (Int) + +0x314C | 98 05 00 00 | UOffset32 | 0x00000598 (1432) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x3150 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x3154 | C0 00 00 00 | UOffset32 | 0x000000C0 (192) Loc: 0x3214 | offset to table[0] + +0x3158 | 74 00 00 00 | UOffset32 | 0x00000074 (116) Loc: 0x31CC | offset to table[1] + +0x315C | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x3184 | offset to table[2] + +string (reflection.Object.name): + +0x3160 | 1E 00 00 00 | uint32_t | 0x0000001E (30) | length of string + +0x3164 | 4D 79 47 61 6D 65 2E 45 | char[30] | MyGame.E | string literal + +0x316C | 78 61 6D 70 6C 65 2E 53 | | xample.S + +0x3174 | 74 72 75 63 74 4F 66 53 | | tructOfS + +0x317C | 74 72 75 63 74 73 | | tructs + +0x3182 | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x3184 | D4 FF FF FF | SOffset32 | 0xFFFFFFD4 (-44) Loc: 0x31B0 | offset to vtable + +0x3188 | 00 00 00 | uint8_t[3] | ... | padding + +0x318B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x318C | 02 00 | uint16_t | 0x0002 (2) | table field `id` (UShort) + +0x318E | 0C 00 | uint16_t | 0x000C (12) | table field `offset` (UShort) + +0x3190 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x31A8 | offset to field `name` (string) + +0x3194 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3198 | offset to field `type` (table) + +table (reflection.Type): + +0x3198 | 80 F9 FF FF | SOffset32 | 0xFFFFF980 (-1664) Loc: 0x3818 | offset to vtable + +0x319C | 00 00 00 | uint8_t[3] | ... | padding + +0x319F | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x31A0 | 00 00 00 00 | uint32_t | 0x00000000 (0) | table field `index` (Int) + +0x31A4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x31A8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x31AC | 63 | char[1] | c | string literal + +0x31AD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x31AE | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x31B0 | 1C 00 | uint16_t | 0x001C (28) | size of this vtable + +0x31B2 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x31B4 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x31B6 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x31B8 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 2) + +0x31BA | 0A 00 | VOffset16 | 0x000A (10) | offset to field `offset` (id: 3) + +0x31BC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x31BE | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x31C0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x31C2 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x31C4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x31C6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 9) (Vector) + +0x31C8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x31CA | 07 00 | VOffset16 | 0x0007 (7) | offset to field `optional` (id: 11) + +table (reflection.Field): + +0x31CC | 1C 00 00 00 | SOffset32 | 0x0000001C (28) Loc: 0x31B0 | offset to vtable + +0x31D0 | 00 00 00 | uint8_t[3] | ... | padding + +0x31D3 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x31D4 | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x31D6 | 08 00 | uint16_t | 0x0008 (8) | table field `offset` (UShort) + +0x31D8 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x31F0 | offset to field `name` (string) + +0x31DC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x31E0 | offset to field `type` (table) + +table (reflection.Type): + +0x31E0 | C8 F9 FF FF | SOffset32 | 0xFFFFF9C8 (-1592) Loc: 0x3818 | offset to vtable + +0x31E4 | 00 00 00 | uint8_t[3] | ... | padding + +0x31E7 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x31E8 | 06 00 00 00 | uint32_t | 0x00000006 (6) | table field `index` (Int) + +0x31EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x31F0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x31F4 | 62 | char[1] | b | string literal + +0x31F5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x31F6 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x31F8 | 1C 00 | uint16_t | 0x001C (28) | size of this vtable + +0x31FA | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x31FC | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x31FE | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x3200 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x3202 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `offset` (id: 3) (UShort) + +0x3204 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x3206 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x3208 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x320A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x320C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x320E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 9) (Vector) + +0x3210 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x3212 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `optional` (id: 11) + +table (reflection.Field): + +0x3214 | 1C 00 00 00 | SOffset32 | 0x0000001C (28) Loc: 0x31F8 | offset to vtable + +0x3218 | 00 00 00 | uint8_t[3] | ... | padding + +0x321B | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x321C | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x3234 | offset to field `name` (string) + +0x3220 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3224 | offset to field `type` (table) + +table (reflection.Type): + +0x3224 | 0C FA FF FF | SOffset32 | 0xFFFFFA0C (-1524) Loc: 0x3818 | offset to vtable + +0x3228 | 00 00 00 | uint8_t[3] | ... | padding + +0x322B | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x322C | 00 00 00 00 | uint32_t | 0x00000000 (0) | table field `index` (Int) + +0x3230 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3234 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3238 | 61 | char[1] | a | string literal + +0x3239 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x323A | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Object): + +0x323C | FC F9 FF FF | SOffset32 | 0xFFFFF9FC (-1540) Loc: 0x3840 | offset to vtable + +0x3240 | 00 00 00 | uint8_t[3] | ... | padding + +0x3243 | 01 | uint8_t | 0x01 (1) | table field `is_struct` (Bool) + +0x3244 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x3264 | offset to field `name` (string) + +0x3248 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x3258 | offset to field `fields` (vector) + +0x324C | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `minalign` (Int) + +0x3250 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `bytesize` (Int) + +0x3254 | 90 04 00 00 | UOffset32 | 0x00000490 (1168) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x3258 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x325C | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x3280 | offset to table[0] + +0x3260 | 64 00 00 00 | UOffset32 | 0x00000064 (100) Loc: 0x32C4 | offset to table[1] + +string (reflection.Object.name): + +0x3264 | 16 00 00 00 | uint32_t | 0x00000016 (22) | length of string + +0x3268 | 4D 79 47 61 6D 65 2E 45 | char[22] | MyGame.E | string literal + +0x3270 | 78 61 6D 70 6C 65 2E 41 | | xample.A + +0x3278 | 62 69 6C 69 74 79 | | bility + +0x327E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x3280 | 04 FE FF FF | SOffset32 | 0xFFFFFE04 (-508) Loc: 0x347C | offset to vtable + +0x3284 | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x3286 | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x3288 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x329C | offset to field `name` (string) + +0x328C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3290 | offset to field `type` (table) + +table (reflection.Type): + +0x3290 | B4 F9 FF FF | SOffset32 | 0xFFFFF9B4 (-1612) Loc: 0x38DC | offset to vtable + +0x3294 | 00 00 00 | uint8_t[3] | ... | padding + +0x3297 | 08 | uint8_t | 0x08 (8) | table field `base_type` (Byte) + +0x3298 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x329C | 08 00 00 00 | uint32_t | 0x00000008 (8) | length of string + +0x32A0 | 64 69 73 74 61 6E 63 65 | char[8] | distance | string literal + +0x32A8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x32A9 | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.Field): + +0x32AC | 18 00 | uint16_t | 0x0018 (24) | size of this vtable + +0x32AE | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x32B0 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x32B2 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x32B4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x32B6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `offset` (id: 3) (UShort) + +0x32B8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x32BA | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x32BC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x32BE | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x32C0 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `key` (id: 8) + +0x32C2 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 9) + +table (reflection.Field): + +0x32C4 | 18 00 00 00 | SOffset32 | 0x00000018 (24) Loc: 0x32AC | offset to vtable + +0x32C8 | 00 00 00 | uint8_t[3] | ... | padding + +0x32CB | 01 | uint8_t | 0x01 (1) | table field `key` (Bool) + +0x32CC | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x3308 | offset to field `name` (string) + +0x32D0 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x32FC | offset to field `type` (table) + +0x32D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x32D8 | offset to field `attributes` (vector) + +vector (reflection.Field.attributes): + +0x32D8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x32DC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x32E0 | offset to table[0] + +table (reflection.KeyValue): + +0x32E0 | 18 FA FF FF | SOffset32 | 0xFFFFFA18 (-1512) Loc: 0x38C8 | offset to vtable + +0x32E4 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x32F4 | offset to field `key` (string) + +0x32E8 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x32EC | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x32EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x32F0 | 30 | char[1] | 0 | string literal + +0x32F1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x32F2 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x32F4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x32F8 | 6B 65 79 | char[3] | key | string literal + +0x32FB | 00 | char | 0x00 (0) | string terminator + +table (reflection.Type): + +0x32FC | 20 FA FF FF | SOffset32 | 0xFFFFFA20 (-1504) Loc: 0x38DC | offset to vtable + +0x3300 | 00 00 00 | uint8_t[3] | ... | padding + +0x3303 | 08 | uint8_t | 0x08 (8) | table field `base_type` (Byte) + +0x3304 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3308 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of string + +0x330C | 69 64 | char[2] | id | string literal + +0x330E | 00 | char | 0x00 (0) | string terminator + +vtable (reflection.Object): + +0x3310 | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x3312 | 20 00 | uint16_t | 0x0020 (32) | size of referring table + +0x3314 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x3316 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `fields` (id: 1) + +0x3318 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `is_struct` (id: 2) + +0x331A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `minalign` (id: 3) + +0x331C | 14 00 | VOffset16 | 0x0014 (20) | offset to field `bytesize` (id: 4) + +0x331E | 18 00 | VOffset16 | 0x0018 (24) | offset to field `attributes` (id: 5) + +0x3320 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 6) (Vector) + +0x3322 | 1C 00 | VOffset16 | 0x001C (28) | offset to field `declaration_file` (id: 7) + +table (reflection.Object): + +0x3324 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x3310 | offset to vtable + +0x3328 | 00 00 00 | uint8_t[3] | ... | padding + +0x332B | 01 | uint8_t | 0x01 (1) | table field `is_struct` (Bool) + +0x332C | 60 00 00 00 | UOffset32 | 0x00000060 (96) Loc: 0x338C | offset to field `name` (string) + +0x3330 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x3370 | offset to field `fields` (vector) + +0x3334 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `minalign` (Int) + +0x3338 | 20 00 00 00 | uint32_t | 0x00000020 (32) | table field `bytesize` (Int) + +0x333C | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x3344 | offset to field `attributes` (vector) + +0x3340 | A4 03 00 00 | UOffset32 | 0x000003A4 (932) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.attributes): + +0x3344 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x3348 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x334C | offset to table[0] + +table (reflection.KeyValue): + +0x334C | 84 FA FF FF | SOffset32 | 0xFFFFFA84 (-1404) Loc: 0x38C8 | offset to vtable + +0x3350 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x3360 | offset to field `key` (string) + +0x3354 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3358 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x3358 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x335C | 38 | char[1] | 8 | string literal + +0x335D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x335E | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x3360 | 0B 00 00 00 | uint32_t | 0x0000000B (11) | length of string + +0x3364 | 66 6F 72 63 65 5F 61 6C | char[11] | force_al | string literal + +0x336C | 69 67 6E | | ign + +0x336F | 00 | char | 0x00 (0) | string terminator + +vector (reflection.Object.fields): + +0x3370 | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of vector (# items) + +0x3374 | B4 00 00 00 | UOffset32 | 0x000000B4 (180) Loc: 0x3428 | offset to table[0] + +0x3378 | 7C 00 00 00 | UOffset32 | 0x0000007C (124) Loc: 0x33F4 | offset to table[1] + +0x337C | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x33C4 | offset to table[2] + +0x3380 | 2C 01 00 00 | UOffset32 | 0x0000012C (300) Loc: 0x34AC | offset to table[3] + +0x3384 | 04 01 00 00 | UOffset32 | 0x00000104 (260) Loc: 0x3488 | offset to table[4] + +0x3388 | CC 00 00 00 | UOffset32 | 0x000000CC (204) Loc: 0x3454 | offset to table[5] + +string (reflection.Object.name): + +0x338C | 13 00 00 00 | uint32_t | 0x00000013 (19) | length of string + +0x3390 | 4D 79 47 61 6D 65 2E 45 | char[19] | MyGame.E | string literal + +0x3398 | 78 61 6D 70 6C 65 2E 56 | | xample.V + +0x33A0 | 65 63 33 | | ec3 + +0x33A3 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x33A4 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x33A6 | 1E 00 | uint16_t | 0x001E (30) | size of this vtable + +0x33A8 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x33AA | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x33AC | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x33AE | 06 00 | VOffset16 | 0x0006 (6) | offset to field `id` (id: 2) + +0x33B0 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `offset` (id: 3) + +0x33B2 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x33B4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x33B6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x33B8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x33BA | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x33BC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 9) (Vector) + +0x33BE | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x33C0 | 05 00 | VOffset16 | 0x0005 (5) | offset to field `optional` (id: 11) + +0x33C2 | 0A 00 | VOffset16 | 0x000A (10) | offset to field `padding` (id: 12) + +table (reflection.Field): + +0x33C4 | 1E 00 00 00 | SOffset32 | 0x0000001E (30) Loc: 0x33A6 | offset to vtable + +0x33C8 | 00 | uint8_t[1] | . | padding + +0x33C9 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x33CA | 05 00 | uint16_t | 0x0005 (5) | table field `id` (UShort) + +0x33CC | 1A 00 | uint16_t | 0x001A (26) | table field `offset` (UShort) + +0x33CE | 02 00 | uint16_t | 0x0002 (2) | table field `padding` (UShort) + +0x33D0 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x33E8 | offset to field `name` (string) + +0x33D4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x33D8 | offset to field `type` (table) + +table (reflection.Type): + +0x33D8 | C0 FB FF FF | SOffset32 | 0xFFFFFBC0 (-1088) Loc: 0x3818 | offset to vtable + +0x33DC | 00 00 00 | uint8_t[3] | ... | padding + +0x33DF | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x33E0 | 06 00 00 00 | uint32_t | 0x00000006 (6) | table field `index` (Int) + +0x33E4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x33E8 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x33EC | 74 65 73 74 33 | char[5] | test3 | string literal + +0x33F1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x33F2 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x33F4 | D6 FD FF FF | SOffset32 | 0xFFFFFDD6 (-554) Loc: 0x361E | offset to vtable + +0x33F8 | 00 00 | uint8_t[2] | .. | padding + +0x33FA | 04 00 | uint16_t | 0x0004 (4) | table field `id` (UShort) + +0x33FC | 18 00 | uint16_t | 0x0018 (24) | table field `offset` (UShort) + +0x33FE | 01 00 | uint16_t | 0x0001 (1) | table field `padding` (UShort) + +0x3400 | 1C 00 00 00 | UOffset32 | 0x0000001C (28) Loc: 0x341C | offset to field `name` (string) + +0x3404 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3408 | offset to field `type` (table) + +table (reflection.Type): + +0x3408 | 5C FE FF FF | SOffset32 | 0xFFFFFE5C (-420) Loc: 0x35AC | offset to vtable + +0x340C | 00 00 00 | uint8_t[3] | ... | padding + +0x340F | 04 | uint8_t | 0x04 (4) | table field `base_type` (Byte) + +0x3410 | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x3414 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x3418 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x341C | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x3420 | 74 65 73 74 32 | char[5] | test2 | string literal + +0x3425 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3426 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x3428 | AC FF FF FF | SOffset32 | 0xFFFFFFAC (-84) Loc: 0x347C | offset to vtable + +0x342C | 03 00 | uint16_t | 0x0003 (3) | table field `id` (UShort) + +0x342E | 10 00 | uint16_t | 0x0010 (16) | table field `offset` (UShort) + +0x3430 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x3448 | offset to field `name` (string) + +0x3434 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3438 | offset to field `type` (table) + +table (reflection.Type): + +0x3438 | C4 FD FF FF | SOffset32 | 0xFFFFFDC4 (-572) Loc: 0x3674 | offset to vtable + +0x343C | 00 00 00 | uint8_t[3] | ... | padding + +0x343F | 0C | uint8_t | 0x0C (12) | table field `base_type` (Byte) + +0x3440 | 08 00 00 00 | uint32_t | 0x00000008 (8) | table field `base_size` (UInt) + +0x3444 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3448 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x344C | 74 65 73 74 31 | char[5] | test1 | string literal + +0x3451 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3452 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x3454 | 36 FE FF FF | SOffset32 | 0xFFFFFE36 (-458) Loc: 0x361E | offset to vtable + +0x3458 | 00 00 | uint8_t[2] | .. | padding + +0x345A | 02 00 | uint16_t | 0x0002 (2) | table field `id` (UShort) + +0x345C | 08 00 | uint16_t | 0x0008 (8) | table field `offset` (UShort) + +0x345E | 04 00 | uint16_t | 0x0004 (4) | table field `padding` (UShort) + +0x3460 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x3474 | offset to field `name` (string) + +0x3464 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3468 | offset to field `type` (table) + +table (reflection.Type): + +0x3468 | 8C FB FF FF | SOffset32 | 0xFFFFFB8C (-1140) Loc: 0x38DC | offset to vtable + +0x346C | 00 00 00 | uint8_t[3] | ... | padding + +0x346F | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x3470 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3474 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3478 | 7A | char[1] | z | string literal + +0x3479 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x347A | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x347C | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x347E | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x3480 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x3482 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x3484 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 2) + +0x3486 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +table (reflection.Field): + +0x3488 | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x347C | offset to vtable + +0x348C | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x348E | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x3490 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x34A4 | offset to field `name` (string) + +0x3494 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3498 | offset to field `type` (table) + +table (reflection.Type): + +0x3498 | BC FB FF FF | SOffset32 | 0xFFFFFBBC (-1092) Loc: 0x38DC | offset to vtable + +0x349C | 00 00 00 | uint8_t[3] | ... | padding + +0x349F | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x34A0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x34A4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x34A8 | 79 | char[1] | y | string literal + +0x34A9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x34AA | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x34AC | E4 FB FF FF | SOffset32 | 0xFFFFFBE4 (-1052) Loc: 0x38C8 | offset to vtable + +0x34B0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x34C4 | offset to field `name` (string) + +0x34B4 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x34B8 | offset to field `type` (table) + +table (reflection.Type): + +0x34B8 | DC FB FF FF | SOffset32 | 0xFFFFFBDC (-1060) Loc: 0x38DC | offset to vtable + +0x34BC | 00 00 00 | uint8_t[3] | ... | padding + +0x34BF | 0B | uint8_t | 0x0B (11) | table field `base_type` (Byte) + +0x34C0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x34C4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x34C8 | 78 | char[1] | x | string literal + +0x34C9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x34CA | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Object): + +0x34CC | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x34CE | 18 00 | uint16_t | 0x0018 (24) | size of referring table + +0x34D0 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x34D2 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `fields` (id: 1) + +0x34D4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `is_struct` (id: 2) (Bool) + +0x34D6 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `minalign` (id: 3) + +0x34D8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `bytesize` (id: 4) (Int) + +0x34DA | 10 00 | VOffset16 | 0x0010 (16) | offset to field `attributes` (id: 5) + +0x34DC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 6) (Vector) + +0x34DE | 14 00 | VOffset16 | 0x0014 (20) | offset to field `declaration_file` (id: 7) + +table (reflection.Object): + +0x34E0 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x34CC | offset to vtable + +0x34E4 | 70 00 00 00 | UOffset32 | 0x00000070 (112) Loc: 0x3554 | offset to field `name` (string) + +0x34E8 | 64 00 00 00 | UOffset32 | 0x00000064 (100) Loc: 0x354C | offset to field `fields` (vector) + +0x34EC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x34F0 | 08 00 00 00 | UOffset32 | 0x00000008 (8) Loc: 0x34F8 | offset to field `attributes` (vector) + +0x34F4 | F0 01 00 00 | UOffset32 | 0x000001F0 (496) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.attributes): + +0x34F8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x34FC | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x3524 | offset to table[0] + +0x3500 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3504 | offset to table[1] + +table (reflection.KeyValue): + +0x3504 | 3C FC FF FF | SOffset32 | 0xFFFFFC3C (-964) Loc: 0x38C8 | offset to vtable + +0x3508 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x3518 | offset to field `key` (string) + +0x350C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3510 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x3510 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3514 | 30 | char[1] | 0 | string literal + +0x3515 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3516 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x3518 | 07 00 00 00 | uint32_t | 0x00000007 (7) | length of string + +0x351C | 70 72 69 76 61 74 65 | char[7] | private | string literal + +0x3523 | 00 | char | 0x00 (0) | string terminator + +table (reflection.KeyValue): + +0x3524 | 5C FC FF FF | SOffset32 | 0xFFFFFC5C (-932) Loc: 0x38C8 | offset to vtable + +0x3528 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x3538 | offset to field `key` (string) + +0x352C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3530 | offset to field `value` (string) + +string (reflection.KeyValue.value): + +0x3530 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3534 | 30 | char[1] | 0 | string literal + +0x3535 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3536 | 00 00 | uint8_t[2] | .. | padding + +string (reflection.KeyValue.key): + +0x3538 | 0E 00 00 00 | uint32_t | 0x0000000E (14) | length of string + +0x353C | 63 73 68 61 72 70 5F 70 | char[14] | csharp_p | string literal + +0x3544 | 61 72 74 69 61 6C | | artial + +0x354A | 00 | char | 0x00 (0) | string terminator + +vector (reflection.Object.fields): + +0x354C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x3550 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x3590 | offset to table[0] + +string (reflection.Object.name): + +0x3554 | 26 00 00 00 | uint32_t | 0x00000026 (38) | length of string + +0x3558 | 4D 79 47 61 6D 65 2E 45 | char[38] | MyGame.E | string literal + +0x3560 | 78 61 6D 70 6C 65 2E 54 | | xample.T + +0x3568 | 65 73 74 53 69 6D 70 6C | | estSimpl + +0x3570 | 65 54 61 62 6C 65 57 69 | | eTableWi + +0x3578 | 74 68 45 6E 75 6D | | thEnum + +0x357E | 00 | char | 0x00 (0) | string terminator + +padding: + +0x357F | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.Field): + +0x3582 | 0E 00 | uint16_t | 0x000E (14) | size of this vtable + +0x3584 | 1C 00 | uint16_t | 0x001C (28) | size of referring table + +0x3586 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x3588 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x358A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x358C | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x358E | 10 00 | VOffset16 | 0x0010 (16) | offset to field `default_integer` (id: 4) + +table (reflection.Field): + +0x3590 | 0E 00 00 00 | SOffset32 | 0x0000000E (14) Loc: 0x3582 | offset to vtable + +0x3594 | 00 00 | uint8_t[2] | .. | padding + +0x3596 | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x3598 | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x35D0 | offset to field `name` (string) + +0x359C | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x35BC | offset to field `type` (table) + +0x35A0 | 02 00 00 00 00 00 00 00 | int64_t | 0x0000000000000002 (2) | table field `default_integer` (Long) + +0x35A8 | 00 00 00 00 | uint8_t[4] | .... | padding + +vtable (reflection.Type): + +0x35AC | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x35AE | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x35B0 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `base_type` (id: 0) + +0x35B2 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `element` (id: 1) (Byte) + +0x35B4 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `index` (id: 2) + +0x35B6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x35B8 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `base_size` (id: 4) + +0x35BA | 10 00 | VOffset16 | 0x0010 (16) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x35BC | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x35AC | offset to vtable + +0x35C0 | 00 00 00 | uint8_t[3] | ... | padding + +0x35C3 | 04 | uint8_t | 0x04 (4) | table field `base_type` (Byte) + +0x35C4 | 03 00 00 00 | uint32_t | 0x00000003 (3) | table field `index` (Int) + +0x35C8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x35CC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x35D0 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x35D4 | 63 6F 6C 6F 72 | char[5] | color | string literal + +0x35D9 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x35DA | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Object): + +0x35DC | 9C FD FF FF | SOffset32 | 0xFFFFFD9C (-612) Loc: 0x3840 | offset to vtable + +0x35E0 | 00 00 00 | uint8_t[3] | ... | padding + +0x35E3 | 01 | uint8_t | 0x01 (1) | table field `is_struct` (Bool) + +0x35E4 | 20 00 00 00 | UOffset32 | 0x00000020 (32) Loc: 0x3604 | offset to field `name` (string) + +0x35E8 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x35F8 | offset to field `fields` (vector) + +0x35EC | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `minalign` (Int) + +0x35F0 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `bytesize` (Int) + +0x35F4 | F0 00 00 00 | UOffset32 | 0x000000F0 (240) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x35F8 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x35FC | 6C 00 00 00 | UOffset32 | 0x0000006C (108) Loc: 0x3668 | offset to table[0] + +0x3600 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x363C | offset to table[1] + +string (reflection.Object.name): + +0x3604 | 13 00 00 00 | uint32_t | 0x00000013 (19) | length of string + +0x3608 | 4D 79 47 61 6D 65 2E 45 | char[19] | MyGame.E | string literal + +0x3610 | 78 61 6D 70 6C 65 2E 54 | | xample.T + +0x3618 | 65 73 74 | | est + +0x361B | 00 | char | 0x00 (0) | string terminator + +padding: + +0x361C | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Field): + +0x361E | 1E 00 | uint16_t | 0x001E (30) | size of this vtable + +0x3620 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x3622 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `name` (id: 0) + +0x3624 | 10 00 | VOffset16 | 0x0010 (16) | offset to field `type` (id: 1) + +0x3626 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `id` (id: 2) + +0x3628 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `offset` (id: 3) + +0x362A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x362C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x362E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x3630 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x3632 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x3634 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 9) (Vector) + +0x3636 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x3638 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `optional` (id: 11) (Bool) + +0x363A | 0A 00 | VOffset16 | 0x000A (10) | offset to field `padding` (id: 12) + +table (reflection.Field): + +0x363C | 1E 00 00 00 | SOffset32 | 0x0000001E (30) Loc: 0x361E | offset to vtable + +0x3640 | 00 00 | uint8_t[2] | .. | padding + +0x3642 | 01 00 | uint16_t | 0x0001 (1) | table field `id` (UShort) + +0x3644 | 02 00 | uint16_t | 0x0002 (2) | table field `offset` (UShort) + +0x3646 | 01 00 | uint16_t | 0x0001 (1) | table field `padding` (UShort) + +0x3648 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x3660 | offset to field `name` (string) + +0x364C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3650 | offset to field `type` (table) + +table (reflection.Type): + +0x3650 | DC FF FF FF | SOffset32 | 0xFFFFFFDC (-36) Loc: 0x3674 | offset to vtable + +0x3654 | 00 00 00 | uint8_t[3] | ... | padding + +0x3657 | 03 | uint8_t | 0x03 (3) | table field `base_type` (Byte) + +0x3658 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `base_size` (UInt) + +0x365C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3660 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3664 | 62 | char[1] | b | string literal + +0x3665 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3666 | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Field): + +0x3668 | A0 FD FF FF | SOffset32 | 0xFFFFFDA0 (-608) Loc: 0x38C8 | offset to vtable + +0x366C | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x3694 | offset to field `name` (string) + +0x3670 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x3684 | offset to field `type` (table) + +vtable (reflection.Type): + +0x3674 | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x3676 | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x3678 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `base_type` (id: 0) + +0x367A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `element` (id: 1) (Byte) + +0x367C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `index` (id: 2) (Int) + +0x367E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x3680 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `base_size` (id: 4) + +0x3682 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x3684 | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x3674 | offset to vtable + +0x3688 | 00 00 00 | uint8_t[3] | ... | padding + +0x368B | 05 | uint8_t | 0x05 (5) | table field `base_type` (Byte) + +0x368C | 02 00 00 00 | uint32_t | 0x00000002 (2) | table field `base_size` (UInt) + +0x3690 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3694 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3698 | 61 | char[1] | a | string literal + +0x3699 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x369A | 00 00 | uint8_t[2] | .. | padding + +table (reflection.Object): + +0x369C | 04 FF FF FF | SOffset32 | 0xFFFFFF04 (-252) Loc: 0x3798 | offset to vtable + +0x36A0 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x36B4 | offset to field `name` (string) + +0x36A4 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x36B0 | offset to field `fields` (vector) + +0x36A8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x36AC | 38 00 00 00 | UOffset32 | 0x00000038 (56) Loc: 0x36E4 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x36B0 | 00 00 00 00 | uint32_t | 0x00000000 (0) | length of vector (# items) + +string (reflection.Object.name): + +0x36B4 | 17 00 00 00 | uint32_t | 0x00000017 (23) | length of string + +0x36B8 | 4D 79 47 61 6D 65 2E 45 | char[23] | MyGame.E | string literal + +0x36C0 | 78 61 6D 70 6C 65 32 2E | | xample2. + +0x36C8 | 4D 6F 6E 73 74 65 72 | | Monster + +0x36CF | 00 | char | 0x00 (0) | string terminator + +table (reflection.Object): + +0x36D0 | 38 FF FF FF | SOffset32 | 0xFFFFFF38 (-200) Loc: 0x3798 | offset to vtable + +0x36D4 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x3700 | offset to field `name` (string) + +0x36D8 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x36FC | offset to field `fields` (vector) + +0x36DC | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x36E0 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x36E4 | offset to field `declaration_file` (string) + +string (reflection.Object.declaration_file): + +0x36E4 | 12 00 00 00 | uint32_t | 0x00000012 (18) | length of string + +0x36E8 | 2F 2F 6D 6F 6E 73 74 65 | char[18] | //monste | string literal + +0x36F0 | 72 5F 74 65 73 74 2E 66 | | r_test.f + +0x36F8 | 62 73 | | bs + +0x36FA | 00 | char | 0x00 (0) | string terminator + +vector (reflection.Object.fields): + +0x36FC | 00 00 00 00 | uint32_t | 0x00000000 (0) | length of vector (# items) + +string (reflection.Object.name): + +0x3700 | 18 00 00 00 | uint32_t | 0x00000018 (24) | length of string + +0x3704 | 4D 79 47 61 6D 65 2E 49 | char[24] | MyGame.I | string literal + +0x370C | 6E 50 61 72 65 6E 74 4E | | nParentN + +0x3714 | 61 6D 65 73 70 61 63 65 | | amespace + +0x371C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x371D | 00 00 00 | uint8_t[3] | ... | padding + +table (reflection.Object): + +0x3720 | 88 FF FF FF | SOffset32 | 0xFFFFFF88 (-120) Loc: 0x3798 | offset to vtable + +0x3724 | 40 00 00 00 | UOffset32 | 0x00000040 (64) Loc: 0x3764 | offset to field `name` (string) + +0x3728 | 34 00 00 00 | UOffset32 | 0x00000034 (52) Loc: 0x375C | offset to field `fields` (vector) + +0x372C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x3730 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3734 | offset to field `declaration_file` (string) + +string (reflection.Object.declaration_file): + +0x3734 | 20 00 00 00 | uint32_t | 0x00000020 (32) | length of string + +0x3738 | 2F 2F 69 6E 63 6C 75 64 | char[32] | //includ | string literal + +0x3740 | 65 5F 74 65 73 74 2F 69 | | e_test/i + +0x3748 | 6E 63 6C 75 64 65 5F 74 | | nclude_t + +0x3750 | 65 73 74 31 2E 66 62 73 | | est1.fbs + +0x3758 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3759 | 00 00 00 | uint8_t[3] | ... | padding + +vector (reflection.Object.fields): + +0x375C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x3760 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x3770 | offset to table[0] + +string (reflection.Object.name): + +0x3764 | 06 00 00 00 | uint32_t | 0x00000006 (6) | length of string + +0x3768 | 54 61 62 6C 65 41 | char[6] | TableA | string literal + +0x376E | 00 | char | 0x00 (0) | string terminator + +table (reflection.Field): + +0x3770 | 84 FF FF FF | SOffset32 | 0xFFFFFF84 (-124) Loc: 0x37EC | offset to vtable + +0x3774 | 00 | uint8_t[1] | . | padding + +0x3775 | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x3776 | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x3778 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x3790 | offset to field `name` (string) + +0x377C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3780 | offset to field `type` (table) + +table (reflection.Type): + +0x3780 | 68 FF FF FF | SOffset32 | 0xFFFFFF68 (-152) Loc: 0x3818 | offset to vtable + +0x3784 | 00 00 00 | uint8_t[3] | ... | padding + +0x3787 | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x3788 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | table field `index` (Int) + +0x378C | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3790 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x3794 | 62 | char[1] | b | string literal + +0x3795 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3796 | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Object): + +0x3798 | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x379A | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x379C | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 0) + +0x379E | 08 00 | VOffset16 | 0x0008 (8) | offset to field `fields` (id: 1) + +0x37A0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `is_struct` (id: 2) (Bool) + +0x37A2 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `minalign` (id: 3) + +0x37A4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `bytesize` (id: 4) (Int) + +0x37A6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 5) (Vector) + +0x37A8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 6) (Vector) + +0x37AA | 10 00 | VOffset16 | 0x0010 (16) | offset to field `declaration_file` (id: 7) + +table (reflection.Object): + +0x37AC | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x3798 | offset to vtable + +0x37B0 | 18 00 00 00 | UOffset32 | 0x00000018 (24) Loc: 0x37C8 | offset to field `name` (string) + +0x37B4 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x37C0 | offset to field `fields` (vector) + +0x37B8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `minalign` (Int) + +0x37BC | B4 00 00 00 | UOffset32 | 0x000000B4 (180) Loc: 0x3870 | offset to field `declaration_file` (string) + +vector (reflection.Object.fields): + +0x37C0 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x37C4 | 44 00 00 00 | UOffset32 | 0x00000044 (68) Loc: 0x3808 | offset to table[0] + +string (reflection.Object.name): + +0x37C8 | 1C 00 00 00 | uint32_t | 0x0000001C (28) | length of string + +0x37CC | 4D 79 47 61 6D 65 2E 4F | char[28] | MyGame.O | string literal + +0x37D4 | 74 68 65 72 4E 61 6D 65 | | therName + +0x37DC | 53 70 61 63 65 2E 54 61 | | Space.Ta + +0x37E4 | 62 6C 65 42 | | bleB + +0x37E8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x37E9 | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.Field): + +0x37EC | 1C 00 | uint16_t | 0x001C (28) | size of this vtable + +0x37EE | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x37F0 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x37F2 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `type` (id: 1) + +0x37F4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `id` (id: 2) (UShort) + +0x37F6 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `offset` (id: 3) + +0x37F8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_integer` (id: 4) (Long) + +0x37FA | 00 00 | VOffset16 | 0x0000 (0) | offset to field `default_real` (id: 5) (Double) + +0x37FC | 00 00 | VOffset16 | 0x0000 (0) | offset to field `deprecated` (id: 6) (Bool) + +0x37FE | 00 00 | VOffset16 | 0x0000 (0) | offset to field `required` (id: 7) (Bool) + +0x3800 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `key` (id: 8) (Bool) + +0x3802 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 9) (Vector) + +0x3804 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 10) (Vector) + +0x3806 | 05 00 | VOffset16 | 0x0005 (5) | offset to field `optional` (id: 11) + +table (reflection.Field): + +0x3808 | 1C 00 00 00 | SOffset32 | 0x0000001C (28) Loc: 0x37EC | offset to vtable + +0x380C | 00 | uint8_t[1] | . | padding + +0x380D | 01 | uint8_t | 0x01 (1) | table field `optional` (Bool) + +0x380E | 04 00 | uint16_t | 0x0004 (4) | table field `offset` (UShort) + +0x3810 | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x3838 | offset to field `name` (string) + +0x3814 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x3828 | offset to field `type` (table) + +vtable (reflection.Type): + +0x3818 | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x381A | 10 00 | uint16_t | 0x0010 (16) | size of referring table + +0x381C | 07 00 | VOffset16 | 0x0007 (7) | offset to field `base_type` (id: 0) + +0x381E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `element` (id: 1) (Byte) + +0x3820 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `index` (id: 2) + +0x3822 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x3824 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `base_size` (id: 4) (UInt) + +0x3826 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x3828 | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x3818 | offset to vtable + +0x382C | 00 00 00 | uint8_t[3] | ... | padding + +0x382F | 0F | uint8_t | 0x0F (15) | table field `base_type` (Byte) + +0x3830 | 0E 00 00 00 | uint32_t | 0x0000000E (14) | table field `index` (Int) + +0x3834 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x3838 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x383C | 61 | char[1] | a | string literal + +0x383D | 00 | char | 0x00 (0) | string terminator + +padding: + +0x383E | 00 00 | uint8_t[2] | .. | padding + +vtable (reflection.Object): + +0x3840 | 14 00 | uint16_t | 0x0014 (20) | size of this vtable + +0x3842 | 1C 00 | uint16_t | 0x001C (28) | size of referring table + +0x3844 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `name` (id: 0) + +0x3846 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `fields` (id: 1) + +0x3848 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `is_struct` (id: 2) + +0x384A | 10 00 | VOffset16 | 0x0010 (16) | offset to field `minalign` (id: 3) + +0x384C | 14 00 | VOffset16 | 0x0014 (20) | offset to field `bytesize` (id: 4) + +0x384E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `attributes` (id: 5) (Vector) + +0x3850 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `documentation` (id: 6) (Vector) + +0x3852 | 18 00 | VOffset16 | 0x0018 (24) | offset to field `declaration_file` (id: 7) + +table (reflection.Object): + +0x3854 | 14 00 00 00 | SOffset32 | 0x00000014 (20) Loc: 0x3840 | offset to vtable + +0x3858 | 00 00 00 | uint8_t[3] | ... | padding + +0x385B | 01 | uint8_t | 0x01 (1) | table field `is_struct` (Bool) + +0x385C | 48 00 00 00 | UOffset32 | 0x00000048 (72) Loc: 0x38A4 | offset to field `name` (string) + +0x3860 | 3C 00 00 00 | UOffset32 | 0x0000003C (60) Loc: 0x389C | offset to field `fields` (vector) + +0x3864 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `minalign` (Int) + +0x3868 | 04 00 00 00 | uint32_t | 0x00000004 (4) | table field `bytesize` (Int) + +0x386C | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x3870 | offset to field `declaration_file` (string) + +string (reflection.Object.declaration_file): + +0x3870 | 24 00 00 00 | uint32_t | 0x00000024 (36) | length of string + +0x3874 | 2F 2F 69 6E 63 6C 75 64 | char[36] | //includ | string literal + +0x387C | 65 5F 74 65 73 74 2F 73 | | e_test/s + +0x3884 | 75 62 2F 69 6E 63 6C 75 | | ub/inclu + +0x388C | 64 65 5F 74 65 73 74 32 | | de_test2 + +0x3894 | 2E 66 62 73 | | .fbs + +0x3898 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x3899 | 00 00 00 | uint8_t[3] | ... | padding + +vector (reflection.Object.fields): + +0x389C | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of vector (# items) + +0x38A0 | 30 00 00 00 | UOffset32 | 0x00000030 (48) Loc: 0x38D0 | offset to table[0] + +string (reflection.Object.name): + +0x38A4 | 1C 00 00 00 | uint32_t | 0x0000001C (28) | length of string + +0x38A8 | 4D 79 47 61 6D 65 2E 4F | char[28] | MyGame.O | string literal + +0x38B0 | 74 68 65 72 4E 61 6D 65 | | therName + +0x38B8 | 53 70 61 63 65 2E 55 6E | | Space.Un + +0x38C0 | 75 73 65 64 | | used + +0x38C4 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x38C5 | 00 00 00 | uint8_t[3] | ... | padding + +vtable (reflection.KeyValue, reflection.Field, reflection.SchemaFile): + +0x38C8 | 08 00 | uint16_t | 0x0008 (8) | size of this vtable + +0x38CA | 0C 00 | uint16_t | 0x000C (12) | size of referring table + +0x38CC | 04 00 | VOffset16 | 0x0004 (4) | offset to field `key` (id: 0) + +0x38CE | 08 00 | VOffset16 | 0x0008 (8) | offset to field `value` (id: 1) + +table (reflection.Field): + +0x38D0 | 08 00 00 00 | SOffset32 | 0x00000008 (8) Loc: 0x38C8 | offset to vtable + +0x38D4 | 24 00 00 00 | UOffset32 | 0x00000024 (36) Loc: 0x38F8 | offset to field `name` (string) + +0x38D8 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x38EC | offset to field `type` (table) + +vtable (reflection.Type): + +0x38DC | 10 00 | uint16_t | 0x0010 (16) | size of this vtable + +0x38DE | 0C 00 | uint16_t | 0x000C (12) | size of referring table + +0x38E0 | 07 00 | VOffset16 | 0x0007 (7) | offset to field `base_type` (id: 0) + +0x38E2 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `element` (id: 1) (Byte) + +0x38E4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `index` (id: 2) (Int) + +0x38E6 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `fixed_length` (id: 3) (UShort) + +0x38E8 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `base_size` (id: 4) (UInt) + +0x38EA | 08 00 | VOffset16 | 0x0008 (8) | offset to field `element_size` (id: 5) + +table (reflection.Type): + +0x38EC | 10 00 00 00 | SOffset32 | 0x00000010 (16) Loc: 0x38DC | offset to vtable + +0x38F0 | 00 00 00 | uint8_t[3] | ... | padding + +0x38F3 | 07 | uint8_t | 0x07 (7) | table field `base_type` (Byte) + +0x38F4 | 01 00 00 00 | uint32_t | 0x00000001 (1) | table field `element_size` (UInt) + +string (reflection.Field.name): + +0x38F8 | 01 00 00 00 | uint32_t | 0x00000001 (1) | length of string + +0x38FC | 61 | char[1] | a | string literal + +0x38FD | 00 | char | 0x00 (0) | string terminator + +padding: + +0x38FE | 00 00 | uint8_t[2] | .. | padding diff --git a/third_party/flatbuffers/tests/monster_test.bfbs b/third_party/flatbuffers/tests/monster_test.bfbs new file mode 100644 index 00000000000..cbf6335dbbd Binary files /dev/null and b/third_party/flatbuffers/tests/monster_test.bfbs differ diff --git a/third_party/flatbuffers/tests/monster_test.cpp b/third_party/flatbuffers/tests/monster_test.cpp new file mode 100644 index 00000000000..b546d2074d8 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.cpp @@ -0,0 +1,901 @@ +#include "monster_test.h" + +#include +#include + +#include "flatbuffers/base.h" +#include "flatbuffers/flatbuffer_builder.h" +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/idl.h" +#include "flatbuffers/registry.h" +#include "flatbuffers/verifier.h" +#include "is_quiet_nan.h" +#include "monster_extra_generated.h" +#include "monster_test_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +// Shortcuts for the infinity. +static const auto infinity_f = std::numeric_limits::infinity(); +static const auto infinity_d = std::numeric_limits::infinity(); + +using namespace MyGame::Example; + +// example of how to build up a serialized buffer algorithmically: +flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer) { + flatbuffers::FlatBufferBuilder builder; + + auto vec = Vec3(1, 2, 3, 0, Color_Red, Test(10, 20)); + + auto name = builder.CreateString("MyMonster"); + + // Use the initializer_list specialization of CreateVector. + auto inventory = + builder.CreateVector({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }); + + // Alternatively, create the vector first, and fill in data later: + // unsigned char *inv_buf = nullptr; + // auto inventory = builder.CreateUninitializedVector( + // 10, &inv_buf); + // memcpy(inv_buf, inv_data, 10); + + Test tests[] = { Test(10, 20), Test(30, 40) }; + auto testv = builder.CreateVectorOfStructs(tests, 2); + + // Create a vector of structures from a lambda. + auto testv2 = builder.CreateVectorOfStructs( + 2, [&](size_t i, Test *s) -> void { *s = tests[i]; }); + + // create monster with very few fields set: + // (same functionality as CreateMonster below, but sets fields manually) + flatbuffers::Offset mlocs[3]; + auto fred = builder.CreateString("Fred"); + auto barney = builder.CreateString("Barney"); + auto wilma = builder.CreateString("Wilma"); + MonsterBuilder mb1(builder); + mb1.add_name(fred); + mlocs[0] = mb1.Finish(); + MonsterBuilder mb2(builder); + mb2.add_name(barney); + mb2.add_hp(1000); + mlocs[1] = mb2.Finish(); + MonsterBuilder mb3(builder); + mb3.add_name(wilma); + mlocs[2] = mb3.Finish(); + + // Create an array of strings. Also test string pooling, and lambdas. + auto vecofstrings = + builder.CreateVector>( + 4, + [](size_t i, flatbuffers::FlatBufferBuilder *b) + -> flatbuffers::Offset { + static const char *names[] = { "bob", "fred", "bob", "fred" }; + return b->CreateSharedString(names[i]); + }, + &builder); + + // Creating vectors of strings in one convenient call. + std::vector names2; + names2.push_back("jane"); + names2.push_back("mary"); + auto vecofstrings2 = builder.CreateVectorOfStrings(names2); + + // Creating vectors from types that are different from std::string + std::vector names3; + names3.push_back("foo"); + names3.push_back("bar"); + builder.CreateVectorOfStrings(names3); // Also an accepted type + +#ifdef FLATBUFFERS_HAS_STRING_VIEW + std::vector names4; + names3.push_back("baz"); + names3.push_back("quux"); + builder.CreateVectorOfStrings(names4); // Also an accepted type +#endif + + // Make sure the template deduces an initializer as std::vector + builder.CreateVectorOfStrings({ "hello", "world" }); + + // Create many vectors of strings + std::vector manyNames; + for (auto i = 0; i < 100; i++) { manyNames.push_back("john_doe"); } + auto manyNamesVec = builder.CreateVectorOfStrings(manyNames); + TEST_EQ(false, manyNamesVec.IsNull()); + auto manyNamesVec2 = + builder.CreateVectorOfStrings(manyNames.cbegin(), manyNames.cend()); + TEST_EQ(false, manyNamesVec2.IsNull()); + + // Create an array of sorted tables, can be used with binary search when read: + auto vecoftables = builder.CreateVectorOfSortedTables(mlocs, 3); + + // Create an array of sorted structs, + // can be used with binary search when read: + std::vector abilities; + abilities.push_back(Ability(4, 40)); + abilities.push_back(Ability(3, 30)); + abilities.push_back(Ability(2, 20)); + abilities.push_back(Ability(0, 0)); + auto vecofstructs = builder.CreateVectorOfSortedStructs(&abilities); + + flatbuffers::Offset mlocs_stats[1]; + auto miss = builder.CreateString("miss"); + StatBuilder mb_miss(builder); + mb_miss.add_id(miss); + mb_miss.add_val(0); + mb_miss.add_count(0); // key + mlocs_stats[0] = mb_miss.Finish(); + auto vec_of_stats = builder.CreateVectorOfSortedTables(mlocs_stats, 1); + + // Create a nested FlatBuffer. + // Nested FlatBuffers are stored in a ubyte vector, which can be convenient + // since they can be memcpy'd around much easier than other FlatBuffer + // values. They have little overhead compared to storing the table directly. + // As a test, create a mostly empty Monster buffer: + flatbuffers::FlatBufferBuilder nested_builder; + auto nmloc = CreateMonster(nested_builder, nullptr, 0, 0, + nested_builder.CreateString("NestedMonster")); + FinishMonsterBuffer(nested_builder, nmloc); + // Now we can store the buffer in the parent. Note that by default, vectors + // are only aligned to their elements or size field, so in this case if the + // buffer contains 64-bit elements, they may not be correctly aligned. We fix + // that with: + builder.ForceVectorAlignment(nested_builder.GetSize(), sizeof(uint8_t), + nested_builder.GetBufferMinAlignment()); + // If for whatever reason you don't have the nested_builder available, you + // can substitute flatbuffers::largest_scalar_t (64-bit) for the alignment, or + // the largest force_align value in your schema if you're using it. + auto nested_flatbuffer_vector = builder.CreateVector( + nested_builder.GetBufferPointer(), nested_builder.GetSize()); + + // Test a nested FlexBuffer: + flexbuffers::Builder flexbuild; + flexbuild.Int(1234); + flexbuild.Finish(); + auto flex = builder.CreateVector(flexbuild.GetBuffer()); + // Test vector of enums. + Color colors[] = { Color_Blue, Color_Green }; + // We use this special creation function because we have an array of + // pre-C++11 (enum class) enums whose size likely is int, yet its declared + // type in the schema is byte. + auto vecofcolors = builder.CreateVectorScalarCast(colors, 2); + + // shortcut for creating monster with all fields set: + auto mloc = CreateMonster( + builder, &vec, 150, 80, name, inventory, Color_Blue, Any_Monster, + mlocs[1].Union(), // Store a union. + testv, vecofstrings, vecoftables, 0, nested_flatbuffer_vector, 0, false, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 3.14159f, 3.0f, 0.0f, vecofstrings2, + vecofstructs, flex, testv2, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + AnyUniqueAliases_NONE, 0, AnyAmbiguousAliases_NONE, 0, vecofcolors, + MyGame::Example::Race_None, 0, vec_of_stats); + + FinishMonsterBuffer(builder, mloc); + + // clang-format off + #ifdef FLATBUFFERS_TEST_VERBOSE + // print byte data for debugging: + auto p = builder.GetBufferPointer(); + for (flatbuffers::uoffset_t i = 0; i < builder.GetSize(); i++) + printf("%d ", p[i]); + #endif + // clang-format on + + // return the buffer for the caller to use. + auto bufferpointer = + reinterpret_cast(builder.GetBufferPointer()); + buffer.assign(bufferpointer, bufferpointer + builder.GetSize()); + + return builder.Release(); +} + +// example of accessing a buffer loaded in memory: +void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length, bool pooled) { + // First, verify the buffers integrity (optional) + flatbuffers::Verifier verifier(flatbuf, length); + std::vector flex_reuse_tracker; + verifier.SetFlexReuseTracker(&flex_reuse_tracker); + TEST_EQ(VerifyMonsterBuffer(verifier), true); + + // clang-format off + #ifdef FLATBUFFERS_TRACK_VERIFIER_BUFFER_SIZE + std::vector test_buff; + test_buff.resize(length * 2); + std::memcpy(&test_buff[0], flatbuf, length); + std::memcpy(&test_buff[length], flatbuf, length); + + flatbuffers::Verifier verifier1(&test_buff[0], length); + TEST_EQ(VerifyMonsterBuffer(verifier1), true); + TEST_EQ(verifier1.GetComputedSize(), length); + + flatbuffers::Verifier verifier2(&test_buff[length], length); + TEST_EQ(VerifyMonsterBuffer(verifier2), true); + TEST_EQ(verifier2.GetComputedSize(), length); + #endif + // clang-format on + + TEST_EQ(strcmp(MonsterIdentifier(), "MONS"), 0); + TEST_EQ(MonsterBufferHasIdentifier(flatbuf), true); + TEST_EQ(strcmp(MonsterExtension(), "mon"), 0); + + // Access the buffer from the root. + auto monster = GetMonster(flatbuf); + + TEST_EQ(monster->hp(), 80); + TEST_EQ(monster->mana(), 150); // default + TEST_EQ_STR(monster->name()->c_str(), "MyMonster"); + // Can't access the following field, it is deprecated in the schema, + // which means accessors are not generated: + // monster.friendly() + + auto pos = monster->pos(); + TEST_NOTNULL(pos); + TEST_EQ(pos->z(), 3); + TEST_EQ(pos->test3().a(), 10); + TEST_EQ(pos->test3().b(), 20); + + auto inventory = monster->inventory(); + TEST_EQ(VectorLength(inventory), 10UL); // Works even if inventory is null. + TEST_NOTNULL(inventory); + unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + // Check compatibilty of iterators with STL. + std::vector inv_vec(inventory->begin(), inventory->end()); + size_t n = 0; + for (auto it = inventory->begin(); it != inventory->end(); ++it, ++n) { + auto indx = it - inventory->begin(); + TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check. + TEST_EQ(*it, inv_data[indx]); + } + TEST_EQ(n, inv_vec.size()); + + n = 0; + for (auto it = inventory->cbegin(); it != inventory->cend(); ++it, ++n) { + auto indx = it - inventory->cbegin(); + TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check. + TEST_EQ(*it, inv_data[indx]); + } + TEST_EQ(n, inv_vec.size()); + + n = 0; + for (auto it = inventory->rbegin(); it != inventory->rend(); ++it, ++n) { + auto indx = inventory->rend() - it - 1; + TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check. + TEST_EQ(*it, inv_data[indx]); + } + TEST_EQ(n, inv_vec.size()); + + n = 0; + for (auto it = inventory->crbegin(); it != inventory->crend(); ++it, ++n) { + auto indx = inventory->crend() - it - 1; + TEST_EQ(*it, inv_vec.at(indx)); // Use bounds-check. + TEST_EQ(*it, inv_data[indx]); + } + TEST_EQ(n, inv_vec.size()); + + TEST_EQ(monster->color(), Color_Blue); + + // Example of accessing a union: + TEST_EQ(monster->test_type(), Any_Monster); // First make sure which it is. + auto monster2 = reinterpret_cast(monster->test()); + TEST_NOTNULL(monster2); + TEST_EQ_STR(monster2->name()->c_str(), "Fred"); + + // Example of accessing a vector of strings: + auto vecofstrings = monster->testarrayofstring(); + TEST_EQ(vecofstrings->size(), 4U); + TEST_EQ_STR(vecofstrings->Get(0)->c_str(), "bob"); + TEST_EQ_STR(vecofstrings->Get(1)->c_str(), "fred"); + if (pooled) { + // These should have pointer equality because of string pooling. + TEST_EQ(vecofstrings->Get(0)->c_str(), vecofstrings->Get(2)->c_str()); + TEST_EQ(vecofstrings->Get(1)->c_str(), vecofstrings->Get(3)->c_str()); + } + + auto vecofstrings2 = monster->testarrayofstring2(); + if (vecofstrings2) { + TEST_EQ(vecofstrings2->size(), 2U); + TEST_EQ_STR(vecofstrings2->Get(0)->c_str(), "jane"); + TEST_EQ_STR(vecofstrings2->Get(1)->c_str(), "mary"); + } + + // Example of accessing a vector of tables: + auto vecoftables = monster->testarrayoftables(); + TEST_EQ(vecoftables->size(), 3U); + for (auto it = vecoftables->begin(); it != vecoftables->end(); ++it) { + TEST_EQ(strlen(it->name()->c_str()) >= 4, true); + } + TEST_EQ_STR(vecoftables->Get(0)->name()->c_str(), "Barney"); + TEST_EQ(vecoftables->Get(0)->hp(), 1000); + TEST_EQ_STR(vecoftables->Get(1)->name()->c_str(), "Fred"); + TEST_EQ_STR(vecoftables->Get(2)->name()->c_str(), "Wilma"); + TEST_NOTNULL(vecoftables->LookupByKey("Barney")); + TEST_NOTNULL(vecoftables->LookupByKey("Fred")); + TEST_NOTNULL(vecoftables->LookupByKey("Wilma")); + + // Verify the same objects are returned for char*-based and string-based + // lookups. + TEST_EQ(vecoftables->LookupByKey("Barney"), + vecoftables->LookupByKey(std::string("Barney"))); + TEST_EQ(vecoftables->LookupByKey("Fred"), + vecoftables->LookupByKey(std::string("Fred"))); + TEST_EQ(vecoftables->LookupByKey("Wilma"), + vecoftables->LookupByKey(std::string("Wilma"))); + +#ifdef FLATBUFFERS_HAS_STRING_VIEW + // Tests for LookupByKey with a key that is a truncated + // version of a longer, invalid key. + const std::string invalid_key = "Barney123"; + std::string_view valid_truncated_key = invalid_key; + valid_truncated_key.remove_suffix(3); // "Barney" + TEST_NOTNULL(vecoftables->LookupByKey(valid_truncated_key)); + TEST_EQ(vecoftables->LookupByKey("Barney"), + vecoftables->LookupByKey(valid_truncated_key)); + + // Tests for LookupByKey with a key that is a truncated + // version of a longer, valid key. + const std::string valid_key = "Barney"; + std::string_view invalid_truncated_key = valid_key; + invalid_truncated_key.remove_suffix(3); // "Bar" + TEST_NULL(vecoftables->LookupByKey(invalid_truncated_key)); +#endif // FLATBUFFERS_HAS_STRING_VIEW + + // Test accessing a vector of sorted structs + auto vecofstructs = monster->testarrayofsortedstruct(); + if (vecofstructs) { // not filled in monster_test.bfbs + for (flatbuffers::uoffset_t i = 0; i < vecofstructs->size() - 1; i++) { + auto left = vecofstructs->Get(i); + auto right = vecofstructs->Get(i + 1); + TEST_EQ(true, (left->KeyCompareLessThan(right))); + } + TEST_NOTNULL(vecofstructs->LookupByKey(0)); // test default value + TEST_NOTNULL(vecofstructs->LookupByKey(3)); + TEST_EQ(static_cast(nullptr), + vecofstructs->LookupByKey(5)); + } + + if (auto vec_of_stat = monster->scalar_key_sorted_tables()) { + auto stat_0 = vec_of_stat->LookupByKey(static_cast(0u)); + TEST_NOTNULL(stat_0); + TEST_NOTNULL(stat_0->id()); + TEST_EQ(0, stat_0->count()); + TEST_EQ_STR("miss", stat_0->id()->c_str()); + } + + // Test nested FlatBuffers if available: + auto nested_buffer = monster->testnestedflatbuffer(); + if (nested_buffer) { + // nested_buffer is a vector of bytes you can memcpy. However, if you + // actually want to access the nested data, this is a convenient + // accessor that directly gives you the root table: + auto nested_monster = monster->testnestedflatbuffer_nested_root(); + TEST_EQ_STR(nested_monster->name()->c_str(), "NestedMonster"); + } + + // Test flexbuffer if available: + auto flex = monster->flex(); + // flex is a vector of bytes you can memcpy etc. + TEST_EQ(flex->size(), 4); // Encoded FlexBuffer bytes. + // However, if you actually want to access the nested data, this is a + // convenient accessor that directly gives you the root value: + TEST_EQ(monster->flex_flexbuffer_root().AsInt16(), 1234); + + // Test vector of enums: + auto colors = monster->vector_of_enums(); + if (colors) { + TEST_EQ(colors->size(), 2); + TEST_EQ(colors->Get(0), Color_Blue); + TEST_EQ(colors->Get(1), Color_Green); + } + + // Since Flatbuffers uses explicit mechanisms to override the default + // compiler alignment, double check that the compiler indeed obeys them: + // (Test consists of a short and byte): + TEST_EQ(flatbuffers::AlignOf(), 2UL); + TEST_EQ(sizeof(Test), 4UL); + + const flatbuffers::Vector *tests_array[] = { + monster->test4(), + monster->test5(), + }; + for (size_t i = 0; i < sizeof(tests_array) / sizeof(tests_array[0]); ++i) { + auto tests = tests_array[i]; + TEST_NOTNULL(tests); + auto test_0 = tests->Get(0); + auto test_1 = tests->Get(1); + TEST_EQ(test_0->a(), 10); + TEST_EQ(test_0->b(), 20); + TEST_EQ(test_1->a(), 30); + TEST_EQ(test_1->b(), 40); + for (auto it = tests->begin(); it != tests->end(); ++it) { + TEST_EQ(it->a() == 10 || it->a() == 30, true); // Just testing iterators. + } + } + + // Checking for presence of fields: + TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_HP), true); + TEST_EQ(flatbuffers::IsFieldPresent(monster, Monster::VT_MANA), false); + + // Obtaining a buffer from a root: + TEST_EQ(GetBufferStartFromRootPointer(monster), flatbuf); +} + +// Change a FlatBuffer in-place, after it has been constructed. +void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length) { + // Get non-const pointer to root. + auto monster = GetMutableMonster(flatbuf); + + // Each of these tests mutates, then tests, then set back to the original, + // so we can test that the buffer in the end still passes our original test. + auto hp_ok = monster->mutate_hp(10); + TEST_EQ(hp_ok, true); // Field was present. + TEST_EQ(monster->hp(), 10); + // Mutate to default value + auto hp_ok_default = monster->mutate_hp(100); + TEST_EQ(hp_ok_default, true); // Field was present. + TEST_EQ(monster->hp(), 100); + // Test that mutate to default above keeps field valid for further mutations + auto hp_ok_2 = monster->mutate_hp(20); + TEST_EQ(hp_ok_2, true); + TEST_EQ(monster->hp(), 20); + monster->mutate_hp(80); + + // Monster originally at 150 mana (default value) + auto mana_default_ok = monster->mutate_mana(150); // Mutate to default value. + TEST_EQ(mana_default_ok, + true); // Mutation should succeed, because default value. + TEST_EQ(monster->mana(), 150); + auto mana_ok = monster->mutate_mana(10); + TEST_EQ(mana_ok, false); // Field was NOT present, because default value. + TEST_EQ(monster->mana(), 150); + + // Mutate structs. + auto pos = monster->mutable_pos(); + auto &test3 = pos->mutable_test3(); // Struct inside a struct. + test3.mutate_a(50); // Struct fields never fail. + TEST_EQ(test3.a(), 50); + test3.mutate_a(10); + + // Mutate vectors. + auto inventory = monster->mutable_inventory(); + inventory->Mutate(9, 100); + TEST_EQ(inventory->Get(9), 100); + inventory->Mutate(9, 9); + + auto tables = monster->mutable_testarrayoftables(); + auto first = tables->GetMutableObject(0); + TEST_EQ(first->hp(), 1000); + first->mutate_hp(0); + TEST_EQ(first->hp(), 0); + first->mutate_hp(1000); + + // Test for each loop over mutable entries + for (auto item : *tables) { + TEST_EQ(item->hp(), 1000); + item->mutate_hp(0); + TEST_EQ(item->hp(), 0); + item->mutate_hp(1000); + break; // one iteration is enough, just testing compilation + } + + // Mutate via LookupByKey + TEST_NOTNULL(tables->MutableLookupByKey("Barney")); + TEST_EQ(static_cast(nullptr), + tables->MutableLookupByKey("DoesntExist")); + TEST_EQ(tables->MutableLookupByKey("Barney")->hp(), 1000); + TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(0), true); + TEST_EQ(tables->LookupByKey("Barney")->hp(), 0); + TEST_EQ(tables->MutableLookupByKey("Barney")->mutate_hp(1000), true); + + // Run the verifier and the regular test to make sure we didn't trample on + // anything. + AccessFlatBufferTest(flatbuf, length); +} + +// Unpack a FlatBuffer into objects. +void ObjectFlatBuffersTest(uint8_t *flatbuf) { + // Optional: we can specify resolver and rehasher functions to turn hashed + // strings into object pointers and back, to implement remote references + // and such. + auto resolver = flatbuffers::resolver_function_t( + [](void **pointer_adr, flatbuffers::hash_value_t hash) { + (void)pointer_adr; + (void)hash; + // Don't actually do anything, leave variable null. + }); + auto rehasher = flatbuffers::rehasher_function_t( + [](void *pointer) -> flatbuffers::hash_value_t { + (void)pointer; + return 0; + }); + + // Turn a buffer into C++ objects. + auto monster1 = UnPackMonster(flatbuf, &resolver); + + // Re-serialize the data. + flatbuffers::FlatBufferBuilder fbb1; + fbb1.Finish(CreateMonster(fbb1, monster1.get(), &rehasher), + MonsterIdentifier()); + + // Unpack again, and re-serialize again. + auto monster2 = UnPackMonster(fbb1.GetBufferPointer(), &resolver); + flatbuffers::FlatBufferBuilder fbb2; + fbb2.Finish(CreateMonster(fbb2, monster2.get(), &rehasher), + MonsterIdentifier()); + + // Now we've gone full round-trip, the two buffers should match. + const auto len1 = fbb1.GetSize(); + const auto len2 = fbb2.GetSize(); + TEST_EQ(len1, len2); + TEST_EQ(memcmp(fbb1.GetBufferPointer(), fbb2.GetBufferPointer(), len1), 0); + + // Test it with the original buffer test to make sure all data survived. + AccessFlatBufferTest(fbb2.GetBufferPointer(), len2, false); + + // Test accessing fields, similar to AccessFlatBufferTest above. + CheckMonsterObject(monster2.get()); + + // Test object copy. + MonsterT monster3 = *monster2; + flatbuffers::FlatBufferBuilder fbb3; + fbb3.Finish(CreateMonster(fbb3, &monster3, &rehasher), MonsterIdentifier()); + const auto len3 = fbb3.GetSize(); + TEST_EQ(len2, len3); + TEST_EQ(memcmp(fbb2.GetBufferPointer(), fbb3.GetBufferPointer(), len2), 0); + // Delete monster1 and monster2, then test accessing fields in monster3. + monster1.reset(); + monster2.reset(); + CheckMonsterObject(&monster3); +} + +// Utility function to check a Monster object. +void CheckMonsterObject(MonsterT *monster2) { + TEST_EQ(monster2->hp, 80); + TEST_EQ(monster2->mana, 150); // default + TEST_EQ_STR(monster2->name.c_str(), "MyMonster"); + + auto &pos = monster2->pos; + TEST_NOTNULL(pos); + TEST_EQ(pos->z(), 3); + TEST_EQ(pos->test3().a(), 10); + TEST_EQ(pos->test3().b(), 20); + + auto &inventory = monster2->inventory; + TEST_EQ(inventory.size(), 10UL); + unsigned char inv_data[] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }; + for (auto it = inventory.begin(); it != inventory.end(); ++it) + TEST_EQ(*it, inv_data[it - inventory.begin()]); + + TEST_EQ(monster2->color, Color_Blue); + + auto monster3 = monster2->test.AsMonster(); + TEST_NOTNULL(monster3); + TEST_EQ_STR(monster3->name.c_str(), "Fred"); + + auto &vecofstrings = monster2->testarrayofstring; + TEST_EQ(vecofstrings.size(), 4U); + TEST_EQ_STR(vecofstrings[0].c_str(), "bob"); + TEST_EQ_STR(vecofstrings[1].c_str(), "fred"); + + auto &vecofstrings2 = monster2->testarrayofstring2; + TEST_EQ(vecofstrings2.size(), 2U); + TEST_EQ_STR(vecofstrings2[0].c_str(), "jane"); + TEST_EQ_STR(vecofstrings2[1].c_str(), "mary"); + + auto &vecoftables = monster2->testarrayoftables; + TEST_EQ(vecoftables.size(), 3U); + TEST_EQ_STR(vecoftables[0]->name.c_str(), "Barney"); + TEST_EQ(vecoftables[0]->hp, 1000); + TEST_EQ_STR(vecoftables[1]->name.c_str(), "Fred"); + TEST_EQ_STR(vecoftables[2]->name.c_str(), "Wilma"); + + auto &tests = monster2->test4; + TEST_EQ(tests[0].a(), 10); + TEST_EQ(tests[0].b(), 20); + TEST_EQ(tests[1].a(), 30); + TEST_EQ(tests[1].b(), 40); +} + +// Prefix a FlatBuffer with a size field. +void SizePrefixedTest() { + // Create size prefixed buffer. + flatbuffers::FlatBufferBuilder fbb; + FinishSizePrefixedMonsterBuffer( + fbb, CreateMonster(fbb, nullptr, 200, 300, fbb.CreateString("bob"))); + + // Verify it. + flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize()); + TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier), true); + + // The prefixed size doesn't include itself, so substract the size of the + // prefix + TEST_EQ(GetPrefixedSize(fbb.GetBufferPointer()), + fbb.GetSize() - sizeof(uoffset_t)); + + // Getting the buffer length does include the prefix size, so it should be the + // full lenght. + TEST_EQ(GetSizePrefixedBufferLength(fbb.GetBufferPointer()), fbb.GetSize()); + + // Access it. + auto m = GetSizePrefixedMonster(fbb.GetBufferPointer()); + TEST_EQ(m->mana(), 200); + TEST_EQ(m->hp(), 300); + TEST_EQ_STR(m->name()->c_str(), "bob"); + + { + // Verify that passing a larger size is OK, but not a smaller + flatbuffers::Verifier verifier_larger(fbb.GetBufferPointer(), + fbb.GetSize() + 10); + TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier_larger), true); + + flatbuffers::Verifier verifier_smaller(fbb.GetBufferPointer(), + fbb.GetSize() - 10); + TEST_EQ(VerifySizePrefixedMonsterBuffer(verifier_smaller), false); + } +} + +void TestMonsterExtraFloats(const std::string &tests_data_path) { +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) + TEST_EQ(is_quiet_nan(1.0), false); + TEST_EQ(is_quiet_nan(infinity_d), false); + TEST_EQ(is_quiet_nan(-infinity_f), false); + TEST_EQ(is_quiet_nan(std::numeric_limits::quiet_NaN()), true); + TEST_EQ(is_quiet_nan(std::numeric_limits::quiet_NaN()), true); + + using namespace flatbuffers; + using namespace MyGame; + // Load FlatBuffer schema (.fbs) from disk. + std::string schemafile; + TEST_EQ(LoadFile((tests_data_path + "monster_extra.fbs").c_str(), false, + &schemafile), + true); + // Parse schema first, so we can use it to parse the data after. + Parser parser; + auto include_test_path = ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); + // Create empty extra and store to json. + parser.opts.output_default_scalars_in_json = true; + parser.opts.output_enum_identifiers = true; + FlatBufferBuilder builder; + const auto def_root = MonsterExtraBuilder(builder).Finish(); + FinishMonsterExtraBuffer(builder, def_root); + const auto def_obj = builder.GetBufferPointer(); + const auto def_extra = GetMonsterExtra(def_obj); + TEST_NOTNULL(def_extra); + TEST_EQ(is_quiet_nan(def_extra->f0()), true); + TEST_EQ(is_quiet_nan(def_extra->f1()), true); + TEST_EQ(def_extra->f2(), +infinity_f); + TEST_EQ(def_extra->f3(), -infinity_f); + TEST_EQ(is_quiet_nan(def_extra->d0()), true); + TEST_EQ(is_quiet_nan(def_extra->d1()), true); + TEST_EQ(def_extra->d2(), +infinity_d); + TEST_EQ(def_extra->d3(), -infinity_d); + std::string jsongen; + auto result = GenText(parser, def_obj, &jsongen); + TEST_NULL(result); + // Check expected default values. + TEST_EQ(std::string::npos != jsongen.find("f0: nan"), true); + TEST_EQ(std::string::npos != jsongen.find("f1: nan"), true); + TEST_EQ(std::string::npos != jsongen.find("f2: inf"), true); + TEST_EQ(std::string::npos != jsongen.find("f3: -inf"), true); + TEST_EQ(std::string::npos != jsongen.find("d0: nan"), true); + TEST_EQ(std::string::npos != jsongen.find("d1: nan"), true); + TEST_EQ(std::string::npos != jsongen.find("d2: inf"), true); + TEST_EQ(std::string::npos != jsongen.find("d3: -inf"), true); + // Parse 'mosterdata_extra.json'. + const auto extra_base = tests_data_path + "monsterdata_extra"; + jsongen = ""; + TEST_EQ(LoadFile((extra_base + ".json").c_str(), false, &jsongen), true); + TEST_EQ(parser.Parse(jsongen.c_str()), true); + const auto test_file = parser.builder_.GetBufferPointer(); + const auto test_size = parser.builder_.GetSize(); + Verifier verifier(test_file, test_size); + TEST_ASSERT(VerifyMonsterExtraBuffer(verifier)); + const auto extra = GetMonsterExtra(test_file); + TEST_NOTNULL(extra); + TEST_EQ(is_quiet_nan(extra->f0()), true); + TEST_EQ(is_quiet_nan(extra->f1()), true); + TEST_EQ(extra->f2(), +infinity_f); + TEST_EQ(extra->f3(), -infinity_f); + TEST_EQ(is_quiet_nan(extra->d0()), true); + TEST_EQ(extra->d1(), +infinity_d); + TEST_EQ(extra->d2(), -infinity_d); + TEST_EQ(is_quiet_nan(extra->d3()), true); + TEST_NOTNULL(extra->fvec()); + TEST_EQ(extra->fvec()->size(), 4); + TEST_EQ(extra->fvec()->Get(0), 1.0f); + TEST_EQ(extra->fvec()->Get(1), -infinity_f); + TEST_EQ(extra->fvec()->Get(2), +infinity_f); + TEST_EQ(is_quiet_nan(extra->fvec()->Get(3)), true); + TEST_NOTNULL(extra->dvec()); + TEST_EQ(extra->dvec()->size(), 4); + TEST_EQ(extra->dvec()->Get(0), 2.0); + TEST_EQ(extra->dvec()->Get(1), +infinity_d); + TEST_EQ(extra->dvec()->Get(2), -infinity_d); + TEST_EQ(is_quiet_nan(extra->dvec()->Get(3)), true); +#endif +} + +void EnumNamesTest() { + TEST_EQ_STR("Red", EnumNameColor(Color_Red)); + TEST_EQ_STR("Green", EnumNameColor(Color_Green)); + TEST_EQ_STR("Blue", EnumNameColor(Color_Blue)); + // Check that Color to string don't crash while decode a mixture of Colors. + // 1) Example::Color enum is enum with unfixed underlying type. + // 2) Valid enum range: [0; 2^(ceil(log2(Color_ANY))) - 1]. + // Consequence: A value is out of this range will lead to UB (since C++17). + // For details see C++17 standard or explanation on the SO: + // stackoverflow.com/questions/18195312/what-happens-if-you-static-cast-invalid-value-to-enum-class + TEST_EQ_STR("", EnumNameColor(static_cast(0))); + TEST_EQ_STR("", EnumNameColor(static_cast(Color_ANY - 1))); + TEST_EQ_STR("", EnumNameColor(static_cast(Color_ANY + 1))); +} + +void TypeAliasesTest() { + flatbuffers::FlatBufferBuilder builder; + + builder.Finish(CreateTypeAliases( + builder, flatbuffers::numeric_limits::min(), + flatbuffers::numeric_limits::max(), + flatbuffers::numeric_limits::min(), + flatbuffers::numeric_limits::max(), + flatbuffers::numeric_limits::min(), + flatbuffers::numeric_limits::max(), + flatbuffers::numeric_limits::min(), + flatbuffers::numeric_limits::max(), 2.3f, 2.3)); + + auto p = builder.GetBufferPointer(); + auto ta = flatbuffers::GetRoot(p); + + TEST_EQ(ta->i8(), flatbuffers::numeric_limits::min()); + TEST_EQ(ta->u8(), flatbuffers::numeric_limits::max()); + TEST_EQ(ta->i16(), flatbuffers::numeric_limits::min()); + TEST_EQ(ta->u16(), flatbuffers::numeric_limits::max()); + TEST_EQ(ta->i32(), flatbuffers::numeric_limits::min()); + TEST_EQ(ta->u32(), flatbuffers::numeric_limits::max()); + TEST_EQ(ta->i64(), flatbuffers::numeric_limits::min()); + TEST_EQ(ta->u64(), flatbuffers::numeric_limits::max()); + TEST_EQ(ta->f32(), 2.3f); + TEST_EQ(ta->f64(), 2.3); + using namespace flatbuffers; // is_same + static_assert(is_samei8()), int8_t>::value, "invalid type"); + static_assert(is_samei16()), int16_t>::value, "invalid type"); + static_assert(is_samei32()), int32_t>::value, "invalid type"); + static_assert(is_samei64()), int64_t>::value, "invalid type"); + static_assert(is_sameu8()), uint8_t>::value, "invalid type"); + static_assert(is_sameu16()), uint16_t>::value, "invalid type"); + static_assert(is_sameu32()), uint32_t>::value, "invalid type"); + static_assert(is_sameu64()), uint64_t>::value, "invalid type"); + static_assert(is_samef32()), float>::value, "invalid type"); + static_assert(is_samef64()), double>::value, "invalid type"); +} + +// example of parsing text straight into a buffer, and generating +// text back from it: +void ParseAndGenerateTextTest(const std::string &tests_data_path, bool binary) { + // load FlatBuffer schema (.fbs) and JSON from disk + std::string schemafile; + std::string jsonfile; + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "monster_test." + (binary ? "bfbs" : "fbs")) + .c_str(), + binary, &schemafile), + true); + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "monsterdata_test.golden").c_str(), false, + &jsonfile), + true); + + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parser; + if (binary) { + flatbuffers::Verifier verifier( + reinterpret_cast(schemafile.c_str()), + schemafile.size()); + TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); + // auto schema = reflection::GetSchema(schemafile.c_str()); + TEST_EQ(parser.Deserialize( + reinterpret_cast(schemafile.c_str()), + schemafile.size()), + true); + } else { + TEST_EQ(parser.Parse(schemafile.c_str(), include_directories), true); + } + TEST_EQ(parser.ParseJson(jsonfile.c_str()), true); + + // here, parser.builder_ contains a binary buffer that is the parsed data. + + // First, verify it, just in case: + flatbuffers::Verifier verifier(parser.builder_.GetBufferPointer(), + parser.builder_.GetSize()); + TEST_EQ(VerifyMonsterBuffer(verifier), true); + + AccessFlatBufferTest(parser.builder_.GetBufferPointer(), + parser.builder_.GetSize(), false); + + // to ensure it is correct, we now generate text back from the binary, + // and compare the two: + std::string jsongen; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), jsonfile.c_str()); + + // We can also do the above using the convenient Registry that knows about + // a set of file_identifiers mapped to schemas. + flatbuffers::Registry registry; + // Make sure schemas can find their includes. + registry.AddIncludeDirectory(tests_data_path.c_str()); + registry.AddIncludeDirectory(include_test_path.c_str()); + // Call this with many schemas if possible. + registry.Register(MonsterIdentifier(), + (tests_data_path + "monster_test.fbs").c_str()); + // Now we got this set up, we can parse by just specifying the identifier, + // the correct schema will be loaded on the fly: + auto buf = registry.TextToFlatBuffer(jsonfile.c_str(), MonsterIdentifier()); + // If this fails, check registry.lasterror_. + TEST_NOTNULL(buf.data()); + // Test the buffer, to be sure: + AccessFlatBufferTest(buf.data(), buf.size(), false); + // We can use the registry to turn this back into text, in this case it + // will get the file_identifier from the binary: + std::string text; + auto ok = registry.FlatBufferToText(buf.data(), buf.size(), &text); + // If this fails, check registry.lasterror_. + TEST_EQ(ok, true); + TEST_EQ_STR(text.c_str(), jsonfile.c_str()); + + // Generate text for UTF-8 strings without escapes. + std::string jsonfile_utf8; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "unicode_test.json").c_str(), + false, &jsonfile_utf8), + true); + TEST_EQ(parser.Parse(jsonfile_utf8.c_str(), include_directories), true); + // To ensure it is correct, generate utf-8 text back from the binary. + std::string jsongen_utf8; + // request natural printing for utf-8 strings + parser.opts.natural_utf8 = true; + parser.opts.strict_json = true; + TEST_NULL(GenText(parser, parser.builder_.GetBufferPointer(), &jsongen_utf8)); + TEST_EQ_STR(jsongen_utf8.c_str(), jsonfile_utf8.c_str()); +} + +void UnPackTo(const uint8_t *flatbuf) { + // Get a monster that has a name and no enemy + auto orig_monster = GetMonster(flatbuf); + TEST_EQ_STR(orig_monster->name()->c_str(), "MyMonster"); + TEST_ASSERT(orig_monster->enemy() == nullptr); + + // Create an enemy + MonsterT *enemy = new MonsterT(); + enemy->name = "Enemy"; + + // And create another monster owning the enemy, + MonsterT mon; + mon.name = "I'm monster 1"; + mon.enemy.reset(enemy); + TEST_ASSERT(mon.enemy != nullptr); + + // Assert that all the Monster objects are correct. + TEST_EQ_STR(mon.name.c_str(), "I'm monster 1"); + TEST_EQ_STR(enemy->name.c_str(), "Enemy"); + TEST_EQ_STR(mon.enemy->name.c_str(), "Enemy"); + + // Now unpack monster ("MyMonster") into monster + orig_monster->UnPackTo(&mon); + + // Monster name should be from monster + TEST_EQ_STR(mon.name.c_str(), "MyMonster"); + + // The monster shouldn't have any enemies, because monster didn't. + TEST_ASSERT(mon.enemy == nullptr); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/monster_test.fbs b/third_party/flatbuffers/tests/monster_test.fbs new file mode 100644 index 00000000000..b40ecf58f95 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.fbs @@ -0,0 +1,180 @@ +// test schema file + +include "include_test1.fbs"; + +namespace MyGame; + +table InParentNamespace {} + +namespace MyGame.Example2; + +table Monster {} // Test having same name as below, but in different namespace. + +namespace MyGame.Example; + +attribute "priority"; + +/// Composite components of Monster color. +enum Color:ubyte (bit_flags) { + Red = 0, // color Red = (1u << 0) + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Green, + /// \brief color Blue (1u << 3) + Blue = 3, +} + +enum Race:byte { + None = -1, + Human = 0, + Dwarf, + Elf, +} + +enum LongEnum:ulong (bit_flags) { + LongOne = 1, + LongTwo = 2, + // Because this is a bitflag, 40 will be out of range of a 32-bit integer, + // allowing us to exercise any logic special to big numbers. + LongBig = 40, +} + +union Any { Monster, TestSimpleTableWithEnum, MyGame.Example2.Monster } + +union AnyUniqueAliases { M: Monster, TS: TestSimpleTableWithEnum, M2: MyGame.Example2.Monster } +union AnyAmbiguousAliases { M1: Monster, M2: Monster, M3: Monster } + +struct Test { a:short; b:byte; } + +table TestSimpleTableWithEnum (csharp_partial, private) { + color: Color = Green; +} + +struct Vec3 (force_align: 8) { + x:float; + y:float; + z:float; + test1:double; + test2:Color; + test3:Test; +} + +struct Ability { + id:uint(key); + distance:uint; +} + +struct StructOfStructs { + a: Ability; + b: Test; + c: Ability; +} + +struct StructOfStructsOfStructs { + a: StructOfStructs; +} + +table Stat { + id:string; + val:long; + count:ushort (key); +} + +table Referrable { + id:ulong(key, hash:"fnv1a_64"); +} + +/// an example documentation comment: "monster object" +table Monster { + pos:Vec3 (id: 0); + hp:short = 100 (id: 2); + mana:short = 150 (id: 1); + name:string (id: 3, key); + color:Color = Blue (id: 6); + inventory:[ubyte] (id: 5); + friendly:bool = false (deprecated, priority: 1, id: 4); + /// an example documentation comment: this will end up in the generated code + /// multiline too + testarrayoftables:[Monster] (id: 11); + testarrayofstring:[string] (id: 10); + testarrayofstring2:[string] (id: 28); + testarrayofbools:[bool] (id: 24); + testarrayofsortedstruct:[Ability] (id: 29); + enemy:MyGame.Example.Monster (id:12); // Test referring by full namespace. + test:Any (id: 8); + test4:[Test] (id: 9); + test5:[Test] (id: 31); + testnestedflatbuffer:[ubyte] (id:13, nested_flatbuffer: "Monster"); + testempty:Stat (id:14); + testbool:bool (id:15); + testhashs32_fnv1:int (id:16, hash:"fnv1_32"); + testhashu32_fnv1:uint (id:17, hash:"fnv1_32"); + testhashs64_fnv1:long (id:18, hash:"fnv1_64"); + testhashu64_fnv1:ulong (id:19, hash:"fnv1_64"); + testhashs32_fnv1a:int (id:20, hash:"fnv1a_32"); + testhashu32_fnv1a:uint (id:21, hash:"fnv1a_32", cpp_type:"Stat"); + testhashs64_fnv1a:long (id:22, hash:"fnv1a_64"); + testhashu64_fnv1a:ulong (id:23, hash:"fnv1a_64"); + testf:float = 3.14159 (id:25); + testf2:float = 3 (id:26); + testf3:float (id:27); + flex:[ubyte] (id:30, flexbuffer); + vector_of_longs:[long] (id:32); + vector_of_doubles:[double] (id:33); + parent_namespace_test:InParentNamespace (id:34); + vector_of_referrables:[Referrable](id:35); + single_weak_reference:ulong(id:36, hash:"fnv1a_64", cpp_type:"ReferrableT"); + vector_of_weak_references:[ulong](id:37, hash:"fnv1a_64", cpp_type:"ReferrableT"); + vector_of_strong_referrables:[Referrable](id:38, cpp_ptr_type:"default_ptr_type"); //was shared_ptr + co_owning_reference:ulong(id:39, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked"); //was shared_ptr as well + vector_of_co_owning_references:[ulong](id:40, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"default_ptr_type", cpp_ptr_type_get:".get()"); //was shared_ptr + non_owning_reference:ulong(id:41, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked", cpp_ptr_type_get:""); //was weak_ptr + vector_of_non_owning_references:[ulong](id:42, hash:"fnv1a_64", cpp_type:"ReferrableT", cpp_ptr_type:"naked", cpp_ptr_type_get:""); //was weak_ptr + any_unique:AnyUniqueAliases(id:44); + any_ambiguous:AnyAmbiguousAliases (id:46); + vector_of_enums:[Color] (id:47); + signed_enum:Race = None (id:48); + testrequirednestedflatbuffer:[ubyte] (id:49, nested_flatbuffer: "Monster"); + scalar_key_sorted_tables:[Stat] (id: 50); + native_inline:Test (id: 51, native_inline); + // The default value of this enum will be a numeric zero, which isn't a valid + // enum value. + long_enum_non_enum_default:LongEnum (id: 52); + long_enum_normal_default:LongEnum = LongOne (id: 53); + // Test that default values nan and +/-inf work. + nan_default:float = nan (id: 54); + inf_default:float = inf (id: 55); + positive_inf_default:float = +inf (id: 56); + infinity_default:float = infinity (id: 57); + positive_infinity_default:float = +infinity (id: 58); + negative_inf_default:float = -inf (id: 59); + negative_infinity_default:float = -infinity (id: 60); + double_inf_default:double = inf (id: 61); +} + +table TypeAliases { + i8:int8; + u8:uint8; + i16:int16; + u16:uint16; + i32:int32; + u32:uint32; + i64:int64; + u64:uint64; + f32:float32; + f64:float64; + v8:[int8]; + vf64:[float64]; +} + +rpc_service MonsterStorage { + Store(Monster):Stat (streaming: "none"); + Retrieve(Stat):Monster (streaming: "server", idempotent); + GetMaxHitPoint(Monster):Stat (streaming: "client"); + GetMinMaxHitPoints(Monster):Stat (streaming: "bidi"); +} + +root_type Monster; + +file_identifier "MONS"; +file_extension "mon"; diff --git a/third_party/flatbuffers/tests/monster_test.grpc.fb.cc b/third_party/flatbuffers/tests/monster_test.grpc.fb.cc new file mode 100644 index 00000000000..f3ac13696aa --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.grpc.fb.cc @@ -0,0 +1,131 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test + +#include "monster_test_generated.h" +#include "monster_test.grpc.fb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +namespace MyGame { +namespace Example { + +static const char* MonsterStorage_method_names[] = { + "/MyGame.Example.MonsterStorage/Store", + "/MyGame.Example.MonsterStorage/Retrieve", + "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", +}; + +std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) { + std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel)); + return stub; +} + +MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) + : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) + , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) + , rpcmethod_GetMaxHitPoint_(MonsterStorage_method_names[2], ::grpc::internal::RpcMethod::CLIENT_STREAMING, channel) + , rpcmethod_GetMinMaxHitPoints_(MonsterStorage_method_names[3], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel) + {} + +::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) { + return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false); +} + +::grpc::ClientReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_Retrieve_, context, request); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr); +} + +::grpc::ClientWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return ::grpc::internal::ClientWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMaxHitPoint_, context, response); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, true, tag); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, false, nullptr); +} + +::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMinMaxHitPointsRaw(::grpc::ClientContext* context) { + return ::grpc::internal::ClientReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMinMaxHitPoints_, context); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, true, tag); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, false, nullptr); +} + +MonsterStorage::Service::Service() { + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[0], + ::grpc::internal::RpcMethod::NORMAL_RPC, + new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Store), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[1], + ::grpc::internal::RpcMethod::SERVER_STREAMING, + new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Retrieve), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[2], + ::grpc::internal::RpcMethod::CLIENT_STREAMING, + new ::grpc::internal::ClientStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMaxHitPoint), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[3], + ::grpc::internal::RpcMethod::BIDI_STREAMING, + new ::grpc::internal::BidiStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMinMaxHitPoints), this))); +} + +MonsterStorage::Service::~Service() { +} + +::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + + +} // namespace MyGame +} // namespace Example + diff --git a/third_party/flatbuffers/tests/monster_test.grpc.fb.h b/third_party/flatbuffers/tests/monster_test.grpc.fb.h new file mode 100644 index 00000000000..e3f3037ba5a --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.grpc.fb.h @@ -0,0 +1,350 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test +#ifndef GRPC_monster_5ftest__INCLUDED +#define GRPC_monster_5ftest__INCLUDED + +#include "monster_test_generated.h" +#include "flatbuffers/grpc.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class Channel; +class ServerCompletionQueue; +class ServerContext; +} // namespace grpc + +namespace MyGame { +namespace Example { + +class MonsterStorage final { + public: + static constexpr char const* service_full_name() { + return "MyGame.Example.MonsterStorage"; + } + class StubInterface { + public: + virtual ~StubInterface() {} + virtual ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + private: + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReader< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientWriter< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override; + const ::grpc::internal::RpcMethod rpcmethod_Store_; + const ::grpc::internal::RpcMethod rpcmethod_Retrieve_; + const ::grpc::internal::RpcMethod rpcmethod_GetMaxHitPoint_; + const ::grpc::internal::RpcMethod rpcmethod_GetMinMaxHitPoints_; + }; + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class Service : public ::grpc::Service { + public: + Service(); + virtual ~Service(); + virtual ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, flatbuffers::grpc::Message* response); + virtual ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, ::grpc::ServerWriter< flatbuffers::grpc::Message>* writer); + virtual ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message>* reader, flatbuffers::grpc::Message* response); + virtual ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream); + }; + template + class WithAsyncMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Store() { + ::grpc::Service::MarkMethodAsync(0); + } + ~WithAsyncMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestStore(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncResponseWriter< flatbuffers::grpc::Message>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Retrieve() { + ::grpc::Service::MarkMethodAsync(1); + } + ~WithAsyncMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestRetrieve(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncWriter< flatbuffers::grpc::Message>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncServerStreaming(1, context, request, writer, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodAsync(2); + } + ~WithAsyncMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* reader, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncClientStreaming(2, context, reader, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodAsync(3); + } + ~WithAsyncMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(3, context, stream, new_call_cq, notification_cq, tag); + } + }; + typedef WithAsyncMethod_Store< WithAsyncMethod_Retrieve< WithAsyncMethod_GetMaxHitPoint< WithAsyncMethod_GetMinMaxHitPoints< Service > > > > AsyncService; + template + class WithGenericMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Store() { + ::grpc::Service::MarkMethodGeneric(0); + } + ~WithGenericMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Retrieve() { + ::grpc::Service::MarkMethodGeneric(1); + } + ~WithGenericMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodGeneric(2); + } + ~WithGenericMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodGeneric(3); + } + ~WithGenericMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithStreamedUnaryMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithStreamedUnaryMethod_Store() { + ::grpc::Service::MarkMethodStreamed(0, + new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithStreamedUnaryMethod_Store::StreamedStore, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedStore(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_unary_streamer) = 0; + }; + typedef WithStreamedUnaryMethod_Store< Service > StreamedUnaryService; + template + class WithSplitStreamingMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) { } + public: + WithSplitStreamingMethod_Retrieve() { + ::grpc::Service::MarkMethodStreamed(1, + new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithSplitStreamingMethod_Retrieve::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithSplitStreamingMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with split streamed + virtual ::grpc::Status StreamedRetrieve(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_split_streamer) = 0; + }; + typedef WithSplitStreamingMethod_Retrieve< Service > SplitStreamedService; + typedef WithStreamedUnaryMethod_Store< WithSplitStreamingMethod_Retrieve< Service > > StreamedService; +}; + +} // namespace Example +} // namespace MyGame + + +#endif // GRPC_monster_5ftest__INCLUDED diff --git a/third_party/flatbuffers/tests/monster_test.h b/third_party/flatbuffers/tests/monster_test.h new file mode 100644 index 00000000000..9a2110a8bfa --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.h @@ -0,0 +1,38 @@ +#ifndef TESTS_MONSTER_TEST_H +#define TESTS_MONSTER_TEST_H + +#include + +#include "flatbuffers/detached_buffer.h" +#include "monster_test_generated.h" + +namespace flatbuffers { +namespace tests { + +flatbuffers::DetachedBuffer CreateFlatBufferTest(std::string &buffer); + +void AccessFlatBufferTest(const uint8_t *flatbuf, size_t length, + bool pooled = true); + +void MutateFlatBuffersTest(uint8_t *flatbuf, std::size_t length); + +void ObjectFlatBuffersTest(uint8_t *flatbuf); + +void CheckMonsterObject(MyGame::Example::MonsterT *monster2); + +void SizePrefixedTest(); + +void TestMonsterExtraFloats(const std::string& tests_data_path); + +void EnumNamesTest(); + +void TypeAliasesTest(); + +void ParseAndGenerateTextTest(const std::string& tests_data_path, bool binary); + +void UnPackTo(const uint8_t *flatbuf); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/monster_test.schema.json b/third_party/flatbuffers/tests/monster_test.schema.json new file mode 100644 index 00000000000..edcfbd9e249 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test.schema.json @@ -0,0 +1,416 @@ +{ + "$schema": "https://json-schema.org/draft/2019-09/schema", + "definitions": { + "MyGame_OtherNameSpace_FromInclude" : { + "type" : "string", + "enum": ["IncludeVal"] + }, + "MyGame_Example_Color" : { + "type" : "string", + "enum": ["Red", "Green", "Blue"] + }, + "MyGame_Example_Race" : { + "type" : "string", + "enum": ["None", "Human", "Dwarf", "Elf"] + }, + "MyGame_Example_LongEnum" : { + "type" : "string", + "enum": ["LongOne", "LongTwo", "LongBig"] + }, + "MyGame_Example_Any" : { + "type" : "string", + "enum": ["NONE", "Monster", "TestSimpleTableWithEnum", "MyGame_Example2_Monster"] + }, + "MyGame_Example_AnyUniqueAliases" : { + "type" : "string", + "enum": ["NONE", "M", "TS", "M2"] + }, + "MyGame_Example_AnyAmbiguousAliases" : { + "type" : "string", + "enum": ["NONE", "M1", "M2", "M3"] + }, + "MyGame_OtherNameSpace_Unused" : { + "type" : "object", + "properties" : { + "a" : { + "type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647 + } + }, + "additionalProperties" : false + }, + "MyGame_OtherNameSpace_TableB" : { + "type" : "object", + "properties" : { + "a" : { + "$ref" : "#/definitions/TableA" + } + }, + "additionalProperties" : false + }, + "TableA" : { + "type" : "object", + "properties" : { + "b" : { + "$ref" : "#/definitions/MyGame_OtherNameSpace_TableB" + } + }, + "additionalProperties" : false + }, + "MyGame_InParentNamespace" : { + "type" : "object", + "properties" : { + }, + "additionalProperties" : false + }, + "MyGame_Example2_Monster" : { + "type" : "object", + "properties" : { + }, + "additionalProperties" : false + }, + "MyGame_Example_Test" : { + "type" : "object", + "properties" : { + "a" : { + "type" : "integer", "minimum" : -32768, "maximum" : 32767 + }, + "b" : { + "type" : "integer", "minimum" : -128, "maximum" : 127 + } + }, + "additionalProperties" : false + }, + "MyGame_Example_TestSimpleTableWithEnum" : { + "type" : "object", + "properties" : { + "color" : { + "$ref" : "#/definitions/MyGame_Example_Color" + } + }, + "additionalProperties" : false + }, + "MyGame_Example_Vec3" : { + "type" : "object", + "properties" : { + "x" : { + "type" : "number" + }, + "y" : { + "type" : "number" + }, + "z" : { + "type" : "number" + }, + "test1" : { + "type" : "number" + }, + "test2" : { + "$ref" : "#/definitions/MyGame_Example_Color" + }, + "test3" : { + "$ref" : "#/definitions/MyGame_Example_Test" + } + }, + "additionalProperties" : false + }, + "MyGame_Example_Ability" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", "minimum" : 0, "maximum" : 4294967295 + }, + "distance" : { + "type" : "integer", "minimum" : 0, "maximum" : 4294967295 + } + }, + "additionalProperties" : false + }, + "MyGame_Example_StructOfStructs" : { + "type" : "object", + "properties" : { + "a" : { + "$ref" : "#/definitions/MyGame_Example_Ability" + }, + "b" : { + "$ref" : "#/definitions/MyGame_Example_Test" + }, + "c" : { + "$ref" : "#/definitions/MyGame_Example_Ability" + } + }, + "additionalProperties" : false + }, + "MyGame_Example_StructOfStructsOfStructs" : { + "type" : "object", + "properties" : { + "a" : { + "$ref" : "#/definitions/MyGame_Example_StructOfStructs" + } + }, + "additionalProperties" : false + }, + "MyGame_Example_Stat" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "string" + }, + "val" : { + "type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807 + }, + "count" : { + "type" : "integer", "minimum" : 0, "maximum" : 65535 + } + }, + "additionalProperties" : false + }, + "MyGame_Example_Referrable" : { + "type" : "object", + "properties" : { + "id" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + } + }, + "additionalProperties" : false + }, + "MyGame_Example_Monster" : { + "type" : "object", + "description" : "an example documentation comment: \"monster object\"", + "properties" : { + "pos" : { + "$ref" : "#/definitions/MyGame_Example_Vec3" + }, + "mana" : { + "type" : "integer", "minimum" : -32768, "maximum" : 32767 + }, + "hp" : { + "type" : "integer", "minimum" : -32768, "maximum" : 32767 + }, + "name" : { + "type" : "string" + }, + "friendly" : { + "type" : "boolean", + "deprecated" : true + }, + "inventory" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255} + }, + "color" : { + "$ref" : "#/definitions/MyGame_Example_Color" + }, + "test_type" : { + "$ref" : "#/definitions/MyGame_Example_Any" + }, + "test" : { + "anyOf": [{ "$ref" : "#/definitions/MyGame_Example_Monster" },{ "$ref" : "#/definitions/MyGame_Example_TestSimpleTableWithEnum" },{ "$ref" : "#/definitions/MyGame_Example2_Monster" }] + }, + "test4" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Test"} + }, + "testarrayofstring" : { + "type" : "array", "items" : {"type" : "string"} + }, + "testarrayoftables" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Monster"}, + "description" : "an example documentation comment: this will end up in the generated code\nmultiline too" + }, + "enemy" : { + "$ref" : "#/definitions/MyGame_Example_Monster" + }, + "testnestedflatbuffer" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255} + }, + "testempty" : { + "$ref" : "#/definitions/MyGame_Example_Stat" + }, + "testbool" : { + "type" : "boolean" + }, + "testhashs32_fnv1" : { + "type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647 + }, + "testhashu32_fnv1" : { + "type" : "integer", "minimum" : 0, "maximum" : 4294967295 + }, + "testhashs64_fnv1" : { + "type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807 + }, + "testhashu64_fnv1" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + }, + "testhashs32_fnv1a" : { + "type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647 + }, + "testhashu32_fnv1a" : { + "type" : "integer", "minimum" : 0, "maximum" : 4294967295 + }, + "testhashs64_fnv1a" : { + "type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807 + }, + "testhashu64_fnv1a" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + }, + "testarrayofbools" : { + "type" : "array", "items" : {"type" : "boolean"} + }, + "testf" : { + "type" : "number" + }, + "testf2" : { + "type" : "number" + }, + "testf3" : { + "type" : "number" + }, + "testarrayofstring2" : { + "type" : "array", "items" : {"type" : "string"} + }, + "testarrayofsortedstruct" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Ability"} + }, + "flex" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255} + }, + "test5" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Test"} + }, + "vector_of_longs" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807} + }, + "vector_of_doubles" : { + "type" : "array", "items" : {"type" : "number"} + }, + "parent_namespace_test" : { + "$ref" : "#/definitions/MyGame_InParentNamespace" + }, + "vector_of_referrables" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Referrable"} + }, + "single_weak_reference" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + }, + "vector_of_weak_references" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615} + }, + "vector_of_strong_referrables" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Referrable"} + }, + "co_owning_reference" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + }, + "vector_of_co_owning_references" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615} + }, + "non_owning_reference" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + }, + "vector_of_non_owning_references" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615} + }, + "any_unique_type" : { + "$ref" : "#/definitions/MyGame_Example_AnyUniqueAliases" + }, + "any_unique" : { + "anyOf": [{ "$ref" : "#/definitions/MyGame_Example_Monster" },{ "$ref" : "#/definitions/MyGame_Example_TestSimpleTableWithEnum" },{ "$ref" : "#/definitions/MyGame_Example2_Monster" }] + }, + "any_ambiguous_type" : { + "$ref" : "#/definitions/MyGame_Example_AnyAmbiguousAliases" + }, + "any_ambiguous" : { + "anyOf": [{ "$ref" : "#/definitions/MyGame_Example_Monster" },{ "$ref" : "#/definitions/MyGame_Example_Monster" },{ "$ref" : "#/definitions/MyGame_Example_Monster" }] + }, + "vector_of_enums" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Color"} + }, + "signed_enum" : { + "$ref" : "#/definitions/MyGame_Example_Race" + }, + "testrequirednestedflatbuffer" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : 0, "maximum" :255} + }, + "scalar_key_sorted_tables" : { + "type" : "array", "items" : {"$ref" : "#/definitions/MyGame_Example_Stat"} + }, + "native_inline" : { + "$ref" : "#/definitions/MyGame_Example_Test" + }, + "long_enum_non_enum_default" : { + "$ref" : "#/definitions/MyGame_Example_LongEnum" + }, + "long_enum_normal_default" : { + "$ref" : "#/definitions/MyGame_Example_LongEnum" + }, + "nan_default" : { + "type" : "number" + }, + "inf_default" : { + "type" : "number" + }, + "positive_inf_default" : { + "type" : "number" + }, + "infinity_default" : { + "type" : "number" + }, + "positive_infinity_default" : { + "type" : "number" + }, + "negative_inf_default" : { + "type" : "number" + }, + "negative_infinity_default" : { + "type" : "number" + }, + "double_inf_default" : { + "type" : "number" + } + }, + "required" : ["name"], + "additionalProperties" : false + }, + "MyGame_Example_TypeAliases" : { + "type" : "object", + "properties" : { + "i8" : { + "type" : "integer", "minimum" : -128, "maximum" : 127 + }, + "u8" : { + "type" : "integer", "minimum" : 0, "maximum" :255 + }, + "i16" : { + "type" : "integer", "minimum" : -32768, "maximum" : 32767 + }, + "u16" : { + "type" : "integer", "minimum" : 0, "maximum" : 65535 + }, + "i32" : { + "type" : "integer", "minimum" : -2147483648, "maximum" : 2147483647 + }, + "u32" : { + "type" : "integer", "minimum" : 0, "maximum" : 4294967295 + }, + "i64" : { + "type" : "integer", "minimum" : -9223372036854775808, "maximum" : 9223372036854775807 + }, + "u64" : { + "type" : "integer", "minimum" : 0, "maximum" : 18446744073709551615 + }, + "f32" : { + "type" : "number" + }, + "f64" : { + "type" : "number" + }, + "v8" : { + "type" : "array", "items" : {"type" : "integer", "minimum" : -128, "maximum" : 127} + }, + "vf64" : { + "type" : "array", "items" : {"type" : "number"} + } + }, + "additionalProperties" : false + } + }, + "$ref" : "#/definitions/MyGame_Example_Monster" +} diff --git a/third_party/flatbuffers/tests/monster_test/mod.rs b/third_party/flatbuffers/tests/monster_test/mod.rs new file mode 100644 index 00000000000..7f1fab13624 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/mod.rs @@ -0,0 +1,58 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod my_game { + use super::*; + pub mod example { + use super::*; + mod color_generated; + pub use self::color_generated::*; + mod race_generated; + pub use self::race_generated::*; + mod long_enum_generated; + pub use self::long_enum_generated::*; + mod any_generated; + pub use self::any_generated::*; + mod any_unique_aliases_generated; + pub use self::any_unique_aliases_generated::*; + mod any_ambiguous_aliases_generated; + pub use self::any_ambiguous_aliases_generated::*; + mod test_generated; + pub use self::test_generated::*; + mod test_simple_table_with_enum_generated; + pub use self::test_simple_table_with_enum_generated::*; + mod vec_3_generated; + pub use self::vec_3_generated::*; + mod ability_generated; + pub use self::ability_generated::*; + mod struct_of_structs_generated; + pub use self::struct_of_structs_generated::*; + mod struct_of_structs_of_structs_generated; + pub use self::struct_of_structs_of_structs_generated::*; + mod stat_generated; + pub use self::stat_generated::*; + mod referrable_generated; + pub use self::referrable_generated::*; + mod monster_generated; + pub use self::monster_generated::*; + mod type_aliases_generated; + pub use self::type_aliases_generated::*; + } // example + pub mod example_2 { + use super::*; + mod monster_generated; + pub use self::monster_generated::*; + } // example_2 + pub mod other_name_space { + use super::*; + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space + mod in_parent_namespace_generated; + pub use self::in_parent_namespace_generated::*; +} // my_game +mod table_a_generated; +pub use self::table_a_generated::*; diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/ability_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/ability_generated.rs new file mode 100644 index 00000000000..0cef974d6ef --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/ability_generated.rs @@ -0,0 +1,173 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Ability, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Ability(pub [u8; 8]); +impl Default for Ability { + fn default() -> Self { + Self([0; 8]) + } +} +impl core::fmt::Debug for Ability { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Ability") + .field("id", &self.id()) + .field("distance", &self.distance()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Ability {} +impl<'a> flatbuffers::Follow<'a> for Ability { + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Ability>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Ability { + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Ability { + type Output = Ability; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Ability as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Ability { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Ability { + #[allow(clippy::too_many_arguments)] + pub fn new( + id: u32, + distance: u32, + ) -> Self { + let mut s = Self([0; 8]); + s.set_id(id); + s.set_distance(distance); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Ability" + } + + pub fn id(&self) -> u32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_id(&mut self, x: u32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + #[inline] + pub fn key_compare_less_than(&self, o: &Ability) -> bool { + self.id() < o.id() + } + + #[inline] + pub fn key_compare_with_value(&self, val: u32) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } + pub fn distance(&self) -> u32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_distance(&mut self, x: u32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> AbilityT { + AbilityT { + id: self.id(), + distance: self.distance(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AbilityT { + pub id: u32, + pub distance: u32, +} +impl AbilityT { + pub fn pack(&self) -> Ability { + Ability::new( + self.id, + self.distance, + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs new file mode 100644 index 00000000000..f4001fd7063 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/any_ambiguous_aliases_generated.rs @@ -0,0 +1,201 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [ + AnyAmbiguousAliases::NONE, + AnyAmbiguousAliases::M1, + AnyAmbiguousAliases::M2, + AnyAmbiguousAliases::M3, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct AnyAmbiguousAliases(pub u8); +#[allow(non_upper_case_globals)] +impl AnyAmbiguousAliases { + pub const NONE: Self = Self(0); + pub const M1: Self = Self(1); + pub const M2: Self = Self(2); + pub const M3: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M1, + Self::M2, + Self::M3, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M1 => Some("M1"), + Self::M2 => Some("M2"), + Self::M3 => Some("M3"), + _ => None, + } + } +} +impl core::fmt::Debug for AnyAmbiguousAliases { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for AnyAmbiguousAliases { + type Output = AnyAmbiguousAliases; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for AnyAmbiguousAliases { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for AnyAmbiguousAliases { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {} +pub struct AnyAmbiguousAliasesUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum AnyAmbiguousAliasesT { + NONE, + M1(Box), + M2(Box), + M3(Box), +} +impl Default for AnyAmbiguousAliasesT { + fn default() -> Self { + Self::NONE + } +} +impl AnyAmbiguousAliasesT { + pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { + match self { + Self::NONE => AnyAmbiguousAliases::NONE, + Self::M1(_) => AnyAmbiguousAliases::M1, + Self::M2(_) => AnyAmbiguousAliases::M2, + Self::M3(_) => AnyAmbiguousAliases::M3, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::M1(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), + Self::M3(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m1(&mut self) -> Option> { + if let Self::M1(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M1(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m1(&self) -> Option<&MonsterT> { + if let Self::M1(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M1(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m2(&self) -> Option<&MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m3(&mut self) -> Option> { + if let Self::M3(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M3(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m3(&self) -> Option<&MonsterT> { + if let Self::M3(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M3(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/any_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/any_generated.rs new file mode 100644 index 00000000000..4669671ea14 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/any_generated.rs @@ -0,0 +1,201 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY: [Any; 4] = [ + Any::NONE, + Any::Monster, + Any::TestSimpleTableWithEnum, + Any::MyGame_Example2_Monster, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct Any(pub u8); +#[allow(non_upper_case_globals)] +impl Any { + pub const NONE: Self = Self(0); + pub const Monster: Self = Self(1); + pub const TestSimpleTableWithEnum: Self = Self(2); + pub const MyGame_Example2_Monster: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::Monster, + Self::TestSimpleTableWithEnum, + Self::MyGame_Example2_Monster, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::Monster => Some("Monster"), + Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"), + Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"), + _ => None, + } + } +} +impl core::fmt::Debug for Any { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for Any { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for Any { + type Output = Any; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for Any { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for Any { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Any {} +pub struct AnyUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum AnyT { + NONE, + Monster(Box), + TestSimpleTableWithEnum(Box), + MyGameExample2Monster(Box), +} +impl Default for AnyT { + fn default() -> Self { + Self::NONE + } +} +impl AnyT { + pub fn any_type(&self) -> Any { + match self { + Self::NONE => Any::NONE, + Self::Monster(_) => Any::Monster, + Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum, + Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::Monster(v) => Some(v.pack(fbb).as_union_value()), + Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()), + Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_monster(&mut self) -> Option> { + if let Self::Monster(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_monster(&self) -> Option<&MonsterT> { + if let Self::Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::Monster(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_test_simple_table_with_enum(&mut self) -> Option> { + if let Self::TestSimpleTableWithEnum(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::TestSimpleTableWithEnum(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_my_game_example_2_monster(&mut self) -> Option> { + if let Self::MyGameExample2Monster(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::MyGameExample2Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/any_unique_aliases_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/any_unique_aliases_generated.rs new file mode 100644 index 00000000000..f2ee8462536 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/any_unique_aliases_generated.rs @@ -0,0 +1,201 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [ + AnyUniqueAliases::NONE, + AnyUniqueAliases::M, + AnyUniqueAliases::TS, + AnyUniqueAliases::M2, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct AnyUniqueAliases(pub u8); +#[allow(non_upper_case_globals)] +impl AnyUniqueAliases { + pub const NONE: Self = Self(0); + pub const M: Self = Self(1); + pub const TS: Self = Self(2); + pub const M2: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M, + Self::TS, + Self::M2, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M => Some("M"), + Self::TS => Some("TS"), + Self::M2 => Some("M2"), + _ => None, + } + } +} +impl core::fmt::Debug for AnyUniqueAliases { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for AnyUniqueAliases { + type Output = AnyUniqueAliases; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for AnyUniqueAliases { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for AnyUniqueAliases { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {} +pub struct AnyUniqueAliasesUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum AnyUniqueAliasesT { + NONE, + M(Box), + TS(Box), + M2(Box), +} +impl Default for AnyUniqueAliasesT { + fn default() -> Self { + Self::NONE + } +} +impl AnyUniqueAliasesT { + pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases { + match self { + Self::NONE => AnyUniqueAliases::NONE, + Self::M(_) => AnyUniqueAliases::M, + Self::TS(_) => AnyUniqueAliases::TS, + Self::M2(_) => AnyUniqueAliases::M2, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::M(v) => Some(v.pack(fbb).as_union_value()), + Self::TS(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m(&mut self) -> Option> { + if let Self::M(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m(&self) -> Option<&MonsterT> { + if let Self::M(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_ts(&mut self) -> Option> { + if let Self::TS(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::TS(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/color_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/color_generated.rs new file mode 100644 index 00000000000..713e2b3da36 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/color_generated.rs @@ -0,0 +1,70 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[allow(non_upper_case_globals)] +mod bitflags_color { + flatbuffers::bitflags::bitflags! { + /// Composite components of Monster color. + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct Color: u8 { + const Red = 1; + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + const Green = 2; + /// \brief color Blue (1u << 3) + const Blue = 8; + } + } +} +pub use self::bitflags_color::Color; + +impl<'a> flatbuffers::Follow<'a> for Color { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self::from_bits_retain(b) + } +} + +impl flatbuffers::Push for Color { + type Output = Color; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.bits()); + } +} + +impl flatbuffers::EndianScalar for Color { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self::from_bits_retain(b) + } +} + +impl<'a> flatbuffers::Verifiable for Color { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Color {} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/long_enum_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/long_enum_generated.rs new file mode 100644 index 00000000000..c912d25b091 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/long_enum_generated.rs @@ -0,0 +1,66 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[allow(non_upper_case_globals)] +mod bitflags_long_enum { + flatbuffers::bitflags::bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct LongEnum: u64 { + const LongOne = 2; + const LongTwo = 4; + const LongBig = 1099511627776; + } + } +} +pub use self::bitflags_long_enum::LongEnum; + +impl<'a> flatbuffers::Follow<'a> for LongEnum { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self::from_bits_retain(b) + } +} + +impl flatbuffers::Push for LongEnum { + type Output = LongEnum; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.bits()); + } +} + +impl flatbuffers::EndianScalar for LongEnum { + type Scalar = u64; + #[inline] + fn to_little_endian(self) -> u64 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u64) -> Self { + let b = u64::from_le(v); + Self::from_bits_retain(b) + } +} + +impl<'a> flatbuffers::Verifiable for LongEnum { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for LongEnum {} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/monster_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/monster_generated.rs new file mode 100644 index 00000000000..9fd096ddf0c --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/monster_generated.rs @@ -0,0 +1,2015 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum MonsterOffset {} +#[derive(Copy, Clone, PartialEq)] + +/// an example documentation comment: "monster object" +pub struct Monster<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Monster<'a> { + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Monster<'a> { + pub const VT_POS: flatbuffers::VOffsetT = 4; + pub const VT_MANA: flatbuffers::VOffsetT = 6; + pub const VT_HP: flatbuffers::VOffsetT = 8; + pub const VT_NAME: flatbuffers::VOffsetT = 10; + pub const VT_INVENTORY: flatbuffers::VOffsetT = 14; + pub const VT_COLOR: flatbuffers::VOffsetT = 16; + pub const VT_TEST_TYPE: flatbuffers::VOffsetT = 18; + pub const VT_TEST: flatbuffers::VOffsetT = 20; + pub const VT_TEST4: flatbuffers::VOffsetT = 22; + pub const VT_TESTARRAYOFSTRING: flatbuffers::VOffsetT = 24; + pub const VT_TESTARRAYOFTABLES: flatbuffers::VOffsetT = 26; + pub const VT_ENEMY: flatbuffers::VOffsetT = 28; + pub const VT_TESTNESTEDFLATBUFFER: flatbuffers::VOffsetT = 30; + pub const VT_TESTEMPTY: flatbuffers::VOffsetT = 32; + pub const VT_TESTBOOL: flatbuffers::VOffsetT = 34; + pub const VT_TESTHASHS32_FNV1: flatbuffers::VOffsetT = 36; + pub const VT_TESTHASHU32_FNV1: flatbuffers::VOffsetT = 38; + pub const VT_TESTHASHS64_FNV1: flatbuffers::VOffsetT = 40; + pub const VT_TESTHASHU64_FNV1: flatbuffers::VOffsetT = 42; + pub const VT_TESTHASHS32_FNV1A: flatbuffers::VOffsetT = 44; + pub const VT_TESTHASHU32_FNV1A: flatbuffers::VOffsetT = 46; + pub const VT_TESTHASHS64_FNV1A: flatbuffers::VOffsetT = 48; + pub const VT_TESTHASHU64_FNV1A: flatbuffers::VOffsetT = 50; + pub const VT_TESTARRAYOFBOOLS: flatbuffers::VOffsetT = 52; + pub const VT_TESTF: flatbuffers::VOffsetT = 54; + pub const VT_TESTF2: flatbuffers::VOffsetT = 56; + pub const VT_TESTF3: flatbuffers::VOffsetT = 58; + pub const VT_TESTARRAYOFSTRING2: flatbuffers::VOffsetT = 60; + pub const VT_TESTARRAYOFSORTEDSTRUCT: flatbuffers::VOffsetT = 62; + pub const VT_FLEX: flatbuffers::VOffsetT = 64; + pub const VT_TEST5: flatbuffers::VOffsetT = 66; + pub const VT_VECTOR_OF_LONGS: flatbuffers::VOffsetT = 68; + pub const VT_VECTOR_OF_DOUBLES: flatbuffers::VOffsetT = 70; + pub const VT_PARENT_NAMESPACE_TEST: flatbuffers::VOffsetT = 72; + pub const VT_VECTOR_OF_REFERRABLES: flatbuffers::VOffsetT = 74; + pub const VT_SINGLE_WEAK_REFERENCE: flatbuffers::VOffsetT = 76; + pub const VT_VECTOR_OF_WEAK_REFERENCES: flatbuffers::VOffsetT = 78; + pub const VT_VECTOR_OF_STRONG_REFERRABLES: flatbuffers::VOffsetT = 80; + pub const VT_CO_OWNING_REFERENCE: flatbuffers::VOffsetT = 82; + pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: flatbuffers::VOffsetT = 84; + pub const VT_NON_OWNING_REFERENCE: flatbuffers::VOffsetT = 86; + pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: flatbuffers::VOffsetT = 88; + pub const VT_ANY_UNIQUE_TYPE: flatbuffers::VOffsetT = 90; + pub const VT_ANY_UNIQUE: flatbuffers::VOffsetT = 92; + pub const VT_ANY_AMBIGUOUS_TYPE: flatbuffers::VOffsetT = 94; + pub const VT_ANY_AMBIGUOUS: flatbuffers::VOffsetT = 96; + pub const VT_VECTOR_OF_ENUMS: flatbuffers::VOffsetT = 98; + pub const VT_SIGNED_ENUM: flatbuffers::VOffsetT = 100; + pub const VT_TESTREQUIREDNESTEDFLATBUFFER: flatbuffers::VOffsetT = 102; + pub const VT_SCALAR_KEY_SORTED_TABLES: flatbuffers::VOffsetT = 104; + pub const VT_NATIVE_INLINE: flatbuffers::VOffsetT = 106; + pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: flatbuffers::VOffsetT = 108; + pub const VT_LONG_ENUM_NORMAL_DEFAULT: flatbuffers::VOffsetT = 110; + pub const VT_NAN_DEFAULT: flatbuffers::VOffsetT = 112; + pub const VT_INF_DEFAULT: flatbuffers::VOffsetT = 114; + pub const VT_POSITIVE_INF_DEFAULT: flatbuffers::VOffsetT = 116; + pub const VT_INFINITY_DEFAULT: flatbuffers::VOffsetT = 118; + pub const VT_POSITIVE_INFINITY_DEFAULT: flatbuffers::VOffsetT = 120; + pub const VT_NEGATIVE_INF_DEFAULT: flatbuffers::VOffsetT = 122; + pub const VT_NEGATIVE_INFINITY_DEFAULT: flatbuffers::VOffsetT = 124; + pub const VT_DOUBLE_INF_DEFAULT: flatbuffers::VOffsetT = 126; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Monster" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Monster { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MonsterArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.add_double_inf_default(args.double_inf_default); + builder.add_long_enum_normal_default(args.long_enum_normal_default); + builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default); + builder.add_non_owning_reference(args.non_owning_reference); + builder.add_co_owning_reference(args.co_owning_reference); + builder.add_single_weak_reference(args.single_weak_reference); + builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a); + builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a); + builder.add_testhashu64_fnv1(args.testhashu64_fnv1); + builder.add_testhashs64_fnv1(args.testhashs64_fnv1); + builder.add_negative_infinity_default(args.negative_infinity_default); + builder.add_negative_inf_default(args.negative_inf_default); + builder.add_positive_infinity_default(args.positive_infinity_default); + builder.add_infinity_default(args.infinity_default); + builder.add_positive_inf_default(args.positive_inf_default); + builder.add_inf_default(args.inf_default); + builder.add_nan_default(args.nan_default); + if let Some(x) = args.native_inline { builder.add_native_inline(x); } + if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); } + if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); } + if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); } + if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); } + if let Some(x) = args.any_unique { builder.add_any_unique(x); } + if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); } + if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); } + if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); } + if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); } + if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); } + if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); } + if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); } + if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); } + if let Some(x) = args.test5 { builder.add_test5(x); } + if let Some(x) = args.flex { builder.add_flex(x); } + if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); } + if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); } + builder.add_testf3(args.testf3); + builder.add_testf2(args.testf2); + builder.add_testf(args.testf); + if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); } + builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a); + builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a); + builder.add_testhashu32_fnv1(args.testhashu32_fnv1); + builder.add_testhashs32_fnv1(args.testhashs32_fnv1); + if let Some(x) = args.testempty { builder.add_testempty(x); } + if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); } + if let Some(x) = args.enemy { builder.add_enemy(x); } + if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); } + if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); } + if let Some(x) = args.test4 { builder.add_test4(x); } + if let Some(x) = args.test { builder.add_test(x); } + if let Some(x) = args.inventory { builder.add_inventory(x); } + if let Some(x) = args.name { builder.add_name(x); } + if let Some(x) = args.pos { builder.add_pos(x); } + builder.add_hp(args.hp); + builder.add_mana(args.mana); + builder.add_signed_enum(args.signed_enum); + builder.add_any_ambiguous_type(args.any_ambiguous_type); + builder.add_any_unique_type(args.any_unique_type); + builder.add_testbool(args.testbool); + builder.add_test_type(args.test_type); + builder.add_color(args.color); + builder.finish() + } + + pub fn unpack(&self) -> MonsterT { + let pos = self.pos().map(|x| { + x.unpack() + }); + let mana = self.mana(); + let hp = self.hp(); + let name = { + let x = self.name(); + x.to_string() + }; + let inventory = self.inventory().map(|x| { + x.into_iter().collect() + }); + let color = self.color(); + let test = match self.test_type() { + Any::NONE => AnyT::NONE, + Any::Monster => AnyT::Monster(Box::new( + self.test_as_monster() + .expect("Invalid union table, expected `Any::Monster`.") + .unpack() + )), + Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(Box::new( + self.test_as_test_simple_table_with_enum() + .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.") + .unpack() + )), + Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(Box::new( + self.test_as_my_game_example_2_monster() + .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.") + .unpack() + )), + _ => AnyT::NONE, + }; + let test4 = self.test4().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let testarrayofstring = self.testarrayofstring().map(|x| { + x.iter().map(|s| s.to_string()).collect() + }); + let testarrayoftables = self.testarrayoftables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let enemy = self.enemy().map(|x| { + Box::new(x.unpack()) + }); + let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let testempty = self.testempty().map(|x| { + Box::new(x.unpack()) + }); + let testbool = self.testbool(); + let testhashs32_fnv1 = self.testhashs32_fnv1(); + let testhashu32_fnv1 = self.testhashu32_fnv1(); + let testhashs64_fnv1 = self.testhashs64_fnv1(); + let testhashu64_fnv1 = self.testhashu64_fnv1(); + let testhashs32_fnv1a = self.testhashs32_fnv1a(); + let testhashu32_fnv1a = self.testhashu32_fnv1a(); + let testhashs64_fnv1a = self.testhashs64_fnv1a(); + let testhashu64_fnv1a = self.testhashu64_fnv1a(); + let testarrayofbools = self.testarrayofbools().map(|x| { + x.into_iter().collect() + }); + let testf = self.testf(); + let testf2 = self.testf2(); + let testf3 = self.testf3(); + let testarrayofstring2 = self.testarrayofstring2().map(|x| { + x.iter().map(|s| s.to_string()).collect() + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let flex = self.flex().map(|x| { + x.into_iter().collect() + }); + let test5 = self.test5().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let vector_of_longs = self.vector_of_longs().map(|x| { + x.into_iter().collect() + }); + let vector_of_doubles = self.vector_of_doubles().map(|x| { + x.into_iter().collect() + }); + let parent_namespace_test = self.parent_namespace_test().map(|x| { + Box::new(x.unpack()) + }); + let vector_of_referrables = self.vector_of_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let single_weak_reference = self.single_weak_reference(); + let vector_of_weak_references = self.vector_of_weak_references().map(|x| { + x.into_iter().collect() + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let co_owning_reference = self.co_owning_reference(); + let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| { + x.into_iter().collect() + }); + let non_owning_reference = self.non_owning_reference(); + let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| { + x.into_iter().collect() + }); + let any_unique = match self.any_unique_type() { + AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE, + AnyUniqueAliases::M => AnyUniqueAliasesT::M(Box::new( + self.any_unique_as_m() + .expect("Invalid union table, expected `AnyUniqueAliases::M`.") + .unpack() + )), + AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(Box::new( + self.any_unique_as_ts() + .expect("Invalid union table, expected `AnyUniqueAliases::TS`.") + .unpack() + )), + AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(Box::new( + self.any_unique_as_m2() + .expect("Invalid union table, expected `AnyUniqueAliases::M2`.") + .unpack() + )), + _ => AnyUniqueAliasesT::NONE, + }; + let any_ambiguous = match self.any_ambiguous_type() { + AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE, + AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(Box::new( + self.any_ambiguous_as_m1() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.") + .unpack() + )), + AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(Box::new( + self.any_ambiguous_as_m2() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.") + .unpack() + )), + AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(Box::new( + self.any_ambiguous_as_m3() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.") + .unpack() + )), + _ => AnyAmbiguousAliasesT::NONE, + }; + let vector_of_enums = self.vector_of_enums().map(|x| { + x.into_iter().collect() + }); + let signed_enum = self.signed_enum(); + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let native_inline = self.native_inline().map(|x| { + x.unpack() + }); + let long_enum_non_enum_default = self.long_enum_non_enum_default(); + let long_enum_normal_default = self.long_enum_normal_default(); + let nan_default = self.nan_default(); + let inf_default = self.inf_default(); + let positive_inf_default = self.positive_inf_default(); + let infinity_default = self.infinity_default(); + let positive_infinity_default = self.positive_infinity_default(); + let negative_inf_default = self.negative_inf_default(); + let negative_infinity_default = self.negative_infinity_default(); + let double_inf_default = self.double_inf_default(); + MonsterT { + pos, + mana, + hp, + name, + inventory, + color, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + } + } + + #[inline] + pub fn pos(&self) -> Option<&'a Vec3> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POS, None)} + } + #[inline] + pub fn mana(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} + } + #[inline] + pub fn hp(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} + } + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Monster) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn inventory(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_INVENTORY, None)} + } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} + } + #[inline] + pub fn test_type(&self) -> Any { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()} + } + #[inline] + pub fn test(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TEST, None)} + } + #[inline] + pub fn test4(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TEST4, None)} + } + #[inline] + pub fn testarrayofstring(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_TESTARRAYOFSTRING, None)} + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + #[inline] + pub fn testarrayoftables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_TESTARRAYOFTABLES, None)} + } + #[inline] + pub fn enemy(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_ENEMY, None)} + } + #[inline] + pub fn testnestedflatbuffer(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTNESTEDFLATBUFFER, None)} + } + pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testnestedflatbuffer().map(|data| { + use flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { >>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn testempty(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_TESTEMPTY, None)} + } + #[inline] + pub fn testbool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTBOOL, Some(false)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1a(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1a(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1a(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1a(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testarrayofbools(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTARRAYOFBOOLS, None)} + } + #[inline] + pub fn testf(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF, Some(3.14159)).unwrap()} + } + #[inline] + pub fn testf2(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF2, Some(3.0)).unwrap()} + } + #[inline] + pub fn testf3(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF3, Some(0.0)).unwrap()} + } + #[inline] + pub fn testarrayofstring2(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_TESTARRAYOFSTRING2, None)} + } + #[inline] + pub fn testarrayofsortedstruct(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None)} + } + #[inline] + pub fn flex(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_FLEX, None)} + } + #[inline] + pub fn test5(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TEST5, None)} + } + #[inline] + pub fn vector_of_longs(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_LONGS, None)} + } + #[inline] + pub fn vector_of_doubles(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_DOUBLES, None)} + } + #[inline] + pub fn parent_namespace_test(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_PARENT_NAMESPACE_TEST, None)} + } + #[inline] + pub fn vector_of_referrables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)} + } + #[inline] + pub fn single_weak_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_weak_references(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)} + } + #[inline] + pub fn vector_of_strong_referrables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)} + } + #[inline] + pub fn co_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_co_owning_references(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)} + } + #[inline] + pub fn non_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_non_owning_references(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)} + } + #[inline] + pub fn any_unique_type(&self) -> AnyUniqueAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_unique(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_ANY_UNIQUE, None)} + } + #[inline] + pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_ambiguous(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_ANY_AMBIGUOUS, None)} + } + #[inline] + pub fn vector_of_enums(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_ENUMS, None)} + } + #[inline] + pub fn signed_enum(&self) -> Race { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()} + } + #[inline] + pub fn testrequirednestedflatbuffer(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None)} + } + pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testrequirednestedflatbuffer().map(|data| { + use flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { >>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn scalar_key_sorted_tables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)} + } + #[inline] + pub fn native_inline(&self) -> Option<&'a Test> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NATIVE_INLINE, None)} + } + #[inline] + pub fn long_enum_non_enum_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()} + } + #[inline] + pub fn long_enum_normal_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()} + } + #[inline] + pub fn nan_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NAN_DEFAULT, Some(f32::NAN)).unwrap()} + } + #[inline] + pub fn inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn negative_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INF_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn negative_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn double_inf_default(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_DOUBLE_INF_DEFAULT, Some(f64::INFINITY)).unwrap()} + } + #[inline] + #[allow(non_snake_case)] + pub fn test_as_monster(&self) -> Option> { + if self.test_type() == Any::Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_test_simple_table_with_enum(&self) -> Option> { + if self.test_type() == Any::TestSimpleTableWithEnum { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_my_game_example_2_monster(&self) -> Option> { + if self.test_type() == Any::MyGame_Example2_Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_ts(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::TS { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m2(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M2 { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m1(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m2(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m3(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + +} + +impl flatbuffers::Verifiable for Monster<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("pos", Self::VT_POS, false)? + .visit_field::("mana", Self::VT_MANA, false)? + .visit_field::("hp", Self::VT_HP, false)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>>("inventory", Self::VT_INVENTORY, false)? + .visit_field::("color", Self::VT_COLOR, false)? + .visit_union::("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| { + match key { + Any::Monster => v.verify_union_variant::>("Any::Monster", pos), + Any::TestSimpleTableWithEnum => v.verify_union_variant::>("Any::TestSimpleTableWithEnum", pos), + Any::MyGame_Example2_Monster => v.verify_union_variant::>("Any::MyGame_Example2_Monster", pos), + _ => Ok(()), + } + })? + .visit_field::>>("test4", Self::VT_TEST4, false)? + .visit_field::>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)? + .visit_field::>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)? + .visit_field::>("enemy", Self::VT_ENEMY, false)? + .visit_field::>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)? + .visit_field::>("testempty", Self::VT_TESTEMPTY, false)? + .visit_field::("testbool", Self::VT_TESTBOOL, false)? + .visit_field::("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)? + .visit_field::("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)? + .visit_field::("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)? + .visit_field::("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)? + .visit_field::("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)? + .visit_field::("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)? + .visit_field::("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)? + .visit_field::("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)? + .visit_field::>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)? + .visit_field::("testf", Self::VT_TESTF, false)? + .visit_field::("testf2", Self::VT_TESTF2, false)? + .visit_field::("testf3", Self::VT_TESTF3, false)? + .visit_field::>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)? + .visit_field::>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)? + .visit_field::>>("flex", Self::VT_FLEX, false)? + .visit_field::>>("test5", Self::VT_TEST5, false)? + .visit_field::>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)? + .visit_field::>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)? + .visit_field::>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)? + .visit_field::>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)? + .visit_field::("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)? + .visit_field::>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)? + .visit_field::>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)? + .visit_field::("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)? + .visit_field::>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)? + .visit_field::("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)? + .visit_field::>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)? + .visit_union::("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| { + match key { + AnyUniqueAliases::M => v.verify_union_variant::>("AnyUniqueAliases::M", pos), + AnyUniqueAliases::TS => v.verify_union_variant::>("AnyUniqueAliases::TS", pos), + AnyUniqueAliases::M2 => v.verify_union_variant::>("AnyUniqueAliases::M2", pos), + _ => Ok(()), + } + })? + .visit_union::("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| { + match key { + AnyAmbiguousAliases::M1 => v.verify_union_variant::>("AnyAmbiguousAliases::M1", pos), + AnyAmbiguousAliases::M2 => v.verify_union_variant::>("AnyAmbiguousAliases::M2", pos), + AnyAmbiguousAliases::M3 => v.verify_union_variant::>("AnyAmbiguousAliases::M3", pos), + _ => Ok(()), + } + })? + .visit_field::>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)? + .visit_field::("signed_enum", Self::VT_SIGNED_ENUM, false)? + .visit_field::>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)? + .visit_field::>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)? + .visit_field::("native_inline", Self::VT_NATIVE_INLINE, false)? + .visit_field::("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)? + .visit_field::("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)? + .visit_field::("nan_default", Self::VT_NAN_DEFAULT, false)? + .visit_field::("inf_default", Self::VT_INF_DEFAULT, false)? + .visit_field::("positive_inf_default", Self::VT_POSITIVE_INF_DEFAULT, false)? + .visit_field::("infinity_default", Self::VT_INFINITY_DEFAULT, false)? + .visit_field::("positive_infinity_default", Self::VT_POSITIVE_INFINITY_DEFAULT, false)? + .visit_field::("negative_inf_default", Self::VT_NEGATIVE_INF_DEFAULT, false)? + .visit_field::("negative_infinity_default", Self::VT_NEGATIVE_INFINITY_DEFAULT, false)? + .visit_field::("double_inf_default", Self::VT_DOUBLE_INF_DEFAULT, false)? + .finish(); + Ok(()) + } +} +pub struct MonsterArgs<'a> { + pub pos: Option<&'a Vec3>, + pub mana: i16, + pub hp: i16, + pub name: Option>, + pub inventory: Option>>, + pub color: Color, + pub test_type: Any, + pub test: Option>, + pub test4: Option>>, + pub testarrayofstring: Option>>>, + pub testarrayoftables: Option>>>>, + pub enemy: Option>>, + pub testnestedflatbuffer: Option>>, + pub testempty: Option>>, + pub testbool: bool, + pub testhashs32_fnv1: i32, + pub testhashu32_fnv1: u32, + pub testhashs64_fnv1: i64, + pub testhashu64_fnv1: u64, + pub testhashs32_fnv1a: i32, + pub testhashu32_fnv1a: u32, + pub testhashs64_fnv1a: i64, + pub testhashu64_fnv1a: u64, + pub testarrayofbools: Option>>, + pub testf: f32, + pub testf2: f32, + pub testf3: f32, + pub testarrayofstring2: Option>>>, + pub testarrayofsortedstruct: Option>>, + pub flex: Option>>, + pub test5: Option>>, + pub vector_of_longs: Option>>, + pub vector_of_doubles: Option>>, + pub parent_namespace_test: Option>>, + pub vector_of_referrables: Option>>>>, + pub single_weak_reference: u64, + pub vector_of_weak_references: Option>>, + pub vector_of_strong_referrables: Option>>>>, + pub co_owning_reference: u64, + pub vector_of_co_owning_references: Option>>, + pub non_owning_reference: u64, + pub vector_of_non_owning_references: Option>>, + pub any_unique_type: AnyUniqueAliases, + pub any_unique: Option>, + pub any_ambiguous_type: AnyAmbiguousAliases, + pub any_ambiguous: Option>, + pub vector_of_enums: Option>>, + pub signed_enum: Race, + pub testrequirednestedflatbuffer: Option>>, + pub scalar_key_sorted_tables: Option>>>>, + pub native_inline: Option<&'a Test>, + pub long_enum_non_enum_default: LongEnum, + pub long_enum_normal_default: LongEnum, + pub nan_default: f32, + pub inf_default: f32, + pub positive_inf_default: f32, + pub infinity_default: f32, + pub positive_infinity_default: f32, + pub negative_inf_default: f32, + pub negative_infinity_default: f32, + pub double_inf_default: f64, +} +impl<'a> Default for MonsterArgs<'a> { + #[inline] + fn default() -> Self { + MonsterArgs { + pos: None, + mana: 150, + hp: 100, + name: None, // required field + inventory: None, + color: Color::Blue, + test_type: Any::NONE, + test: None, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique_type: AnyUniqueAliases::NONE, + any_unique: None, + any_ambiguous_type: AnyAmbiguousAliases::NONE, + any_ambiguous: None, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, + } + } +} + +pub struct MonsterBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { + #[inline] + pub fn add_pos(&mut self, pos: &Vec3) { + self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos); + } + #[inline] + pub fn add_mana(&mut self, mana: i16) { + self.fbb_.push_slot::(Monster::VT_MANA, mana, 150); + } + #[inline] + pub fn add_hp(&mut self, hp: i16) { + self.fbb_.push_slot::(Monster::VT_HP, hp, 100); + } + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Monster::VT_NAME, name); + } + #[inline] + pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_INVENTORY, inventory); + } + #[inline] + pub fn add_color(&mut self, color: Color) { + self.fbb_.push_slot::(Monster::VT_COLOR, color, Color::Blue); + } + #[inline] + pub fn add_test_type(&mut self, test_type: Any) { + self.fbb_.push_slot::(Monster::VT_TEST_TYPE, test_type, Any::NONE); + } + #[inline] + pub fn add_test(&mut self, test: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Monster::VT_TEST, test); + } + #[inline] + pub fn add_test4(&mut self, test4: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TEST4, test4); + } + #[inline] + pub fn add_testarrayofstring(&mut self, testarrayofstring: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + #[inline] + pub fn add_testarrayoftables(&mut self, testarrayoftables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + #[inline] + pub fn add_enemy(&mut self, enemy: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_ENEMY, enemy); + } + #[inline] + pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + #[inline] + pub fn add_testempty(&mut self, testempty: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTEMPTY, testempty); + } + #[inline] + pub fn add_testbool(&mut self, testbool: bool) { + self.fbb_.push_slot::(Monster::VT_TESTBOOL, testbool, false); + } + #[inline] + pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + #[inline] + pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + #[inline] + pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + #[inline] + pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + #[inline] + pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + #[inline] + pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + #[inline] + pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + #[inline] + pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + #[inline] + pub fn add_testarrayofbools(&mut self, testarrayofbools: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + #[inline] + pub fn add_testf(&mut self, testf: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF, testf, 3.14159); + } + #[inline] + pub fn add_testf2(&mut self, testf2: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF2, testf2, 3.0); + } + #[inline] + pub fn add_testf3(&mut self, testf3: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF3, testf3, 0.0); + } + #[inline] + pub fn add_testarrayofstring2(&mut self, testarrayofstring2: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + #[inline] + pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + #[inline] + pub fn add_flex(&mut self, flex: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_FLEX, flex); + } + #[inline] + pub fn add_test5(&mut self, test5: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TEST5, test5); + } + #[inline] + pub fn add_vector_of_longs(&mut self, vector_of_longs: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + #[inline] + pub fn add_vector_of_doubles(&mut self, vector_of_doubles: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + #[inline] + pub fn add_parent_namespace_test(&mut self, parent_namespace_test: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + #[inline] + pub fn add_vector_of_referrables(&mut self, vector_of_referrables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + #[inline] + pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) { + self.fbb_.push_slot::(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + #[inline] + pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + #[inline] + pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + #[inline] + pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + #[inline] + pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + #[inline] + pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE); + } + #[inline] + pub fn add_any_unique(&mut self, any_unique: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Monster::VT_ANY_UNIQUE, any_unique); + } + #[inline] + pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE); + } + #[inline] + pub fn add_any_ambiguous(&mut self, any_ambiguous: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + #[inline] + pub fn add_vector_of_enums(&mut self, vector_of_enums: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + #[inline] + pub fn add_signed_enum(&mut self, signed_enum: Race) { + self.fbb_.push_slot::(Monster::VT_SIGNED_ENUM, signed_enum, Race::None); + } + #[inline] + pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + #[inline] + pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + #[inline] + pub fn add_native_inline(&mut self, native_inline: &Test) { + self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline); + } + #[inline] + pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default()); + } + #[inline] + pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne); + } + #[inline] + pub fn add_nan_default(&mut self, nan_default: f32) { + self.fbb_.push_slot::(Monster::VT_NAN_DEFAULT, nan_default, f32::NAN); + } + #[inline] + pub fn add_inf_default(&mut self, inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_INF_DEFAULT, inf_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_inf_default(&mut self, positive_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, f32::INFINITY); + } + #[inline] + pub fn add_infinity_default(&mut self, infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_INFINITY_DEFAULT, infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_infinity_default(&mut self, positive_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_negative_inf_default(&mut self, negative_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_negative_infinity_default(&mut self, negative_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_double_inf_default(&mut self, double_inf_default: f64) { + self.fbb_.push_slot::(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, f64::INFINITY); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Monster::VT_NAME,"name"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Monster<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.field("pos", &self.pos()); + ds.field("mana", &self.mana()); + ds.field("hp", &self.hp()); + ds.field("name", &self.name()); + ds.field("inventory", &self.inventory()); + ds.field("color", &self.color()); + ds.field("test_type", &self.test_type()); + match self.test_type() { + Any::Monster => { + if let Some(x) = self.test_as_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::TestSimpleTableWithEnum => { + if let Some(x) = self.test_as_test_simple_table_with_enum() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::MyGame_Example2_Monster => { + if let Some(x) = self.test_as_my_game_example_2_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("test", &x) + }, + }; + ds.field("test4", &self.test4()); + ds.field("testarrayofstring", &self.testarrayofstring()); + ds.field("testarrayoftables", &self.testarrayoftables()); + ds.field("enemy", &self.enemy()); + ds.field("testnestedflatbuffer", &self.testnestedflatbuffer()); + ds.field("testempty", &self.testempty()); + ds.field("testbool", &self.testbool()); + ds.field("testhashs32_fnv1", &self.testhashs32_fnv1()); + ds.field("testhashu32_fnv1", &self.testhashu32_fnv1()); + ds.field("testhashs64_fnv1", &self.testhashs64_fnv1()); + ds.field("testhashu64_fnv1", &self.testhashu64_fnv1()); + ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a()); + ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a()); + ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a()); + ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a()); + ds.field("testarrayofbools", &self.testarrayofbools()); + ds.field("testf", &self.testf()); + ds.field("testf2", &self.testf2()); + ds.field("testf3", &self.testf3()); + ds.field("testarrayofstring2", &self.testarrayofstring2()); + ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct()); + ds.field("flex", &self.flex()); + ds.field("test5", &self.test5()); + ds.field("vector_of_longs", &self.vector_of_longs()); + ds.field("vector_of_doubles", &self.vector_of_doubles()); + ds.field("parent_namespace_test", &self.parent_namespace_test()); + ds.field("vector_of_referrables", &self.vector_of_referrables()); + ds.field("single_weak_reference", &self.single_weak_reference()); + ds.field("vector_of_weak_references", &self.vector_of_weak_references()); + ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables()); + ds.field("co_owning_reference", &self.co_owning_reference()); + ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references()); + ds.field("non_owning_reference", &self.non_owning_reference()); + ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references()); + ds.field("any_unique_type", &self.any_unique_type()); + match self.any_unique_type() { + AnyUniqueAliases::M => { + if let Some(x) = self.any_unique_as_m() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::TS => { + if let Some(x) = self.any_unique_as_ts() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::M2 => { + if let Some(x) = self.any_unique_as_m2() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_unique", &x) + }, + }; + ds.field("any_ambiguous_type", &self.any_ambiguous_type()); + match self.any_ambiguous_type() { + AnyAmbiguousAliases::M1 => { + if let Some(x) = self.any_ambiguous_as_m1() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M2 => { + if let Some(x) = self.any_ambiguous_as_m2() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M3 => { + if let Some(x) = self.any_ambiguous_as_m3() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_ambiguous", &x) + }, + }; + ds.field("vector_of_enums", &self.vector_of_enums()); + ds.field("signed_enum", &self.signed_enum()); + ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer()); + ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables()); + ds.field("native_inline", &self.native_inline()); + ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default()); + ds.field("long_enum_normal_default", &self.long_enum_normal_default()); + ds.field("nan_default", &self.nan_default()); + ds.field("inf_default", &self.inf_default()); + ds.field("positive_inf_default", &self.positive_inf_default()); + ds.field("infinity_default", &self.infinity_default()); + ds.field("positive_infinity_default", &self.positive_infinity_default()); + ds.field("negative_inf_default", &self.negative_inf_default()); + ds.field("negative_infinity_default", &self.negative_infinity_default()); + ds.field("double_inf_default", &self.double_inf_default()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct MonsterT { + pub pos: Option, + pub mana: i16, + pub hp: i16, + pub name: String, + pub inventory: Option>, + pub color: Color, + pub test: AnyT, + pub test4: Option>, + pub testarrayofstring: Option>, + pub testarrayoftables: Option>, + pub enemy: Option>, + pub testnestedflatbuffer: Option>, + pub testempty: Option>, + pub testbool: bool, + pub testhashs32_fnv1: i32, + pub testhashu32_fnv1: u32, + pub testhashs64_fnv1: i64, + pub testhashu64_fnv1: u64, + pub testhashs32_fnv1a: i32, + pub testhashu32_fnv1a: u32, + pub testhashs64_fnv1a: i64, + pub testhashu64_fnv1a: u64, + pub testarrayofbools: Option>, + pub testf: f32, + pub testf2: f32, + pub testf3: f32, + pub testarrayofstring2: Option>, + pub testarrayofsortedstruct: Option>, + pub flex: Option>, + pub test5: Option>, + pub vector_of_longs: Option>, + pub vector_of_doubles: Option>, + pub parent_namespace_test: Option>, + pub vector_of_referrables: Option>, + pub single_weak_reference: u64, + pub vector_of_weak_references: Option>, + pub vector_of_strong_referrables: Option>, + pub co_owning_reference: u64, + pub vector_of_co_owning_references: Option>, + pub non_owning_reference: u64, + pub vector_of_non_owning_references: Option>, + pub any_unique: AnyUniqueAliasesT, + pub any_ambiguous: AnyAmbiguousAliasesT, + pub vector_of_enums: Option>, + pub signed_enum: Race, + pub testrequirednestedflatbuffer: Option>, + pub scalar_key_sorted_tables: Option>, + pub native_inline: Option, + pub long_enum_non_enum_default: LongEnum, + pub long_enum_normal_default: LongEnum, + pub nan_default: f32, + pub inf_default: f32, + pub positive_inf_default: f32, + pub infinity_default: f32, + pub positive_infinity_default: f32, + pub negative_inf_default: f32, + pub negative_infinity_default: f32, + pub double_inf_default: f64, +} +impl Default for MonsterT { + fn default() -> Self { + Self { + pos: None, + mana: 150, + hp: 100, + name: "".to_string(), + inventory: None, + color: Color::Blue, + test: AnyT::NONE, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique: AnyUniqueAliasesT::NONE, + any_ambiguous: AnyAmbiguousAliasesT::NONE, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, + } + } +} +impl MonsterT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let pos_tmp = self.pos.as_ref().map(|x| x.pack()); + let pos = pos_tmp.as_ref(); + let mana = self.mana; + let hp = self.hp; + let name = Some({ + let x = &self.name; + _fbb.create_string(x) + }); + let inventory = self.inventory.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let color = self.color; + let test_type = self.test.any_type(); + let test = self.test.pack(_fbb); + let test4 = self.test4.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let enemy = self.enemy.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testempty = self.testempty.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testbool = self.testbool; + let testhashs32_fnv1 = self.testhashs32_fnv1; + let testhashu32_fnv1 = self.testhashu32_fnv1; + let testhashs64_fnv1 = self.testhashs64_fnv1; + let testhashu64_fnv1 = self.testhashu64_fnv1; + let testhashs32_fnv1a = self.testhashs32_fnv1a; + let testhashu32_fnv1a = self.testhashu32_fnv1a; + let testhashs64_fnv1a = self.testhashs64_fnv1a; + let testhashu64_fnv1a = self.testhashu64_fnv1a; + let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testf = self.testf; + let testf2 = self.testf2; + let testf3 = self.testf3; + let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let flex = self.flex.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let test5 = self.test5.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{ + x.pack(_fbb) + }); + let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let single_weak_reference = self.single_weak_reference; + let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let co_owning_reference = self.co_owning_reference; + let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let non_owning_reference = self.non_owning_reference; + let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let any_unique_type = self.any_unique.any_unique_aliases_type(); + let any_unique = self.any_unique.pack(_fbb); + let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type(); + let any_ambiguous = self.any_ambiguous.pack(_fbb); + let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let signed_enum = self.signed_enum; + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack()); + let native_inline = native_inline_tmp.as_ref(); + let long_enum_non_enum_default = self.long_enum_non_enum_default; + let long_enum_normal_default = self.long_enum_normal_default; + let nan_default = self.nan_default; + let inf_default = self.inf_default; + let positive_inf_default = self.positive_inf_default; + let infinity_default = self.infinity_default; + let positive_infinity_default = self.positive_infinity_default; + let negative_inf_default = self.negative_inf_default; + let negative_infinity_default = self.negative_infinity_default; + let double_inf_default = self.double_inf_default; + Monster::create(_fbb, &MonsterArgs{ + pos, + mana, + hp, + name, + inventory, + color, + test_type, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + }) + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `Monster` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_monster_unchecked`. +pub fn root_as_monster(buf: &[u8]) -> Result { + flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `Monster` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_monster_unchecked`. +pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result { + flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `Monster` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_monster_unchecked`. +pub fn root_as_monster_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `Monster` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_monster_unchecked`. +pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a Monster and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `Monster`. +pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster { + flatbuffers::root_unchecked::(buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed Monster and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `Monster`. +pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster { + flatbuffers::size_prefixed_root_unchecked::(buf) +} +pub const MONSTER_IDENTIFIER: &str = "MONS"; + +#[inline] +pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false) +} + +#[inline] +pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true) +} + +pub const MONSTER_EXTENSION: &str = "mon"; + +#[inline] +pub fn finish_monster_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( + fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + root: flatbuffers::WIPOffset>) { + fbb.finish(root, Some(MONSTER_IDENTIFIER)); +} + +#[inline] +pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER)); +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/race_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/race_generated.rs new file mode 100644 index 00000000000..dd48b4e1eeb --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/race_generated.rs @@ -0,0 +1,104 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_RACE: i8 = -1; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_RACE: i8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_RACE: [Race; 4] = [ + Race::None, + Race::Human, + Race::Dwarf, + Race::Elf, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct Race(pub i8); +#[allow(non_upper_case_globals)] +impl Race { + pub const None: Self = Self(-1); + pub const Human: Self = Self(0); + pub const Dwarf: Self = Self(1); + pub const Elf: Self = Self(2); + + pub const ENUM_MIN: i8 = -1; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::Human, + Self::Dwarf, + Self::Elf, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::Human => Some("Human"), + Self::Dwarf => Some("Dwarf"), + Self::Elf => Some("Elf"), + _ => None, + } + } +} +impl core::fmt::Debug for Race { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for Race { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for Race { + type Output = Race; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for Race { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for Race { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Race {} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/referrable_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/referrable_generated.rs new file mode 100644 index 00000000000..4932b35fe4d --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/referrable_generated.rs @@ -0,0 +1,151 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum ReferrableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Referrable<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Referrable<'a> { + type Inner = Referrable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Referrable<'a> { + pub const VT_ID: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Referrable" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Referrable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ReferrableArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = ReferrableBuilder::new(_fbb); + builder.add_id(args.id); + builder.finish() + } + + pub fn unpack(&self) -> ReferrableT { + let id = self.id(); + ReferrableT { + id, + } + } + + #[inline] + pub fn id(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Referrable::VT_ID, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Referrable) -> bool { + self.id() < o.id() + } + + #[inline] + pub fn key_compare_with_value(&self, val: u64) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } +} + +impl flatbuffers::Verifiable for Referrable<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("id", Self::VT_ID, false)? + .finish(); + Ok(()) + } +} +pub struct ReferrableArgs { + pub id: u64, +} +impl<'a> Default for ReferrableArgs { + #[inline] + fn default() -> Self { + ReferrableArgs { + id: 0, + } + } +} + +pub struct ReferrableBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ReferrableBuilder<'a, 'b, A> { + #[inline] + pub fn add_id(&mut self, id: u64) { + self.fbb_.push_slot::(Referrable::VT_ID, id, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ReferrableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ReferrableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Referrable<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Referrable"); + ds.field("id", &self.id()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct ReferrableT { + pub id: u64, +} +impl Default for ReferrableT { + fn default() -> Self { + Self { + id: 0, + } + } +} +impl ReferrableT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let id = self.id; + Referrable::create(_fbb, &ReferrableArgs{ + id, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/stat_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/stat_generated.rs new file mode 100644 index 00000000000..d94ff273549 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/stat_generated.rs @@ -0,0 +1,201 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum StatOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Stat<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Stat<'a> { + type Inner = Stat<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Stat<'a> { + pub const VT_ID: flatbuffers::VOffsetT = 4; + pub const VT_VAL: flatbuffers::VOffsetT = 6; + pub const VT_COUNT: flatbuffers::VOffsetT = 8; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Stat" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Stat { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args StatArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = StatBuilder::new(_fbb); + builder.add_val(args.val); + if let Some(x) = args.id { builder.add_id(x); } + builder.add_count(args.count); + builder.finish() + } + + pub fn unpack(&self) -> StatT { + let id = self.id().map(|x| { + x.to_string() + }); + let val = self.val(); + let count = self.count(); + StatT { + id, + val, + count, + } + } + + #[inline] + pub fn id(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Stat::VT_ID, None)} + } + #[inline] + pub fn val(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_VAL, Some(0)).unwrap()} + } + #[inline] + pub fn count(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_COUNT, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Stat) -> bool { + self.count() < o.count() + } + + #[inline] + pub fn key_compare_with_value(&self, val: u16) -> ::core::cmp::Ordering { + let key = self.count(); + key.cmp(&val) + } +} + +impl flatbuffers::Verifiable for Stat<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("id", Self::VT_ID, false)? + .visit_field::("val", Self::VT_VAL, false)? + .visit_field::("count", Self::VT_COUNT, false)? + .finish(); + Ok(()) + } +} +pub struct StatArgs<'a> { + pub id: Option>, + pub val: i64, + pub count: u16, +} +impl<'a> Default for StatArgs<'a> { + #[inline] + fn default() -> Self { + StatArgs { + id: None, + val: 0, + count: 0, + } + } +} + +pub struct StatBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> StatBuilder<'a, 'b, A> { + #[inline] + pub fn add_id(&mut self, id: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Stat::VT_ID, id); + } + #[inline] + pub fn add_val(&mut self, val: i64) { + self.fbb_.push_slot::(Stat::VT_VAL, val, 0); + } + #[inline] + pub fn add_count(&mut self, count: u16) { + self.fbb_.push_slot::(Stat::VT_COUNT, count, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> StatBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + StatBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Stat<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Stat"); + ds.field("id", &self.id()); + ds.field("val", &self.val()); + ds.field("count", &self.count()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct StatT { + pub id: Option, + pub val: i64, + pub count: u16, +} +impl Default for StatT { + fn default() -> Self { + Self { + id: None, + val: 0, + count: 0, + } + } +} +impl StatT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let id = self.id.as_ref().map(|x|{ + _fbb.create_string(x) + }); + let val = self.val; + let count = self.count; + Stat::create(_fbb, &StatArgs{ + id, + val, + count, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/struct_of_structs_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/struct_of_structs_generated.rs new file mode 100644 index 00000000000..675a846cd70 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/struct_of_structs_generated.rs @@ -0,0 +1,147 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct StructOfStructs, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct StructOfStructs(pub [u8; 20]); +impl Default for StructOfStructs { + fn default() -> Self { + Self([0; 20]) + } +} +impl core::fmt::Debug for StructOfStructs { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("StructOfStructs") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for StructOfStructs {} +impl<'a> flatbuffers::Follow<'a> for StructOfStructs { + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a StructOfStructs>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a StructOfStructs { + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for StructOfStructs { + type Output = StructOfStructs; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const StructOfStructs as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for StructOfStructs { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> StructOfStructs { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &Ability, + b: &Test, + c: &Ability, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructs" + } + + pub fn a(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const Ability) } + } + + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &Ability) { + self.0[0..0 + 8].copy_from_slice(&x.0) + } + + pub fn b(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[8..].as_ptr() as *const Test) } + } + + #[allow(clippy::identity_op)] + pub fn set_b(&mut self, x: &Test) { + self.0[8..8 + 4].copy_from_slice(&x.0) + } + + pub fn c(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[12..].as_ptr() as *const Ability) } + } + + #[allow(clippy::identity_op)] + pub fn set_c(&mut self, x: &Ability) { + self.0[12..12 + 8].copy_from_slice(&x.0) + } + + pub fn unpack(&self) -> StructOfStructsT { + StructOfStructsT { + a: self.a().unpack(), + b: self.b().unpack(), + c: self.c().unpack(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct StructOfStructsT { + pub a: AbilityT, + pub b: TestT, + pub c: AbilityT, +} +impl StructOfStructsT { + pub fn pack(&self) -> StructOfStructs { + StructOfStructs::new( + &self.a.pack(), + &self.b.pack(), + &self.c.pack(), + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs new file mode 100644 index 00000000000..3eaa7055638 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/struct_of_structs_of_structs_generated.rs @@ -0,0 +1,111 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct StructOfStructsOfStructs, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct StructOfStructsOfStructs(pub [u8; 20]); +impl Default for StructOfStructsOfStructs { + fn default() -> Self { + Self([0; 20]) + } +} +impl core::fmt::Debug for StructOfStructsOfStructs { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("StructOfStructsOfStructs") + .field("a", &self.a()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for StructOfStructsOfStructs {} +impl<'a> flatbuffers::Follow<'a> for StructOfStructsOfStructs { + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a StructOfStructsOfStructs>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a StructOfStructsOfStructs { + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for StructOfStructsOfStructs { + type Output = StructOfStructsOfStructs; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const StructOfStructsOfStructs as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for StructOfStructsOfStructs { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> StructOfStructsOfStructs { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &StructOfStructs, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructsOfStructs" + } + + pub fn a(&self) -> &StructOfStructs { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const StructOfStructs) } + } + + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &StructOfStructs) { + self.0[0..0 + 20].copy_from_slice(&x.0) + } + + pub fn unpack(&self) -> StructOfStructsOfStructsT { + StructOfStructsOfStructsT { + a: self.a().unpack(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct StructOfStructsOfStructsT { + pub a: StructOfStructsT, +} +impl StructOfStructsOfStructsT { + pub fn pack(&self) -> StructOfStructsOfStructs { + StructOfStructsOfStructs::new( + &self.a.pack(), + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/test_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/test_generated.rs new file mode 100644 index 00000000000..65ef25031d3 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/test_generated.rs @@ -0,0 +1,163 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Test, aligned to 2 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Test(pub [u8; 4]); +impl Default for Test { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Test { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Test") + .field("a", &self.a()) + .field("b", &self.b()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Test {} +impl<'a> flatbuffers::Follow<'a> for Test { + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Test>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Test { + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Test { + type Output = Test; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Test as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(2) + } +} + +impl<'a> flatbuffers::Verifiable for Test { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Test { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i16, + b: i8, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s.set_b(b); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Test" + } + + pub fn a(&self) -> i16 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i16) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn b(&self) -> i8 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[2..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_b(&mut self, x: i8) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[2..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> TestT { + TestT { + a: self.a(), + b: self.b(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct TestT { + pub a: i16, + pub b: i8, +} +impl TestT { + pub fn pack(&self) -> Test { + Test::new( + self.a, + self.b, + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs new file mode 100644 index 00000000000..daa5174408c --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/test_simple_table_with_enum_generated.rs @@ -0,0 +1,141 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TestSimpleTableWithEnumOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TestSimpleTableWithEnum<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> { + type Inner = TestSimpleTableWithEnum<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TestSimpleTableWithEnum<'a> { + pub const VT_COLOR: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TestSimpleTableWithEnum" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TestSimpleTableWithEnum { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TestSimpleTableWithEnumArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb); + builder.add_color(args.color); + builder.finish() + } + + pub fn unpack(&self) -> TestSimpleTableWithEnumT { + let color = self.color(); + TestSimpleTableWithEnumT { + color, + } + } + + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()} + } +} + +impl flatbuffers::Verifiable for TestSimpleTableWithEnum<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("color", Self::VT_COLOR, false)? + .finish(); + Ok(()) + } +} +pub struct TestSimpleTableWithEnumArgs { + pub color: Color, +} +impl<'a> Default for TestSimpleTableWithEnumArgs { + #[inline] + fn default() -> Self { + TestSimpleTableWithEnumArgs { + color: Color::Green, + } + } +} + +pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TestSimpleTableWithEnumBuilder<'a, 'b, A> { + #[inline] + pub fn add_color(&mut self, color: Color) { + self.fbb_.push_slot::(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TestSimpleTableWithEnumBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TestSimpleTableWithEnumBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TestSimpleTableWithEnum<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TestSimpleTableWithEnum"); + ds.field("color", &self.color()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TestSimpleTableWithEnumT { + pub color: Color, +} +impl Default for TestSimpleTableWithEnumT { + fn default() -> Self { + Self { + color: Color::Green, + } + } +} +impl TestSimpleTableWithEnumT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let color = self.color; + TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{ + color, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/type_aliases_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/type_aliases_generated.rs new file mode 100644 index 00000000000..f813c25907e --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/type_aliases_generated.rs @@ -0,0 +1,402 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TypeAliasesOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TypeAliases<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TypeAliases<'a> { + type Inner = TypeAliases<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TypeAliases<'a> { + pub const VT_I8_: flatbuffers::VOffsetT = 4; + pub const VT_U8_: flatbuffers::VOffsetT = 6; + pub const VT_I16_: flatbuffers::VOffsetT = 8; + pub const VT_U16_: flatbuffers::VOffsetT = 10; + pub const VT_I32_: flatbuffers::VOffsetT = 12; + pub const VT_U32_: flatbuffers::VOffsetT = 14; + pub const VT_I64_: flatbuffers::VOffsetT = 16; + pub const VT_U64_: flatbuffers::VOffsetT = 18; + pub const VT_F32_: flatbuffers::VOffsetT = 20; + pub const VT_F64_: flatbuffers::VOffsetT = 22; + pub const VT_V8: flatbuffers::VOffsetT = 24; + pub const VT_VF64: flatbuffers::VOffsetT = 26; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TypeAliases" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TypeAliases { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TypeAliasesArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TypeAliasesBuilder::new(_fbb); + builder.add_f64_(args.f64_); + builder.add_u64_(args.u64_); + builder.add_i64_(args.i64_); + if let Some(x) = args.vf64 { builder.add_vf64(x); } + if let Some(x) = args.v8 { builder.add_v8(x); } + builder.add_f32_(args.f32_); + builder.add_u32_(args.u32_); + builder.add_i32_(args.i32_); + builder.add_u16_(args.u16_); + builder.add_i16_(args.i16_); + builder.add_u8_(args.u8_); + builder.add_i8_(args.i8_); + builder.finish() + } + + pub fn unpack(&self) -> TypeAliasesT { + let i8_ = self.i8_(); + let u8_ = self.u8_(); + let i16_ = self.i16_(); + let u16_ = self.u16_(); + let i32_ = self.i32_(); + let u32_ = self.u32_(); + let i64_ = self.i64_(); + let u64_ = self.u64_(); + let f32_ = self.f32_(); + let f64_ = self.f64_(); + let v8 = self.v8().map(|x| { + x.into_iter().collect() + }); + let vf64 = self.vf64().map(|x| { + x.into_iter().collect() + }); + TypeAliasesT { + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, + } + } + + #[inline] + pub fn i8_(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I8_, Some(0)).unwrap()} + } + #[inline] + pub fn u8_(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U8_, Some(0)).unwrap()} + } + #[inline] + pub fn i16_(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I16_, Some(0)).unwrap()} + } + #[inline] + pub fn u16_(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U16_, Some(0)).unwrap()} + } + #[inline] + pub fn i32_(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I32_, Some(0)).unwrap()} + } + #[inline] + pub fn u32_(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U32_, Some(0)).unwrap()} + } + #[inline] + pub fn i64_(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I64_, Some(0)).unwrap()} + } + #[inline] + pub fn u64_(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U64_, Some(0)).unwrap()} + } + #[inline] + pub fn f32_(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F32_, Some(0.0)).unwrap()} + } + #[inline] + pub fn f64_(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F64_, Some(0.0)).unwrap()} + } + #[inline] + pub fn v8(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(TypeAliases::VT_V8, None)} + } + #[inline] + pub fn vf64(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(TypeAliases::VT_VF64, None)} + } +} + +impl flatbuffers::Verifiable for TypeAliases<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("i8_", Self::VT_I8_, false)? + .visit_field::("u8_", Self::VT_U8_, false)? + .visit_field::("i16_", Self::VT_I16_, false)? + .visit_field::("u16_", Self::VT_U16_, false)? + .visit_field::("i32_", Self::VT_I32_, false)? + .visit_field::("u32_", Self::VT_U32_, false)? + .visit_field::("i64_", Self::VT_I64_, false)? + .visit_field::("u64_", Self::VT_U64_, false)? + .visit_field::("f32_", Self::VT_F32_, false)? + .visit_field::("f64_", Self::VT_F64_, false)? + .visit_field::>>("v8", Self::VT_V8, false)? + .visit_field::>>("vf64", Self::VT_VF64, false)? + .finish(); + Ok(()) + } +} +pub struct TypeAliasesArgs<'a> { + pub i8_: i8, + pub u8_: u8, + pub i16_: i16, + pub u16_: u16, + pub i32_: i32, + pub u32_: u32, + pub i64_: i64, + pub u64_: u64, + pub f32_: f32, + pub f64_: f64, + pub v8: Option>>, + pub vf64: Option>>, +} +impl<'a> Default for TypeAliasesArgs<'a> { + #[inline] + fn default() -> Self { + TypeAliasesArgs { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, + } + } +} + +pub struct TypeAliasesBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TypeAliasesBuilder<'a, 'b, A> { + #[inline] + pub fn add_i8_(&mut self, i8_: i8) { + self.fbb_.push_slot::(TypeAliases::VT_I8_, i8_, 0); + } + #[inline] + pub fn add_u8_(&mut self, u8_: u8) { + self.fbb_.push_slot::(TypeAliases::VT_U8_, u8_, 0); + } + #[inline] + pub fn add_i16_(&mut self, i16_: i16) { + self.fbb_.push_slot::(TypeAliases::VT_I16_, i16_, 0); + } + #[inline] + pub fn add_u16_(&mut self, u16_: u16) { + self.fbb_.push_slot::(TypeAliases::VT_U16_, u16_, 0); + } + #[inline] + pub fn add_i32_(&mut self, i32_: i32) { + self.fbb_.push_slot::(TypeAliases::VT_I32_, i32_, 0); + } + #[inline] + pub fn add_u32_(&mut self, u32_: u32) { + self.fbb_.push_slot::(TypeAliases::VT_U32_, u32_, 0); + } + #[inline] + pub fn add_i64_(&mut self, i64_: i64) { + self.fbb_.push_slot::(TypeAliases::VT_I64_, i64_, 0); + } + #[inline] + pub fn add_u64_(&mut self, u64_: u64) { + self.fbb_.push_slot::(TypeAliases::VT_U64_, u64_, 0); + } + #[inline] + pub fn add_f32_(&mut self, f32_: f32) { + self.fbb_.push_slot::(TypeAliases::VT_F32_, f32_, 0.0); + } + #[inline] + pub fn add_f64_(&mut self, f64_: f64) { + self.fbb_.push_slot::(TypeAliases::VT_F64_, f64_, 0.0); + } + #[inline] + pub fn add_v8(&mut self, v8: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TypeAliases::VT_V8, v8); + } + #[inline] + pub fn add_vf64(&mut self, vf64: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TypeAliases::VT_VF64, vf64); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TypeAliasesBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TypeAliasesBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TypeAliases<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TypeAliases"); + ds.field("i8_", &self.i8_()); + ds.field("u8_", &self.u8_()); + ds.field("i16_", &self.i16_()); + ds.field("u16_", &self.u16_()); + ds.field("i32_", &self.i32_()); + ds.field("u32_", &self.u32_()); + ds.field("i64_", &self.i64_()); + ds.field("u64_", &self.u64_()); + ds.field("f32_", &self.f32_()); + ds.field("f64_", &self.f64_()); + ds.field("v8", &self.v8()); + ds.field("vf64", &self.vf64()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TypeAliasesT { + pub i8_: i8, + pub u8_: u8, + pub i16_: i16, + pub u16_: u16, + pub i32_: i32, + pub u32_: u32, + pub i64_: i64, + pub u64_: u64, + pub f32_: f32, + pub f64_: f64, + pub v8: Option>, + pub vf64: Option>, +} +impl Default for TypeAliasesT { + fn default() -> Self { + Self { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, + } + } +} +impl TypeAliasesT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let i8_ = self.i8_; + let u8_ = self.u8_; + let i16_ = self.i16_; + let u16_ = self.u16_; + let i32_ = self.i32_; + let u32_ = self.u32_; + let i64_ = self.i64_; + let u64_ = self.u64_; + let f32_ = self.f32_; + let f64_ = self.f64_; + let v8 = self.v8.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vf64 = self.vf64.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + TypeAliases::create(_fbb, &TypeAliasesArgs{ + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example/vec_3_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example/vec_3_generated.rs new file mode 100644 index 00000000000..8aebab50a2c --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example/vec_3_generated.rs @@ -0,0 +1,286 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Vec3, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Vec3(pub [u8; 32]); +impl Default for Vec3 { + fn default() -> Self { + Self([0; 32]) + } +} +impl core::fmt::Debug for Vec3 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Vec3") + .field("x", &self.x()) + .field("y", &self.y()) + .field("z", &self.z()) + .field("test1", &self.test1()) + .field("test2", &self.test2()) + .field("test3", &self.test3()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Vec3 {} +impl<'a> flatbuffers::Follow<'a> for Vec3 { + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Vec3>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Vec3 { + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Vec3 { + type Output = Vec3; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> flatbuffers::Verifiable for Vec3 { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Vec3 { + #[allow(clippy::too_many_arguments)] + pub fn new( + x: f32, + y: f32, + z: f32, + test1: f64, + test2: Color, + test3: &Test, + ) -> Self { + let mut s = Self([0; 32]); + s.set_x(x); + s.set_y(y); + s.set_z(z); + s.set_test1(test1); + s.set_test2(test2); + s.set_test3(test3); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Vec3" + } + + pub fn x(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_x(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn y(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_y(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn z(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_z(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn test1(&self) -> f64 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[16..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_test1(&mut self, x: f64) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[16..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn test2(&self) -> Color { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[24..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_test2(&mut self, x: Color) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[24..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn test3(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[26..].as_ptr() as *const Test) } + } + + #[allow(clippy::identity_op)] + pub fn set_test3(&mut self, x: &Test) { + self.0[26..26 + 4].copy_from_slice(&x.0) + } + + pub fn unpack(&self) -> Vec3T { + Vec3T { + x: self.x(), + y: self.y(), + z: self.z(), + test1: self.test1(), + test2: self.test2(), + test3: self.test3().unpack(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Vec3T { + pub x: f32, + pub y: f32, + pub z: f32, + pub test1: f64, + pub test2: Color, + pub test3: TestT, +} +impl Vec3T { + pub fn pack(&self) -> Vec3 { + Vec3::new( + self.x, + self.y, + self.z, + self.test1, + self.test2, + &self.test3.pack(), + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test/my_game/example_2/monster_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/example_2/monster_generated.rs new file mode 100644 index 00000000000..a0a138dc7a6 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/example_2/monster_generated.rs @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum MonsterOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Monster<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Monster<'a> { + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Monster<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example2.Monster" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Monster { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args MonsterArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> MonsterT { + MonsterT { + } + } +} + +impl flatbuffers::Verifiable for Monster<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct MonsterArgs { +} +impl<'a> Default for MonsterArgs { + #[inline] + fn default() -> Self { + MonsterArgs { + } + } +} + +pub struct MonsterBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Monster<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct MonsterT { +} +impl Default for MonsterT { + fn default() -> Self { + Self { + } + } +} +impl MonsterT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + Monster::create(_fbb, &MonsterArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/in_parent_namespace_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/in_parent_namespace_generated.rs new file mode 100644 index 00000000000..5885714720b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/in_parent_namespace_generated.rs @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum InParentNamespaceOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct InParentNamespace<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for InParentNamespace<'a> { + type Inner = InParentNamespace<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> InParentNamespace<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.InParentNamespace" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + InParentNamespace { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args InParentNamespaceArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = InParentNamespaceBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> InParentNamespaceT { + InParentNamespaceT { + } + } +} + +impl flatbuffers::Verifiable for InParentNamespace<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct InParentNamespaceArgs { +} +impl<'a> Default for InParentNamespaceArgs { + #[inline] + fn default() -> Self { + InParentNamespaceArgs { + } + } +} + +pub struct InParentNamespaceBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> InParentNamespaceBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> InParentNamespaceBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + InParentNamespaceBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for InParentNamespace<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("InParentNamespace"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct InParentNamespaceT { +} +impl Default for InParentNamespaceT { + fn default() -> Self { + Self { + } + } +} +impl InParentNamespaceT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + InParentNamespace::create(_fbb, &InParentNamespaceArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/from_include_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/from_include_generated.rs new file mode 100644 index 00000000000..70cb407c1ea --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/from_include_generated.rs @@ -0,0 +1,92 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ + FromInclude::IncludeVal, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FromInclude(pub i64); +#[allow(non_upper_case_globals)] +impl FromInclude { + pub const IncludeVal: Self = Self(0); + + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, + } + } +} +impl core::fmt::Debug for FromInclude { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for FromInclude { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for FromInclude { + type Output = FromInclude; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for FromInclude { + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for FromInclude { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/table_b_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/table_b_generated.rs new file mode 100644 index 00000000000..84932cbc5ad --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/table_b_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableBOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableB<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableB<'a> { + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableB<'a> { + pub const VT_A: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + Box::new(x.unpack()) + }); + TableBT { + a, + } + } + + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableB::VT_A, None)} + } +} + +impl flatbuffers::Verifiable for TableB<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct TableBArgs<'a> { + pub a: Option>>, +} +impl<'a> Default for TableBArgs<'a> { + #[inline] + fn default() -> Self { + TableBArgs { + a: None, + } + } +} + +pub struct TableBBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableB<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableBT { + pub a: Option>, +} +impl Default for TableBT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl TableBT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/unused_generated.rs b/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/unused_generated.rs new file mode 100644 index 00000000000..11af62f073b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/my_game/other_name_space/unused_generated.rs @@ -0,0 +1,128 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Unused, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Unused(pub [u8; 4]); +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Unused { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Unused {} +impl<'a> flatbuffers::Follow<'a> for Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Unused>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Unused { + type Output = Unused; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Unused { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Unused { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } + + pub fn a(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct UnusedT { + pub a: i32, +} +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test/table_a_generated.rs b/third_party/flatbuffers/tests/monster_test/table_a_generated.rs new file mode 100644 index 00000000000..781a6c469db --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test/table_a_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableAOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableA<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableA<'a> { + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableA<'a> { + pub const VT_B: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + Box::new(x.unpack()) + }); + TableAT { + b, + } + } + + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableA::VT_B, None)} + } +} + +impl flatbuffers::Verifiable for TableA<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } +} +pub struct TableAArgs<'a> { + pub b: Option>>, +} +impl<'a> Default for TableAArgs<'a> { + #[inline] + fn default() -> Self { + TableAArgs { + b: None, + } + } +} + +pub struct TableABuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { + #[inline] + pub fn add_b(&mut self, b: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableA<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableAT { + pub b: Option>, +} +impl Default for TableAT { + fn default() -> Self { + Self { + b: None, + } + } +} +impl TableAT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_bfbs_generated.h b/third_party/flatbuffers/tests/monster_test_bfbs_generated.h new file mode 100644 index 00000000000..3a4c001000f --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_bfbs_generated.h @@ -0,0 +1,763 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_BFBS_H_ +#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_BFBS_H_ + +#include +#include +namespace MyGame { +namespace Example { + +struct MonsterBinarySchema { + static const uint8_t *data() { + // Buffer containing the binary schema. + static const uint8_t bfbsData[14592] = { + 0x20,0x00,0x00,0x00,0x42,0x46,0x42,0x53,0x00,0x00,0x00,0x00,0x14,0x00,0x20,0x00,0x04,0x00,0x08,0x00, + 0x0C,0x00,0x10,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x00,0x00,0x58,0x00,0x00,0x00, + 0x34,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x50,0x0D,0x00,0x00,0x08,0x00,0x00,0x00, + 0x80,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xDC,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6D,0x6F,0x6E,0x00, + 0x04,0x00,0x00,0x00,0x4D,0x4F,0x4E,0x53,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0xD4,0x04,0x00,0x00, + 0x90,0x02,0x00,0x00,0xA8,0x03,0x00,0x00,0x30,0x08,0x00,0x00,0x00,0x06,0x00,0x00,0x0C,0x07,0x00,0x00, + 0x10,0x0A,0x00,0x00,0x0F,0x00,0x00,0x00,0xBC,0x31,0x00,0x00,0x00,0x0D,0x00,0x00,0x6C,0x2E,0x00,0x00, + 0x38,0x2F,0x00,0x00,0xA4,0x30,0x00,0x00,0x28,0x30,0x00,0x00,0x44,0x35,0x00,0x00,0x44,0x34,0x00,0x00, + 0x84,0x0A,0x00,0x00,0x80,0x32,0x00,0x00,0xF4,0x35,0x00,0x00,0x24,0x36,0x00,0x00,0xFC,0x36,0x00,0x00, + 0xA0,0x37,0x00,0x00,0x68,0x36,0x00,0x00,0x03,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x1C,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x04,0xC8,0xFF,0xFF,0x14,0x36,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x58,0x36,0x00,0x00,0x18,0xC8,0xFF,0xFF,0x8C,0x37,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x44,0x36,0x00,0x00,0x7C,0x37,0x00,0x00,0x30,0xC8,0xFF,0xFF,0x38,0x36,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x2C,0x36,0x00,0x00,0x64,0x37,0x00,0x00,0x00,0x00,0x0E,0x00,0x10,0x00,0x04,0x00, + 0x08,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x0E,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0xB8,0x35,0x00,0x00,0x04,0x00,0x00,0x00,0x70,0x01,0x00,0x00,0xE4,0x00,0x00,0x00,0x88,0x00,0x00,0x00, + 0x28,0x00,0x00,0x00,0x1D,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70, + 0x6C,0x65,0x2E,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x53,0x74,0x6F,0x72,0x61,0x67,0x65,0x00,0x00,0x00, + 0xD0,0xFE,0xFF,0xFF,0x40,0x00,0x00,0x00,0x14,0x0C,0x00,0x00,0x50,0x2E,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xBC,0xC8,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x62,0x69,0x64,0x69,0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65, + 0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x47,0x65,0x74,0x4D,0x69,0x6E,0x4D,0x61, + 0x78,0x48,0x69,0x74,0x50,0x6F,0x69,0x6E,0x74,0x73,0x00,0x00,0x2C,0xFF,0xFF,0xFF,0x40,0x00,0x00,0x00, + 0xB8,0x0B,0x00,0x00,0xF4,0x2D,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x18,0xC9,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x63,0x6C,0x69,0x65, + 0x6E,0x74,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00, + 0x0E,0x00,0x00,0x00,0x47,0x65,0x74,0x4D,0x61,0x78,0x48,0x69,0x74,0x50,0x6F,0x69,0x6E,0x74,0x00,0x00, + 0x84,0xFF,0xFF,0xFF,0x68,0x00,0x00,0x00,0xA0,0x2D,0x00,0x00,0x5C,0x0B,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x74,0xC9,0xFF,0xFF,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x73,0x65,0x72,0x76,0x65,0x72,0x00,0x00,0x09,0x00,0x00,0x00, + 0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E,0x67,0x00,0x00,0x00,0x9C,0xC9,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x69,0x64,0x65,0x6D, + 0x70,0x6F,0x74,0x65,0x6E,0x74,0x00,0x00,0x08,0x00,0x00,0x00,0x52,0x65,0x74,0x72,0x69,0x65,0x76,0x65, + 0x00,0x00,0x00,0x00,0x0C,0x00,0x14,0x00,0x04,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,0x0C,0x00,0x00,0x00, + 0x40,0x00,0x00,0x00,0xD8,0x0A,0x00,0x00,0x14,0x2D,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xF8,0xC9,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x6E,0x6F,0x6E,0x65,0x00,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x73,0x74,0x72,0x65,0x61,0x6D,0x69,0x6E, + 0x67,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x53,0x74,0x6F,0x72,0x65,0x00,0x00,0x00,0xD2,0xFD,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x38,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0xDC,0x33,0x00,0x00, + 0x60,0xCD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xC8,0x00,0x00,0x00,0x94,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x2C,0x00,0x00,0x00, + 0x22,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41, + 0x6E,0x79,0x41,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75,0x73,0x41,0x6C,0x69,0x61,0x73,0x65,0x73,0x00,0x00, + 0x0C,0xFB,0xFF,0xFF,0x24,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x5C,0xCB,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x4D,0x33,0x00,0x00,0x3C,0xFB,0xFF,0xFF,0x24,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x8C,0xCB,0xFF,0xFF,0x00,0x00,0x00,0x0F, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x4D,0x32,0x00,0x00,0x6C,0xFB,0xFF,0xFF, + 0x24,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0xBC,0xCB,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x4D,0x31,0x00,0x00,0x0C,0xF9,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0xF9,0xFF,0xFF, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x00,0x00, + 0xEE,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x38,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0xC0,0x32,0x00,0x00,0x7C,0xCE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x90,0x00,0x00,0x00,0x5C,0x00,0x00,0x00, + 0x28,0x00,0x00,0x00,0x1F,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70, + 0x6C,0x65,0x2E,0x41,0x6E,0x79,0x55,0x6E,0x69,0x71,0x75,0x65,0x41,0x6C,0x69,0x61,0x73,0x65,0x73,0x00, + 0x24,0xFC,0xFF,0xFF,0x24,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x74,0xCC,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x0A,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x4D,0x32,0x00,0x00,0x54,0xFC,0xFF,0xFF,0x24,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xA4,0xCC,0xFF,0xFF,0x00,0x00,0x00,0x0F, + 0x07,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x54,0x53,0x00,0x00,0x94,0xFA,0xFF,0xFF, + 0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xD0,0xCC,0xFF,0xFF, + 0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x4D,0x00,0x00,0x00, + 0x20,0xFA,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0xFA,0xFF,0xFF,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x12,0x00,0x18,0x00,0x08,0x00, + 0x0C,0x00,0x07,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x12,0x00,0x00,0x00,0x00,0x00,0x00,0x01, + 0x38,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x9C,0x31,0x00,0x00,0xA0,0xCF,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xD8,0x00,0x00,0x00,0xA4,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x12,0x00,0x00,0x00, + 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41,0x6E,0x79,0x00,0x00, + 0x4C,0xFB,0xFF,0xFF,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x88,0xCD,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x0A,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x17,0x00,0x00,0x00, + 0x4D,0x79,0x47,0x61,0x6D,0x65,0x5F,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x32,0x5F,0x4D,0x6F,0x6E,0x73, + 0x74,0x65,0x72,0x00,0x8C,0xFB,0xFF,0xFF,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0xC8,0xCD,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x07,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x17,0x00,0x00,0x00,0x54,0x65,0x73,0x74,0x53,0x69,0x6D,0x70,0x6C,0x65,0x54,0x61,0x62,0x6C,0x65,0x57, + 0x69,0x74,0x68,0x45,0x6E,0x75,0x6D,0x00,0xCC,0xFB,0xFF,0xFF,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0xCE,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x5C,0xFB,0xFF,0xFF, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x50,0xFB,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x4E,0x4F,0x4E,0x45,0x00,0x00,0x12,0x00,0x18,0x00,0x04,0x00,0x08,0x00,0x00,0x00, + 0x0C,0x00,0x10,0x00,0x00,0x00,0x14,0x00,0x12,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x50,0x00,0x00,0x00, + 0x38,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x60,0x30,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xC8,0xCD,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00, + 0x09,0x00,0x00,0x00,0x62,0x69,0x74,0x5F,0x66,0x6C,0x61,0x67,0x73,0x00,0x00,0x00,0x08,0xD1,0xFF,0xFF, + 0x00,0x00,0x00,0x0A,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00, + 0x88,0x00,0x00,0x00,0x54,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61, + 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4C,0x6F,0x6E,0x67,0x45,0x6E,0x75,0x6D,0x00, + 0xA4,0xFE,0xFF,0xFF,0x20,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00, + 0x00,0x00,0x00,0x00,0x14,0xFC,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00, + 0x4C,0x6F,0x6E,0x67,0x42,0x69,0x67,0x00,0xD4,0xFE,0xFF,0xFF,0x20,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x44,0xFC,0xFF,0xFF,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4C,0x6F,0x6E,0x67,0x54,0x77,0x6F,0x00,0x14,0xFD,0xFF,0xFF, + 0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x70,0xFC,0xFF,0xFF, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4C,0x6F,0x6E,0x67,0x4F,0x6E,0x65,0x00, + 0x0A,0xFD,0xFF,0xFF,0x38,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x54,0x2F,0x00,0x00, + 0xE8,0xD1,0xFF,0xFF,0x00,0x00,0x00,0x03,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x48,0x00,0x00,0x00,0x1C,0x00,0x00,0x00, + 0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x52, + 0x61,0x63,0x65,0x00,0x94,0xFD,0xFF,0xFF,0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0xF0,0xFC,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00, + 0x45,0x6C,0x66,0x00,0xAC,0xFF,0xFF,0xFF,0x20,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x1C,0xFD,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x05,0x00,0x00,0x00,0x44,0x77,0x61,0x72,0x66,0x00,0x00,0x00,0x4C,0xFD,0xFF,0xFF,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x40,0xFD,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00, + 0x48,0x75,0x6D,0x61,0x6E,0x00,0x00,0x00,0x0C,0x00,0x18,0x00,0x04,0x00,0x0C,0x00,0x00,0x00,0x08,0x00, + 0x0C,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF,0xFF, + 0x00,0x00,0x00,0x00,0x7C,0xFD,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x4E,0x6F,0x6E,0x65,0x00,0x00,0x12,0x00,0x1C,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x10,0x00, + 0x14,0x00,0x18,0x00,0x12,0x00,0x00,0x00,0x9C,0x00,0x00,0x00,0x88,0x00,0x00,0x00,0x70,0x00,0x00,0x00, + 0x40,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x30,0x2E,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x27,0x00,0x00,0x00,0x20,0x43,0x6F,0x6D,0x70,0x6F,0x73,0x69,0x74,0x65,0x20,0x63,0x6F,0x6D,0x70,0x6F, + 0x6E,0x65,0x6E,0x74,0x73,0x20,0x6F,0x66,0x20,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x20,0x63,0x6F,0x6C, + 0x6F,0x72,0x2E,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x2C,0xD0,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x62,0x69,0x74,0x5F, + 0x66,0x6C,0x61,0x67,0x73,0x00,0x00,0x00,0x6C,0xD3,0xFF,0xFF,0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x1C,0x01,0x00,0x00,0x8C,0x00,0x00,0x00, + 0x20,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70, + 0x6C,0x65,0x2E,0x43,0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00,0x00,0xA6,0xFF,0xFF,0xFF,0x4C,0x00,0x00,0x00, + 0x3C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x20,0x5C,0x62,0x72,0x69,0x65,0x66,0x20,0x63,0x6F,0x6C,0x6F, + 0x72,0x20,0x42,0x6C,0x75,0x65,0x20,0x28,0x31,0x75,0x20,0x3C,0x3C,0x20,0x33,0x29,0x00,0x00,0x00,0x00, + 0xA4,0xFE,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x42,0x6C,0x75,0x65, + 0x00,0x00,0x0E,0x00,0x18,0x00,0x04,0x00,0x10,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x0E,0x00,0x00,0x00, + 0x70,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x27,0x00,0x00,0x00,0x20,0x47,0x72,0x65, + 0x65,0x6E,0x20,0x69,0x73,0x20,0x62,0x69,0x74,0x5F,0x66,0x6C,0x61,0x67,0x20,0x77,0x69,0x74,0x68,0x20, + 0x76,0x61,0x6C,0x75,0x65,0x20,0x28,0x31,0x75,0x20,0x3C,0x3C,0x20,0x31,0x29,0x00,0x13,0x00,0x00,0x00, + 0x20,0x5C,0x62,0x72,0x69,0x65,0x66,0x20,0x63,0x6F,0x6C,0x6F,0x72,0x20,0x47,0x72,0x65,0x65,0x6E,0x00, + 0x30,0xFF,0xFF,0xFF,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x47,0x72,0x65,0x65, + 0x6E,0x00,0x00,0x00,0x0C,0x00,0x14,0x00,0x04,0x00,0x0C,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x00,0x00, + 0x1C,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x68,0xFF,0xFF,0xFF, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x52,0x65,0x64,0x00,0x00,0x00,0x12,0x00, + 0x14,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x12,0x00,0x00,0x00, + 0x2C,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0xD8,0x2D,0x00,0x00,0xF0,0xD4,0xFF,0xFF, + 0x00,0x00,0x00,0x09,0x06,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x38,0x00,0x00,0x00,0x21,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72, + 0x4E,0x61,0x6D,0x65,0x53,0x70,0x61,0x63,0x65,0x2E,0x46,0x72,0x6F,0x6D,0x49,0x6E,0x63,0x6C,0x75,0x64, + 0x65,0x00,0x00,0x00,0x0C,0x00,0x0C,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x04,0x00,0x08,0x00,0x10,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00, + 0x49,0x6E,0x63,0x6C,0x75,0x64,0x65,0x56,0x61,0x6C,0x00,0x00,0x8C,0xD3,0xFF,0xFF,0x44,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xB0,0x2B,0x00,0x00,0x0C,0x00,0x00,0x00,0xCC,0x00,0x00,0x00, + 0xA0,0x00,0x00,0x00,0xA8,0x01,0x00,0x00,0x58,0x01,0x00,0x00,0x08,0x01,0x00,0x00,0xF8,0x01,0x00,0x00, + 0x70,0x01,0x00,0x00,0x24,0x01,0x00,0x00,0xD0,0x00,0x00,0x00,0xB4,0x01,0x00,0x00,0x54,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x1A,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70, + 0x6C,0x65,0x2E,0x54,0x79,0x70,0x65,0x41,0x6C,0x69,0x61,0x73,0x65,0x73,0x00,0x00,0xDC,0xD9,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x0B,0x00,0x1A,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x60,0xDF,0xFF,0xFF, + 0x00,0x00,0x0E,0x0C,0x08,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x76,0x66,0x36,0x34,0x00,0x00,0x00,0x00, + 0x08,0xDA,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0A,0x00,0x18,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x8C,0xDF,0xFF,0xFF,0x00,0x00,0x0E,0x03,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x76,0x38,0x00,0x00, + 0x64,0xD7,0xFF,0xFF,0x09,0x00,0x16,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x7C,0xD5,0xFF,0xFF, + 0x00,0x00,0x00,0x0C,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x66,0x36,0x34,0x00, + 0x8C,0xD7,0xFF,0xFF,0x08,0x00,0x14,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x3C,0xD3,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x66,0x33,0x32,0x00,0xB0,0xD7,0xFF,0xFF, + 0x07,0x00,0x12,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xC8,0xD5,0xFF,0xFF,0x00,0x00,0x00,0x0A, + 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x75,0x36,0x34,0x00,0xD8,0xD7,0xFF,0xFF, + 0x06,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF0,0xD5,0xFF,0xFF,0x00,0x00,0x00,0x09, + 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x69,0x36,0x34,0x00,0x00,0xD8,0xFF,0xFF, + 0x05,0x00,0x0E,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xB0,0xD3,0xFF,0xFF,0x00,0x00,0x00,0x08, + 0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x75,0x33,0x32,0x00,0x24,0xD8,0xFF,0xFF,0x04,0x00,0x0C,0x00, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD4,0xD3,0xFF,0xFF,0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00, + 0x03,0x00,0x00,0x00,0x69,0x33,0x32,0x00,0x48,0xD8,0xFF,0xFF,0x03,0x00,0x0A,0x00,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x60,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x06,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x03,0x00,0x00,0x00,0x75,0x31,0x36,0x00,0x70,0xD8,0xFF,0xFF,0x02,0x00,0x08,0x00,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x88,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x05,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x03,0x00,0x00,0x00,0x69,0x31,0x36,0x00,0x98,0xD8,0xFF,0xFF,0x01,0x00,0x06,0x00,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xB0,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x04,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x75,0x38,0x00,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00, + 0x0C,0x00,0x00,0x00,0x00,0x00,0x04,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xD6,0xFF,0xFF, + 0x00,0x00,0x00,0x03,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x38,0x00,0x00, + 0x14,0x00,0x18,0x00,0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00, + 0x14,0x00,0x00,0x00,0x50,0x01,0x00,0x00,0x50,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x4C,0x29,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x20,0x61,0x6E,0x20, + 0x65,0x78,0x61,0x6D,0x70,0x6C,0x65,0x20,0x64,0x6F,0x63,0x75,0x6D,0x65,0x6E,0x74,0x61,0x74,0x69,0x6F, + 0x6E,0x20,0x63,0x6F,0x6D,0x6D,0x65,0x6E,0x74,0x3A,0x20,0x22,0x6D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x20, + 0x6F,0x62,0x6A,0x65,0x63,0x74,0x22,0x00,0x3E,0x00,0x00,0x00,0xA8,0x07,0x00,0x00,0x04,0x08,0x00,0x00, + 0x64,0x08,0x00,0x00,0xBC,0x08,0x00,0x00,0x98,0x0C,0x00,0x00,0x90,0x1D,0x00,0x00,0xFC,0x00,0x00,0x00, + 0x90,0x1A,0x00,0x00,0xE8,0x11,0x00,0x00,0x80,0x1E,0x00,0x00,0xB4,0x1F,0x00,0x00,0x68,0x03,0x00,0x00, + 0x94,0x02,0x00,0x00,0xF0,0x1D,0x00,0x00,0xA8,0x04,0x00,0x00,0x30,0x04,0x00,0x00,0x0C,0x20,0x00,0x00, + 0x24,0x1F,0x00,0x00,0xC4,0x03,0x00,0x00,0x00,0x05,0x00,0x00,0x9C,0x01,0x00,0x00,0x28,0x01,0x00,0x00, + 0xF8,0x09,0x00,0x00,0x30,0x10,0x00,0x00,0x64,0x20,0x00,0x00,0xC8,0x02,0x00,0x00,0xEC,0x01,0x00,0x00, + 0x6C,0x05,0x00,0x00,0x74,0x06,0x00,0x00,0xC0,0x0E,0x00,0x00,0x48,0x1C,0x00,0x00,0xDC,0x1B,0x00,0x00, + 0x30,0x11,0x00,0x00,0xAC,0x1C,0x00,0x00,0xDC,0x13,0x00,0x00,0xF8,0x11,0x00,0x00,0x68,0x1B,0x00,0x00, + 0x58,0x12,0x00,0x00,0x88,0x1A,0x00,0x00,0xC4,0x18,0x00,0x00,0x18,0x19,0x00,0x00,0x68,0x13,0x00,0x00, + 0xF4,0x12,0x00,0x00,0xA0,0x12,0x00,0x00,0x2C,0x18,0x00,0x00,0x0C,0x16,0x00,0x00,0x18,0x17,0x00,0x00, + 0x94,0x14,0x00,0x00,0x98,0x17,0x00,0x00,0x18,0x15,0x00,0x00,0x80,0x16,0x00,0x00,0xF8,0x13,0x00,0x00, + 0x44,0x19,0x00,0x00,0x70,0x05,0x00,0x00,0x98,0x0A,0x00,0x00,0x18,0x10,0x00,0x00,0x68,0x06,0x00,0x00, + 0x70,0x10,0x00,0x00,0x40,0x08,0x00,0x00,0x38,0x0F,0x00,0x00,0xA4,0x0C,0x00,0x00,0x4C,0x0D,0x00,0x00, + 0x16,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x4D, + 0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x00,0x20,0xED,0xFF,0xFF,0x3D,0x00,0x7E,0x00,0x48,0x00,0x00,0x00, + 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0x7F,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x50,0xD6,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x36,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC0,0xD8,0xFF,0xFF,0x00,0x00,0x00,0x0C, + 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x64,0x6F,0x75,0x62,0x6C,0x65,0x5F,0x69, + 0x6E,0x66,0x5F,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x00,0x00,0x88,0xFD,0xFF,0xFF,0x3C,0x00,0x7C,0x00, + 0x48,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0xFF, + 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xBC,0xD6,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x36,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0xC4,0xD6,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x19,0x00,0x00,0x00,0x6E,0x65,0x67,0x61, + 0x74,0x69,0x76,0x65,0x5F,0x69,0x6E,0x66,0x69,0x6E,0x69,0x74,0x79,0x5F,0x64,0x65,0x66,0x61,0x75,0x6C, + 0x74,0x00,0x00,0x00,0xF8,0xED,0xFF,0xFF,0x3B,0x00,0x7A,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0xFF,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x28,0xD7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x39,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x30,0xD7,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00, + 0x14,0x00,0x00,0x00,0x6E,0x65,0x67,0x61,0x74,0x69,0x76,0x65,0x5F,0x69,0x6E,0x66,0x5F,0x64,0x65,0x66, + 0x61,0x75,0x6C,0x74,0x00,0x00,0x00,0x00,0x60,0xFE,0xFF,0xFF,0x3A,0x00,0x78,0x00,0x48,0x00,0x00,0x00, + 0x38,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0x7F,0x00,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x94,0xD7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x35,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x9C,0xD7,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x19,0x00,0x00,0x00,0x70,0x6F,0x73,0x69,0x74,0x69,0x76,0x65, + 0x5F,0x69,0x6E,0x66,0x69,0x6E,0x69,0x74,0x79,0x5F,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x00,0x00,0x00, + 0xD0,0xFE,0xFF,0xFF,0x39,0x00,0x76,0x00,0x48,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0x7F,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x04,0xD8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x37,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x0C,0xD8,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00, + 0x10,0x00,0x00,0x00,0x69,0x6E,0x66,0x69,0x6E,0x69,0x74,0x79,0x5F,0x64,0x65,0x66,0x61,0x75,0x6C,0x74, + 0x00,0x00,0x00,0x00,0x38,0xEF,0xFF,0xFF,0x38,0x00,0x74,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0x7F,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x68,0xD8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x36,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x70,0xD8,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00, + 0x14,0x00,0x00,0x00,0x70,0x6F,0x73,0x69,0x74,0x69,0x76,0x65,0x5F,0x69,0x6E,0x66,0x5F,0x64,0x65,0x66, + 0x61,0x75,0x6C,0x74,0x00,0x00,0x00,0x00,0xA0,0xFF,0xFF,0xFF,0x37,0x00,0x72,0x00,0x48,0x00,0x00,0x00, + 0x38,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF0,0x7F,0x00,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD4,0xD8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x35,0x35,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xDC,0xD8,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x69,0x6E,0x66,0x5F,0x64,0x65,0x66,0x61, + 0x75,0x6C,0x74,0x00,0x18,0x00,0x20,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x00,0x00,0x14,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x36,0x00,0x70,0x00,0x48,0x00,0x00,0x00, + 0x38,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0xF8,0x7F,0x00,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x4C,0xD9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x35,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x54,0xD9,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x6E,0x61,0x6E,0x5F,0x64,0x65,0x66,0x61, + 0x75,0x6C,0x74,0x00,0x38,0xE4,0xFF,0xFF,0x35,0x00,0x6E,0x00,0x4C,0x00,0x00,0x00,0x34,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xA8,0xD9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x33,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xE0,0xDC,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x04,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x6C,0x6F,0x6E,0x67,0x5F,0x65,0x6E,0x75, + 0x6D,0x5F,0x6E,0x6F,0x72,0x6D,0x61,0x6C,0x5F,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x00,0x00,0x00,0x00, + 0xC8,0xE7,0xFF,0xFF,0x34,0x00,0x6C,0x00,0x44,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0xDA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x35,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x4C,0xDD,0xFF,0xFF, + 0x00,0x00,0x00,0x0A,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x1A,0x00,0x00,0x00, + 0x6C,0x6F,0x6E,0x67,0x5F,0x65,0x6E,0x75,0x6D,0x5F,0x6E,0x6F,0x6E,0x5F,0x65,0x6E,0x75,0x6D,0x5F,0x64, + 0x65,0x66,0x61,0x75,0x6C,0x74,0x00,0x00,0x44,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x01,0x33,0x00,0x6A,0x00, + 0x6C,0x00,0x00,0x00,0x58,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x30,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x88,0xDA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x30,0x00,0x00,0x00,0x0D,0x00,0x00,0x00,0x6E,0x61,0x74,0x69,0x76,0x65,0x5F,0x69,0x6E,0x6C,0x69,0x6E, + 0x65,0x00,0x00,0x00,0xB0,0xDA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x35,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x7C,0xDB,0xFF,0xFF,0x00,0x00,0x00,0x0F, + 0x06,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0D,0x00,0x00,0x00,0x6E,0x61,0x74,0x69,0x76,0x65,0x5F,0x69, + 0x6E,0x6C,0x69,0x6E,0x65,0x00,0x00,0x00,0xD0,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x01,0x32,0x00,0x68,0x00, + 0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x10,0xDB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x35,0x30,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x80,0xE9,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x03,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x18,0x00,0x00,0x00,0x73,0x63,0x61,0x6C,0x61,0x72,0x5F,0x6B,0x65,0x79,0x5F,0x73, + 0x6F,0x72,0x74,0x65,0x64,0x5F,0x74,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x00,0x3C,0xE8,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x31,0x00,0x66,0x00,0x70,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0xDB,0xFF,0xFF,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x11,0x00,0x00,0x00, + 0x6E,0x65,0x73,0x74,0x65,0x64,0x5F,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x00, + 0xB0,0xDB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x39,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x54,0xE8,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00, + 0x1C,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x72,0x65,0x71,0x75,0x69,0x72,0x65,0x64,0x6E,0x65,0x73,0x74, + 0x65,0x64,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x00,0x00,0xB0,0xE6,0xFF,0xFF, + 0x30,0x00,0x64,0x00,0x4C,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0xFF,0xFF,0xFF,0xFF, + 0xFF,0xFF,0xFF,0xFF,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x20,0xDC,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0x58,0xDF,0xFF,0xFF,0x00,0x00,0x00,0x03,0x05,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x0B,0x00,0x00,0x00,0x73,0x69,0x67,0x6E,0x65,0x64,0x5F,0x65,0x6E,0x75,0x6D,0x00,0x40,0xE9,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x2F,0x00,0x62,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0xDC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x34,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xF0,0xEA,0xFF,0xFF, + 0x00,0x00,0x0E,0x04,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x76,0x65,0x63,0x74, + 0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x65,0x6E,0x75,0x6D,0x73,0x00,0xA0,0xE9,0xFF,0xFF,0x00,0x00,0x00,0x01, + 0x2E,0x00,0x60,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xE0,0xDC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x34,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xAC,0xDD,0xFF,0xFF,0x00,0x00,0x00,0x10, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0D,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x61,0x6D,0x62,0x69, + 0x67,0x75,0x6F,0x75,0x73,0x00,0x00,0x00,0xF0,0xEA,0xFF,0xFF,0x2D,0x00,0x5E,0x00,0x44,0x00,0x00,0x00, + 0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x3C,0xDD,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x35,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0x74,0xE0,0xFF,0xFF,0x00,0x00,0x00,0x01,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x61,0x6D,0x62,0x69,0x67,0x75,0x6F,0x75, + 0x73,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x64,0xEA,0xFF,0xFF,0x00,0x00,0x00,0x01,0x2C,0x00,0x5C,0x00, + 0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xA4,0xDD,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x34,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x70,0xDE,0xFF,0xFF,0x00,0x00,0x00,0x10,0x02,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x61,0x6E,0x79,0x5F,0x75,0x6E,0x69,0x71,0x75,0x65,0x00,0x00, + 0xB0,0xEB,0xFF,0xFF,0x2B,0x00,0x5A,0x00,0x44,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xFC,0xDD,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x34,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x34,0xE1,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x0F,0x00,0x00,0x00, + 0x61,0x6E,0x79,0x5F,0x75,0x6E,0x69,0x71,0x75,0x65,0x5F,0x74,0x79,0x70,0x65,0x00,0x20,0xEB,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x2A,0x00,0x58,0x00,0xF8,0x00,0x00,0x00,0xE8,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x05,0x00,0x00,0x00,0xB0,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x70,0xDE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x34,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x8C,0xDE,0xFF,0xFF,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xB4,0xDE,0xFF,0xFF,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00, + 0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xE0,0xDE,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x5F,0x67,0x65,0x74,0x00,0x00,0x00,0x00, + 0x0C,0xDF,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65, + 0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65, + 0x00,0x00,0x00,0x00,0xC0,0xEB,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x08,0x00,0x00,0x00,0x1F,0x00,0x00,0x00, + 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x6E,0x6F,0x6E,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67, + 0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x73,0x00,0x38,0xED,0xFF,0xFF,0x29,0x00,0x56,0x00, + 0xFC,0x00,0x00,0x00,0xE8,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB0,0x00,0x00,0x00, + 0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x94,0xDF,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x34,0x31,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0xB0,0xDF,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68, + 0x00,0x00,0x00,0x00,0xD8,0xDF,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00, + 0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F, + 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x04,0xE0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F, + 0x74,0x79,0x70,0x65,0x5F,0x67,0x65,0x74,0x00,0x00,0x00,0x00,0x30,0xE0,0xFF,0xFF,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00, + 0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xB0,0xE2,0xFF,0xFF, + 0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x6E,0x6F,0x6E,0x5F, + 0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x00,0x00,0x00,0x00, + 0x68,0xED,0xFF,0xFF,0x00,0x00,0x00,0x01,0x28,0x00,0x54,0x00,0x08,0x01,0x00,0x00,0xF8,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xB8,0xE0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x34,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xD4,0xE0,0xFF,0xFF, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34, + 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xFC,0xE0,0xFF,0xFF, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62, + 0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00, + 0x28,0xE1,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x2E,0x67,0x65,0x74, + 0x28,0x29,0x00,0x00,0x10,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65, + 0x5F,0x67,0x65,0x74,0x00,0x00,0x00,0x00,0x58,0xE1,0xFF,0xFF,0x20,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x10,0x00,0x00,0x00,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65, + 0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65, + 0x00,0x00,0x00,0x00,0x18,0xEE,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x08,0x00,0x00,0x00,0x1E,0x00,0x00,0x00, + 0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x63,0x6F,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F, + 0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x73,0x00,0x00,0x90,0xEF,0xFF,0xFF,0x27,0x00,0x52,0x00, + 0xCC,0x00,0x00,0x00,0xB8,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00, + 0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE8,0xE1,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0x04,0xE2,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31, + 0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00, + 0x2C,0xE2,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65, + 0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00,0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65, + 0x00,0x00,0x00,0x00,0x58,0xE2,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00, + 0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F, + 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xD8,0xE4,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x63,0x6F,0x5F,0x6F,0x77,0x6E,0x69,0x6E,0x67,0x5F,0x72,0x65, + 0x66,0x65,0x72,0x65,0x6E,0x63,0x65,0x00,0x8C,0xEF,0xFF,0xFF,0x00,0x00,0x00,0x01,0x26,0x00,0x50,0x00, + 0x7C,0x00,0x00,0x00,0x68,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xD0,0xE2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x33,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xEC,0xE2,0xFF,0xFF,0x20,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x64,0x65,0x66,0x61,0x75,0x6C,0x74,0x5F,0x70,0x74,0x72,0x5F, + 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F, + 0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x78,0xF1,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x02,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x73,0x74, + 0x72,0x6F,0x6E,0x67,0x5F,0x72,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x00, + 0x38,0xF0,0xFF,0xFF,0x00,0x00,0x00,0x01,0x25,0x00,0x4E,0x00,0xC8,0x00,0x00,0x00,0xB8,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x84,0xE3,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x33,0x37,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xA0,0xE3,0xFF,0xFF,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xC8,0xE3,0xFF,0xFF,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00, + 0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xF4,0xE3,0xFF,0xFF, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00, + 0xA8,0xF0,0xFF,0xFF,0x00,0x00,0x0E,0x0A,0x08,0x00,0x00,0x00,0x19,0x00,0x00,0x00,0x76,0x65,0x63,0x74, + 0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x77,0x65,0x61,0x6B,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63,0x65, + 0x73,0x00,0x00,0x00,0x1C,0xF2,0xFF,0xFF,0x24,0x00,0x4C,0x00,0xCC,0x00,0x00,0x00,0xB8,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0x00,0x00,0x00,0x50,0x00,0x00,0x00,0x24,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x74,0xE4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x33,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x90,0xE4,0xFF,0xFF,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0xB8,0xE4,0xFF,0xFF,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x54,0x00, + 0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0xE4,0xE4,0xFF,0xFF, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00, + 0x64,0xE7,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x15,0x00,0x00,0x00, + 0x73,0x69,0x6E,0x67,0x6C,0x65,0x5F,0x77,0x65,0x61,0x6B,0x5F,0x72,0x65,0x66,0x65,0x72,0x65,0x6E,0x63, + 0x65,0x00,0x00,0x00,0x1C,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01,0x23,0x00,0x4A,0x00,0x40,0x00,0x00,0x00, + 0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x5C,0xE5,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x35,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0xCC,0xF3,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x15,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x72,0x65,0x66,0x65,0x72,0x72, + 0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x84,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01,0x22,0x00,0x48,0x00, + 0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xC4,0xE5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x34,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x90,0xE6,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x0B,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x15,0x00,0x00,0x00,0x70,0x61,0x72,0x65,0x6E,0x74,0x5F,0x6E,0x61,0x6D,0x65,0x73, + 0x70,0x61,0x63,0x65,0x5F,0x74,0x65,0x73,0x74,0x00,0x00,0x00,0xEC,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x01, + 0x21,0x00,0x46,0x00,0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x2C,0xE6,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x33,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xD0,0xF2,0xFF,0xFF,0x00,0x00,0x0E,0x0C, + 0x08,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x64,0x6F, + 0x75,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0x4C,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x20,0x00,0x44,0x00, + 0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x8C,0xE6,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x32,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x30,0xF3,0xFF,0xFF,0x00,0x00,0x0E,0x09,0x08,0x00,0x00,0x00, + 0x0F,0x00,0x00,0x00,0x76,0x65,0x63,0x74,0x6F,0x72,0x5F,0x6F,0x66,0x5F,0x6C,0x6F,0x6E,0x67,0x73,0x00, + 0xA8,0xF3,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1F,0x00,0x42,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE8,0xE6,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x33,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0x58,0xF5,0xFF,0xFF,0x00,0x00,0x0E,0x0F,0x06,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00, + 0x74,0x65,0x73,0x74,0x35,0x00,0x00,0x00,0x00,0xF4,0xFF,0xFF,0x00,0x00,0x00,0x01,0x1E,0x00,0x40,0x00, + 0x64,0x00,0x00,0x00,0x54,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x44,0xE7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x33,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x60,0xE7,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x0A,0x00,0x00,0x00,0x66,0x6C,0x65,0x78, + 0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x0C,0xF4,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x66,0x6C,0x65,0x78,0x00,0x00,0x00,0x00,0x7C,0xF4,0xFF,0xFF,0x00,0x00,0x00,0x01, + 0x1D,0x00,0x3E,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xBC,0xE7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x32,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x2C,0xF6,0xFF,0xFF,0x00,0x00,0x0E,0x0F, + 0x00,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x17,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61, + 0x79,0x6F,0x66,0x73,0x6F,0x72,0x74,0x65,0x64,0x73,0x74,0x72,0x75,0x63,0x74,0x00,0xE4,0xF4,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x1C,0x00,0x3C,0x00,0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x24,0xE8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x32,0x38,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC8,0xF4,0xFF,0xFF, + 0x00,0x00,0x0E,0x0D,0x04,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61, + 0x79,0x6F,0x66,0x73,0x74,0x72,0x69,0x6E,0x67,0x32,0x00,0x00,0x34,0xF6,0xFF,0xFF,0x1B,0x00,0x3A,0x00, + 0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x80,0xE8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x37,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x88,0xE8,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00, + 0x06,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x66,0x33,0x00,0x00,0xA8,0xFF,0xFF,0xFF,0x1A,0x00,0x38,0x00, + 0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x40, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xD8,0xE8,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x32,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xE0,0xE8,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x66,0x32,0x00,0x00, + 0x18,0x00,0x1C,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x19,0x00,0x36,0x00,0x44,0x00,0x00,0x00,0x34,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x6E,0x86,0x1B,0xF0,0xF9,0x21,0x09,0x40,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x48,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x35,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x50,0xE9,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00, + 0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x66,0x00,0x00,0x00,0x5C,0xF6,0xFF,0xFF,0x00,0x00,0x00,0x01, + 0x18,0x00,0x34,0x00,0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x9C,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x32,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x40,0xF6,0xFF,0xFF,0x00,0x00,0x0E,0x02, + 0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x62, + 0x6F,0x6F,0x6C,0x73,0x00,0x00,0x00,0x00,0xAC,0xF7,0xFF,0xFF,0x17,0x00,0x32,0x00,0x6C,0x00,0x00,0x00, + 0x58,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xFC,0xE9,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x33,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x18,0xEA,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x94,0xEC,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x75,0x36,0x34,0x5F, + 0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0x38,0xF8,0xFF,0xFF,0x16,0x00,0x30,0x00,0x6C,0x00,0x00,0x00, + 0x58,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x88,0xEA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x32,0x32,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xA4,0xEA,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x20,0xED,0xFF,0xFF,0x00,0x00,0x00,0x09,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x36,0x34,0x5F, + 0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0xC4,0xF8,0xFF,0xFF,0x15,0x00,0x2E,0x00,0xC4,0x00,0x00,0x00, + 0xB4,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x50,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x1C,0xEB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x32,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x38,0xEB,0xFF,0xFF, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x33,0x32, + 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x60,0xEB,0xFF,0xFF, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x53,0x74,0x61,0x74,0x00,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00,0x88,0xEB,0xFF,0xFF, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x6E,0x61,0x6B,0x65,0x64,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x63,0x70,0x70,0x5F,0x70,0x74,0x72,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x00, + 0xA0,0xEB,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74, + 0x68,0x61,0x73,0x68,0x75,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0xA8,0xF9,0xFF,0xFF, + 0x14,0x00,0x2C,0x00,0x68,0x00,0x00,0x00,0x58,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF8,0xEB,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x32,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x14,0xEC,0xFF,0xFF, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x61,0x5F,0x33,0x32, + 0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x28,0xEC,0xFF,0xFF, + 0x00,0x00,0x00,0x07,0x01,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68, + 0x73,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x61,0x00,0x00,0x00,0x30,0xFA,0xFF,0xFF,0x13,0x00,0x2A,0x00, + 0x68,0x00,0x00,0x00,0x54,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x80,0xEC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x31,0x39,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x9C,0xEC,0xFF,0xFF,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x36,0x34,0x00,0x04,0x00,0x00,0x00, + 0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x14,0xEF,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x75,0x36,0x34,0x5F, + 0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0xB8,0xFA,0xFF,0xFF,0x12,0x00,0x28,0x00,0x68,0x00,0x00,0x00, + 0x54,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x08,0xED,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x38,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x24,0xED,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x36,0x34,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68, + 0x00,0x00,0x00,0x00,0x9C,0xEF,0xFF,0xFF,0x00,0x00,0x00,0x09,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x36,0x34,0x5F,0x66,0x6E,0x76,0x31, + 0x00,0x00,0x00,0x00,0x40,0xFB,0xFF,0xFF,0x11,0x00,0x26,0x00,0x64,0x00,0x00,0x00,0x54,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x90,0xED,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x37,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0xAC,0xED,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00, + 0x66,0x6E,0x76,0x31,0x5F,0x33,0x32,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00, + 0xBC,0xED,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74, + 0x68,0x61,0x73,0x68,0x75,0x33,0x32,0x5F,0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0xC4,0xFB,0xFF,0xFF, + 0x10,0x00,0x24,0x00,0x64,0x00,0x00,0x00,0x54,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0xEE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x31,0x36,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x30,0xEE,0xFF,0xFF, + 0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x66,0x6E,0x76,0x31,0x5F,0x33,0x32,0x00, + 0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68,0x00,0x00,0x00,0x00,0x40,0xEE,0xFF,0xFF,0x00,0x00,0x00,0x07, + 0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x68,0x61,0x73,0x68,0x73,0x33,0x32,0x5F, + 0x66,0x6E,0x76,0x31,0x00,0x00,0x00,0x00,0x48,0xFC,0xFF,0xFF,0x0F,0x00,0x22,0x00,0x40,0x00,0x00,0x00, + 0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x94,0xEE,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x35,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0x04,0xF1,0xFF,0xFF,0x00,0x00,0x00,0x02,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x62,0x6F,0x6F,0x6C,0x00,0x00,0x00,0x00,0xB0,0xFB,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x0E,0x00,0x20,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF0,0xEE,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x31,0x34,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xBC,0xEF,0xFF,0xFF, + 0x00,0x00,0x00,0x0F,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x09,0x00,0x00,0x00,0x74,0x65,0x73,0x74, + 0x65,0x6D,0x70,0x74,0x79,0x00,0x00,0x00,0x0C,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0D,0x00,0x1E,0x00, + 0x70,0x00,0x00,0x00,0x60,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x38,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x50,0xEF,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x07,0x00,0x00,0x00, + 0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x11,0x00,0x00,0x00,0x6E,0x65,0x73,0x74,0x65,0x64,0x5F,0x66, + 0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x00,0x80,0xEF,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x33,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0x24,0xFC,0xFF,0xFF,0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x74,0x65,0x73,0x74, + 0x6E,0x65,0x73,0x74,0x65,0x64,0x66,0x6C,0x61,0x74,0x62,0x75,0x66,0x66,0x65,0x72,0x00,0x00,0x00,0x00, + 0xA4,0xFC,0xFF,0xFF,0x00,0x00,0x00,0x01,0x0C,0x00,0x1C,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xEF,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x31,0x32,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0xB0,0xF0,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00, + 0x65,0x6E,0x65,0x6D,0x79,0x00,0x00,0x00,0x1C,0x00,0x1C,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x18,0x00,0x07,0x00,0x1C,0x00,0x00,0x00, + 0x00,0x00,0x00,0x01,0x0B,0x00,0x1A,0x00,0xB4,0x00,0x00,0x00,0xA0,0x00,0x00,0x00,0x78,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0E,0x00,0x00,0x00, + 0x20,0x6D,0x75,0x6C,0x74,0x69,0x6C,0x69,0x6E,0x65,0x20,0x74,0x6F,0x6F,0x00,0x00,0x49,0x00,0x00,0x00, + 0x20,0x61,0x6E,0x20,0x65,0x78,0x61,0x6D,0x70,0x6C,0x65,0x20,0x64,0x6F,0x63,0x75,0x6D,0x65,0x6E,0x74, + 0x61,0x74,0x69,0x6F,0x6E,0x20,0x63,0x6F,0x6D,0x6D,0x65,0x6E,0x74,0x3A,0x20,0x74,0x68,0x69,0x73,0x20, + 0x77,0x69,0x6C,0x6C,0x20,0x65,0x6E,0x64,0x20,0x75,0x70,0x20,0x69,0x6E,0x20,0x74,0x68,0x65,0x20,0x67, + 0x65,0x6E,0x65,0x72,0x61,0x74,0x65,0x64,0x20,0x63,0x6F,0x64,0x65,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xCC,0xF0,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x31,0x31,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x3C,0xFF,0xFF,0xFF,0x00,0x00,0x0E,0x0F, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61, + 0x79,0x6F,0x66,0x74,0x61,0x62,0x6C,0x65,0x73,0x00,0x00,0x00,0xF0,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01, + 0x0A,0x00,0x18,0x00,0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x30,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x31,0x30,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xD4,0xFD,0xFF,0xFF,0x00,0x00,0x0E,0x0D, + 0x04,0x00,0x00,0x00,0x11,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x61,0x72,0x72,0x61,0x79,0x6F,0x66,0x73, + 0x74,0x72,0x69,0x6E,0x67,0x00,0x00,0x00,0x50,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01,0x09,0x00,0x16,0x00, + 0x50,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x90,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x39,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x10,0x00,0x10,0x00,0x06,0x00,0x07,0x00,0x08,0x00,0x00,0x00, + 0x00,0x00,0x0C,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x0E,0x0F,0x06,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x34,0x00,0x00,0x00,0xB8,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x01, + 0x08,0x00,0x14,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xF8,0xF1,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x38,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC4,0xF2,0xFF,0xFF,0x00,0x00,0x00,0x10, + 0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x00,0x00,0x00,0x00, + 0x18,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x07,0x00,0x12,0x00,0x44,0x00,0x00,0x00,0x2C,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x64,0xF2,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x37,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0x9C,0xF5,0xFF,0xFF,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x09,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x5F,0x74,0x79,0x70,0x65,0x00,0x00,0x00,0x18,0x00,0x20,0x00, + 0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00, + 0x18,0x00,0x00,0x00,0x06,0x00,0x10,0x00,0x50,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0xE4,0xF2,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x36,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x1C,0xF6,0xFF,0xFF,0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00, + 0x1C,0x00,0x18,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x14,0x00,0x00,0x00,0x07,0x00,0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x05,0x00,0x0E,0x00, + 0x4C,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x5C,0xF3,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x35,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x10,0x00,0x0C,0x00,0x06,0x00,0x07,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x0E,0x04,0x01,0x00,0x00,0x00,0x09,0x00,0x00,0x00, + 0x69,0x6E,0x76,0x65,0x6E,0x74,0x6F,0x72,0x79,0x00,0x00,0x00,0x18,0x00,0x18,0x00,0x0C,0x00,0x10,0x00, + 0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x14,0x00,0x18,0x00,0x00,0x00, + 0x00,0x00,0x00,0x01,0x04,0x00,0x0C,0x00,0x90,0x00,0x00,0x00,0x7C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x03,0x00,0x00,0x00,0x4C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xE4,0xF3,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x31,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x70,0x72,0x69,0x6F,0x72,0x69,0x74,0x79,0x00,0x00,0x00,0x00,0x08,0xF4,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00, + 0x24,0xF4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00, + 0x0A,0x00,0x00,0x00,0x64,0x65,0x70,0x72,0x65,0x63,0x61,0x74,0x65,0x64,0x00,0x00,0x9C,0xF6,0xFF,0xFF, + 0x00,0x00,0x00,0x02,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x66,0x72,0x69,0x65, + 0x6E,0x64,0x6C,0x79,0x00,0x00,0x00,0x00,0x18,0x00,0x18,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x06,0x00,0x07,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x01,0x01, + 0x03,0x00,0x0A,0x00,0x5C,0x00,0x00,0x00,0x4C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xA4,0xF4,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6B,0x65,0x79,0x00,0xC0,0xF4,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x33,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0xC8,0xF4,0xFF,0xFF,0x00,0x00,0x00,0x0D,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x6E,0x61,0x6D,0x65,0x00,0x00,0x00,0x00,0xA8,0xFF,0xFF,0xFF,0x02,0x00,0x08,0x00,0x48,0x00,0x00,0x00, + 0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x18,0xF5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x32,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x88,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x05, + 0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x68,0x70,0x00,0x00,0x18,0x00,0x1C,0x00, + 0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00, + 0x18,0x00,0x00,0x00,0x01,0x00,0x06,0x00,0x48,0x00,0x00,0x00,0x34,0x00,0x00,0x00,0x0C,0x00,0x00,0x00, + 0x96,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x88,0xF5,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x31,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x69,0x64,0x00,0x00,0xF8,0xF7,0xFF,0xFF,0x00,0x00,0x00,0x05,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x6D,0x61,0x6E,0x61,0x00,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x08,0x00,0x0C,0x00, + 0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x05,0x00, + 0x1C,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF8,0xF5,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0xC4,0xF6,0xFF,0xFF, + 0x00,0x00,0x00,0x0F,0x09,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x70,0x6F,0x73,0x00, + 0x5C,0xF7,0xFF,0xFF,0x18,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xE0,0x07,0x00,0x00, + 0x01,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x19,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45, + 0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x52,0x65,0x66,0x65,0x72,0x72,0x61,0x62,0x6C,0x65,0x00,0x00,0x00, + 0x18,0x00,0x14,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x05,0x00,0x10,0x00,0x18,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x6C,0x00,0x00,0x00,0x58,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xA0,0xF6,0xFF,0xFF, + 0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00, + 0x6B,0x65,0x79,0x00,0xBC,0xF6,0xFF,0xFF,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x66,0x6E,0x76,0x31,0x61,0x5F,0x36,0x34,0x00,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0x61,0x73,0x68, + 0x00,0x00,0x00,0x00,0x38,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x0A,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x2C,0xF8,0xFF,0xFF,0x20,0x00,0x00,0x00,0x0C,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x10,0x07,0x00,0x00,0x03,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0xB8,0x00,0x00,0x00, + 0x8C,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70, + 0x6C,0x65,0x2E,0x53,0x74,0x61,0x74,0x00,0x18,0x00,0x18,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x00,0x00,0x00,0x01, + 0x02,0x00,0x08,0x00,0x40,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x70,0xF7,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6B,0x65,0x79,0x00,0xE0,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x06, + 0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x63,0x6F,0x75,0x6E,0x74,0x00,0x00,0x00, + 0xF4,0xFB,0xFF,0xFF,0x01,0x00,0x06,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0C,0xFA,0xFF,0xFF, + 0x00,0x00,0x00,0x09,0x08,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x76,0x61,0x6C,0x00, + 0xAC,0xF8,0xFF,0xFF,0x00,0x01,0x04,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xCC,0xF7,0xFF,0xFF, + 0x00,0x00,0x00,0x0D,0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x7C,0xF8,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x1C,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x10,0x06,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x27,0x00,0x00,0x00,0x4D,0x79,0x47,0x61, + 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x53,0x74,0x72,0x75,0x63,0x74,0x4F,0x66,0x53, + 0x74,0x72,0x75,0x63,0x74,0x73,0x4F,0x66,0x53,0x74,0x72,0x75,0x63,0x74,0x73,0x00,0x14,0xFF,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x04,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x0F, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00,0xF4,0xF8,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x24,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x98,0x05,0x00,0x00,0x03,0x00,0x00,0x00,0xC0,0x00,0x00,0x00,0x74,0x00,0x00,0x00,0x28,0x00,0x00,0x00, + 0x1E,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x53, + 0x74,0x72,0x75,0x63,0x74,0x4F,0x66,0x53,0x74,0x72,0x75,0x63,0x74,0x73,0x00,0x00,0xD4,0xFF,0xFF,0xFF, + 0x00,0x00,0x00,0x01,0x02,0x00,0x0C,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x80,0xF9,0xFF,0xFF, + 0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x63,0x00,0x00,0x00, + 0x1C,0x00,0x14,0x00,0x0C,0x00,0x10,0x00,0x08,0x00,0x0A,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x01,0x00,0x08,0x00, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xC8,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x06,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,0x1C,0x00,0x10,0x00,0x08,0x00,0x0C,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00, + 0x1C,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x0C,0xFA,0xFF,0xFF, + 0x00,0x00,0x00,0x0F,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00, + 0xFC,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x01,0x20,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x08,0x00,0x00,0x00,0x90,0x04,0x00,0x00,0x02,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x64,0x00,0x00,0x00, + 0x16,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x41, + 0x62,0x69,0x6C,0x69,0x74,0x79,0x00,0x00,0x04,0xFE,0xFF,0xFF,0x01,0x00,0x04,0x00,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xB4,0xF9,0xFF,0xFF,0x00,0x00,0x00,0x08,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0x64,0x69,0x73,0x74,0x61,0x6E,0x63,0x65,0x00,0x00,0x00,0x00,0x18,0x00,0x14,0x00,0x08,0x00,0x0C,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x07,0x00,0x10,0x00,0x18,0x00,0x00,0x00, + 0x00,0x00,0x00,0x01,0x3C,0x00,0x00,0x00,0x2C,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x18,0xFA,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x30,0x00,0x00,0x00,0x03,0x00,0x00,0x00,0x6B,0x65,0x79,0x00,0x20,0xFA,0xFF,0xFF,0x00,0x00,0x00,0x08, + 0x01,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x69,0x64,0x00,0x00,0x14,0x00,0x20,0x00,0x08,0x00,0x0C,0x00, + 0x07,0x00,0x10,0x00,0x14,0x00,0x18,0x00,0x00,0x00,0x1C,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x01, + 0x60,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x08,0x00,0x00,0x00, + 0xA4,0x03,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x84,0xFA,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00,0x0B,0x00,0x00,0x00,0x66,0x6F,0x72,0x63, + 0x65,0x5F,0x61,0x6C,0x69,0x67,0x6E,0x00,0x06,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x7C,0x00,0x00,0x00, + 0x48,0x00,0x00,0x00,0x2C,0x01,0x00,0x00,0x04,0x01,0x00,0x00,0xCC,0x00,0x00,0x00,0x13,0x00,0x00,0x00, + 0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x56,0x65,0x63,0x33,0x00, + 0x00,0x00,0x1E,0x00,0x14,0x00,0x0C,0x00,0x10,0x00,0x06,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x05,0x00,0x0A,0x00,0x1E,0x00,0x00,0x00,0x00,0x01,0x05,0x00, + 0x1A,0x00,0x02,0x00,0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xC0,0xFB,0xFF,0xFF,0x00,0x00,0x00,0x0F, + 0x06,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x33,0x00,0x00,0x00, + 0xD6,0xFD,0xFF,0xFF,0x00,0x00,0x04,0x00,0x18,0x00,0x01,0x00,0x1C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x5C,0xFE,0xFF,0xFF,0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x32,0x00,0x00,0x00,0xAC,0xFF,0xFF,0xFF,0x03,0x00,0x10,0x00, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xC4,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x0C,0x08,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00,0x74,0x65,0x73,0x74,0x31,0x00,0x00,0x00,0x36,0xFE,0xFF,0xFF, + 0x00,0x00,0x02,0x00,0x08,0x00,0x04,0x00,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x8C,0xFB,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x7A,0x00,0x00,0x00,0x0C,0x00,0x10,0x00, + 0x08,0x00,0x0C,0x00,0x04,0x00,0x06,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x04,0x00,0x14,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xBC,0xFB,0xFF,0xFF,0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x79,0x00,0x00,0x00,0xE4,0xFB,0xFF,0xFF,0x14,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xDC,0xFB,0xFF,0xFF, + 0x00,0x00,0x00,0x0B,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x78,0x00,0x00,0x00,0x14,0x00,0x18,0x00, + 0x04,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x10,0x00,0x00,0x00,0x14,0x00,0x14,0x00,0x00,0x00, + 0x70,0x00,0x00,0x00,0x64,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0xF0,0x01,0x00,0x00, + 0x02,0x00,0x00,0x00,0x28,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x3C,0xFC,0xFF,0xFF,0x10,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00,0x07,0x00,0x00,0x00,0x70,0x72,0x69,0x76, + 0x61,0x74,0x65,0x00,0x5C,0xFC,0xFF,0xFF,0x10,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x30,0x00,0x00,0x00,0x0E,0x00,0x00,0x00,0x63,0x73,0x68,0x61,0x72,0x70,0x5F,0x70,0x61,0x72,0x74,0x69, + 0x61,0x6C,0x00,0x00,0x01,0x00,0x00,0x00,0x40,0x00,0x00,0x00,0x26,0x00,0x00,0x00,0x4D,0x79,0x47,0x61, + 0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x54,0x65,0x73,0x74,0x53,0x69,0x6D,0x70,0x6C, + 0x65,0x54,0x61,0x62,0x6C,0x65,0x57,0x69,0x74,0x68,0x45,0x6E,0x75,0x6D,0x00,0x00,0x00,0x00,0x0E,0x00, + 0x1C,0x00,0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,0x10,0x00,0x0E,0x00,0x00,0x00,0x00,0x00,0x04,0x00, + 0x38,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x10,0x00,0x14,0x00,0x07,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x10,0x00,0x00,0x00, + 0x00,0x00,0x00,0x04,0x03,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x05,0x00,0x00,0x00, + 0x63,0x6F,0x6C,0x6F,0x72,0x00,0x00,0x00,0x9C,0xFD,0xFF,0xFF,0x00,0x00,0x00,0x01,0x20,0x00,0x00,0x00, + 0x10,0x00,0x00,0x00,0x02,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0xF0,0x00,0x00,0x00,0x02,0x00,0x00,0x00, + 0x6C,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x13,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45, + 0x78,0x61,0x6D,0x70,0x6C,0x65,0x2E,0x54,0x65,0x73,0x74,0x00,0x00,0x00,0x1E,0x00,0x14,0x00,0x0C,0x00, + 0x10,0x00,0x06,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x0A,0x00,0x1E,0x00,0x00,0x00,0x00,0x00,0x01,0x00,0x02,0x00,0x01,0x00,0x18,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0xDC,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x03,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,0xA0,0xFD,0xFF,0xFF,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x10,0x00,0x10,0x00,0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00,0x10,0x00,0x00,0x00, + 0x00,0x00,0x00,0x05,0x02,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00, + 0x04,0xFF,0xFF,0xFF,0x14,0x00,0x00,0x00,0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x38,0x00,0x00,0x00, + 0x00,0x00,0x00,0x00,0x17,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x45,0x78,0x61,0x6D,0x70, + 0x6C,0x65,0x32,0x2E,0x4D,0x6F,0x6E,0x73,0x74,0x65,0x72,0x00,0x38,0xFF,0xFF,0xFF,0x2C,0x00,0x00,0x00, + 0x24,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x12,0x00,0x00,0x00,0x2F,0x2F,0x6D,0x6F, + 0x6E,0x73,0x74,0x65,0x72,0x5F,0x74,0x65,0x73,0x74,0x2E,0x66,0x62,0x73,0x00,0x00,0x00,0x00,0x00,0x00, + 0x18,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x49,0x6E,0x50,0x61,0x72,0x65,0x6E,0x74,0x4E, + 0x61,0x6D,0x65,0x73,0x70,0x61,0x63,0x65,0x00,0x00,0x00,0x00,0x88,0xFF,0xFF,0xFF,0x40,0x00,0x00,0x00, + 0x34,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x20,0x00,0x00,0x00,0x2F,0x2F,0x69,0x6E, + 0x63,0x6C,0x75,0x64,0x65,0x5F,0x74,0x65,0x73,0x74,0x2F,0x69,0x6E,0x63,0x6C,0x75,0x64,0x65,0x5F,0x74, + 0x65,0x73,0x74,0x31,0x2E,0x66,0x62,0x73,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x10,0x00,0x00,0x00, + 0x06,0x00,0x00,0x00,0x54,0x61,0x62,0x6C,0x65,0x41,0x00,0x00,0x84,0xFF,0xFF,0xFF,0x00,0x01,0x04,0x00, + 0x18,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x68,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x0F,0x0C,0x00,0x00,0x00, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x62,0x00,0x00,0x00,0x14,0x00,0x14,0x00,0x04,0x00,0x08,0x00, + 0x00,0x00,0x0C,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x10,0x00,0x14,0x00,0x00,0x00,0x18,0x00,0x00,0x00, + 0x0C,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0xB4,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x44,0x00,0x00,0x00, + 0x1C,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65, + 0x53,0x70,0x61,0x63,0x65,0x2E,0x54,0x61,0x62,0x6C,0x65,0x42,0x00,0x00,0x00,0x00,0x1C,0x00,0x10,0x00, + 0x08,0x00,0x0C,0x00,0x00,0x00,0x06,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00, + 0x00,0x00,0x05,0x00,0x1C,0x00,0x00,0x00,0x00,0x01,0x04,0x00,0x28,0x00,0x00,0x00,0x14,0x00,0x00,0x00, + 0x10,0x00,0x10,0x00,0x07,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x00,0x00,0x0C,0x00,0x10,0x00,0x00,0x00, + 0x00,0x00,0x00,0x0F,0x0E,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00, + 0x14,0x00,0x1C,0x00,0x08,0x00,0x0C,0x00,0x07,0x00,0x10,0x00,0x14,0x00,0x00,0x00,0x00,0x00,0x18,0x00, + 0x14,0x00,0x00,0x00,0x00,0x00,0x00,0x01,0x48,0x00,0x00,0x00,0x3C,0x00,0x00,0x00,0x04,0x00,0x00,0x00, + 0x04,0x00,0x00,0x00,0x04,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x2F,0x2F,0x69,0x6E,0x63,0x6C,0x75,0x64, + 0x65,0x5F,0x74,0x65,0x73,0x74,0x2F,0x73,0x75,0x62,0x2F,0x69,0x6E,0x63,0x6C,0x75,0x64,0x65,0x5F,0x74, + 0x65,0x73,0x74,0x32,0x2E,0x66,0x62,0x73,0x00,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x30,0x00,0x00,0x00, + 0x1C,0x00,0x00,0x00,0x4D,0x79,0x47,0x61,0x6D,0x65,0x2E,0x4F,0x74,0x68,0x65,0x72,0x4E,0x61,0x6D,0x65, + 0x53,0x70,0x61,0x63,0x65,0x2E,0x55,0x6E,0x75,0x73,0x65,0x64,0x00,0x00,0x00,0x00,0x08,0x00,0x0C,0x00, + 0x04,0x00,0x08,0x00,0x08,0x00,0x00,0x00,0x24,0x00,0x00,0x00,0x14,0x00,0x00,0x00,0x10,0x00,0x0C,0x00, + 0x07,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x08,0x00,0x10,0x00,0x00,0x00,0x00,0x00,0x00,0x07, + 0x01,0x00,0x00,0x00,0x01,0x00,0x00,0x00,0x61,0x00,0x00,0x00 + }; + return bfbsData; + } + static size_t size() { + return 14592; + } + const uint8_t *begin() { + return data(); + } + const uint8_t *end() { + return data() + size(); + } +}; + +} // namespace Example +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_BFBS_H_ diff --git a/third_party/flatbuffers/tests/monster_test_generated.grpc.fb.cc b/third_party/flatbuffers/tests/monster_test_generated.grpc.fb.cc new file mode 100644 index 00000000000..9a56eb8540b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_generated.grpc.fb.cc @@ -0,0 +1,130 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test + +#include "monster_test_generated.grpc.fb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +namespace MyGame { +namespace Example { + +static const char* MonsterStorage_method_names[] = { + "/MyGame.Example.MonsterStorage/Store", + "/MyGame.Example.MonsterStorage/Retrieve", + "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", +}; + +std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) { + std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel)); + return stub; +} + +MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) + : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) + , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) + , rpcmethod_GetMaxHitPoint_(MonsterStorage_method_names[2], ::grpc::internal::RpcMethod::CLIENT_STREAMING, channel) + , rpcmethod_GetMinMaxHitPoints_(MonsterStorage_method_names[3], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel) + {} + +::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) { + return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false); +} + +::grpc::ClientReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_Retrieve_, context, request); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr); +} + +::grpc::ClientWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return ::grpc::internal::ClientWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMaxHitPoint_, context, response); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, true, tag); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, false, nullptr); +} + +::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMinMaxHitPointsRaw(::grpc::ClientContext* context) { + return ::grpc::internal::ClientReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMinMaxHitPoints_, context); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, true, tag); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, false, nullptr); +} + +MonsterStorage::Service::Service() { + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[0], + ::grpc::internal::RpcMethod::NORMAL_RPC, + new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Store), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[1], + ::grpc::internal::RpcMethod::SERVER_STREAMING, + new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Retrieve), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[2], + ::grpc::internal::RpcMethod::CLIENT_STREAMING, + new ::grpc::internal::ClientStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMaxHitPoint), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[3], + ::grpc::internal::RpcMethod::BIDI_STREAMING, + new ::grpc::internal::BidiStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMinMaxHitPoints), this))); +} + +MonsterStorage::Service::~Service() { +} + +::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + + +} // namespace MyGame +} // namespace Example + diff --git a/third_party/flatbuffers/tests/monster_test_generated.grpc.fb.h b/third_party/flatbuffers/tests/monster_test_generated.grpc.fb.h new file mode 100644 index 00000000000..4d726e10d76 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_generated.grpc.fb.h @@ -0,0 +1,350 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test +#ifndef GRPC_monster_5ftest__INCLUDED +#define GRPC_monster_5ftest__INCLUDED + +#include "monster_test_generated.h" +#include "flatbuffers/grpc.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class Channel; +class ServerCompletionQueue; +class ServerContext; +} // namespace grpc + +namespace MyGame { +namespace Example { + +class MonsterStorage final { + public: + static constexpr char const* service_full_name() { + return "MyGame.Example.MonsterStorage"; + } + class StubInterface { + public: + virtual ~StubInterface() {} + virtual ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + private: + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReader< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientWriter< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override; + const ::grpc::internal::RpcMethod rpcmethod_Store_; + const ::grpc::internal::RpcMethod rpcmethod_Retrieve_; + const ::grpc::internal::RpcMethod rpcmethod_GetMaxHitPoint_; + const ::grpc::internal::RpcMethod rpcmethod_GetMinMaxHitPoints_; + }; + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class Service : public ::grpc::Service { + public: + Service(); + virtual ~Service(); + virtual ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, flatbuffers::grpc::Message* response); + virtual ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, ::grpc::ServerWriter< flatbuffers::grpc::Message>* writer); + virtual ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message>* reader, flatbuffers::grpc::Message* response); + virtual ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream); + }; + template + class WithAsyncMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Store() { + ::grpc::Service::MarkMethodAsync(0); + } + ~WithAsyncMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestStore(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncResponseWriter< flatbuffers::grpc::Message>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Retrieve() { + ::grpc::Service::MarkMethodAsync(1); + } + ~WithAsyncMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestRetrieve(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncWriter< flatbuffers::grpc::Message>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncServerStreaming(1, context, request, writer, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodAsync(2); + } + ~WithAsyncMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* response) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* reader, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncClientStreaming(2, context, reader, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodAsync(3); + } + ~WithAsyncMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(3, context, stream, new_call_cq, notification_cq, tag); + } + }; + typedef WithAsyncMethod_Store< WithAsyncMethod_Retrieve< WithAsyncMethod_GetMaxHitPoint< WithAsyncMethod_GetMinMaxHitPoints< Service > > > > AsyncService; + template + class WithGenericMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Store() { + ::grpc::Service::MarkMethodGeneric(0); + } + ~WithGenericMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Retrieve() { + ::grpc::Service::MarkMethodGeneric(1); + } + ~WithGenericMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodGeneric(2); + } + ~WithGenericMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodGeneric(3); + } + ~WithGenericMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithStreamedUnaryMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithStreamedUnaryMethod_Store() { + ::grpc::Service::MarkMethodStreamed(0, + new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithStreamedUnaryMethod_Store::StreamedStore, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedStore(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_unary_streamer) = 0; + }; + typedef WithStreamedUnaryMethod_Store< Service > StreamedUnaryService; + template + class WithSplitStreamingMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) { } + public: + WithSplitStreamingMethod_Retrieve() { + ::grpc::Service::MarkMethodStreamed(1, + new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithSplitStreamingMethod_Retrieve::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithSplitStreamingMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with split streamed + virtual ::grpc::Status StreamedRetrieve(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_split_streamer) = 0; + }; + typedef WithSplitStreamingMethod_Retrieve< Service > SplitStreamedService; + typedef WithStreamedUnaryMethod_Store< WithSplitStreamingMethod_Retrieve< Service > > StreamedService; +}; + +} // namespace Example +} // namespace MyGame + + +#endif // GRPC_monster_5ftest__INCLUDED diff --git a/third_party/flatbuffers/tests/monster_test_generated.h b/third_party/flatbuffers/tests/monster_test_generated.h new file mode 100644 index 00000000000..df6367e1314 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_generated.h @@ -0,0 +1,4248 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ +#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/flex_flat_util.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +// For access to the binary schema that produced this file. +#include "monster_test_bfbs_generated.h" + +namespace MyGame { + +struct InParentNamespace; +struct InParentNamespaceBuilder; +struct InParentNamespaceT; + +namespace Example2 { + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +} // namespace Example2 + +namespace Example { + +struct Test; + +struct TestSimpleTableWithEnum; +struct TestSimpleTableWithEnumBuilder; +struct TestSimpleTableWithEnumT; + +struct Vec3; + +struct Ability; + +struct StructOfStructs; + +struct StructOfStructsOfStructs; + +struct Stat; +struct StatBuilder; +struct StatT; + +struct Referrable; +struct ReferrableBuilder; +struct ReferrableT; + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +struct TypeAliases; +struct TypeAliasesBuilder; +struct TypeAliasesT; + +} // namespace Example + +bool operator==(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +namespace Example2 { + +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +} // namespace Example2 + +namespace Example { + +bool operator==(const Test &lhs, const Test &rhs); +bool operator!=(const Test &lhs, const Test &rhs); +bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator==(const Vec3 &lhs, const Vec3 &rhs); +bool operator!=(const Vec3 &lhs, const Vec3 &rhs); +bool operator==(const Ability &lhs, const Ability &rhs); +bool operator!=(const Ability &lhs, const Ability &rhs); +bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator==(const StatT &lhs, const StatT &rhs); +bool operator!=(const StatT &lhs, const StatT &rhs); +bool operator==(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs); +bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs); + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable(); + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable(); + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable(); + +inline const ::flatbuffers::TypeTable *Vec3TypeTable(); + +inline const ::flatbuffers::TypeTable *AbilityTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StatTypeTable(); + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable(); + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable(); + +/// Composite components of Monster color. +enum Color : uint8_t { + Color_Red = 1, + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Color_Green = 2, + /// \brief color Blue (1u << 3) + Color_Blue = 8, + Color_NONE = 0, + Color_ANY = 11 +}; + +inline const Color (&EnumValuesColor())[3] { + static const Color values[] = { + Color_Red, + Color_Green, + Color_Blue + }; + return values; +} + +inline const char * const *EnumNamesColor() { + static const char * const names[9] = { + "Red", + "Green", + "", + "", + "", + "", + "", + "Blue", + nullptr + }; + return names; +} + +inline const char *EnumNameColor(Color e) { + if (::flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return ""; + const size_t index = static_cast(e) - static_cast(Color_Red); + return EnumNamesColor()[index]; +} + +enum Race : int8_t { + Race_None = -1, + Race_Human = 0, + Race_Dwarf = 1, + Race_Elf = 2, + Race_MIN = Race_None, + Race_MAX = Race_Elf +}; + +inline const Race (&EnumValuesRace())[4] { + static const Race values[] = { + Race_None, + Race_Human, + Race_Dwarf, + Race_Elf + }; + return values; +} + +inline const char * const *EnumNamesRace() { + static const char * const names[5] = { + "None", + "Human", + "Dwarf", + "Elf", + nullptr + }; + return names; +} + +inline const char *EnumNameRace(Race e) { + if (::flatbuffers::IsOutRange(e, Race_None, Race_Elf)) return ""; + const size_t index = static_cast(e) - static_cast(Race_None); + return EnumNamesRace()[index]; +} + +enum LongEnum : uint64_t { + LongEnum_LongOne = 2ULL, + LongEnum_LongTwo = 4ULL, + LongEnum_LongBig = 1099511627776ULL, + LongEnum_NONE = 0, + LongEnum_ANY = 1099511627782ULL +}; + +inline const LongEnum (&EnumValuesLongEnum())[3] { + static const LongEnum values[] = { + LongEnum_LongOne, + LongEnum_LongTwo, + LongEnum_LongBig + }; + return values; +} + +inline const char *EnumNameLongEnum(LongEnum e) { + switch (e) { + case LongEnum_LongOne: return "LongOne"; + case LongEnum_LongTwo: return "LongTwo"; + case LongEnum_LongBig: return "LongBig"; + default: return ""; + } +} + +enum Any : uint8_t { + Any_NONE = 0, + Any_Monster = 1, + Any_TestSimpleTableWithEnum = 2, + Any_MyGame_Example2_Monster = 3, + Any_MIN = Any_NONE, + Any_MAX = Any_MyGame_Example2_Monster +}; + +inline const Any (&EnumValuesAny())[4] { + static const Any values[] = { + Any_NONE, + Any_Monster, + Any_TestSimpleTableWithEnum, + Any_MyGame_Example2_Monster + }; + return values; +} + +inline const char * const *EnumNamesAny() { + static const char * const names[5] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster", + nullptr + }; + return names; +} + +inline const char *EnumNameAny(Any e) { + if (::flatbuffers::IsOutRange(e, Any_NONE, Any_MyGame_Example2_Monster)) return ""; + const size_t index = static_cast(e); + return EnumNamesAny()[index]; +} + +template struct AnyTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +template struct AnyUnionTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +struct AnyUnion { + Any type; + void *value; + + AnyUnion() : type(Any_NONE), value(nullptr) {} + AnyUnion(AnyUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Any_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUnion(const AnyUnion &); + AnyUnion &operator=(const AnyUnion &u) + { AnyUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUnion &operator=(AnyUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUnionTraits::enum_value; + if (type != Any_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsMonster() { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsMonster() const { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() const { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() const { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUnion &lhs, const AnyUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_TestSimpleTableWithEnum: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_MyGame_Example2_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUnion &lhs, const AnyUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type); +bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyUniqueAliases : uint8_t { + AnyUniqueAliases_NONE = 0, + AnyUniqueAliases_M = 1, + AnyUniqueAliases_TS = 2, + AnyUniqueAliases_M2 = 3, + AnyUniqueAliases_MIN = AnyUniqueAliases_NONE, + AnyUniqueAliases_MAX = AnyUniqueAliases_M2 +}; + +inline const AnyUniqueAliases (&EnumValuesAnyUniqueAliases())[4] { + static const AnyUniqueAliases values[] = { + AnyUniqueAliases_NONE, + AnyUniqueAliases_M, + AnyUniqueAliases_TS, + AnyUniqueAliases_M2 + }; + return values; +} + +inline const char * const *EnumNamesAnyUniqueAliases() { + static const char * const names[5] = { + "NONE", + "M", + "TS", + "M2", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyUniqueAliases(AnyUniqueAliases e) { + if (::flatbuffers::IsOutRange(e, AnyUniqueAliases_NONE, AnyUniqueAliases_M2)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyUniqueAliases()[index]; +} + +template struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +template struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +struct AnyUniqueAliasesUnion { + AnyUniqueAliases type; + void *value; + + AnyUniqueAliasesUnion() : type(AnyUniqueAliases_NONE), value(nullptr) {} + AnyUniqueAliasesUnion(AnyUniqueAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyUniqueAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &); + AnyUniqueAliasesUnion &operator=(const AnyUniqueAliasesUnion &u) + { AnyUniqueAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUniqueAliasesUnion &operator=(AnyUniqueAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUniqueAliasesUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUniqueAliasesUnionTraits::enum_value; + if (type != AnyUniqueAliases_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM() { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM() const { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTS() { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTS() const { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsM2() { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsM2() const { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_TS: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type); +bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyAmbiguousAliases : uint8_t { + AnyAmbiguousAliases_NONE = 0, + AnyAmbiguousAliases_M1 = 1, + AnyAmbiguousAliases_M2 = 2, + AnyAmbiguousAliases_M3 = 3, + AnyAmbiguousAliases_MIN = AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_MAX = AnyAmbiguousAliases_M3 +}; + +inline const AnyAmbiguousAliases (&EnumValuesAnyAmbiguousAliases())[4] { + static const AnyAmbiguousAliases values[] = { + AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_M1, + AnyAmbiguousAliases_M2, + AnyAmbiguousAliases_M3 + }; + return values; +} + +inline const char * const *EnumNamesAnyAmbiguousAliases() { + static const char * const names[5] = { + "NONE", + "M1", + "M2", + "M3", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyAmbiguousAliases(AnyAmbiguousAliases e) { + if (::flatbuffers::IsOutRange(e, AnyAmbiguousAliases_NONE, AnyAmbiguousAliases_M3)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyAmbiguousAliases()[index]; +} + +struct AnyAmbiguousAliasesUnion { + AnyAmbiguousAliases type; + void *value; + + AnyAmbiguousAliasesUnion() : type(AnyAmbiguousAliases_NONE), value(nullptr) {} + AnyAmbiguousAliasesUnion(AnyAmbiguousAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyAmbiguousAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &); + AnyAmbiguousAliasesUnion &operator=(const AnyAmbiguousAliasesUnion &u) + { AnyAmbiguousAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyAmbiguousAliasesUnion &operator=(AnyAmbiguousAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyAmbiguousAliasesUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM1() { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM1() const { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM2() { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM2() const { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM3() { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM3() const { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M3: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type); +bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS { + private: + int16_t a_; + int8_t b_; + int8_t padding0__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestTypeTable(); + } + Test() + : a_(0), + b_(0), + padding0__(0) { + (void)padding0__; + } + Test(int16_t _a, int8_t _b) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0) { + (void)padding0__; + } + int16_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int16_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + int8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(int8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Test, 4); + +inline bool operator==(const Test &lhs, const Test &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Test &lhs, const Test &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Vec3 FLATBUFFERS_FINAL_CLASS { + private: + float x_; + float y_; + float z_; + int32_t padding0__; + double test1_; + uint8_t test2_; + int8_t padding1__; + MyGame::Example::Test test3_; + int16_t padding2__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vec3TypeTable(); + } + Vec3() + : x_(0), + y_(0), + z_(0), + padding0__(0), + test1_(0), + test2_(0), + padding1__(0), + test3_(), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + Vec3(float _x, float _y, float _z, double _test1, MyGame::Example::Color _test2, const MyGame::Example::Test &_test3) + : x_(::flatbuffers::EndianScalar(_x)), + y_(::flatbuffers::EndianScalar(_y)), + z_(::flatbuffers::EndianScalar(_z)), + padding0__(0), + test1_(::flatbuffers::EndianScalar(_test1)), + test2_(::flatbuffers::EndianScalar(static_cast(_test2))), + padding1__(0), + test3_(_test3), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + float x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(float _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } + float y() const { + return ::flatbuffers::EndianScalar(y_); + } + void mutate_y(float _y) { + ::flatbuffers::WriteScalar(&y_, _y); + } + float z() const { + return ::flatbuffers::EndianScalar(z_); + } + void mutate_z(float _z) { + ::flatbuffers::WriteScalar(&z_, _z); + } + double test1() const { + return ::flatbuffers::EndianScalar(test1_); + } + void mutate_test1(double _test1) { + ::flatbuffers::WriteScalar(&test1_, _test1); + } + MyGame::Example::Color test2() const { + return static_cast(::flatbuffers::EndianScalar(test2_)); + } + void mutate_test2(MyGame::Example::Color _test2) { + ::flatbuffers::WriteScalar(&test2_, static_cast(_test2)); + } + const MyGame::Example::Test &test3() const { + return test3_; + } + MyGame::Example::Test &mutable_test3() { + return test3_; + } +}; +FLATBUFFERS_STRUCT_END(Vec3, 32); + +inline bool operator==(const Vec3 &lhs, const Vec3 &rhs) { + return + (lhs.x() == rhs.x()) && + (lhs.y() == rhs.y()) && + (lhs.z() == rhs.z()) && + (lhs.test1() == rhs.test1()) && + (lhs.test2() == rhs.test2()) && + (lhs.test3() == rhs.test3()); +} + +inline bool operator!=(const Vec3 &lhs, const Vec3 &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Ability FLATBUFFERS_FINAL_CLASS { + private: + uint32_t id_; + uint32_t distance_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AbilityTypeTable(); + } + Ability() + : id_(0), + distance_(0) { + } + Ability(uint32_t _id, uint32_t _distance) + : id_(::flatbuffers::EndianScalar(_id)), + distance_(::flatbuffers::EndianScalar(_distance)) { + } + uint32_t id() const { + return ::flatbuffers::EndianScalar(id_); + } + void mutate_id(uint32_t _id) { + ::flatbuffers::WriteScalar(&id_, _id); + } + bool KeyCompareLessThan(const Ability * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint32_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + uint32_t distance() const { + return ::flatbuffers::EndianScalar(distance_); + } + void mutate_distance(uint32_t _distance) { + ::flatbuffers::WriteScalar(&distance_, _distance); + } +}; +FLATBUFFERS_STRUCT_END(Ability, 8); + +inline bool operator==(const Ability &lhs, const Ability &rhs) { + return + (lhs.id() == rhs.id()) && + (lhs.distance() == rhs.distance()); +} + +inline bool operator!=(const Ability &lhs, const Ability &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::Ability a_; + MyGame::Example::Test b_; + MyGame::Example::Ability c_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsTypeTable(); + } + StructOfStructs() + : a_(), + b_(), + c_() { + } + StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c) + : a_(_a), + b_(_b), + c_(_c) { + } + const MyGame::Example::Ability &a() const { + return a_; + } + MyGame::Example::Ability &mutable_a() { + return a_; + } + const MyGame::Example::Test &b() const { + return b_; + } + MyGame::Example::Test &mutable_b() { + return b_; + } + const MyGame::Example::Ability &c() const { + return c_; + } + MyGame::Example::Ability &mutable_c() { + return c_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructs, 20); + +inline bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()) && + (lhs.c() == rhs.c()); +} + +inline bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructsOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::StructOfStructs a_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsOfStructsTypeTable(); + } + StructOfStructsOfStructs() + : a_() { + } + StructOfStructsOfStructs(const MyGame::Example::StructOfStructs &_a) + : a_(_a) { + } + const MyGame::Example::StructOfStructs &a() const { + return a_; + } + MyGame::Example::StructOfStructs &mutable_a() { + return a_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructsOfStructs, 20); + +inline bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return + (lhs.a() == rhs.a()); +} + +inline bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return !(lhs == rhs); +} + + +} // namespace Example + +struct InParentNamespaceT : public ::flatbuffers::NativeTable { + typedef InParentNamespace TableType; +}; + +struct InParentNamespace FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef InParentNamespaceT NativeTableType; + typedef InParentNamespaceBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return InParentNamespaceTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + InParentNamespaceT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct InParentNamespaceBuilder { + typedef InParentNamespace Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit InParentNamespaceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateInParentNamespace( + ::flatbuffers::FlatBufferBuilder &_fbb) { + InParentNamespaceBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +namespace Example2 { + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; +}; + +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb) { + MonsterBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example2 + +namespace Example { + +struct TestSimpleTableWithEnumT : public ::flatbuffers::NativeTable { + typedef TestSimpleTableWithEnum TableType; + MyGame::Example::Color color = MyGame::Example::Color_Green; +}; + +struct TestSimpleTableWithEnum FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TestSimpleTableWithEnumT NativeTableType; + typedef TestSimpleTableWithEnumBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestSimpleTableWithEnumTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_COLOR = 4 + }; + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 2)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(2)) { + return SetField(VT_COLOR, static_cast(_color), 2); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_COLOR, 1) && + verifier.EndTable(); + } + TestSimpleTableWithEnumT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TestSimpleTableWithEnumBuilder { + typedef TestSimpleTableWithEnum Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(TestSimpleTableWithEnum::VT_COLOR, static_cast(color), 2); + } + explicit TestSimpleTableWithEnumBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum( + ::flatbuffers::FlatBufferBuilder &_fbb, + MyGame::Example::Color color = MyGame::Example::Color_Green) { + TestSimpleTableWithEnumBuilder builder_(_fbb); + builder_.add_color(color); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct StatT : public ::flatbuffers::NativeTable { + typedef Stat TableType; + std::string id{}; + int64_t val = 0; + uint16_t count = 0; +}; + +struct Stat FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StatT NativeTableType; + typedef StatBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StatTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4, + VT_VAL = 6, + VT_COUNT = 8 + }; + const ::flatbuffers::String *id() const { + return GetPointer(VT_ID); + } + ::flatbuffers::String *mutable_id() { + return GetPointer<::flatbuffers::String *>(VT_ID); + } + int64_t val() const { + return GetField(VT_VAL, 0); + } + bool mutate_val(int64_t _val = 0) { + return SetField(VT_VAL, _val, 0); + } + uint16_t count() const { + return GetField(VT_COUNT, 0); + } + bool mutate_count(uint16_t _count = 0) { + return SetField(VT_COUNT, _count, 0); + } + bool KeyCompareLessThan(const Stat * const o) const { + return count() < o->count(); + } + int KeyCompareWithValue(uint16_t _count) const { + return static_cast(count() > _count) - static_cast(count() < _count); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ID) && + verifier.VerifyString(id()) && + VerifyField(verifier, VT_VAL, 8) && + VerifyField(verifier, VT_COUNT, 2) && + verifier.EndTable(); + } + StatT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct StatBuilder { + typedef Stat Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(::flatbuffers::Offset<::flatbuffers::String> id) { + fbb_.AddOffset(Stat::VT_ID, id); + } + void add_val(int64_t val) { + fbb_.AddElement(Stat::VT_VAL, val, 0); + } + void add_count(uint16_t count) { + fbb_.AddElement(Stat::VT_COUNT, count, 0); + } + explicit StatBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStat( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> id = 0, + int64_t val = 0, + uint16_t count = 0) { + StatBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_id(id); + builder_.add_count(count); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStatDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *id = nullptr, + int64_t val = 0, + uint16_t count = 0) { + auto id__ = id ? _fbb.CreateString(id) : 0; + return MyGame::Example::CreateStat( + _fbb, + id__, + val, + count); +} + +::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct ReferrableT : public ::flatbuffers::NativeTable { + typedef Referrable TableType; + uint64_t id = 0; +}; + +struct Referrable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ReferrableT NativeTableType; + typedef ReferrableBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ReferrableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4 + }; + uint64_t id() const { + return GetField(VT_ID, 0); + } + bool mutate_id(uint64_t _id = 0) { + return SetField(VT_ID, _id, 0); + } + bool KeyCompareLessThan(const Referrable * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint64_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_ID, 8) && + verifier.EndTable(); + } + ReferrableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ReferrableBuilder { + typedef Referrable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(uint64_t id) { + fbb_.AddElement(Referrable::VT_ID, id, 0); + } + explicit ReferrableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateReferrable( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint64_t id = 0) { + ReferrableBuilder builder_(_fbb); + builder_.add_id(id); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; + std::unique_ptr pos{}; + int16_t mana = 150; + int16_t hp = 100; + std::string name{}; + std::vector inventory{}; + MyGame::Example::Color color = MyGame::Example::Color_Blue; + MyGame::Example::AnyUnion test{}; + std::vector test4{}; + std::vector testarrayofstring{}; + std::vector> testarrayoftables{}; + std::unique_ptr enemy{}; + std::vector testnestedflatbuffer{}; + std::unique_ptr testempty{}; + bool testbool = false; + int32_t testhashs32_fnv1 = 0; + uint32_t testhashu32_fnv1 = 0; + int64_t testhashs64_fnv1 = 0; + uint64_t testhashu64_fnv1 = 0; + int32_t testhashs32_fnv1a = 0; + Stat *testhashu32_fnv1a = nullptr; + int64_t testhashs64_fnv1a = 0; + uint64_t testhashu64_fnv1a = 0; + std::vector testarrayofbools{}; + float testf = 3.14159f; + float testf2 = 3.0f; + float testf3 = 0.0f; + std::vector testarrayofstring2{}; + std::vector testarrayofsortedstruct{}; + std::vector flex{}; + std::vector test5{}; + std::vector vector_of_longs{}; + std::vector vector_of_doubles{}; + std::unique_ptr parent_namespace_test{}; + std::vector> vector_of_referrables{}; + ReferrableT *single_weak_reference = nullptr; + std::vector vector_of_weak_references{}; + std::vector> vector_of_strong_referrables{}; + ReferrableT *co_owning_reference = nullptr; + std::vector> vector_of_co_owning_references{}; + ReferrableT *non_owning_reference = nullptr; + std::vector vector_of_non_owning_references{}; + MyGame::Example::AnyUniqueAliasesUnion any_unique{}; + MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous{}; + std::vector vector_of_enums{}; + MyGame::Example::Race signed_enum = MyGame::Example::Race_None; + std::vector testrequirednestedflatbuffer{}; + std::vector> scalar_key_sorted_tables{}; + MyGame::Example::Test native_inline{}; + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0); + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne; + float nan_default = std::numeric_limits::quiet_NaN(); + float inf_default = std::numeric_limits::infinity(); + float positive_inf_default = std::numeric_limits::infinity(); + float infinity_default = std::numeric_limits::infinity(); + float positive_infinity_default = std::numeric_limits::infinity(); + float negative_inf_default = -std::numeric_limits::infinity(); + float negative_infinity_default = -std::numeric_limits::infinity(); + double double_inf_default = std::numeric_limits::infinity(); + MonsterT() = default; + MonsterT(const MonsterT &o); + MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default; + MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT; +}; + +/// an example documentation comment: "monster object" +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_POS = 4, + VT_MANA = 6, + VT_HP = 8, + VT_NAME = 10, + VT_INVENTORY = 14, + VT_COLOR = 16, + VT_TEST_TYPE = 18, + VT_TEST = 20, + VT_TEST4 = 22, + VT_TESTARRAYOFSTRING = 24, + VT_TESTARRAYOFTABLES = 26, + VT_ENEMY = 28, + VT_TESTNESTEDFLATBUFFER = 30, + VT_TESTEMPTY = 32, + VT_TESTBOOL = 34, + VT_TESTHASHS32_FNV1 = 36, + VT_TESTHASHU32_FNV1 = 38, + VT_TESTHASHS64_FNV1 = 40, + VT_TESTHASHU64_FNV1 = 42, + VT_TESTHASHS32_FNV1A = 44, + VT_TESTHASHU32_FNV1A = 46, + VT_TESTHASHS64_FNV1A = 48, + VT_TESTHASHU64_FNV1A = 50, + VT_TESTARRAYOFBOOLS = 52, + VT_TESTF = 54, + VT_TESTF2 = 56, + VT_TESTF3 = 58, + VT_TESTARRAYOFSTRING2 = 60, + VT_TESTARRAYOFSORTEDSTRUCT = 62, + VT_FLEX = 64, + VT_TEST5 = 66, + VT_VECTOR_OF_LONGS = 68, + VT_VECTOR_OF_DOUBLES = 70, + VT_PARENT_NAMESPACE_TEST = 72, + VT_VECTOR_OF_REFERRABLES = 74, + VT_SINGLE_WEAK_REFERENCE = 76, + VT_VECTOR_OF_WEAK_REFERENCES = 78, + VT_VECTOR_OF_STRONG_REFERRABLES = 80, + VT_CO_OWNING_REFERENCE = 82, + VT_VECTOR_OF_CO_OWNING_REFERENCES = 84, + VT_NON_OWNING_REFERENCE = 86, + VT_VECTOR_OF_NON_OWNING_REFERENCES = 88, + VT_ANY_UNIQUE_TYPE = 90, + VT_ANY_UNIQUE = 92, + VT_ANY_AMBIGUOUS_TYPE = 94, + VT_ANY_AMBIGUOUS = 96, + VT_VECTOR_OF_ENUMS = 98, + VT_SIGNED_ENUM = 100, + VT_TESTREQUIREDNESTEDFLATBUFFER = 102, + VT_SCALAR_KEY_SORTED_TABLES = 104, + VT_NATIVE_INLINE = 106, + VT_LONG_ENUM_NON_ENUM_DEFAULT = 108, + VT_LONG_ENUM_NORMAL_DEFAULT = 110, + VT_NAN_DEFAULT = 112, + VT_INF_DEFAULT = 114, + VT_POSITIVE_INF_DEFAULT = 116, + VT_INFINITY_DEFAULT = 118, + VT_POSITIVE_INFINITY_DEFAULT = 120, + VT_NEGATIVE_INF_DEFAULT = 122, + VT_NEGATIVE_INFINITY_DEFAULT = 124, + VT_DOUBLE_INF_DEFAULT = 126 + }; + const MyGame::Example::Vec3 *pos() const { + return GetStruct(VT_POS); + } + MyGame::Example::Vec3 *mutable_pos() { + return GetStruct(VT_POS); + } + int16_t mana() const { + return GetField(VT_MANA, 150); + } + bool mutate_mana(int16_t _mana = 150) { + return SetField(VT_MANA, _mana, 150); + } + int16_t hp() const { + return GetField(VT_HP, 100); + } + bool mutate_hp(int16_t _hp = 100) { + return SetField(VT_HP, _hp, 100); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + bool KeyCompareLessThan(const Monster * const o) const { + return *name() < *o->name(); + } + int KeyCompareWithValue(const char *_name) const { + return strcmp(name()->c_str(), _name); + } + template + int KeyCompareWithValue(const StringType& _name) const { + if (name()->c_str() < _name) return -1; + if (_name < name()->c_str()) return 1; + return 0; + } + const ::flatbuffers::Vector *inventory() const { + return GetPointer *>(VT_INVENTORY); + } + ::flatbuffers::Vector *mutable_inventory() { + return GetPointer<::flatbuffers::Vector *>(VT_INVENTORY); + } + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 8)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(8)) { + return SetField(VT_COLOR, static_cast(_color), 8); + } + MyGame::Example::Any test_type() const { + return static_cast(GetField(VT_TEST_TYPE, 0)); + } + const void *test() const { + return GetPointer(VT_TEST); + } + template const T *test_as() const; + const MyGame::Example::Monster *test_as_Monster() const { + return test_type() == MyGame::Example::Any_Monster ? static_cast(test()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *test_as_TestSimpleTableWithEnum() const { + return test_type() == MyGame::Example::Any_TestSimpleTableWithEnum ? static_cast(test()) : nullptr; + } + const MyGame::Example2::Monster *test_as_MyGame_Example2_Monster() const { + return test_type() == MyGame::Example::Any_MyGame_Example2_Monster ? static_cast(test()) : nullptr; + } + void *mutable_test() { + return GetPointer(VT_TEST); + } + const ::flatbuffers::Vector *test4() const { + return GetPointer *>(VT_TEST4); + } + ::flatbuffers::Vector *mutable_test4() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST4); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING); + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + const ::flatbuffers::Vector<::flatbuffers::Offset> *testarrayoftables() const { + return GetPointer> *>(VT_TESTARRAYOFTABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_testarrayoftables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_TESTARRAYOFTABLES); + } + const MyGame::Example::Monster *enemy() const { + return GetPointer(VT_ENEMY); + } + MyGame::Example::Monster *mutable_enemy() { + return GetPointer(VT_ENEMY); + } + const ::flatbuffers::Vector *testnestedflatbuffer() const { + return GetPointer *>(VT_TESTNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testnestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testnestedflatbuffer_nested_root() const { + const auto _f = testnestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const MyGame::Example::Stat *testempty() const { + return GetPointer(VT_TESTEMPTY); + } + MyGame::Example::Stat *mutable_testempty() { + return GetPointer(VT_TESTEMPTY); + } + bool testbool() const { + return GetField(VT_TESTBOOL, 0) != 0; + } + bool mutate_testbool(bool _testbool = 0) { + return SetField(VT_TESTBOOL, static_cast(_testbool), 0); + } + int32_t testhashs32_fnv1() const { + return GetField(VT_TESTHASHS32_FNV1, 0); + } + bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) { + return SetField(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0); + } + uint32_t testhashu32_fnv1() const { + return GetField(VT_TESTHASHU32_FNV1, 0); + } + bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) { + return SetField(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0); + } + int64_t testhashs64_fnv1() const { + return GetField(VT_TESTHASHS64_FNV1, 0); + } + bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) { + return SetField(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0); + } + uint64_t testhashu64_fnv1() const { + return GetField(VT_TESTHASHU64_FNV1, 0); + } + bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) { + return SetField(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0); + } + int32_t testhashs32_fnv1a() const { + return GetField(VT_TESTHASHS32_FNV1A, 0); + } + bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) { + return SetField(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0); + } + uint32_t testhashu32_fnv1a() const { + return GetField(VT_TESTHASHU32_FNV1A, 0); + } + bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) { + return SetField(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0); + } + int64_t testhashs64_fnv1a() const { + return GetField(VT_TESTHASHS64_FNV1A, 0); + } + bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) { + return SetField(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0); + } + uint64_t testhashu64_fnv1a() const { + return GetField(VT_TESTHASHU64_FNV1A, 0); + } + bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) { + return SetField(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0); + } + const ::flatbuffers::Vector *testarrayofbools() const { + return GetPointer *>(VT_TESTARRAYOFBOOLS); + } + ::flatbuffers::Vector *mutable_testarrayofbools() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFBOOLS); + } + float testf() const { + return GetField(VT_TESTF, 3.14159f); + } + bool mutate_testf(float _testf = 3.14159f) { + return SetField(VT_TESTF, _testf, 3.14159f); + } + float testf2() const { + return GetField(VT_TESTF2, 3.0f); + } + bool mutate_testf2(float _testf2 = 3.0f) { + return SetField(VT_TESTF2, _testf2, 3.0f); + } + float testf3() const { + return GetField(VT_TESTF3, 0.0f); + } + bool mutate_testf3(float _testf3 = 0.0f) { + return SetField(VT_TESTF3, _testf3, 0.0f); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING2); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring2() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING2); + } + const ::flatbuffers::Vector *testarrayofsortedstruct() const { + return GetPointer *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + ::flatbuffers::Vector *mutable_testarrayofsortedstruct() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + const ::flatbuffers::Vector *flex() const { + return GetPointer *>(VT_FLEX); + } + ::flatbuffers::Vector *mutable_flex() { + return GetPointer<::flatbuffers::Vector *>(VT_FLEX); + } + flexbuffers::Reference flex_flexbuffer_root() const { + const auto _f = flex(); + return _f ? flexbuffers::GetRoot(_f->Data(), _f->size()) + : flexbuffers::Reference(); + } + const ::flatbuffers::Vector *test5() const { + return GetPointer *>(VT_TEST5); + } + ::flatbuffers::Vector *mutable_test5() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST5); + } + const ::flatbuffers::Vector *vector_of_longs() const { + return GetPointer *>(VT_VECTOR_OF_LONGS); + } + ::flatbuffers::Vector *mutable_vector_of_longs() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_LONGS); + } + const ::flatbuffers::Vector *vector_of_doubles() const { + return GetPointer *>(VT_VECTOR_OF_DOUBLES); + } + ::flatbuffers::Vector *mutable_vector_of_doubles() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_DOUBLES); + } + const MyGame::InParentNamespace *parent_namespace_test() const { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + MyGame::InParentNamespace *mutable_parent_namespace_test() { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_REFERRABLES); + } + uint64_t single_weak_reference() const { + return GetField(VT_SINGLE_WEAK_REFERENCE, 0); + } + bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) { + return SetField(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0); + } + const ::flatbuffers::Vector *vector_of_weak_references() const { + return GetPointer *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_weak_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_strong_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_strong_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + uint64_t co_owning_reference() const { + return GetField(VT_CO_OWNING_REFERENCE, 0); + } + bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) { + return SetField(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_co_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_co_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + uint64_t non_owning_reference() const { + return GetField(VT_NON_OWNING_REFERENCE, 0); + } + bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) { + return SetField(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_non_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_non_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + MyGame::Example::AnyUniqueAliases any_unique_type() const { + return static_cast(GetField(VT_ANY_UNIQUE_TYPE, 0)); + } + const void *any_unique() const { + return GetPointer(VT_ANY_UNIQUE); + } + template const T *any_unique_as() const; + const MyGame::Example::Monster *any_unique_as_M() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *any_unique_as_TS() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_TS ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example2::Monster *any_unique_as_M2() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M2 ? static_cast(any_unique()) : nullptr; + } + void *mutable_any_unique() { + return GetPointer(VT_ANY_UNIQUE); + } + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type() const { + return static_cast(GetField(VT_ANY_AMBIGUOUS_TYPE, 0)); + } + const void *any_ambiguous() const { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const MyGame::Example::Monster *any_ambiguous_as_M1() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M1 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M2() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M2 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M3() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M3 ? static_cast(any_ambiguous()) : nullptr; + } + void *mutable_any_ambiguous() { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const ::flatbuffers::Vector *vector_of_enums() const { + return GetPointer *>(VT_VECTOR_OF_ENUMS); + } + ::flatbuffers::Vector *mutable_vector_of_enums() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_ENUMS); + } + MyGame::Example::Race signed_enum() const { + return static_cast(GetField(VT_SIGNED_ENUM, -1)); + } + bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast(-1)) { + return SetField(VT_SIGNED_ENUM, static_cast(_signed_enum), -1); + } + const ::flatbuffers::Vector *testrequirednestedflatbuffer() const { + return GetPointer *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testrequirednestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const { + const auto _f = testrequirednestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *scalar_key_sorted_tables() const { + return GetPointer> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_scalar_key_sorted_tables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + const MyGame::Example::Test *native_inline() const { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::Test *mutable_native_inline() { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::LongEnum long_enum_non_enum_default() const { + return static_cast(GetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0)); + } + bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast(0)) { + return SetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(_long_enum_non_enum_default), 0); + } + MyGame::Example::LongEnum long_enum_normal_default() const { + return static_cast(GetField(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL)); + } + bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast(2ULL)) { + return SetField(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(_long_enum_normal_default), 2ULL); + } + float nan_default() const { + return GetField(VT_NAN_DEFAULT, std::numeric_limits::quiet_NaN()); + } + bool mutate_nan_default(float _nan_default = std::numeric_limits::quiet_NaN()) { + return SetField(VT_NAN_DEFAULT, _nan_default, std::numeric_limits::quiet_NaN()); + } + float inf_default() const { + return GetField(VT_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_inf_default(float _inf_default = std::numeric_limits::infinity()) { + return SetField(VT_INF_DEFAULT, _inf_default, std::numeric_limits::infinity()); + } + float positive_inf_default() const { + return GetField(VT_POSITIVE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_inf_default(float _positive_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INF_DEFAULT, _positive_inf_default, std::numeric_limits::infinity()); + } + float infinity_default() const { + return GetField(VT_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_infinity_default(float _infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_INFINITY_DEFAULT, _infinity_default, std::numeric_limits::infinity()); + } + float positive_infinity_default() const { + return GetField(VT_POSITIVE_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_infinity_default(float _positive_infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INFINITY_DEFAULT, _positive_infinity_default, std::numeric_limits::infinity()); + } + float negative_inf_default() const { + return GetField(VT_NEGATIVE_INF_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_inf_default(float _negative_inf_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INF_DEFAULT, _negative_inf_default, -std::numeric_limits::infinity()); + } + float negative_infinity_default() const { + return GetField(VT_NEGATIVE_INFINITY_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_infinity_default(float _negative_infinity_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INFINITY_DEFAULT, _negative_infinity_default, -std::numeric_limits::infinity()); + } + double double_inf_default() const { + return GetField(VT_DOUBLE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_double_inf_default(double _double_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_DOUBLE_INF_DEFAULT, _double_inf_default, std::numeric_limits::infinity()); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_POS, 8) && + VerifyField(verifier, VT_MANA, 2) && + VerifyField(verifier, VT_HP, 2) && + VerifyOffsetRequired(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_INVENTORY) && + verifier.VerifyVector(inventory()) && + VerifyField(verifier, VT_COLOR, 1) && + VerifyField(verifier, VT_TEST_TYPE, 1) && + VerifyOffset(verifier, VT_TEST) && + VerifyAny(verifier, test(), test_type()) && + VerifyOffset(verifier, VT_TEST4) && + verifier.VerifyVector(test4()) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING) && + verifier.VerifyVector(testarrayofstring()) && + verifier.VerifyVectorOfStrings(testarrayofstring()) && + VerifyOffset(verifier, VT_TESTARRAYOFTABLES) && + verifier.VerifyVector(testarrayoftables()) && + verifier.VerifyVectorOfTables(testarrayoftables()) && + VerifyOffset(verifier, VT_ENEMY) && + verifier.VerifyTable(enemy()) && + VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) && + verifier.VerifyVector(testnestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testnestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_TESTEMPTY) && + verifier.VerifyTable(testempty()) && + VerifyField(verifier, VT_TESTBOOL, 1) && + VerifyField(verifier, VT_TESTHASHS32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHS32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1A, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1A, 8) && + VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) && + verifier.VerifyVector(testarrayofbools()) && + VerifyField(verifier, VT_TESTF, 4) && + VerifyField(verifier, VT_TESTF2, 4) && + VerifyField(verifier, VT_TESTF3, 4) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) && + verifier.VerifyVector(testarrayofstring2()) && + verifier.VerifyVectorOfStrings(testarrayofstring2()) && + VerifyOffset(verifier, VT_TESTARRAYOFSORTEDSTRUCT) && + verifier.VerifyVector(testarrayofsortedstruct()) && + VerifyOffset(verifier, VT_FLEX) && + verifier.VerifyVector(flex()) && + flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) && + VerifyOffset(verifier, VT_TEST5) && + verifier.VerifyVector(test5()) && + VerifyOffset(verifier, VT_VECTOR_OF_LONGS) && + verifier.VerifyVector(vector_of_longs()) && + VerifyOffset(verifier, VT_VECTOR_OF_DOUBLES) && + verifier.VerifyVector(vector_of_doubles()) && + VerifyOffset(verifier, VT_PARENT_NAMESPACE_TEST) && + verifier.VerifyTable(parent_namespace_test()) && + VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) && + verifier.VerifyVector(vector_of_referrables()) && + verifier.VerifyVectorOfTables(vector_of_referrables()) && + VerifyField(verifier, VT_SINGLE_WEAK_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) && + verifier.VerifyVector(vector_of_weak_references()) && + VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) && + verifier.VerifyVector(vector_of_strong_referrables()) && + verifier.VerifyVectorOfTables(vector_of_strong_referrables()) && + VerifyField(verifier, VT_CO_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_co_owning_references()) && + VerifyField(verifier, VT_NON_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_non_owning_references()) && + VerifyField(verifier, VT_ANY_UNIQUE_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_UNIQUE) && + VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) && + VerifyField(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_AMBIGUOUS) && + VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) && + VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) && + verifier.VerifyVector(vector_of_enums()) && + VerifyField(verifier, VT_SIGNED_ENUM, 1) && + VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) && + verifier.VerifyVector(testrequirednestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testrequirednestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) && + verifier.VerifyVector(scalar_key_sorted_tables()) && + verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) && + VerifyField(verifier, VT_NATIVE_INLINE, 2) && + VerifyField(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) && + VerifyField(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) && + VerifyField(verifier, VT_NAN_DEFAULT, 4) && + VerifyField(verifier, VT_INF_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_DOUBLE_INF_DEFAULT, 8) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const MyGame::Example::Monster *Monster::test_as() const { + return test_as_Monster(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::test_as() const { + return test_as_TestSimpleTableWithEnum(); +} + +template<> inline const MyGame::Example2::Monster *Monster::test_as() const { + return test_as_MyGame_Example2_Monster(); +} + +template<> inline const MyGame::Example::Monster *Monster::any_unique_as() const { + return any_unique_as_M(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::any_unique_as() const { + return any_unique_as_TS(); +} + +template<> inline const MyGame::Example2::Monster *Monster::any_unique_as() const { + return any_unique_as_M2(); +} + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_pos(const MyGame::Example::Vec3 *pos) { + fbb_.AddStruct(Monster::VT_POS, pos); + } + void add_mana(int16_t mana) { + fbb_.AddElement(Monster::VT_MANA, mana, 150); + } + void add_hp(int16_t hp) { + fbb_.AddElement(Monster::VT_HP, hp, 100); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Monster::VT_NAME, name); + } + void add_inventory(::flatbuffers::Offset<::flatbuffers::Vector> inventory) { + fbb_.AddOffset(Monster::VT_INVENTORY, inventory); + } + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(Monster::VT_COLOR, static_cast(color), 8); + } + void add_test_type(MyGame::Example::Any test_type) { + fbb_.AddElement(Monster::VT_TEST_TYPE, static_cast(test_type), 0); + } + void add_test(::flatbuffers::Offset test) { + fbb_.AddOffset(Monster::VT_TEST, test); + } + void add_test4(::flatbuffers::Offset<::flatbuffers::Vector> test4) { + fbb_.AddOffset(Monster::VT_TEST4, test4); + } + void add_testarrayofstring(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + void add_testarrayoftables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + void add_enemy(::flatbuffers::Offset enemy) { + fbb_.AddOffset(Monster::VT_ENEMY, enemy); + } + void add_testnestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + void add_testempty(::flatbuffers::Offset testempty) { + fbb_.AddOffset(Monster::VT_TESTEMPTY, testempty); + } + void add_testbool(bool testbool) { + fbb_.AddElement(Monster::VT_TESTBOOL, static_cast(testbool), 0); + } + void add_testhashs32_fnv1(int32_t testhashs32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + void add_testhashu32_fnv1(uint32_t testhashu32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + void add_testhashs64_fnv1(int64_t testhashs64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + void add_testhashu64_fnv1(uint64_t testhashu64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + void add_testhashs32_fnv1a(int32_t testhashs32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + void add_testhashu32_fnv1a(uint32_t testhashu32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + void add_testhashs64_fnv1a(int64_t testhashs64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + void add_testhashu64_fnv1a(uint64_t testhashu64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + void add_testarrayofbools(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + void add_testf(float testf) { + fbb_.AddElement(Monster::VT_TESTF, testf, 3.14159f); + } + void add_testf2(float testf2) { + fbb_.AddElement(Monster::VT_TESTF2, testf2, 3.0f); + } + void add_testf3(float testf3) { + fbb_.AddElement(Monster::VT_TESTF3, testf3, 0.0f); + } + void add_testarrayofstring2(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + void add_testarrayofsortedstruct(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + void add_flex(::flatbuffers::Offset<::flatbuffers::Vector> flex) { + fbb_.AddOffset(Monster::VT_FLEX, flex); + } + void add_test5(::flatbuffers::Offset<::flatbuffers::Vector> test5) { + fbb_.AddOffset(Monster::VT_TEST5, test5); + } + void add_vector_of_longs(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + void add_vector_of_doubles(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + void add_parent_namespace_test(::flatbuffers::Offset parent_namespace_test) { + fbb_.AddOffset(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + void add_vector_of_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + void add_single_weak_reference(uint64_t single_weak_reference) { + fbb_.AddElement(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + void add_vector_of_weak_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + void add_vector_of_strong_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + void add_co_owning_reference(uint64_t co_owning_reference) { + fbb_.AddElement(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + void add_vector_of_co_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + void add_non_owning_reference(uint64_t non_owning_reference) { + fbb_.AddElement(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + void add_vector_of_non_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + void add_any_unique_type(MyGame::Example::AnyUniqueAliases any_unique_type) { + fbb_.AddElement(Monster::VT_ANY_UNIQUE_TYPE, static_cast(any_unique_type), 0); + } + void add_any_unique(::flatbuffers::Offset any_unique) { + fbb_.AddOffset(Monster::VT_ANY_UNIQUE, any_unique); + } + void add_any_ambiguous_type(MyGame::Example::AnyAmbiguousAliases any_ambiguous_type) { + fbb_.AddElement(Monster::VT_ANY_AMBIGUOUS_TYPE, static_cast(any_ambiguous_type), 0); + } + void add_any_ambiguous(::flatbuffers::Offset any_ambiguous) { + fbb_.AddOffset(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + void add_vector_of_enums(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + void add_signed_enum(MyGame::Example::Race signed_enum) { + fbb_.AddElement(Monster::VT_SIGNED_ENUM, static_cast(signed_enum), -1); + } + void add_testrequirednestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + void add_scalar_key_sorted_tables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables) { + fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + void add_native_inline(const MyGame::Example::Test *native_inline) { + fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline); + } + void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(long_enum_non_enum_default), 0); + } + void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(long_enum_normal_default), 2ULL); + } + void add_nan_default(float nan_default) { + fbb_.AddElement(Monster::VT_NAN_DEFAULT, nan_default, std::numeric_limits::quiet_NaN()); + } + void add_inf_default(float inf_default) { + fbb_.AddElement(Monster::VT_INF_DEFAULT, inf_default, std::numeric_limits::infinity()); + } + void add_positive_inf_default(float positive_inf_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, std::numeric_limits::infinity()); + } + void add_infinity_default(float infinity_default) { + fbb_.AddElement(Monster::VT_INFINITY_DEFAULT, infinity_default, std::numeric_limits::infinity()); + } + void add_positive_infinity_default(float positive_infinity_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, std::numeric_limits::infinity()); + } + void add_negative_inf_default(float negative_inf_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, -std::numeric_limits::infinity()); + } + void add_negative_infinity_default(float negative_infinity_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, -std::numeric_limits::infinity()); + } + void add_double_inf_default(double double_inf_default) { + fbb_.AddElement(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, std::numeric_limits::infinity()); + } + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + fbb_.Required(o, Monster::VT_NAME); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> inventory = 0, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test4 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables = 0, + ::flatbuffers::Offset enemy = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer = 0, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools = 0, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> flex = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test5 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles = 0, + ::flatbuffers::Offset parent_namespace_test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables = 0, + uint64_t single_weak_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables = 0, + uint64_t co_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references = 0, + uint64_t non_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references = 0, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums = 0, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + ::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables = 0, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + MonsterBuilder builder_(_fbb); + builder_.add_double_inf_default(double_inf_default); + builder_.add_long_enum_normal_default(long_enum_normal_default); + builder_.add_long_enum_non_enum_default(long_enum_non_enum_default); + builder_.add_non_owning_reference(non_owning_reference); + builder_.add_co_owning_reference(co_owning_reference); + builder_.add_single_weak_reference(single_weak_reference); + builder_.add_testhashu64_fnv1a(testhashu64_fnv1a); + builder_.add_testhashs64_fnv1a(testhashs64_fnv1a); + builder_.add_testhashu64_fnv1(testhashu64_fnv1); + builder_.add_testhashs64_fnv1(testhashs64_fnv1); + builder_.add_negative_infinity_default(negative_infinity_default); + builder_.add_negative_inf_default(negative_inf_default); + builder_.add_positive_infinity_default(positive_infinity_default); + builder_.add_infinity_default(infinity_default); + builder_.add_positive_inf_default(positive_inf_default); + builder_.add_inf_default(inf_default); + builder_.add_nan_default(nan_default); + builder_.add_native_inline(native_inline); + builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables); + builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer); + builder_.add_vector_of_enums(vector_of_enums); + builder_.add_any_ambiguous(any_ambiguous); + builder_.add_any_unique(any_unique); + builder_.add_vector_of_non_owning_references(vector_of_non_owning_references); + builder_.add_vector_of_co_owning_references(vector_of_co_owning_references); + builder_.add_vector_of_strong_referrables(vector_of_strong_referrables); + builder_.add_vector_of_weak_references(vector_of_weak_references); + builder_.add_vector_of_referrables(vector_of_referrables); + builder_.add_parent_namespace_test(parent_namespace_test); + builder_.add_vector_of_doubles(vector_of_doubles); + builder_.add_vector_of_longs(vector_of_longs); + builder_.add_test5(test5); + builder_.add_flex(flex); + builder_.add_testarrayofsortedstruct(testarrayofsortedstruct); + builder_.add_testarrayofstring2(testarrayofstring2); + builder_.add_testf3(testf3); + builder_.add_testf2(testf2); + builder_.add_testf(testf); + builder_.add_testarrayofbools(testarrayofbools); + builder_.add_testhashu32_fnv1a(testhashu32_fnv1a); + builder_.add_testhashs32_fnv1a(testhashs32_fnv1a); + builder_.add_testhashu32_fnv1(testhashu32_fnv1); + builder_.add_testhashs32_fnv1(testhashs32_fnv1); + builder_.add_testempty(testempty); + builder_.add_testnestedflatbuffer(testnestedflatbuffer); + builder_.add_enemy(enemy); + builder_.add_testarrayoftables(testarrayoftables); + builder_.add_testarrayofstring(testarrayofstring); + builder_.add_test4(test4); + builder_.add_test(test); + builder_.add_inventory(inventory); + builder_.add_name(name); + builder_.add_pos(pos); + builder_.add_hp(hp); + builder_.add_mana(mana); + builder_.add_signed_enum(signed_enum); + builder_.add_any_ambiguous_type(any_ambiguous_type); + builder_.add_any_unique_type(any_unique_type); + builder_.add_testbool(testbool); + builder_.add_test_type(test_type); + builder_.add_color(color); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMonsterDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + const char *name = nullptr, + const std::vector *inventory = nullptr, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + const std::vector *test4 = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring = nullptr, + std::vector<::flatbuffers::Offset> *testarrayoftables = nullptr, + ::flatbuffers::Offset enemy = 0, + const std::vector *testnestedflatbuffer = nullptr, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + const std::vector *testarrayofbools = nullptr, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2 = nullptr, + std::vector *testarrayofsortedstruct = nullptr, + const std::vector *flex = nullptr, + const std::vector *test5 = nullptr, + const std::vector *vector_of_longs = nullptr, + const std::vector *vector_of_doubles = nullptr, + ::flatbuffers::Offset parent_namespace_test = 0, + std::vector<::flatbuffers::Offset> *vector_of_referrables = nullptr, + uint64_t single_weak_reference = 0, + const std::vector *vector_of_weak_references = nullptr, + std::vector<::flatbuffers::Offset> *vector_of_strong_referrables = nullptr, + uint64_t co_owning_reference = 0, + const std::vector *vector_of_co_owning_references = nullptr, + uint64_t non_owning_reference = 0, + const std::vector *vector_of_non_owning_references = nullptr, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + const std::vector *vector_of_enums = nullptr, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + const std::vector *testrequirednestedflatbuffer = nullptr, + std::vector<::flatbuffers::Offset> *scalar_key_sorted_tables = nullptr, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto inventory__ = inventory ? _fbb.CreateVector(*inventory) : 0; + auto test4__ = test4 ? _fbb.CreateVectorOfStructs(*test4) : 0; + auto testarrayofstring__ = testarrayofstring ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring) : 0; + auto testarrayoftables__ = testarrayoftables ? _fbb.CreateVectorOfSortedTables(testarrayoftables) : 0; + auto testnestedflatbuffer__ = testnestedflatbuffer ? _fbb.CreateVector(*testnestedflatbuffer) : 0; + auto testarrayofbools__ = testarrayofbools ? _fbb.CreateVector(*testarrayofbools) : 0; + auto testarrayofstring2__ = testarrayofstring2 ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring2) : 0; + auto testarrayofsortedstruct__ = testarrayofsortedstruct ? _fbb.CreateVectorOfSortedStructs(testarrayofsortedstruct) : 0; + auto flex__ = flex ? _fbb.CreateVector(*flex) : 0; + auto test5__ = test5 ? _fbb.CreateVectorOfStructs(*test5) : 0; + auto vector_of_longs__ = vector_of_longs ? _fbb.CreateVector(*vector_of_longs) : 0; + auto vector_of_doubles__ = vector_of_doubles ? _fbb.CreateVector(*vector_of_doubles) : 0; + auto vector_of_referrables__ = vector_of_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_referrables) : 0; + auto vector_of_weak_references__ = vector_of_weak_references ? _fbb.CreateVector(*vector_of_weak_references) : 0; + auto vector_of_strong_referrables__ = vector_of_strong_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_strong_referrables) : 0; + auto vector_of_co_owning_references__ = vector_of_co_owning_references ? _fbb.CreateVector(*vector_of_co_owning_references) : 0; + auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector(*vector_of_non_owning_references) : 0; + auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector(*vector_of_enums) : 0; + auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector(*testrequirednestedflatbuffer) : 0; + auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables(scalar_key_sorted_tables) : 0; + return MyGame::Example::CreateMonster( + _fbb, + pos, + mana, + hp, + name__, + inventory__, + color, + test_type, + test, + test4__, + testarrayofstring__, + testarrayoftables__, + enemy, + testnestedflatbuffer__, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools__, + testf, + testf2, + testf3, + testarrayofstring2__, + testarrayofsortedstruct__, + flex__, + test5__, + vector_of_longs__, + vector_of_doubles__, + parent_namespace_test, + vector_of_referrables__, + single_weak_reference, + vector_of_weak_references__, + vector_of_strong_referrables__, + co_owning_reference, + vector_of_co_owning_references__, + non_owning_reference, + vector_of_non_owning_references__, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums__, + signed_enum, + testrequirednestedflatbuffer__, + scalar_key_sorted_tables__, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct TypeAliasesT : public ::flatbuffers::NativeTable { + typedef TypeAliases TableType; + int8_t i8 = 0; + uint8_t u8 = 0; + int16_t i16 = 0; + uint16_t u16 = 0; + int32_t i32 = 0; + uint32_t u32 = 0; + int64_t i64 = 0; + uint64_t u64 = 0; + float f32 = 0.0f; + double f64 = 0.0; + std::vector v8{}; + std::vector vf64{}; +}; + +struct TypeAliases FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TypeAliasesT NativeTableType; + typedef TypeAliasesBuilder Builder; + typedef MyGame::Example::MonsterBinarySchema BinarySchema; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TypeAliasesTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_I8 = 4, + VT_U8 = 6, + VT_I16 = 8, + VT_U16 = 10, + VT_I32 = 12, + VT_U32 = 14, + VT_I64 = 16, + VT_U64 = 18, + VT_F32 = 20, + VT_F64 = 22, + VT_V8 = 24, + VT_VF64 = 26 + }; + int8_t i8() const { + return GetField(VT_I8, 0); + } + bool mutate_i8(int8_t _i8 = 0) { + return SetField(VT_I8, _i8, 0); + } + uint8_t u8() const { + return GetField(VT_U8, 0); + } + bool mutate_u8(uint8_t _u8 = 0) { + return SetField(VT_U8, _u8, 0); + } + int16_t i16() const { + return GetField(VT_I16, 0); + } + bool mutate_i16(int16_t _i16 = 0) { + return SetField(VT_I16, _i16, 0); + } + uint16_t u16() const { + return GetField(VT_U16, 0); + } + bool mutate_u16(uint16_t _u16 = 0) { + return SetField(VT_U16, _u16, 0); + } + int32_t i32() const { + return GetField(VT_I32, 0); + } + bool mutate_i32(int32_t _i32 = 0) { + return SetField(VT_I32, _i32, 0); + } + uint32_t u32() const { + return GetField(VT_U32, 0); + } + bool mutate_u32(uint32_t _u32 = 0) { + return SetField(VT_U32, _u32, 0); + } + int64_t i64() const { + return GetField(VT_I64, 0); + } + bool mutate_i64(int64_t _i64 = 0) { + return SetField(VT_I64, _i64, 0); + } + uint64_t u64() const { + return GetField(VT_U64, 0); + } + bool mutate_u64(uint64_t _u64 = 0) { + return SetField(VT_U64, _u64, 0); + } + float f32() const { + return GetField(VT_F32, 0.0f); + } + bool mutate_f32(float _f32 = 0.0f) { + return SetField(VT_F32, _f32, 0.0f); + } + double f64() const { + return GetField(VT_F64, 0.0); + } + bool mutate_f64(double _f64 = 0.0) { + return SetField(VT_F64, _f64, 0.0); + } + const ::flatbuffers::Vector *v8() const { + return GetPointer *>(VT_V8); + } + ::flatbuffers::Vector *mutable_v8() { + return GetPointer<::flatbuffers::Vector *>(VT_V8); + } + const ::flatbuffers::Vector *vf64() const { + return GetPointer *>(VT_VF64); + } + ::flatbuffers::Vector *mutable_vf64() { + return GetPointer<::flatbuffers::Vector *>(VT_VF64); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_I8, 1) && + VerifyField(verifier, VT_U8, 1) && + VerifyField(verifier, VT_I16, 2) && + VerifyField(verifier, VT_U16, 2) && + VerifyField(verifier, VT_I32, 4) && + VerifyField(verifier, VT_U32, 4) && + VerifyField(verifier, VT_I64, 8) && + VerifyField(verifier, VT_U64, 8) && + VerifyField(verifier, VT_F32, 4) && + VerifyField(verifier, VT_F64, 8) && + VerifyOffset(verifier, VT_V8) && + verifier.VerifyVector(v8()) && + VerifyOffset(verifier, VT_VF64) && + verifier.VerifyVector(vf64()) && + verifier.EndTable(); + } + TypeAliasesT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TypeAliasesBuilder { + typedef TypeAliases Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_i8(int8_t i8) { + fbb_.AddElement(TypeAliases::VT_I8, i8, 0); + } + void add_u8(uint8_t u8) { + fbb_.AddElement(TypeAliases::VT_U8, u8, 0); + } + void add_i16(int16_t i16) { + fbb_.AddElement(TypeAliases::VT_I16, i16, 0); + } + void add_u16(uint16_t u16) { + fbb_.AddElement(TypeAliases::VT_U16, u16, 0); + } + void add_i32(int32_t i32) { + fbb_.AddElement(TypeAliases::VT_I32, i32, 0); + } + void add_u32(uint32_t u32) { + fbb_.AddElement(TypeAliases::VT_U32, u32, 0); + } + void add_i64(int64_t i64) { + fbb_.AddElement(TypeAliases::VT_I64, i64, 0); + } + void add_u64(uint64_t u64) { + fbb_.AddElement(TypeAliases::VT_U64, u64, 0); + } + void add_f32(float f32) { + fbb_.AddElement(TypeAliases::VT_F32, f32, 0.0f); + } + void add_f64(double f64) { + fbb_.AddElement(TypeAliases::VT_F64, f64, 0.0); + } + void add_v8(::flatbuffers::Offset<::flatbuffers::Vector> v8) { + fbb_.AddOffset(TypeAliases::VT_V8, v8); + } + void add_vf64(::flatbuffers::Offset<::flatbuffers::Vector> vf64) { + fbb_.AddOffset(TypeAliases::VT_VF64, vf64); + } + explicit TypeAliasesBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTypeAliases( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + ::flatbuffers::Offset<::flatbuffers::Vector> v8 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vf64 = 0) { + TypeAliasesBuilder builder_(_fbb); + builder_.add_f64(f64); + builder_.add_u64(u64); + builder_.add_i64(i64); + builder_.add_vf64(vf64); + builder_.add_v8(v8); + builder_.add_f32(f32); + builder_.add_u32(u32); + builder_.add_i32(i32); + builder_.add_u16(u16); + builder_.add_i16(i16); + builder_.add_u8(u8); + builder_.add_i8(i8); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTypeAliasesDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + const std::vector *v8 = nullptr, + const std::vector *vf64 = nullptr) { + auto v8__ = v8 ? _fbb.CreateVector(*v8) : 0; + auto vf64__ = vf64 ? _fbb.CreateVector(*vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + i8, + u8, + i16, + u16, + i32, + u32, + i64, + u64, + f32, + f64, + v8__, + vf64__); +} + +::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example + + +inline bool operator==(const InParentNamespaceT &, const InParentNamespaceT &) { + return true; +} + +inline bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs) { + return !(lhs == rhs); +} + + +inline InParentNamespaceT *InParentNamespace::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new InParentNamespaceT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void InParentNamespace::UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset InParentNamespace::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateInParentNamespace(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const InParentNamespaceT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::CreateInParentNamespace( + _fbb); +} + +namespace Example2 { + + +inline bool operator==(const MonsterT &, const MonsterT &) { + return true; +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::Example2::CreateMonster( + _fbb); +} + +} // namespace Example2 + +namespace Example { + + +inline bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return + (lhs.color == rhs.color); +} + +inline bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return !(lhs == rhs); +} + + +inline TestSimpleTableWithEnumT *TestSimpleTableWithEnum::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TestSimpleTableWithEnumT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TestSimpleTableWithEnum::UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = color(); _o->color = _e; } +} + +inline ::flatbuffers::Offset TestSimpleTableWithEnum::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTestSimpleTableWithEnum(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TestSimpleTableWithEnumT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _color = _o->color; + return MyGame::Example::CreateTestSimpleTableWithEnum( + _fbb, + _color); +} + + +inline bool operator==(const StatT &lhs, const StatT &rhs) { + return + (lhs.id == rhs.id) && + (lhs.val == rhs.val) && + (lhs.count == rhs.count); +} + +inline bool operator!=(const StatT &lhs, const StatT &rhs) { + return !(lhs == rhs); +} + + +inline StatT *Stat::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new StatT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Stat::UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); if (_e) _o->id = _e->str(); } + { auto _e = val(); _o->val = _e; } + { auto _e = count(); _o->count = _e; } +} + +inline ::flatbuffers::Offset Stat::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateStat(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const StatT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id.empty() ? 0 : _fbb.CreateString(_o->id); + auto _val = _o->val; + auto _count = _o->count; + return MyGame::Example::CreateStat( + _fbb, + _id, + _val, + _count); +} + + +inline bool operator==(const ReferrableT &lhs, const ReferrableT &rhs) { + return + (lhs.id == rhs.id); +} + +inline bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs) { + return !(lhs == rhs); +} + + +inline ReferrableT *Referrable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new ReferrableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Referrable::UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); _o->id = _e; } +} + +inline ::flatbuffers::Offset Referrable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateReferrable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ReferrableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id; + return MyGame::Example::CreateReferrable( + _fbb, + _id); +} + + +inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) { + return + ((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) && + (lhs.mana == rhs.mana) && + (lhs.hp == rhs.hp) && + (lhs.name == rhs.name) && + (lhs.inventory == rhs.inventory) && + (lhs.color == rhs.color) && + (lhs.test == rhs.test) && + (lhs.test4 == rhs.test4) && + (lhs.testarrayofstring == rhs.testarrayofstring) && + (lhs.testarrayoftables.size() == rhs.testarrayoftables.size() && std::equal(lhs.testarrayoftables.cbegin(), lhs.testarrayoftables.cend(), rhs.testarrayoftables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + ((lhs.enemy == rhs.enemy) || (lhs.enemy && rhs.enemy && *lhs.enemy == *rhs.enemy)) && + (lhs.testnestedflatbuffer == rhs.testnestedflatbuffer) && + ((lhs.testempty == rhs.testempty) || (lhs.testempty && rhs.testempty && *lhs.testempty == *rhs.testempty)) && + (lhs.testbool == rhs.testbool) && + (lhs.testhashs32_fnv1 == rhs.testhashs32_fnv1) && + (lhs.testhashu32_fnv1 == rhs.testhashu32_fnv1) && + (lhs.testhashs64_fnv1 == rhs.testhashs64_fnv1) && + (lhs.testhashu64_fnv1 == rhs.testhashu64_fnv1) && + (lhs.testhashs32_fnv1a == rhs.testhashs32_fnv1a) && + (lhs.testhashu32_fnv1a == rhs.testhashu32_fnv1a) && + (lhs.testhashs64_fnv1a == rhs.testhashs64_fnv1a) && + (lhs.testhashu64_fnv1a == rhs.testhashu64_fnv1a) && + (lhs.testarrayofbools == rhs.testarrayofbools) && + (lhs.testf == rhs.testf) && + (lhs.testf2 == rhs.testf2) && + (lhs.testf3 == rhs.testf3) && + (lhs.testarrayofstring2 == rhs.testarrayofstring2) && + (lhs.testarrayofsortedstruct == rhs.testarrayofsortedstruct) && + (lhs.flex == rhs.flex) && + (lhs.test5 == rhs.test5) && + (lhs.vector_of_longs == rhs.vector_of_longs) && + (lhs.vector_of_doubles == rhs.vector_of_doubles) && + ((lhs.parent_namespace_test == rhs.parent_namespace_test) || (lhs.parent_namespace_test && rhs.parent_namespace_test && *lhs.parent_namespace_test == *rhs.parent_namespace_test)) && + (lhs.vector_of_referrables.size() == rhs.vector_of_referrables.size() && std::equal(lhs.vector_of_referrables.cbegin(), lhs.vector_of_referrables.cend(), rhs.vector_of_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.single_weak_reference == rhs.single_weak_reference) && + (lhs.vector_of_weak_references == rhs.vector_of_weak_references) && + (lhs.vector_of_strong_referrables.size() == rhs.vector_of_strong_referrables.size() && std::equal(lhs.vector_of_strong_referrables.cbegin(), lhs.vector_of_strong_referrables.cend(), rhs.vector_of_strong_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.co_owning_reference == rhs.co_owning_reference) && + (lhs.vector_of_co_owning_references == rhs.vector_of_co_owning_references) && + (lhs.non_owning_reference == rhs.non_owning_reference) && + (lhs.vector_of_non_owning_references == rhs.vector_of_non_owning_references) && + (lhs.any_unique == rhs.any_unique) && + (lhs.any_ambiguous == rhs.any_ambiguous) && + (lhs.vector_of_enums == rhs.vector_of_enums) && + (lhs.signed_enum == rhs.signed_enum) && + (lhs.testrequirednestedflatbuffer == rhs.testrequirednestedflatbuffer) && + (lhs.scalar_key_sorted_tables.size() == rhs.scalar_key_sorted_tables.size() && std::equal(lhs.scalar_key_sorted_tables.cbegin(), lhs.scalar_key_sorted_tables.cend(), rhs.scalar_key_sorted_tables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.native_inline == rhs.native_inline) && + (lhs.long_enum_non_enum_default == rhs.long_enum_non_enum_default) && + (lhs.long_enum_normal_default == rhs.long_enum_normal_default) && + (lhs.nan_default == rhs.nan_default) && + (lhs.inf_default == rhs.inf_default) && + (lhs.positive_inf_default == rhs.positive_inf_default) && + (lhs.infinity_default == rhs.infinity_default) && + (lhs.positive_infinity_default == rhs.positive_infinity_default) && + (lhs.negative_inf_default == rhs.negative_inf_default) && + (lhs.negative_infinity_default == rhs.negative_infinity_default) && + (lhs.double_inf_default == rhs.double_inf_default); +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT::MonsterT(const MonsterT &o) + : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr), + mana(o.mana), + hp(o.hp), + name(o.name), + inventory(o.inventory), + color(o.color), + test(o.test), + test4(o.test4), + testarrayofstring(o.testarrayofstring), + enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr), + testnestedflatbuffer(o.testnestedflatbuffer), + testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr), + testbool(o.testbool), + testhashs32_fnv1(o.testhashs32_fnv1), + testhashu32_fnv1(o.testhashu32_fnv1), + testhashs64_fnv1(o.testhashs64_fnv1), + testhashu64_fnv1(o.testhashu64_fnv1), + testhashs32_fnv1a(o.testhashs32_fnv1a), + testhashu32_fnv1a(o.testhashu32_fnv1a), + testhashs64_fnv1a(o.testhashs64_fnv1a), + testhashu64_fnv1a(o.testhashu64_fnv1a), + testarrayofbools(o.testarrayofbools), + testf(o.testf), + testf2(o.testf2), + testf3(o.testf3), + testarrayofstring2(o.testarrayofstring2), + testarrayofsortedstruct(o.testarrayofsortedstruct), + flex(o.flex), + test5(o.test5), + vector_of_longs(o.vector_of_longs), + vector_of_doubles(o.vector_of_doubles), + parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr), + single_weak_reference(o.single_weak_reference), + vector_of_weak_references(o.vector_of_weak_references), + co_owning_reference(o.co_owning_reference), + non_owning_reference(o.non_owning_reference), + vector_of_non_owning_references(o.vector_of_non_owning_references), + any_unique(o.any_unique), + any_ambiguous(o.any_ambiguous), + vector_of_enums(o.vector_of_enums), + signed_enum(o.signed_enum), + testrequirednestedflatbuffer(o.testrequirednestedflatbuffer), + native_inline(o.native_inline), + long_enum_non_enum_default(o.long_enum_non_enum_default), + long_enum_normal_default(o.long_enum_normal_default), + nan_default(o.nan_default), + inf_default(o.inf_default), + positive_inf_default(o.positive_inf_default), + infinity_default(o.infinity_default), + positive_infinity_default(o.positive_infinity_default), + negative_inf_default(o.negative_inf_default), + negative_infinity_default(o.negative_infinity_default), + double_inf_default(o.double_inf_default) { + testarrayoftables.reserve(o.testarrayoftables.size()); + for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); } + vector_of_referrables.reserve(o.vector_of_referrables.size()); + for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); } + vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size()); + for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); } + vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size()); + for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); } + scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size()); + for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); } +} + +inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT { + std::swap(pos, o.pos); + std::swap(mana, o.mana); + std::swap(hp, o.hp); + std::swap(name, o.name); + std::swap(inventory, o.inventory); + std::swap(color, o.color); + std::swap(test, o.test); + std::swap(test4, o.test4); + std::swap(testarrayofstring, o.testarrayofstring); + std::swap(testarrayoftables, o.testarrayoftables); + std::swap(enemy, o.enemy); + std::swap(testnestedflatbuffer, o.testnestedflatbuffer); + std::swap(testempty, o.testempty); + std::swap(testbool, o.testbool); + std::swap(testhashs32_fnv1, o.testhashs32_fnv1); + std::swap(testhashu32_fnv1, o.testhashu32_fnv1); + std::swap(testhashs64_fnv1, o.testhashs64_fnv1); + std::swap(testhashu64_fnv1, o.testhashu64_fnv1); + std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a); + std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a); + std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a); + std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a); + std::swap(testarrayofbools, o.testarrayofbools); + std::swap(testf, o.testf); + std::swap(testf2, o.testf2); + std::swap(testf3, o.testf3); + std::swap(testarrayofstring2, o.testarrayofstring2); + std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct); + std::swap(flex, o.flex); + std::swap(test5, o.test5); + std::swap(vector_of_longs, o.vector_of_longs); + std::swap(vector_of_doubles, o.vector_of_doubles); + std::swap(parent_namespace_test, o.parent_namespace_test); + std::swap(vector_of_referrables, o.vector_of_referrables); + std::swap(single_weak_reference, o.single_weak_reference); + std::swap(vector_of_weak_references, o.vector_of_weak_references); + std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables); + std::swap(co_owning_reference, o.co_owning_reference); + std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references); + std::swap(non_owning_reference, o.non_owning_reference); + std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references); + std::swap(any_unique, o.any_unique); + std::swap(any_ambiguous, o.any_ambiguous); + std::swap(vector_of_enums, o.vector_of_enums); + std::swap(signed_enum, o.signed_enum); + std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer); + std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables); + std::swap(native_inline, o.native_inline); + std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default); + std::swap(long_enum_normal_default, o.long_enum_normal_default); + std::swap(nan_default, o.nan_default); + std::swap(inf_default, o.inf_default); + std::swap(positive_inf_default, o.positive_inf_default); + std::swap(infinity_default, o.infinity_default); + std::swap(positive_infinity_default, o.positive_infinity_default); + std::swap(negative_inf_default, o.negative_inf_default); + std::swap(negative_infinity_default, o.negative_infinity_default); + std::swap(double_inf_default, o.double_inf_default); + return *this; +} + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = pos(); if (_e) _o->pos = std::unique_ptr(new MyGame::Example::Vec3(*_e)); } + { auto _e = mana(); _o->mana = _e; } + { auto _e = hp(); _o->hp = _e; } + { auto _e = name(); if (_e) _o->name = _e->str(); } + { auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } } + { auto _e = color(); _o->color = _e; } + { auto _e = test_type(); _o->test.type = _e; } + { auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); } + { auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } else { _o->test4.resize(0); } } + { auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring.resize(0); } } + { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->testarrayoftables.resize(0); } } + { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->enemy) { _o->enemy.reset(); } } + { auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } } + { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->testempty) { _o->testempty.reset(); } } + { auto _e = testbool(); _o->testbool = _e; } + { auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; } + { auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; } + { auto _e = testhashs64_fnv1(); _o->testhashs64_fnv1 = _e; } + { auto _e = testhashu64_fnv1(); _o->testhashu64_fnv1 = _e; } + { auto _e = testhashs32_fnv1a(); _o->testhashs32_fnv1a = _e; } + { auto _e = testhashu32_fnv1a(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->testhashu32_fnv1a), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->testhashu32_fnv1a = nullptr; } + { auto _e = testhashs64_fnv1a(); _o->testhashs64_fnv1a = _e; } + { auto _e = testhashu64_fnv1a(); _o->testhashu64_fnv1a = _e; } + { auto _e = testarrayofbools(); if (_e) { _o->testarrayofbools.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofbools[_i] = _e->Get(_i) != 0; } } else { _o->testarrayofbools.resize(0); } } + { auto _e = testf(); _o->testf = _e; } + { auto _e = testf2(); _o->testf2 = _e; } + { auto _e = testf3(); _o->testf3 = _e; } + { auto _e = testarrayofstring2(); if (_e) { _o->testarrayofstring2.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring2[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring2.resize(0); } } + { auto _e = testarrayofsortedstruct(); if (_e) { _o->testarrayofsortedstruct.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofsortedstruct[_i] = *_e->Get(_i); } } else { _o->testarrayofsortedstruct.resize(0); } } + { auto _e = flex(); if (_e) { _o->flex.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->flex.begin()); } } + { auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } else { _o->test5.resize(0); } } + { auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } else { _o->vector_of_longs.resize(0); } } + { auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } else { _o->vector_of_doubles.resize(0); } } + { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->parent_namespace_test) { _o->parent_namespace_test.reset(); } } + { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_referrables.resize(0); } } + { auto _e = single_weak_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->single_weak_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; } + { auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_weak_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } else { _o->vector_of_weak_references.resize(0); } } + { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_strong_referrables.resize(0); } } + { auto _e = co_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->co_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; } + { auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, default_ptr_type*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_co_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i)));/* else do nothing */} } else { _o->vector_of_co_owning_references.resize(0); } } + { auto _e = non_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->non_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->non_owning_reference = nullptr; } + { auto _e = vector_of_non_owning_references(); if (_e) { _o->vector_of_non_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_non_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_non_owning_references[_i] = nullptr; } } else { _o->vector_of_non_owning_references.resize(0); } } + { auto _e = any_unique_type(); _o->any_unique.type = _e; } + { auto _e = any_unique(); if (_e) _o->any_unique.value = MyGame::Example::AnyUniqueAliasesUnion::UnPack(_e, any_unique_type(), _resolver); } + { auto _e = any_ambiguous_type(); _o->any_ambiguous.type = _e; } + { auto _e = any_ambiguous(); if (_e) _o->any_ambiguous.value = MyGame::Example::AnyAmbiguousAliasesUnion::UnPack(_e, any_ambiguous_type(), _resolver); } + { auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast(_e->Get(_i)); } } else { _o->vector_of_enums.resize(0); } } + { auto _e = signed_enum(); _o->signed_enum = _e; } + { auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } } + { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->scalar_key_sorted_tables.resize(0); } } + { auto _e = native_inline(); if (_e) _o->native_inline = *_e; } + { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; } + { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; } + { auto _e = nan_default(); _o->nan_default = _e; } + { auto _e = inf_default(); _o->inf_default = _e; } + { auto _e = positive_inf_default(); _o->positive_inf_default = _e; } + { auto _e = infinity_default(); _o->infinity_default = _e; } + { auto _e = positive_infinity_default(); _o->positive_infinity_default = _e; } + { auto _e = negative_inf_default(); _o->negative_inf_default = _e; } + { auto _e = negative_infinity_default(); _o->negative_infinity_default = _e; } + { auto _e = double_inf_default(); _o->double_inf_default = _e; } +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _pos = _o->pos ? _o->pos.get() : nullptr; + auto _mana = _o->mana; + auto _hp = _o->hp; + auto _name = _fbb.CreateString(_o->name); + auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0; + auto _color = _o->color; + auto _test_type = _o->test.type; + auto _test = _o->test.Pack(_fbb); + auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; + auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testbool = _o->testbool; + auto _testhashs32_fnv1 = _o->testhashs32_fnv1; + auto _testhashu32_fnv1 = _o->testhashu32_fnv1; + auto _testhashs64_fnv1 = _o->testhashs64_fnv1; + auto _testhashu64_fnv1 = _o->testhashu64_fnv1; + auto _testhashs32_fnv1a = _o->testhashs32_fnv1a; + auto _testhashu32_fnv1a = _rehasher ? static_cast((*_rehasher)(_o->testhashu32_fnv1a)) : 0; + auto _testhashs64_fnv1a = _o->testhashs64_fnv1a; + auto _testhashu64_fnv1a = _o->testhashu64_fnv1a; + auto _testarrayofbools = _o->testarrayofbools.size() ? _fbb.CreateVector(_o->testarrayofbools) : 0; + auto _testf = _o->testf; + auto _testf2 = _o->testf2; + auto _testf3 = _o->testf3; + auto _testarrayofstring2 = _o->testarrayofstring2.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring2) : 0; + auto _testarrayofsortedstruct = _o->testarrayofsortedstruct.size() ? _fbb.CreateVectorOfStructs(_o->testarrayofsortedstruct) : 0; + auto _flex = _o->flex.size() ? _fbb.CreateVector(_o->flex) : 0; + auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; + auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; + auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; + auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; + auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; + auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; + auto _vector_of_non_owning_references = _o->vector_of_non_owning_references.size() ? _fbb.CreateVector(_o->vector_of_non_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_non_owning_references[i])) : 0; }, &_va ) : 0; + auto _any_unique_type = _o->any_unique.type; + auto _any_unique = _o->any_unique.Pack(_fbb); + auto _any_ambiguous_type = _o->any_ambiguous.type; + auto _any_ambiguous = _o->any_ambiguous.Pack(_fbb); + auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; + auto _signed_enum = _o->signed_enum; + auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _native_inline = &_o->native_inline; + auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; + auto _long_enum_normal_default = _o->long_enum_normal_default; + auto _nan_default = _o->nan_default; + auto _inf_default = _o->inf_default; + auto _positive_inf_default = _o->positive_inf_default; + auto _infinity_default = _o->infinity_default; + auto _positive_infinity_default = _o->positive_infinity_default; + auto _negative_inf_default = _o->negative_inf_default; + auto _negative_infinity_default = _o->negative_infinity_default; + auto _double_inf_default = _o->double_inf_default; + return MyGame::Example::CreateMonster( + _fbb, + _pos, + _mana, + _hp, + _name, + _inventory, + _color, + _test_type, + _test, + _test4, + _testarrayofstring, + _testarrayoftables, + _enemy, + _testnestedflatbuffer, + _testempty, + _testbool, + _testhashs32_fnv1, + _testhashu32_fnv1, + _testhashs64_fnv1, + _testhashu64_fnv1, + _testhashs32_fnv1a, + _testhashu32_fnv1a, + _testhashs64_fnv1a, + _testhashu64_fnv1a, + _testarrayofbools, + _testf, + _testf2, + _testf3, + _testarrayofstring2, + _testarrayofsortedstruct, + _flex, + _test5, + _vector_of_longs, + _vector_of_doubles, + _parent_namespace_test, + _vector_of_referrables, + _single_weak_reference, + _vector_of_weak_references, + _vector_of_strong_referrables, + _co_owning_reference, + _vector_of_co_owning_references, + _non_owning_reference, + _vector_of_non_owning_references, + _any_unique_type, + _any_unique, + _any_ambiguous_type, + _any_ambiguous, + _vector_of_enums, + _signed_enum, + _testrequirednestedflatbuffer, + _scalar_key_sorted_tables, + _native_inline, + _long_enum_non_enum_default, + _long_enum_normal_default, + _nan_default, + _inf_default, + _positive_inf_default, + _infinity_default, + _positive_infinity_default, + _negative_inf_default, + _negative_infinity_default, + _double_inf_default); +} + + +inline bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return + (lhs.i8 == rhs.i8) && + (lhs.u8 == rhs.u8) && + (lhs.i16 == rhs.i16) && + (lhs.u16 == rhs.u16) && + (lhs.i32 == rhs.i32) && + (lhs.u32 == rhs.u32) && + (lhs.i64 == rhs.i64) && + (lhs.u64 == rhs.u64) && + (lhs.f32 == rhs.f32) && + (lhs.f64 == rhs.f64) && + (lhs.v8 == rhs.v8) && + (lhs.vf64 == rhs.vf64); +} + +inline bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return !(lhs == rhs); +} + + +inline TypeAliasesT *TypeAliases::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TypeAliasesT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TypeAliases::UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = i8(); _o->i8 = _e; } + { auto _e = u8(); _o->u8 = _e; } + { auto _e = i16(); _o->i16 = _e; } + { auto _e = u16(); _o->u16 = _e; } + { auto _e = i32(); _o->i32 = _e; } + { auto _e = u32(); _o->u32 = _e; } + { auto _e = i64(); _o->i64 = _e; } + { auto _e = u64(); _o->u64 = _e; } + { auto _e = f32(); _o->f32 = _e; } + { auto _e = f64(); _o->f64 = _e; } + { auto _e = v8(); if (_e) { _o->v8.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->v8.begin()); } } + { auto _e = vf64(); if (_e) { _o->vf64.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vf64[_i] = _e->Get(_i); } } else { _o->vf64.resize(0); } } +} + +inline ::flatbuffers::Offset TypeAliases::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTypeAliases(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TypeAliasesT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _i8 = _o->i8; + auto _u8 = _o->u8; + auto _i16 = _o->i16; + auto _u16 = _o->u16; + auto _i32 = _o->i32; + auto _u32 = _o->u32; + auto _i64 = _o->i64; + auto _u64 = _o->u64; + auto _f32 = _o->f32; + auto _f64 = _o->f64; + auto _v8 = _o->v8.size() ? _fbb.CreateVector(_o->v8) : 0; + auto _vf64 = _o->vf64.size() ? _fbb.CreateVector(_o->vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + _i8, + _u8, + _i16, + _u16, + _i32, + _u32, + _i64, + _u64, + _f32, + _f64, + _v8, + _vf64); +} + +inline bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type) { + switch (type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAny( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUnion::UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Any_Monster: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case Any_TestSimpleTableWithEnum: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case Any_MyGame_Example2_Monster: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUnion::Reset() { + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Any_NONE; +} + +inline bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type) { + switch (type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyUniqueAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUniqueAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyUniqueAliases_M: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_TS: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_M2: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUniqueAliasesUnion::Reset() { + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyUniqueAliases_NONE; +} + +inline bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type) { + switch (type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyAmbiguousAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyAmbiguousAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyAmbiguousAliases_M1: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M2: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M3: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyAmbiguousAliasesUnion::Reset() { + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyAmbiguousAliases_NONE; +} + +inline const ::flatbuffers::TypeTable *ColorTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const int64_t values[] = { 1, 2, 8 }; + static const char * const names[] = { + "Red", + "Green", + "Blue" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RaceTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::RaceTypeTable + }; + static const int64_t values[] = { -1, 0, 1, 2 }; + static const char * const names[] = { + "None", + "Human", + "Dwarf", + "Elf" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 4, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *LongEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::LongEnumTypeTable + }; + static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL }; + static const char * const names[] = { + "LongOne", + "LongTwo", + "LongBig" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyUniqueAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M", + "TS", + "M2" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyAmbiguousAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M1", + "M2", + "M3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 } + }; + static const int64_t values[] = { 0, 2, 4 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const char * const names[] = { + "color" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *Vec3TypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 4, 8, 16, 24, 26, 32 }; + static const char * const names[] = { + "x", + "y", + "z", + "test1", + "test2", + "test3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 6, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AbilityTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "id", + "distance" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::AbilityTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 8, 12, 20 }; + static const char * const names[] = { + "a", + "b", + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::StructOfStructsTypeTable + }; + static const int64_t values[] = { 0, 20 }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StatTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 } + }; + static const char * const names[] = { + "id", + "val", + "count" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, -1 } + }; + static const char * const names[] = { + "id" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 1 }, + { ::flatbuffers::ET_UTYPE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 4 }, + { ::flatbuffers::ET_SEQUENCE, 0, 4 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 5 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_BOOL, 1, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 6 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_LONG, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 7 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_UTYPE, 0, 9 }, + { ::flatbuffers::ET_SEQUENCE, 0, 9 }, + { ::flatbuffers::ET_UTYPE, 0, 10 }, + { ::flatbuffers::ET_SEQUENCE, 0, 10 }, + { ::flatbuffers::ET_UCHAR, 1, 1 }, + { ::flatbuffers::ET_CHAR, 0, 11 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 5 }, + { ::flatbuffers::ET_SEQUENCE, 0, 3 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::Vec3TypeTable, + MyGame::Example::ColorTypeTable, + MyGame::Example::AnyTypeTable, + MyGame::Example::TestTypeTable, + MyGame::Example::MonsterTypeTable, + MyGame::Example::StatTypeTable, + MyGame::Example::AbilityTypeTable, + MyGame::InParentNamespaceTypeTable, + MyGame::Example::ReferrableTypeTable, + MyGame::Example::AnyUniqueAliasesTypeTable, + MyGame::Example::AnyAmbiguousAliasesTypeTable, + MyGame::Example::RaceTypeTable, + MyGame::Example::LongEnumTypeTable + }; + static const char * const names[] = { + "pos", + "mana", + "hp", + "name", + "friendly", + "inventory", + "color", + "test_type", + "test", + "test4", + "testarrayofstring", + "testarrayoftables", + "enemy", + "testnestedflatbuffer", + "testempty", + "testbool", + "testhashs32_fnv1", + "testhashu32_fnv1", + "testhashs64_fnv1", + "testhashu64_fnv1", + "testhashs32_fnv1a", + "testhashu32_fnv1a", + "testhashs64_fnv1a", + "testhashu64_fnv1a", + "testarrayofbools", + "testf", + "testf2", + "testf3", + "testarrayofstring2", + "testarrayofsortedstruct", + "flex", + "test5", + "vector_of_longs", + "vector_of_doubles", + "parent_namespace_test", + "vector_of_referrables", + "single_weak_reference", + "vector_of_weak_references", + "vector_of_strong_referrables", + "co_owning_reference", + "vector_of_co_owning_references", + "non_owning_reference", + "vector_of_non_owning_references", + "any_unique_type", + "any_unique", + "any_ambiguous_type", + "any_ambiguous", + "vector_of_enums", + "signed_enum", + "testrequirednestedflatbuffer", + "scalar_key_sorted_tables", + "native_inline", + "long_enum_non_enum_default", + "long_enum_normal_default", + "nan_default", + "inf_default", + "positive_inf_default", + "infinity_default", + "positive_infinity_default", + "negative_inf_default", + "negative_infinity_default", + "double_inf_default" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 62, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_CHAR, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 } + }; + static const char * const names[] = { + "i8", + "u8", + "i16", + "u16", + "i32", + "u32", + "i64", + "u64", + "f32", + "f64", + "v8", + "vf64" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 12, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const MyGame::Example::Monster *GetMonster(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const MyGame::Example::Monster *GetSizePrefixedMonster(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Monster *GetMutableMonster(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MonsterIdentifier() { + return "MONS"; +} + +inline bool MonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier()); +} + +inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier(), true); +} + +inline bool VerifyMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MonsterIdentifier()); +} + +inline bool VerifySizePrefixedMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MonsterIdentifier()); +} + +inline const char *MonsterExtension() { + return "mon"; +} + +inline void FinishMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MonsterIdentifier()); +} + +inline void FinishSizePrefixedMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MonsterIdentifier()); +} + +inline std::unique_ptr UnPackMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMonster(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMonster(buf)->UnPack(res)); +} + +} // namespace Example +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ diff --git a/third_party/flatbuffers/tests/monster_test_generated.lobster b/third_party/flatbuffers/tests/monster_test_generated.lobster new file mode 100644 index 00000000000..9d3cccdee3e --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_generated.lobster @@ -0,0 +1,855 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import flatbuffers + +namespace MyGame.Example + +/// Composite components of Monster color. +enum Color: + Color_Red = 1 + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Color_Green = 2 + /// \brief color Blue (1u << 3) + Color_Blue = 8 + +enum Race: + Race_None = -1 + Race_Human = 0 + Race_Dwarf = 1 + Race_Elf = 2 + +enum LongEnum: + LongEnum_LongOne = 2 + LongEnum_LongTwo = 4 + LongEnum_LongBig = 1099511627776 + +enum Any: + Any_NONE = 0 + Any_Monster = 1 + Any_TestSimpleTableWithEnum = 2 + Any_MyGame_Example2_Monster = 3 + +enum AnyUniqueAliases: + AnyUniqueAliases_NONE = 0 + AnyUniqueAliases_M = 1 + AnyUniqueAliases_TS = 2 + AnyUniqueAliases_M2 = 3 + +enum AnyAmbiguousAliases: + AnyAmbiguousAliases_NONE = 0 + AnyAmbiguousAliases_M1 = 1 + AnyAmbiguousAliases_M2 = 2 + AnyAmbiguousAliases_M3 = 3 + +namespace MyGame + +class InParentNamespace + +namespace MyGame.Example2 + +class Monster + +namespace MyGame.Example + +class Test + +class TestSimpleTableWithEnum + +class Vec3 + +class Ability + +class StructOfStructs + +class StructOfStructsOfStructs + +class Stat + +class Referrable + +class Monster + +class TypeAliases + +namespace MyGame + +class InParentNamespace : flatbuffers.handle + +def GetRootAsInParentNamespace(buf:string): return InParentNamespace { buf, flatbuffers.indirect(buf, 0) } + +struct InParentNamespaceBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(0) + return this + def end(): + return b_.EndObject() + +namespace MyGame.Example2 + +class Monster : flatbuffers.handle + +def GetRootAsMonster(buf:string): return Monster { buf, flatbuffers.indirect(buf, 0) } + +struct MonsterBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(0) + return this + def end(): + return b_.EndObject() + +namespace MyGame.Example + +class Test : flatbuffers.handle + def a() -> int: + return buf_.read_int16_le(pos_ + 0) + def b() -> int: + return buf_.read_int8_le(pos_ + 2) + +def CreateTest(b_:flatbuffers.builder, a:int, b:int): + b_.Prep(2, 4) + b_.Pad(1) + b_.PrependInt8(b) + b_.PrependInt16(a) + return b_.Offset() + +class TestSimpleTableWithEnum : flatbuffers.handle + def color() -> Color: + return Color(flatbuffers.field_uint8(buf_, pos_, 4, 2)) + +def GetRootAsTestSimpleTableWithEnum(buf:string): return TestSimpleTableWithEnum { buf, flatbuffers.indirect(buf, 0) } + +struct TestSimpleTableWithEnumBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(1) + return this + def add_color(color:Color): + b_.PrependUint8Slot(0, color, 2) + return this + def end(): + return b_.EndObject() + +class Vec3 : flatbuffers.handle + def x() -> float: + return buf_.read_float32_le(pos_ + 0) + def y() -> float: + return buf_.read_float32_le(pos_ + 4) + def z() -> float: + return buf_.read_float32_le(pos_ + 8) + def test1() -> float: + return buf_.read_float64_le(pos_ + 16) + def test2() -> Color: + return Color(buf_.read_uint8_le(pos_ + 24)) + def test3() -> MyGame.Example.Test: + return MyGame.Example.Test{ buf_, pos_ + 26 } + +def CreateVec3(b_:flatbuffers.builder, x:float, y:float, z:float, test1:float, test2:Color, test3_a:int, test3_b:int): + b_.Prep(8, 32) + b_.Pad(2) + b_.Prep(2, 4) + b_.Pad(1) + b_.PrependInt8(test3_b) + b_.PrependInt16(test3_a) + b_.Pad(1) + b_.PrependUint8(test2) + b_.PrependFloat64(test1) + b_.Pad(4) + b_.PrependFloat32(z) + b_.PrependFloat32(y) + b_.PrependFloat32(x) + return b_.Offset() + +class Ability : flatbuffers.handle + def id() -> int: + return buf_.read_uint32_le(pos_ + 0) + def distance() -> int: + return buf_.read_uint32_le(pos_ + 4) + +def CreateAbility(b_:flatbuffers.builder, id:int, distance:int): + b_.Prep(4, 8) + b_.PrependUint32(distance) + b_.PrependUint32(id) + return b_.Offset() + +class StructOfStructs : flatbuffers.handle + def a() -> MyGame.Example.Ability: + return MyGame.Example.Ability{ buf_, pos_ + 0 } + def b() -> MyGame.Example.Test: + return MyGame.Example.Test{ buf_, pos_ + 8 } + def c() -> MyGame.Example.Ability: + return MyGame.Example.Ability{ buf_, pos_ + 12 } + +def CreateStructOfStructs(b_:flatbuffers.builder, a_id:int, a_distance:int, b_a:int, b_b:int, c_id:int, c_distance:int): + b_.Prep(4, 20) + b_.Prep(4, 8) + b_.PrependUint32(c_distance) + b_.PrependUint32(c_id) + b_.Prep(2, 4) + b_.Pad(1) + b_.PrependInt8(b_b) + b_.PrependInt16(b_a) + b_.Prep(4, 8) + b_.PrependUint32(a_distance) + b_.PrependUint32(a_id) + return b_.Offset() + +class StructOfStructsOfStructs : flatbuffers.handle + def a() -> MyGame.Example.StructOfStructs: + return MyGame.Example.StructOfStructs{ buf_, pos_ + 0 } + +def CreateStructOfStructsOfStructs(b_:flatbuffers.builder, a_a_id:int, a_a_distance:int, a_b_a:int, a_b_b:int, a_c_id:int, a_c_distance:int): + b_.Prep(4, 20) + b_.Prep(4, 20) + b_.Prep(4, 8) + b_.PrependUint32(a_c_distance) + b_.PrependUint32(a_c_id) + b_.Prep(2, 4) + b_.Pad(1) + b_.PrependInt8(a_b_b) + b_.PrependInt16(a_b_a) + b_.Prep(4, 8) + b_.PrependUint32(a_a_distance) + b_.PrependUint32(a_a_id) + return b_.Offset() + +class Stat : flatbuffers.handle + def id() -> string: + return flatbuffers.field_string(buf_, pos_, 4) + def val() -> int: + return flatbuffers.field_int64(buf_, pos_, 6, 0) + def count() -> int: + return flatbuffers.field_uint16(buf_, pos_, 8, 0) + +def GetRootAsStat(buf:string): return Stat { buf, flatbuffers.indirect(buf, 0) } + +struct StatBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(3) + return this + def add_id(id:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(0, id) + return this + def add_val(val:int): + b_.PrependInt64Slot(1, val, 0) + return this + def add_count(count:int): + b_.PrependUint16Slot(2, count, 0) + return this + def end(): + return b_.EndObject() + +class Referrable : flatbuffers.handle + def id() -> int: + return flatbuffers.field_uint64(buf_, pos_, 4, 0) + +def GetRootAsReferrable(buf:string): return Referrable { buf, flatbuffers.indirect(buf, 0) } + +struct ReferrableBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(1) + return this + def add_id(id:int): + b_.PrependUint64Slot(0, id, 0) + return this + def end(): + return b_.EndObject() + +/// an example documentation comment: "monster object" +class Monster : flatbuffers.handle + def pos() -> MyGame.Example.Vec3?: + let o = flatbuffers.field_struct(buf_, pos_, 4) + return if o: MyGame.Example.Vec3 { buf_, o } else: nil + def mana() -> int: + return flatbuffers.field_int16(buf_, pos_, 6, 150) + def hp() -> int: + return flatbuffers.field_int16(buf_, pos_, 8, 100) + def name() -> string: + return flatbuffers.field_string(buf_, pos_, 10) + def inventory(i:int) -> int: + return read_uint8_le(buf_, buf_.flatbuffers.field_vector(pos_, 14) + i * 1) + def inventory_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 14) + def color() -> Color: + return Color(flatbuffers.field_uint8(buf_, pos_, 16, 8)) + def test_type() -> Any: + return Any(flatbuffers.field_uint8(buf_, pos_, 18, 0)) + def test_as_Monster(): + return MyGame.Example.Monster { buf_, flatbuffers.field_table(buf_, pos_, 20) } + def test_as_TestSimpleTableWithEnum(): + return MyGame.Example.TestSimpleTableWithEnum { buf_, flatbuffers.field_table(buf_, pos_, 20) } + def test_as_MyGame_Example2_Monster(): + return MyGame.Example2.Monster { buf_, flatbuffers.field_table(buf_, pos_, 20) } + def test4(i:int) -> MyGame.Example.Test: + return MyGame.Example.Test { buf_, flatbuffers.field_vector(buf_, pos_, 22) + i * 4 } + def test4_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 22) + def testarrayofstring(i:int) -> string: + return flatbuffers.string(buf_, buf_.flatbuffers.field_vector(pos_, 24) + i * 4) + def testarrayofstring_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 24) + /// an example documentation comment: this will end up in the generated code + /// multiline too + def testarrayoftables(i:int) -> MyGame.Example.Monster: + return MyGame.Example.Monster { buf_, flatbuffers.indirect(buf_, flatbuffers.field_vector(buf_, pos_, 26) + i * 4) } + def testarrayoftables_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 26) + def enemy() -> MyGame.Example.Monster?: + let o = flatbuffers.field_table(buf_, pos_, 28) + return if o: MyGame.Example.Monster { buf_, o } else: nil + def testnestedflatbuffer(i:int) -> int: + return read_uint8_le(buf_, buf_.flatbuffers.field_vector(pos_, 30) + i * 1) + def testnestedflatbuffer_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 30) + def testempty() -> MyGame.Example.Stat?: + let o = flatbuffers.field_table(buf_, pos_, 32) + return if o: MyGame.Example.Stat { buf_, o } else: nil + def testbool() -> bool: + return bool(flatbuffers.field_int8(buf_, pos_, 34, 0)) + def testhashs32_fnv1() -> int: + return flatbuffers.field_int32(buf_, pos_, 36, 0) + def testhashu32_fnv1() -> int: + return flatbuffers.field_uint32(buf_, pos_, 38, 0) + def testhashs64_fnv1() -> int: + return flatbuffers.field_int64(buf_, pos_, 40, 0) + def testhashu64_fnv1() -> int: + return flatbuffers.field_uint64(buf_, pos_, 42, 0) + def testhashs32_fnv1a() -> int: + return flatbuffers.field_int32(buf_, pos_, 44, 0) + def testhashu32_fnv1a() -> int: + return flatbuffers.field_uint32(buf_, pos_, 46, 0) + def testhashs64_fnv1a() -> int: + return flatbuffers.field_int64(buf_, pos_, 48, 0) + def testhashu64_fnv1a() -> int: + return flatbuffers.field_uint64(buf_, pos_, 50, 0) + def testarrayofbools(i:int) -> bool: + return read_int8_le(buf_, buf_.flatbuffers.field_vector(pos_, 52) + i * 1) + def testarrayofbools_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 52) + def testf() -> float: + return flatbuffers.field_float32(buf_, pos_, 54, 3.14159) + def testf2() -> float: + return flatbuffers.field_float32(buf_, pos_, 56, 3.0) + def testf3() -> float: + return flatbuffers.field_float32(buf_, pos_, 58, 0.0) + def testarrayofstring2(i:int) -> string: + return flatbuffers.string(buf_, buf_.flatbuffers.field_vector(pos_, 60) + i * 4) + def testarrayofstring2_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 60) + def testarrayofsortedstruct(i:int) -> MyGame.Example.Ability: + return MyGame.Example.Ability { buf_, flatbuffers.field_vector(buf_, pos_, 62) + i * 8 } + def testarrayofsortedstruct_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 62) + def flex(i:int) -> int: + return read_uint8_le(buf_, buf_.flatbuffers.field_vector(pos_, 64) + i * 1) + def flex_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 64) + def test5(i:int) -> MyGame.Example.Test: + return MyGame.Example.Test { buf_, flatbuffers.field_vector(buf_, pos_, 66) + i * 4 } + def test5_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 66) + def vector_of_longs(i:int) -> int: + return read_int64_le(buf_, buf_.flatbuffers.field_vector(pos_, 68) + i * 8) + def vector_of_longs_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 68) + def vector_of_doubles(i:int) -> float: + return read_float64_le(buf_, buf_.flatbuffers.field_vector(pos_, 70) + i * 8) + def vector_of_doubles_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 70) + def parent_namespace_test() -> MyGame.InParentNamespace?: + let o = flatbuffers.field_table(buf_, pos_, 72) + return if o: MyGame.InParentNamespace { buf_, o } else: nil + def vector_of_referrables(i:int) -> MyGame.Example.Referrable: + return MyGame.Example.Referrable { buf_, flatbuffers.indirect(buf_, flatbuffers.field_vector(buf_, pos_, 74) + i * 4) } + def vector_of_referrables_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 74) + def single_weak_reference() -> int: + return flatbuffers.field_uint64(buf_, pos_, 76, 0) + def vector_of_weak_references(i:int) -> int: + return read_uint64_le(buf_, buf_.flatbuffers.field_vector(pos_, 78) + i * 8) + def vector_of_weak_references_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 78) + def vector_of_strong_referrables(i:int) -> MyGame.Example.Referrable: + return MyGame.Example.Referrable { buf_, flatbuffers.indirect(buf_, flatbuffers.field_vector(buf_, pos_, 80) + i * 4) } + def vector_of_strong_referrables_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 80) + def co_owning_reference() -> int: + return flatbuffers.field_uint64(buf_, pos_, 82, 0) + def vector_of_co_owning_references(i:int) -> int: + return read_uint64_le(buf_, buf_.flatbuffers.field_vector(pos_, 84) + i * 8) + def vector_of_co_owning_references_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 84) + def non_owning_reference() -> int: + return flatbuffers.field_uint64(buf_, pos_, 86, 0) + def vector_of_non_owning_references(i:int) -> int: + return read_uint64_le(buf_, buf_.flatbuffers.field_vector(pos_, 88) + i * 8) + def vector_of_non_owning_references_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 88) + def any_unique_type() -> AnyUniqueAliases: + return AnyUniqueAliases(flatbuffers.field_uint8(buf_, pos_, 90, 0)) + def any_unique_as_M(): + return MyGame.Example.Monster { buf_, flatbuffers.field_table(buf_, pos_, 92) } + def any_unique_as_TS(): + return MyGame.Example.TestSimpleTableWithEnum { buf_, flatbuffers.field_table(buf_, pos_, 92) } + def any_unique_as_M2(): + return MyGame.Example2.Monster { buf_, flatbuffers.field_table(buf_, pos_, 92) } + def any_ambiguous_type() -> AnyAmbiguousAliases: + return AnyAmbiguousAliases(flatbuffers.field_uint8(buf_, pos_, 94, 0)) + def any_ambiguous_as_M1(): + return MyGame.Example.Monster { buf_, flatbuffers.field_table(buf_, pos_, 96) } + def any_ambiguous_as_M2(): + return MyGame.Example.Monster { buf_, flatbuffers.field_table(buf_, pos_, 96) } + def any_ambiguous_as_M3(): + return MyGame.Example.Monster { buf_, flatbuffers.field_table(buf_, pos_, 96) } + def vector_of_enums(i:int) -> Color: + return read_uint8_le(buf_, buf_.flatbuffers.field_vector(pos_, 98) + i * 1) + def vector_of_enums_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 98) + def signed_enum() -> Race: + return Race(flatbuffers.field_int8(buf_, pos_, 100, -1)) + def testrequirednestedflatbuffer(i:int) -> int: + return read_uint8_le(buf_, buf_.flatbuffers.field_vector(pos_, 102) + i * 1) + def testrequirednestedflatbuffer_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 102) + def scalar_key_sorted_tables(i:int) -> MyGame.Example.Stat: + return MyGame.Example.Stat { buf_, flatbuffers.indirect(buf_, flatbuffers.field_vector(buf_, pos_, 104) + i * 4) } + def scalar_key_sorted_tables_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 104) + def native_inline() -> MyGame.Example.Test?: + let o = flatbuffers.field_struct(buf_, pos_, 106) + return if o: MyGame.Example.Test { buf_, o } else: nil + def long_enum_non_enum_default() -> LongEnum: + return LongEnum(flatbuffers.field_uint64(buf_, pos_, 108, 0)) + def long_enum_normal_default() -> LongEnum: + return LongEnum(flatbuffers.field_uint64(buf_, pos_, 110, 2)) + def nan_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 112, nan) + def inf_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 114, inf) + def positive_inf_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 116, +inf) + def infinity_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 118, infinity) + def positive_infinity_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 120, +infinity) + def negative_inf_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 122, -inf) + def negative_infinity_default() -> float: + return flatbuffers.field_float32(buf_, pos_, 124, -infinity) + def double_inf_default() -> float: + return flatbuffers.field_float64(buf_, pos_, 126, inf) + +def GetRootAsMonster(buf:string): return Monster { buf, flatbuffers.indirect(buf, 0) } + +struct MonsterBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(62) + return this + def add_pos(pos:flatbuffers.offset): + b_.PrependStructSlot(0, pos) + return this + def add_mana(mana:int): + b_.PrependInt16Slot(1, mana, 150) + return this + def add_hp(hp:int): + b_.PrependInt16Slot(2, hp, 100) + return this + def add_name(name:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(3, name) + return this + def add_inventory(inventory:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(5, inventory) + return this + def add_color(color:Color): + b_.PrependUint8Slot(6, color, 8) + return this + def add_test_type(test_type:Any): + b_.PrependUint8Slot(7, test_type, 0) + return this + def add_test(test:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(8, test) + return this + def add_test4(test4:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(9, test4) + return this + def add_testarrayofstring(testarrayofstring:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(10, testarrayofstring) + return this + def add_testarrayoftables(testarrayoftables:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(11, testarrayoftables) + return this + def add_enemy(enemy:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(12, enemy) + return this + def add_testnestedflatbuffer(testnestedflatbuffer:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(13, testnestedflatbuffer) + return this + def add_testempty(testempty:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(14, testempty) + return this + def add_testbool(testbool:bool): + b_.PrependBoolSlot(15, testbool, 0) + return this + def add_testhashs32_fnv1(testhashs32_fnv1:int): + b_.PrependInt32Slot(16, testhashs32_fnv1, 0) + return this + def add_testhashu32_fnv1(testhashu32_fnv1:int): + b_.PrependUint32Slot(17, testhashu32_fnv1, 0) + return this + def add_testhashs64_fnv1(testhashs64_fnv1:int): + b_.PrependInt64Slot(18, testhashs64_fnv1, 0) + return this + def add_testhashu64_fnv1(testhashu64_fnv1:int): + b_.PrependUint64Slot(19, testhashu64_fnv1, 0) + return this + def add_testhashs32_fnv1a(testhashs32_fnv1a:int): + b_.PrependInt32Slot(20, testhashs32_fnv1a, 0) + return this + def add_testhashu32_fnv1a(testhashu32_fnv1a:int): + b_.PrependUint32Slot(21, testhashu32_fnv1a, 0) + return this + def add_testhashs64_fnv1a(testhashs64_fnv1a:int): + b_.PrependInt64Slot(22, testhashs64_fnv1a, 0) + return this + def add_testhashu64_fnv1a(testhashu64_fnv1a:int): + b_.PrependUint64Slot(23, testhashu64_fnv1a, 0) + return this + def add_testarrayofbools(testarrayofbools:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(24, testarrayofbools) + return this + def add_testf(testf:float): + b_.PrependFloat32Slot(25, testf, 3.14159) + return this + def add_testf2(testf2:float): + b_.PrependFloat32Slot(26, testf2, 3.0) + return this + def add_testf3(testf3:float): + b_.PrependFloat32Slot(27, testf3, 0.0) + return this + def add_testarrayofstring2(testarrayofstring2:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(28, testarrayofstring2) + return this + def add_testarrayofsortedstruct(testarrayofsortedstruct:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(29, testarrayofsortedstruct) + return this + def add_flex(flex:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(30, flex) + return this + def add_test5(test5:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(31, test5) + return this + def add_vector_of_longs(vector_of_longs:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(32, vector_of_longs) + return this + def add_vector_of_doubles(vector_of_doubles:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(33, vector_of_doubles) + return this + def add_parent_namespace_test(parent_namespace_test:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(34, parent_namespace_test) + return this + def add_vector_of_referrables(vector_of_referrables:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(35, vector_of_referrables) + return this + def add_single_weak_reference(single_weak_reference:int): + b_.PrependUint64Slot(36, single_weak_reference, 0) + return this + def add_vector_of_weak_references(vector_of_weak_references:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(37, vector_of_weak_references) + return this + def add_vector_of_strong_referrables(vector_of_strong_referrables:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(38, vector_of_strong_referrables) + return this + def add_co_owning_reference(co_owning_reference:int): + b_.PrependUint64Slot(39, co_owning_reference, 0) + return this + def add_vector_of_co_owning_references(vector_of_co_owning_references:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(40, vector_of_co_owning_references) + return this + def add_non_owning_reference(non_owning_reference:int): + b_.PrependUint64Slot(41, non_owning_reference, 0) + return this + def add_vector_of_non_owning_references(vector_of_non_owning_references:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(42, vector_of_non_owning_references) + return this + def add_any_unique_type(any_unique_type:AnyUniqueAliases): + b_.PrependUint8Slot(43, any_unique_type, 0) + return this + def add_any_unique(any_unique:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(44, any_unique) + return this + def add_any_ambiguous_type(any_ambiguous_type:AnyAmbiguousAliases): + b_.PrependUint8Slot(45, any_ambiguous_type, 0) + return this + def add_any_ambiguous(any_ambiguous:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(46, any_ambiguous) + return this + def add_vector_of_enums(vector_of_enums:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(47, vector_of_enums) + return this + def add_signed_enum(signed_enum:Race): + b_.PrependInt8Slot(48, signed_enum, -1) + return this + def add_testrequirednestedflatbuffer(testrequirednestedflatbuffer:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(49, testrequirednestedflatbuffer) + return this + def add_scalar_key_sorted_tables(scalar_key_sorted_tables:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(50, scalar_key_sorted_tables) + return this + def add_native_inline(native_inline:flatbuffers.offset): + b_.PrependStructSlot(51, native_inline) + return this + def add_long_enum_non_enum_default(long_enum_non_enum_default:LongEnum): + b_.PrependUint64Slot(52, long_enum_non_enum_default, 0) + return this + def add_long_enum_normal_default(long_enum_normal_default:LongEnum): + b_.PrependUint64Slot(53, long_enum_normal_default, 2) + return this + def add_nan_default(nan_default:float): + b_.PrependFloat32Slot(54, nan_default, nan) + return this + def add_inf_default(inf_default:float): + b_.PrependFloat32Slot(55, inf_default, inf) + return this + def add_positive_inf_default(positive_inf_default:float): + b_.PrependFloat32Slot(56, positive_inf_default, +inf) + return this + def add_infinity_default(infinity_default:float): + b_.PrependFloat32Slot(57, infinity_default, infinity) + return this + def add_positive_infinity_default(positive_infinity_default:float): + b_.PrependFloat32Slot(58, positive_infinity_default, +infinity) + return this + def add_negative_inf_default(negative_inf_default:float): + b_.PrependFloat32Slot(59, negative_inf_default, -inf) + return this + def add_negative_infinity_default(negative_infinity_default:float): + b_.PrependFloat32Slot(60, negative_infinity_default, -infinity) + return this + def add_double_inf_default(double_inf_default:float): + b_.PrependFloat64Slot(61, double_inf_default, inf) + return this + def end(): + return b_.EndObject() + +def MonsterStartInventoryVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def MonsterCreateInventoryVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependUint8(e_) + return b_.EndVector(v_.length) + +def MonsterStartTest4Vector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 2) + +def MonsterStartTestarrayofstringVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def MonsterCreateTestarrayofstringVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + +def MonsterStartTestarrayoftablesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def MonsterCreateTestarrayoftablesVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + +def MonsterStartTestnestedflatbufferVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def MonsterCreateTestnestedflatbufferVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependUint8(e_) + return b_.EndVector(v_.length) + +def MonsterStartTestarrayofboolsVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def MonsterCreateTestarrayofboolsVector(b_:flatbuffers.builder, v_:[bool]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependBool(e_) + return b_.EndVector(v_.length) + +def MonsterStartTestarrayofstring2Vector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def MonsterCreateTestarrayofstring2Vector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + +def MonsterStartTestarrayofsortedstructVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 4) + +def MonsterStartFlexVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def MonsterCreateFlexVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependUint8(e_) + return b_.EndVector(v_.length) + +def MonsterStartTest5Vector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 2) + +def MonsterStartVectorOfLongsVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 8) +def MonsterCreateVectorOfLongsVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(8, v_.length, 8) + reverse(v_) e_: b_.PrependInt64(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfDoublesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 8) +def MonsterCreateVectorOfDoublesVector(b_:flatbuffers.builder, v_:[float]): + b_.StartVector(8, v_.length, 8) + reverse(v_) e_: b_.PrependFloat64(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfReferrablesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def MonsterCreateVectorOfReferrablesVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfWeakReferencesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 8) +def MonsterCreateVectorOfWeakReferencesVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(8, v_.length, 8) + reverse(v_) e_: b_.PrependUint64(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfStrongReferrablesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def MonsterCreateVectorOfStrongReferrablesVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfCoOwningReferencesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 8) +def MonsterCreateVectorOfCoOwningReferencesVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(8, v_.length, 8) + reverse(v_) e_: b_.PrependUint64(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfNonOwningReferencesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 8) +def MonsterCreateVectorOfNonOwningReferencesVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(8, v_.length, 8) + reverse(v_) e_: b_.PrependUint64(e_) + return b_.EndVector(v_.length) + +def MonsterStartVectorOfEnumsVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def MonsterCreateVectorOfEnumsVector(b_:flatbuffers.builder, v_:[Color]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependUint8(e_) + return b_.EndVector(v_.length) + +def MonsterStartTestrequirednestedflatbufferVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def MonsterCreateTestrequirednestedflatbufferVector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependUint8(e_) + return b_.EndVector(v_.length) + +def MonsterStartScalarKeySortedTablesVector(b_:flatbuffers.builder, n_:int): + b_.StartVector(4, n_, 4) +def MonsterCreateScalarKeySortedTablesVector(b_:flatbuffers.builder, v_:[flatbuffers.offset]): + b_.StartVector(4, v_.length, 4) + reverse(v_) e_: b_.PrependUOffsetTRelative(e_) + return b_.EndVector(v_.length) + +class TypeAliases : flatbuffers.handle + def i8() -> int: + return flatbuffers.field_int8(buf_, pos_, 4, 0) + def u8() -> int: + return flatbuffers.field_uint8(buf_, pos_, 6, 0) + def i16() -> int: + return flatbuffers.field_int16(buf_, pos_, 8, 0) + def u16() -> int: + return flatbuffers.field_uint16(buf_, pos_, 10, 0) + def i32() -> int: + return flatbuffers.field_int32(buf_, pos_, 12, 0) + def u32() -> int: + return flatbuffers.field_uint32(buf_, pos_, 14, 0) + def i64() -> int: + return flatbuffers.field_int64(buf_, pos_, 16, 0) + def u64() -> int: + return flatbuffers.field_uint64(buf_, pos_, 18, 0) + def f32() -> float: + return flatbuffers.field_float32(buf_, pos_, 20, 0.0) + def f64() -> float: + return flatbuffers.field_float64(buf_, pos_, 22, 0.0) + def v8(i:int) -> int: + return read_int8_le(buf_, buf_.flatbuffers.field_vector(pos_, 24) + i * 1) + def v8_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 24) + def vf64(i:int) -> float: + return read_float64_le(buf_, buf_.flatbuffers.field_vector(pos_, 26) + i * 8) + def vf64_length() -> int: + return flatbuffers.field_vector_len(buf_, pos_, 26) + +def GetRootAsTypeAliases(buf:string): return TypeAliases { buf, flatbuffers.indirect(buf, 0) } + +struct TypeAliasesBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(12) + return this + def add_i8(i8:int): + b_.PrependInt8Slot(0, i8, 0) + return this + def add_u8(u8:int): + b_.PrependUint8Slot(1, u8, 0) + return this + def add_i16(i16:int): + b_.PrependInt16Slot(2, i16, 0) + return this + def add_u16(u16:int): + b_.PrependUint16Slot(3, u16, 0) + return this + def add_i32(i32:int): + b_.PrependInt32Slot(4, i32, 0) + return this + def add_u32(u32:int): + b_.PrependUint32Slot(5, u32, 0) + return this + def add_i64(i64:int): + b_.PrependInt64Slot(6, i64, 0) + return this + def add_u64(u64:int): + b_.PrependUint64Slot(7, u64, 0) + return this + def add_f32(f32:float): + b_.PrependFloat32Slot(8, f32, 0.0) + return this + def add_f64(f64:float): + b_.PrependFloat64Slot(9, f64, 0.0) + return this + def add_v8(v8:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(10, v8) + return this + def add_vf64(vf64:flatbuffers.offset): + b_.PrependUOffsetTRelativeSlot(11, vf64) + return this + def end(): + return b_.EndObject() + +def TypeAliasesStartV8Vector(b_:flatbuffers.builder, n_:int): + b_.StartVector(1, n_, 1) +def TypeAliasesCreateV8Vector(b_:flatbuffers.builder, v_:[int]): + b_.StartVector(1, v_.length, 1) + reverse(v_) e_: b_.PrependInt8(e_) + return b_.EndVector(v_.length) + +def TypeAliasesStartVf64Vector(b_:flatbuffers.builder, n_:int): + b_.StartVector(8, n_, 8) +def TypeAliasesCreateVf64Vector(b_:flatbuffers.builder, v_:[float]): + b_.StartVector(8, v_.length, 8) + reverse(v_) e_: b_.PrependFloat64(e_) + return b_.EndVector(v_.length) + diff --git a/third_party/flatbuffers/tests/monster_test_generated.py b/third_party/flatbuffers/tests/monster_test_generated.py new file mode 100644 index 00000000000..71139c65c06 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_generated.py @@ -0,0 +1,2807 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: Example + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +# Composite components of Monster color. +class Color(object): + Red = 1 + # \brief color Green + # Green is bit_flag with value (1u << 1) + Green = 2 + # \brief color Blue (1u << 3) + Blue = 8 + + +class Race(object): + None_ = -1 + Human = 0 + Dwarf = 1 + Elf = 2 + + +class LongEnum(object): + LongOne = 2 + LongTwo = 4 + LongBig = 1099511627776 + + +class Any(object): + NONE = 0 + Monster = 1 + TestSimpleTableWithEnum = 2 + MyGame_Example2_Monster = 3 + +def AnyCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == Any.Monster: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == Any.TestSimpleTableWithEnum: + return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + if unionType == Any.MyGame_Example2_Monster: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class AnyUniqueAliases(object): + NONE = 0 + M = 1 + TS = 2 + M2 = 3 + +def AnyUniqueAliasesCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == AnyUniqueAliases.M: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyUniqueAliases.TS: + return TestSimpleTableWithEnumT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyUniqueAliases.M2: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class AnyAmbiguousAliases(object): + NONE = 0 + M1 = 1 + M2 = 2 + M3 = 3 + +def AnyAmbiguousAliasesCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == AnyAmbiguousAliases.M1: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyAmbiguousAliases.M2: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + if unionType == AnyAmbiguousAliases.M3: + return MonsterT.InitFromBuf(table.Bytes, table.Pos) + return None + + +class InParentNamespace(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = InParentNamespace() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsInParentNamespace(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def InParentNamespaceBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # InParentNamespace + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def InParentNamespaceStart(builder): + builder.StartObject(0) + +def InParentNamespaceEnd(builder): + return builder.EndObject() + + + +class InParentNamespaceT(object): + + # InParentNamespaceT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + inParentNamespace = InParentNamespace() + inParentNamespace.Init(buf, pos) + return cls.InitFromObj(inParentNamespace) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, inParentNamespace): + x = InParentNamespaceT() + x._UnPack(inParentNamespace) + return x + + # InParentNamespaceT + def _UnPack(self, inParentNamespace): + if inParentNamespace is None: + return + + # InParentNamespaceT + def Pack(self, builder): + InParentNamespaceStart(builder) + inParentNamespace = InParentNamespaceEnd(builder) + return inParentNamespace + + +class Monster(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Monster() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMonster(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Monster + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + +def MonsterStart(builder): + builder.StartObject(0) + +def MonsterEnd(builder): + return builder.EndObject() + + + +class MonsterT(object): + + # MonsterT + def __init__(self): + pass + + @classmethod + def InitFromBuf(cls, buf, pos): + monster = Monster() + monster.Init(buf, pos) + return cls.InitFromObj(monster) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, monster): + x = MonsterT() + x._UnPack(monster) + return x + + # MonsterT + def _UnPack(self, monster): + if monster is None: + return + + # MonsterT + def Pack(self, builder): + MonsterStart(builder) + monster = MonsterEnd(builder) + return monster + + +class Test(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 4 + + # Test + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Test + def A(self): return self._tab.Get(flatbuffers.number_types.Int16Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Test + def B(self): return self._tab.Get(flatbuffers.number_types.Int8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(2)) + +def CreateTest(builder, a, b): + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b) + builder.PrependInt16(a) + return builder.Offset() + + +class TestT(object): + + # TestT + def __init__(self): + self.a = 0 # type: int + self.b = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + test = Test() + test.Init(buf, pos) + return cls.InitFromObj(test) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, test): + x = TestT() + x._UnPack(test) + return x + + # TestT + def _UnPack(self, test): + if test is None: + return + self.a = test.A() + self.b = test.B() + + # TestT + def Pack(self, builder): + return CreateTest(builder, self.a, self.b) + + +class TestSimpleTableWithEnum(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TestSimpleTableWithEnum() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTestSimpleTableWithEnum(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TestSimpleTableWithEnumBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # TestSimpleTableWithEnum + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TestSimpleTableWithEnum + def Color(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 2 + +def TestSimpleTableWithEnumStart(builder): + builder.StartObject(1) + +def TestSimpleTableWithEnumAddColor(builder, color): + builder.PrependUint8Slot(0, color, 2) + +def TestSimpleTableWithEnumEnd(builder): + return builder.EndObject() + + + +class TestSimpleTableWithEnumT(object): + + # TestSimpleTableWithEnumT + def __init__(self): + self.color = 2 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + testSimpleTableWithEnum = TestSimpleTableWithEnum() + testSimpleTableWithEnum.Init(buf, pos) + return cls.InitFromObj(testSimpleTableWithEnum) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, testSimpleTableWithEnum): + x = TestSimpleTableWithEnumT() + x._UnPack(testSimpleTableWithEnum) + return x + + # TestSimpleTableWithEnumT + def _UnPack(self, testSimpleTableWithEnum): + if testSimpleTableWithEnum is None: + return + self.color = testSimpleTableWithEnum.Color() + + # TestSimpleTableWithEnumT + def Pack(self, builder): + TestSimpleTableWithEnumStart(builder) + TestSimpleTableWithEnumAddColor(builder, self.color) + testSimpleTableWithEnum = TestSimpleTableWithEnumEnd(builder) + return testSimpleTableWithEnum + + +class Vec3(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 32 + + # Vec3 + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Vec3 + def X(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Vec3 + def Y(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4)) + # Vec3 + def Z(self): return self._tab.Get(flatbuffers.number_types.Float32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(8)) + # Vec3 + def Test1(self): return self._tab.Get(flatbuffers.number_types.Float64Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(16)) + # Vec3 + def Test2(self): return self._tab.Get(flatbuffers.number_types.Uint8Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(24)) + # Vec3 + def Test3(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 26) + return obj + + +def CreateVec3(builder, x, y, z, test1, test2, test3_a, test3_b): + builder.Prep(8, 32) + builder.Pad(2) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(test3_b) + builder.PrependInt16(test3_a) + builder.Pad(1) + builder.PrependUint8(test2) + builder.PrependFloat64(test1) + builder.Pad(4) + builder.PrependFloat32(z) + builder.PrependFloat32(y) + builder.PrependFloat32(x) + return builder.Offset() + +try: + from typing import Optional +except: + pass + +class Vec3T(object): + + # Vec3T + def __init__(self): + self.x = 0.0 # type: float + self.y = 0.0 # type: float + self.z = 0.0 # type: float + self.test1 = 0.0 # type: float + self.test2 = 0 # type: int + self.test3 = None # type: Optional[TestT] + + @classmethod + def InitFromBuf(cls, buf, pos): + vec3 = Vec3() + vec3.Init(buf, pos) + return cls.InitFromObj(vec3) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, vec3): + x = Vec3T() + x._UnPack(vec3) + return x + + # Vec3T + def _UnPack(self, vec3): + if vec3 is None: + return + self.x = vec3.X() + self.y = vec3.Y() + self.z = vec3.Z() + self.test1 = vec3.Test1() + self.test2 = vec3.Test2() + if vec3.Test3(Test()) is not None: + self.test3 = TestT.InitFromObj(vec3.Test3(Test())) + + # Vec3T + def Pack(self, builder): + return CreateVec3(builder, self.x, self.y, self.z, self.test1, self.test2, self.test3.a, self.test3.b) + + +class Ability(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 8 + + # Ability + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Ability + def Id(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # Ability + def Distance(self): return self._tab.Get(flatbuffers.number_types.Uint32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4)) + +def CreateAbility(builder, id, distance): + builder.Prep(4, 8) + builder.PrependUint32(distance) + builder.PrependUint32(id) + return builder.Offset() + + +class AbilityT(object): + + # AbilityT + def __init__(self): + self.id = 0 # type: int + self.distance = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + ability = Ability() + ability.Init(buf, pos) + return cls.InitFromObj(ability) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, ability): + x = AbilityT() + x._UnPack(ability) + return x + + # AbilityT + def _UnPack(self, ability): + if ability is None: + return + self.id = ability.Id() + self.distance = ability.Distance() + + # AbilityT + def Pack(self, builder): + return CreateAbility(builder, self.id, self.distance) + + +class StructOfStructs(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 20 + + # StructOfStructs + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StructOfStructs + def A(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 0) + return obj + + # StructOfStructs + def B(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 8) + return obj + + # StructOfStructs + def C(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 12) + return obj + + +def CreateStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance): + builder.Prep(4, 20) + builder.Prep(4, 8) + builder.PrependUint32(c_distance) + builder.PrependUint32(c_id) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(b_b) + builder.PrependInt16(b_a) + builder.Prep(4, 8) + builder.PrependUint32(a_distance) + builder.PrependUint32(a_id) + return builder.Offset() + +try: + from typing import Optional +except: + pass + +class StructOfStructsT(object): + + # StructOfStructsT + def __init__(self): + self.a = None # type: Optional[AbilityT] + self.b = None # type: Optional[TestT] + self.c = None # type: Optional[AbilityT] + + @classmethod + def InitFromBuf(cls, buf, pos): + structOfStructs = StructOfStructs() + structOfStructs.Init(buf, pos) + return cls.InitFromObj(structOfStructs) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, structOfStructs): + x = StructOfStructsT() + x._UnPack(structOfStructs) + return x + + # StructOfStructsT + def _UnPack(self, structOfStructs): + if structOfStructs is None: + return + if structOfStructs.A(Ability()) is not None: + self.a = AbilityT.InitFromObj(structOfStructs.A(Ability())) + if structOfStructs.B(Test()) is not None: + self.b = TestT.InitFromObj(structOfStructs.B(Test())) + if structOfStructs.C(Ability()) is not None: + self.c = AbilityT.InitFromObj(structOfStructs.C(Ability())) + + # StructOfStructsT + def Pack(self, builder): + return CreateStructOfStructs(builder, self.a.id, self.a.distance, self.b.a, self.b.b, self.c.id, self.c.distance) + + +class StructOfStructsOfStructs(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 20 + + # StructOfStructsOfStructs + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StructOfStructsOfStructs + def A(self, obj): + obj.Init(self._tab.Bytes, self._tab.Pos + 0) + return obj + + +def CreateStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, a_c_id, a_c_distance): + builder.Prep(4, 20) + builder.Prep(4, 20) + builder.Prep(4, 8) + builder.PrependUint32(a_c_distance) + builder.PrependUint32(a_c_id) + builder.Prep(2, 4) + builder.Pad(1) + builder.PrependInt8(a_b_b) + builder.PrependInt16(a_b_a) + builder.Prep(4, 8) + builder.PrependUint32(a_a_distance) + builder.PrependUint32(a_a_id) + return builder.Offset() + +try: + from typing import Optional +except: + pass + +class StructOfStructsOfStructsT(object): + + # StructOfStructsOfStructsT + def __init__(self): + self.a = None # type: Optional[StructOfStructsT] + + @classmethod + def InitFromBuf(cls, buf, pos): + structOfStructsOfStructs = StructOfStructsOfStructs() + structOfStructsOfStructs.Init(buf, pos) + return cls.InitFromObj(structOfStructsOfStructs) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, structOfStructsOfStructs): + x = StructOfStructsOfStructsT() + x._UnPack(structOfStructsOfStructs) + return x + + # StructOfStructsOfStructsT + def _UnPack(self, structOfStructsOfStructs): + if structOfStructsOfStructs is None: + return + if structOfStructsOfStructs.A(StructOfStructs()) is not None: + self.a = StructOfStructsT.InitFromObj(structOfStructsOfStructs.A(StructOfStructs())) + + # StructOfStructsOfStructsT + def Pack(self, builder): + return CreateStructOfStructsOfStructs(builder, self.a.a.id, self.a.a.distance, self.a.b.a, self.a.b.b, self.a.c.id, self.a.c.distance) + + +class Stat(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Stat() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsStat(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def StatBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Stat + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Stat + def Id(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Stat + def Val(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Stat + def Count(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return 0 + +def StatStart(builder): + builder.StartObject(3) + +def StatAddId(builder, id): + builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(id), 0) + +def StatAddVal(builder, val): + builder.PrependInt64Slot(1, val, 0) + +def StatAddCount(builder, count): + builder.PrependUint16Slot(2, count, 0) + +def StatEnd(builder): + return builder.EndObject() + + + +class StatT(object): + + # StatT + def __init__(self): + self.id = None # type: str + self.val = 0 # type: int + self.count = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + stat = Stat() + stat.Init(buf, pos) + return cls.InitFromObj(stat) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, stat): + x = StatT() + x._UnPack(stat) + return x + + # StatT + def _UnPack(self, stat): + if stat is None: + return + self.id = stat.Id() + self.val = stat.Val() + self.count = stat.Count() + + # StatT + def Pack(self, builder): + if self.id is not None: + id = builder.CreateString(self.id) + StatStart(builder) + if self.id is not None: + StatAddId(builder, id) + StatAddVal(builder, self.val) + StatAddCount(builder, self.count) + stat = StatEnd(builder) + return stat + + +class Referrable(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Referrable() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsReferrable(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ReferrableBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Referrable + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Referrable + def Id(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + +def ReferrableStart(builder): + builder.StartObject(1) + +def ReferrableAddId(builder, id): + builder.PrependUint64Slot(0, id, 0) + +def ReferrableEnd(builder): + return builder.EndObject() + + + +class ReferrableT(object): + + # ReferrableT + def __init__(self): + self.id = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + referrable = Referrable() + referrable.Init(buf, pos) + return cls.InitFromObj(referrable) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, referrable): + x = ReferrableT() + x._UnPack(referrable) + return x + + # ReferrableT + def _UnPack(self, referrable): + if referrable is None: + return + self.id = referrable.Id() + + # ReferrableT + def Pack(self, builder): + ReferrableStart(builder) + ReferrableAddId(builder, self.id) + referrable = ReferrableEnd(builder) + return referrable + + +# an example documentation comment: "monster object" +class Monster(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = Monster() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsMonster(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def MonsterBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # Monster + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # Monster + def Pos(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = o + self._tab.Pos + obj = Vec3() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Mana(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 150 + + # Monster + def Hp(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 100 + + # Monster + def Name(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.String(o + self._tab.Pos) + return None + + # Monster + def Inventory(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def InventoryAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def InventoryLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def InventoryIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + return o == 0 + + # Monster + def Color(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 8 + + # Monster + def TestType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Monster + def Test(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Monster + def Test4(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Test4Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def Test4IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + return o == 0 + + # Monster + def Testarrayofstring(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Monster + def TestarrayofstringLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayofstringIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # an example documentation comment: this will end up in the generated code + # multiline too + # Monster + def Testarrayoftables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Monster() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def TestarrayoftablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayoftablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + return o == 0 + + # Monster + def Enemy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = Monster() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Testnestedflatbuffer(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def TestnestedflatbufferAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def TestnestedflatbufferNestedRoot(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + from MyGame.Example.Monster import Monster + return Monster.GetRootAs(self._tab.Bytes, self._tab.Vector(o)) + return 0 + + # Monster + def TestnestedflatbufferLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestnestedflatbufferIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + return o == 0 + + # Monster + def Testempty(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(32)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = Stat() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Testbool(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(34)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # Monster + def Testhashs32Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu32Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(38)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashs64Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(40)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu64Fnv1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(42)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashs32Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(44)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu32Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(46)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashs64Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(48)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testhashu64Fnv1a(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(50)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def Testarrayofbools(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.BoolFlags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def TestarrayofboolsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.BoolFlags, o) + return 0 + + # Monster + def TestarrayofboolsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayofboolsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + return o == 0 + + # Monster + def Testf(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(54)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 3.14159 + + # Monster + def Testf2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(56)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 3.0 + + # Monster + def Testf3(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(58)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # Monster + def Testarrayofstring2(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.String(a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 4)) + return "" + + # Monster + def Testarrayofstring2Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def Testarrayofstring2IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + return o == 0 + + # Monster + def Testarrayofsortedstruct(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 8 + obj = Ability() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def TestarrayofsortedstructLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestarrayofsortedstructIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + return o == 0 + + # Monster + def Flex(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def FlexAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def FlexLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def FlexIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + return o == 0 + + # Monster + def Test5(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def Test5Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def Test5IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + return o == 0 + + # Monster + def VectorOfLongs(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfLongsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int64Flags, o) + return 0 + + # Monster + def VectorOfLongsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfLongsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + return o == 0 + + # Monster + def VectorOfDoubles(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfDoublesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o) + return 0 + + # Monster + def VectorOfDoublesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfDoublesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + return o == 0 + + # Monster + def ParentNamespaceTest(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(72)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = InParentNamespace() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def VectorOfReferrables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Referrable() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def VectorOfReferrablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfReferrablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + return o == 0 + + # Monster + def SingleWeakReference(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(76)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def VectorOfWeakReferences(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfWeakReferencesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # Monster + def VectorOfWeakReferencesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfWeakReferencesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(78)) + return o == 0 + + # Monster + def VectorOfStrongReferrables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Referrable() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def VectorOfStrongReferrablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfStrongReferrablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(80)) + return o == 0 + + # Monster + def CoOwningReference(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(82)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def VectorOfCoOwningReferences(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfCoOwningReferencesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # Monster + def VectorOfCoOwningReferencesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfCoOwningReferencesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(84)) + return o == 0 + + # Monster + def NonOwningReference(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(86)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def VectorOfNonOwningReferences(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # Monster + def VectorOfNonOwningReferencesAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint64Flags, o) + return 0 + + # Monster + def VectorOfNonOwningReferencesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfNonOwningReferencesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(88)) + return o == 0 + + # Monster + def AnyUniqueType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(90)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Monster + def AnyUnique(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(92)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Monster + def AnyAmbiguousType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(94)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # Monster + def AnyAmbiguous(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(96)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # Monster + def VectorOfEnums(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def VectorOfEnumsAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def VectorOfEnumsLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def VectorOfEnumsIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(98)) + return o == 0 + + # Monster + def SignedEnum(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(100)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return -1 + + # Monster + def Testrequirednestedflatbuffer(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Uint8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # Monster + def TestrequirednestedflatbufferAsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Uint8Flags, o) + return 0 + + # Monster + def TestrequirednestedflatbufferNestedRoot(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + from MyGame.Example.Monster import Monster + return Monster.GetRootAs(self._tab.Bytes, self._tab.Vector(o)) + return 0 + + # Monster + def TestrequirednestedflatbufferLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def TestrequirednestedflatbufferIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(102)) + return o == 0 + + # Monster + def ScalarKeySortedTables(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104)) + if o != 0: + x = self._tab.Vector(o) + x += flatbuffers.number_types.UOffsetTFlags.py_type(j) * 4 + x = self._tab.Indirect(x) + obj = Stat() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def ScalarKeySortedTablesLength(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # Monster + def ScalarKeySortedTablesIsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(104)) + return o == 0 + + # Monster + def NativeInline(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(106)) + if o != 0: + x = o + self._tab.Pos + obj = Test() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # Monster + def LongEnumNonEnumDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(108)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # Monster + def LongEnumNormalDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(110)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 2 + + # Monster + def NanDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(112)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('nan') + + # Monster + def InfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(114)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def PositiveInfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(116)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def InfinityDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(118)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def PositiveInfinityDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(120)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('inf') + + # Monster + def NegativeInfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(122)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('-inf') + + # Monster + def NegativeInfinityDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(124)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return float('-inf') + + # Monster + def DoubleInfDefault(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(126)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return float('inf') + +def MonsterStart(builder): + builder.StartObject(62) + +def MonsterAddPos(builder, pos): + builder.PrependStructSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(pos), 0) + +def MonsterAddMana(builder, mana): + builder.PrependInt16Slot(1, mana, 150) + +def MonsterAddHp(builder, hp): + builder.PrependInt16Slot(2, hp, 100) + +def MonsterAddName(builder, name): + builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(name), 0) + +def MonsterAddInventory(builder, inventory): + builder.PrependUOffsetTRelativeSlot(5, flatbuffers.number_types.UOffsetTFlags.py_type(inventory), 0) + +def MonsterStartInventoryVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def MonsterAddColor(builder, color): + builder.PrependUint8Slot(6, color, 8) + +def MonsterAddTestType(builder, testType): + builder.PrependUint8Slot(7, testType, 0) + +def MonsterAddTest(builder, test): + builder.PrependUOffsetTRelativeSlot(8, flatbuffers.number_types.UOffsetTFlags.py_type(test), 0) + +def MonsterAddTest4(builder, test4): + builder.PrependUOffsetTRelativeSlot(9, flatbuffers.number_types.UOffsetTFlags.py_type(test4), 0) + +def MonsterStartTest4Vector(builder, numElems): + return builder.StartVector(4, numElems, 2) + +def MonsterAddTestarrayofstring(builder, testarrayofstring): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring), 0) + +def MonsterStartTestarrayofstringVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def MonsterAddTestarrayoftables(builder, testarrayoftables): + builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayoftables), 0) + +def MonsterStartTestarrayoftablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def MonsterAddEnemy(builder, enemy): + builder.PrependUOffsetTRelativeSlot(12, flatbuffers.number_types.UOffsetTFlags.py_type(enemy), 0) + +def MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer): + builder.PrependUOffsetTRelativeSlot(13, flatbuffers.number_types.UOffsetTFlags.py_type(testnestedflatbuffer), 0) + +def MonsterStartTestnestedflatbufferVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def MonsterMakeTestnestedflatbufferVectorFromBytes(builder, bytes): + builder.StartVector(1, len(bytes), 1) + builder.head = builder.head - len(bytes) + builder.Bytes[builder.head : builder.head + len(bytes)] = bytes + return builder.EndVector() +def MonsterAddTestempty(builder, testempty): + builder.PrependUOffsetTRelativeSlot(14, flatbuffers.number_types.UOffsetTFlags.py_type(testempty), 0) + +def MonsterAddTestbool(builder, testbool): + builder.PrependBoolSlot(15, testbool, 0) + +def MonsterAddTesthashs32Fnv1(builder, testhashs32Fnv1): + builder.PrependInt32Slot(16, testhashs32Fnv1, 0) + +def MonsterAddTesthashu32Fnv1(builder, testhashu32Fnv1): + builder.PrependUint32Slot(17, testhashu32Fnv1, 0) + +def MonsterAddTesthashs64Fnv1(builder, testhashs64Fnv1): + builder.PrependInt64Slot(18, testhashs64Fnv1, 0) + +def MonsterAddTesthashu64Fnv1(builder, testhashu64Fnv1): + builder.PrependUint64Slot(19, testhashu64Fnv1, 0) + +def MonsterAddTesthashs32Fnv1a(builder, testhashs32Fnv1a): + builder.PrependInt32Slot(20, testhashs32Fnv1a, 0) + +def MonsterAddTesthashu32Fnv1a(builder, testhashu32Fnv1a): + builder.PrependUint32Slot(21, testhashu32Fnv1a, 0) + +def MonsterAddTesthashs64Fnv1a(builder, testhashs64Fnv1a): + builder.PrependInt64Slot(22, testhashs64Fnv1a, 0) + +def MonsterAddTesthashu64Fnv1a(builder, testhashu64Fnv1a): + builder.PrependUint64Slot(23, testhashu64Fnv1a, 0) + +def MonsterAddTestarrayofbools(builder, testarrayofbools): + builder.PrependUOffsetTRelativeSlot(24, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofbools), 0) + +def MonsterStartTestarrayofboolsVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def MonsterAddTestf(builder, testf): + builder.PrependFloat32Slot(25, testf, 3.14159) + +def MonsterAddTestf2(builder, testf2): + builder.PrependFloat32Slot(26, testf2, 3.0) + +def MonsterAddTestf3(builder, testf3): + builder.PrependFloat32Slot(27, testf3, 0.0) + +def MonsterAddTestarrayofstring2(builder, testarrayofstring2): + builder.PrependUOffsetTRelativeSlot(28, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofstring2), 0) + +def MonsterStartTestarrayofstring2Vector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct): + builder.PrependUOffsetTRelativeSlot(29, flatbuffers.number_types.UOffsetTFlags.py_type(testarrayofsortedstruct), 0) + +def MonsterStartTestarrayofsortedstructVector(builder, numElems): + return builder.StartVector(8, numElems, 4) + +def MonsterAddFlex(builder, flex): + builder.PrependUOffsetTRelativeSlot(30, flatbuffers.number_types.UOffsetTFlags.py_type(flex), 0) + +def MonsterStartFlexVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def MonsterAddTest5(builder, test5): + builder.PrependUOffsetTRelativeSlot(31, flatbuffers.number_types.UOffsetTFlags.py_type(test5), 0) + +def MonsterStartTest5Vector(builder, numElems): + return builder.StartVector(4, numElems, 2) + +def MonsterAddVectorOfLongs(builder, vectorOfLongs): + builder.PrependUOffsetTRelativeSlot(32, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfLongs), 0) + +def MonsterStartVectorOfLongsVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def MonsterAddVectorOfDoubles(builder, vectorOfDoubles): + builder.PrependUOffsetTRelativeSlot(33, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfDoubles), 0) + +def MonsterStartVectorOfDoublesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def MonsterAddParentNamespaceTest(builder, parentNamespaceTest): + builder.PrependUOffsetTRelativeSlot(34, flatbuffers.number_types.UOffsetTFlags.py_type(parentNamespaceTest), 0) + +def MonsterAddVectorOfReferrables(builder, vectorOfReferrables): + builder.PrependUOffsetTRelativeSlot(35, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfReferrables), 0) + +def MonsterStartVectorOfReferrablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def MonsterAddSingleWeakReference(builder, singleWeakReference): + builder.PrependUint64Slot(36, singleWeakReference, 0) + +def MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences): + builder.PrependUOffsetTRelativeSlot(37, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfWeakReferences), 0) + +def MonsterStartVectorOfWeakReferencesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables): + builder.PrependUOffsetTRelativeSlot(38, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfStrongReferrables), 0) + +def MonsterStartVectorOfStrongReferrablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def MonsterAddCoOwningReference(builder, coOwningReference): + builder.PrependUint64Slot(39, coOwningReference, 0) + +def MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences): + builder.PrependUOffsetTRelativeSlot(40, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfCoOwningReferences), 0) + +def MonsterStartVectorOfCoOwningReferencesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def MonsterAddNonOwningReference(builder, nonOwningReference): + builder.PrependUint64Slot(41, nonOwningReference, 0) + +def MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences): + builder.PrependUOffsetTRelativeSlot(42, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfNonOwningReferences), 0) + +def MonsterStartVectorOfNonOwningReferencesVector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def MonsterAddAnyUniqueType(builder, anyUniqueType): + builder.PrependUint8Slot(43, anyUniqueType, 0) + +def MonsterAddAnyUnique(builder, anyUnique): + builder.PrependUOffsetTRelativeSlot(44, flatbuffers.number_types.UOffsetTFlags.py_type(anyUnique), 0) + +def MonsterAddAnyAmbiguousType(builder, anyAmbiguousType): + builder.PrependUint8Slot(45, anyAmbiguousType, 0) + +def MonsterAddAnyAmbiguous(builder, anyAmbiguous): + builder.PrependUOffsetTRelativeSlot(46, flatbuffers.number_types.UOffsetTFlags.py_type(anyAmbiguous), 0) + +def MonsterAddVectorOfEnums(builder, vectorOfEnums): + builder.PrependUOffsetTRelativeSlot(47, flatbuffers.number_types.UOffsetTFlags.py_type(vectorOfEnums), 0) + +def MonsterStartVectorOfEnumsVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def MonsterAddSignedEnum(builder, signedEnum): + builder.PrependInt8Slot(48, signedEnum, -1) + +def MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer): + builder.PrependUOffsetTRelativeSlot(49, flatbuffers.number_types.UOffsetTFlags.py_type(testrequirednestedflatbuffer), 0) + +def MonsterStartTestrequirednestedflatbufferVector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def MonsterMakeTestrequirednestedflatbufferVectorFromBytes(builder, bytes): + builder.StartVector(1, len(bytes), 1) + builder.head = builder.head - len(bytes) + builder.Bytes[builder.head : builder.head + len(bytes)] = bytes + return builder.EndVector() +def MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables): + builder.PrependUOffsetTRelativeSlot(50, flatbuffers.number_types.UOffsetTFlags.py_type(scalarKeySortedTables), 0) + +def MonsterStartScalarKeySortedTablesVector(builder, numElems): + return builder.StartVector(4, numElems, 4) + +def MonsterAddNativeInline(builder, nativeInline): + builder.PrependStructSlot(51, flatbuffers.number_types.UOffsetTFlags.py_type(nativeInline), 0) + +def MonsterAddLongEnumNonEnumDefault(builder, longEnumNonEnumDefault): + builder.PrependUint64Slot(52, longEnumNonEnumDefault, 0) + +def MonsterAddLongEnumNormalDefault(builder, longEnumNormalDefault): + builder.PrependUint64Slot(53, longEnumNormalDefault, 2) + +def MonsterAddNanDefault(builder, nanDefault): + builder.PrependFloat32Slot(54, nanDefault, float('nan')) + +def MonsterAddInfDefault(builder, infDefault): + builder.PrependFloat32Slot(55, infDefault, float('inf')) + +def MonsterAddPositiveInfDefault(builder, positiveInfDefault): + builder.PrependFloat32Slot(56, positiveInfDefault, float('inf')) + +def MonsterAddInfinityDefault(builder, infinityDefault): + builder.PrependFloat32Slot(57, infinityDefault, float('inf')) + +def MonsterAddPositiveInfinityDefault(builder, positiveInfinityDefault): + builder.PrependFloat32Slot(58, positiveInfinityDefault, float('inf')) + +def MonsterAddNegativeInfDefault(builder, negativeInfDefault): + builder.PrependFloat32Slot(59, negativeInfDefault, float('-inf')) + +def MonsterAddNegativeInfinityDefault(builder, negativeInfinityDefault): + builder.PrependFloat32Slot(60, negativeInfinityDefault, float('-inf')) + +def MonsterAddDoubleInfDefault(builder, doubleInfDefault): + builder.PrependFloat64Slot(61, doubleInfDefault, float('inf')) + +def MonsterEnd(builder): + return builder.EndObject() + + +try: + from typing import List, Optional, Union +except: + pass + +class MonsterT(object): + + # MonsterT + def __init__(self): + self.pos = None # type: Optional[Vec3T] + self.mana = 150 # type: int + self.hp = 100 # type: int + self.name = None # type: str + self.inventory = None # type: List[int] + self.color = 8 # type: int + self.testType = 0 # type: int + self.test = None # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT] + self.test4 = None # type: List[TestT] + self.testarrayofstring = None # type: List[str] + self.testarrayoftables = None # type: List[MonsterT] + self.enemy = None # type: Optional[MonsterT] + self.testnestedflatbuffer = None # type: List[int] + self.testempty = None # type: Optional[StatT] + self.testbool = False # type: bool + self.testhashs32Fnv1 = 0 # type: int + self.testhashu32Fnv1 = 0 # type: int + self.testhashs64Fnv1 = 0 # type: int + self.testhashu64Fnv1 = 0 # type: int + self.testhashs32Fnv1a = 0 # type: int + self.testhashu32Fnv1a = 0 # type: int + self.testhashs64Fnv1a = 0 # type: int + self.testhashu64Fnv1a = 0 # type: int + self.testarrayofbools = None # type: List[bool] + self.testf = 3.14159 # type: float + self.testf2 = 3.0 # type: float + self.testf3 = 0.0 # type: float + self.testarrayofstring2 = None # type: List[str] + self.testarrayofsortedstruct = None # type: List[AbilityT] + self.flex = None # type: List[int] + self.test5 = None # type: List[TestT] + self.vectorOfLongs = None # type: List[int] + self.vectorOfDoubles = None # type: List[float] + self.parentNamespaceTest = None # type: Optional[InParentNamespaceT] + self.vectorOfReferrables = None # type: List[ReferrableT] + self.singleWeakReference = 0 # type: int + self.vectorOfWeakReferences = None # type: List[int] + self.vectorOfStrongReferrables = None # type: List[ReferrableT] + self.coOwningReference = 0 # type: int + self.vectorOfCoOwningReferences = None # type: List[int] + self.nonOwningReference = 0 # type: int + self.vectorOfNonOwningReferences = None # type: List[int] + self.anyUniqueType = 0 # type: int + self.anyUnique = None # type: Union[None, MonsterT, TestSimpleTableWithEnumT, MonsterT] + self.anyAmbiguousType = 0 # type: int + self.anyAmbiguous = None # type: Union[None, MonsterT, MonsterT, MonsterT] + self.vectorOfEnums = None # type: List[int] + self.signedEnum = -1 # type: int + self.testrequirednestedflatbuffer = None # type: List[int] + self.scalarKeySortedTables = None # type: List[StatT] + self.nativeInline = None # type: Optional[TestT] + self.longEnumNonEnumDefault = 0 # type: int + self.longEnumNormalDefault = 2 # type: int + self.nanDefault = float('nan') # type: float + self.infDefault = float('inf') # type: float + self.positiveInfDefault = float('inf') # type: float + self.infinityDefault = float('inf') # type: float + self.positiveInfinityDefault = float('inf') # type: float + self.negativeInfDefault = float('-inf') # type: float + self.negativeInfinityDefault = float('-inf') # type: float + self.doubleInfDefault = float('inf') # type: float + + @classmethod + def InitFromBuf(cls, buf, pos): + monster = Monster() + monster.Init(buf, pos) + return cls.InitFromObj(monster) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, monster): + x = MonsterT() + x._UnPack(monster) + return x + + # MonsterT + def _UnPack(self, monster): + if monster is None: + return + if monster.Pos() is not None: + self.pos = Vec3T.InitFromObj(monster.Pos()) + self.mana = monster.Mana() + self.hp = monster.Hp() + self.name = monster.Name() + if not monster.InventoryIsNone(): + if np is None: + self.inventory = [] + for i in range(monster.InventoryLength()): + self.inventory.append(monster.Inventory(i)) + else: + self.inventory = monster.InventoryAsNumpy() + self.color = monster.Color() + self.testType = monster.TestType() + self.test = AnyCreator(self.testType, monster.Test()) + if not monster.Test4IsNone(): + self.test4 = [] + for i in range(monster.Test4Length()): + if monster.Test4(i) is None: + self.test4.append(None) + else: + test_ = TestT.InitFromObj(monster.Test4(i)) + self.test4.append(test_) + if not monster.TestarrayofstringIsNone(): + self.testarrayofstring = [] + for i in range(monster.TestarrayofstringLength()): + self.testarrayofstring.append(monster.Testarrayofstring(i)) + if not monster.TestarrayoftablesIsNone(): + self.testarrayoftables = [] + for i in range(monster.TestarrayoftablesLength()): + if monster.Testarrayoftables(i) is None: + self.testarrayoftables.append(None) + else: + monster_ = MonsterT.InitFromObj(monster.Testarrayoftables(i)) + self.testarrayoftables.append(monster_) + if monster.Enemy() is not None: + self.enemy = MonsterT.InitFromObj(monster.Enemy()) + if not monster.TestnestedflatbufferIsNone(): + if np is None: + self.testnestedflatbuffer = [] + for i in range(monster.TestnestedflatbufferLength()): + self.testnestedflatbuffer.append(monster.Testnestedflatbuffer(i)) + else: + self.testnestedflatbuffer = monster.TestnestedflatbufferAsNumpy() + if monster.Testempty() is not None: + self.testempty = StatT.InitFromObj(monster.Testempty()) + self.testbool = monster.Testbool() + self.testhashs32Fnv1 = monster.Testhashs32Fnv1() + self.testhashu32Fnv1 = monster.Testhashu32Fnv1() + self.testhashs64Fnv1 = monster.Testhashs64Fnv1() + self.testhashu64Fnv1 = monster.Testhashu64Fnv1() + self.testhashs32Fnv1a = monster.Testhashs32Fnv1a() + self.testhashu32Fnv1a = monster.Testhashu32Fnv1a() + self.testhashs64Fnv1a = monster.Testhashs64Fnv1a() + self.testhashu64Fnv1a = monster.Testhashu64Fnv1a() + if not monster.TestarrayofboolsIsNone(): + if np is None: + self.testarrayofbools = [] + for i in range(monster.TestarrayofboolsLength()): + self.testarrayofbools.append(monster.Testarrayofbools(i)) + else: + self.testarrayofbools = monster.TestarrayofboolsAsNumpy() + self.testf = monster.Testf() + self.testf2 = monster.Testf2() + self.testf3 = monster.Testf3() + if not monster.Testarrayofstring2IsNone(): + self.testarrayofstring2 = [] + for i in range(monster.Testarrayofstring2Length()): + self.testarrayofstring2.append(monster.Testarrayofstring2(i)) + if not monster.TestarrayofsortedstructIsNone(): + self.testarrayofsortedstruct = [] + for i in range(monster.TestarrayofsortedstructLength()): + if monster.Testarrayofsortedstruct(i) is None: + self.testarrayofsortedstruct.append(None) + else: + ability_ = AbilityT.InitFromObj(monster.Testarrayofsortedstruct(i)) + self.testarrayofsortedstruct.append(ability_) + if not monster.FlexIsNone(): + if np is None: + self.flex = [] + for i in range(monster.FlexLength()): + self.flex.append(monster.Flex(i)) + else: + self.flex = monster.FlexAsNumpy() + if not monster.Test5IsNone(): + self.test5 = [] + for i in range(monster.Test5Length()): + if monster.Test5(i) is None: + self.test5.append(None) + else: + test_ = TestT.InitFromObj(monster.Test5(i)) + self.test5.append(test_) + if not monster.VectorOfLongsIsNone(): + if np is None: + self.vectorOfLongs = [] + for i in range(monster.VectorOfLongsLength()): + self.vectorOfLongs.append(monster.VectorOfLongs(i)) + else: + self.vectorOfLongs = monster.VectorOfLongsAsNumpy() + if not monster.VectorOfDoublesIsNone(): + if np is None: + self.vectorOfDoubles = [] + for i in range(monster.VectorOfDoublesLength()): + self.vectorOfDoubles.append(monster.VectorOfDoubles(i)) + else: + self.vectorOfDoubles = monster.VectorOfDoublesAsNumpy() + if monster.ParentNamespaceTest() is not None: + self.parentNamespaceTest = InParentNamespaceT.InitFromObj(monster.ParentNamespaceTest()) + if not monster.VectorOfReferrablesIsNone(): + self.vectorOfReferrables = [] + for i in range(monster.VectorOfReferrablesLength()): + if monster.VectorOfReferrables(i) is None: + self.vectorOfReferrables.append(None) + else: + referrable_ = ReferrableT.InitFromObj(monster.VectorOfReferrables(i)) + self.vectorOfReferrables.append(referrable_) + self.singleWeakReference = monster.SingleWeakReference() + if not monster.VectorOfWeakReferencesIsNone(): + if np is None: + self.vectorOfWeakReferences = [] + for i in range(monster.VectorOfWeakReferencesLength()): + self.vectorOfWeakReferences.append(monster.VectorOfWeakReferences(i)) + else: + self.vectorOfWeakReferences = monster.VectorOfWeakReferencesAsNumpy() + if not monster.VectorOfStrongReferrablesIsNone(): + self.vectorOfStrongReferrables = [] + for i in range(monster.VectorOfStrongReferrablesLength()): + if monster.VectorOfStrongReferrables(i) is None: + self.vectorOfStrongReferrables.append(None) + else: + referrable_ = ReferrableT.InitFromObj(monster.VectorOfStrongReferrables(i)) + self.vectorOfStrongReferrables.append(referrable_) + self.coOwningReference = monster.CoOwningReference() + if not monster.VectorOfCoOwningReferencesIsNone(): + if np is None: + self.vectorOfCoOwningReferences = [] + for i in range(monster.VectorOfCoOwningReferencesLength()): + self.vectorOfCoOwningReferences.append(monster.VectorOfCoOwningReferences(i)) + else: + self.vectorOfCoOwningReferences = monster.VectorOfCoOwningReferencesAsNumpy() + self.nonOwningReference = monster.NonOwningReference() + if not monster.VectorOfNonOwningReferencesIsNone(): + if np is None: + self.vectorOfNonOwningReferences = [] + for i in range(monster.VectorOfNonOwningReferencesLength()): + self.vectorOfNonOwningReferences.append(monster.VectorOfNonOwningReferences(i)) + else: + self.vectorOfNonOwningReferences = monster.VectorOfNonOwningReferencesAsNumpy() + self.anyUniqueType = monster.AnyUniqueType() + self.anyUnique = AnyUniqueAliasesCreator(self.anyUniqueType, monster.AnyUnique()) + self.anyAmbiguousType = monster.AnyAmbiguousType() + self.anyAmbiguous = AnyAmbiguousAliasesCreator(self.anyAmbiguousType, monster.AnyAmbiguous()) + if not monster.VectorOfEnumsIsNone(): + if np is None: + self.vectorOfEnums = [] + for i in range(monster.VectorOfEnumsLength()): + self.vectorOfEnums.append(monster.VectorOfEnums(i)) + else: + self.vectorOfEnums = monster.VectorOfEnumsAsNumpy() + self.signedEnum = monster.SignedEnum() + if not monster.TestrequirednestedflatbufferIsNone(): + if np is None: + self.testrequirednestedflatbuffer = [] + for i in range(monster.TestrequirednestedflatbufferLength()): + self.testrequirednestedflatbuffer.append(monster.Testrequirednestedflatbuffer(i)) + else: + self.testrequirednestedflatbuffer = monster.TestrequirednestedflatbufferAsNumpy() + if not monster.ScalarKeySortedTablesIsNone(): + self.scalarKeySortedTables = [] + for i in range(monster.ScalarKeySortedTablesLength()): + if monster.ScalarKeySortedTables(i) is None: + self.scalarKeySortedTables.append(None) + else: + stat_ = StatT.InitFromObj(monster.ScalarKeySortedTables(i)) + self.scalarKeySortedTables.append(stat_) + if monster.NativeInline() is not None: + self.nativeInline = TestT.InitFromObj(monster.NativeInline()) + self.longEnumNonEnumDefault = monster.LongEnumNonEnumDefault() + self.longEnumNormalDefault = monster.LongEnumNormalDefault() + self.nanDefault = monster.NanDefault() + self.infDefault = monster.InfDefault() + self.positiveInfDefault = monster.PositiveInfDefault() + self.infinityDefault = monster.InfinityDefault() + self.positiveInfinityDefault = monster.PositiveInfinityDefault() + self.negativeInfDefault = monster.NegativeInfDefault() + self.negativeInfinityDefault = monster.NegativeInfinityDefault() + self.doubleInfDefault = monster.DoubleInfDefault() + + # MonsterT + def Pack(self, builder): + if self.name is not None: + name = builder.CreateString(self.name) + if self.inventory is not None: + if np is not None and type(self.inventory) is np.ndarray: + inventory = builder.CreateNumpyVector(self.inventory) + else: + MonsterStartInventoryVector(builder, len(self.inventory)) + for i in reversed(range(len(self.inventory))): + builder.PrependUint8(self.inventory[i]) + inventory = builder.EndVector() + if self.test is not None: + test = self.test.Pack(builder) + if self.test4 is not None: + MonsterStartTest4Vector(builder, len(self.test4)) + for i in reversed(range(len(self.test4))): + self.test4[i].Pack(builder) + test4 = builder.EndVector() + if self.testarrayofstring is not None: + testarrayofstringlist = [] + for i in range(len(self.testarrayofstring)): + testarrayofstringlist.append(builder.CreateString(self.testarrayofstring[i])) + MonsterStartTestarrayofstringVector(builder, len(self.testarrayofstring)) + for i in reversed(range(len(self.testarrayofstring))): + builder.PrependUOffsetTRelative(testarrayofstringlist[i]) + testarrayofstring = builder.EndVector() + if self.testarrayoftables is not None: + testarrayoftableslist = [] + for i in range(len(self.testarrayoftables)): + testarrayoftableslist.append(self.testarrayoftables[i].Pack(builder)) + MonsterStartTestarrayoftablesVector(builder, len(self.testarrayoftables)) + for i in reversed(range(len(self.testarrayoftables))): + builder.PrependUOffsetTRelative(testarrayoftableslist[i]) + testarrayoftables = builder.EndVector() + if self.enemy is not None: + enemy = self.enemy.Pack(builder) + if self.testnestedflatbuffer is not None: + if np is not None and type(self.testnestedflatbuffer) is np.ndarray: + testnestedflatbuffer = builder.CreateNumpyVector(self.testnestedflatbuffer) + else: + MonsterStartTestnestedflatbufferVector(builder, len(self.testnestedflatbuffer)) + for i in reversed(range(len(self.testnestedflatbuffer))): + builder.PrependUint8(self.testnestedflatbuffer[i]) + testnestedflatbuffer = builder.EndVector() + if self.testempty is not None: + testempty = self.testempty.Pack(builder) + if self.testarrayofbools is not None: + if np is not None and type(self.testarrayofbools) is np.ndarray: + testarrayofbools = builder.CreateNumpyVector(self.testarrayofbools) + else: + MonsterStartTestarrayofboolsVector(builder, len(self.testarrayofbools)) + for i in reversed(range(len(self.testarrayofbools))): + builder.PrependBool(self.testarrayofbools[i]) + testarrayofbools = builder.EndVector() + if self.testarrayofstring2 is not None: + testarrayofstring2list = [] + for i in range(len(self.testarrayofstring2)): + testarrayofstring2list.append(builder.CreateString(self.testarrayofstring2[i])) + MonsterStartTestarrayofstring2Vector(builder, len(self.testarrayofstring2)) + for i in reversed(range(len(self.testarrayofstring2))): + builder.PrependUOffsetTRelative(testarrayofstring2list[i]) + testarrayofstring2 = builder.EndVector() + if self.testarrayofsortedstruct is not None: + MonsterStartTestarrayofsortedstructVector(builder, len(self.testarrayofsortedstruct)) + for i in reversed(range(len(self.testarrayofsortedstruct))): + self.testarrayofsortedstruct[i].Pack(builder) + testarrayofsortedstruct = builder.EndVector() + if self.flex is not None: + if np is not None and type(self.flex) is np.ndarray: + flex = builder.CreateNumpyVector(self.flex) + else: + MonsterStartFlexVector(builder, len(self.flex)) + for i in reversed(range(len(self.flex))): + builder.PrependUint8(self.flex[i]) + flex = builder.EndVector() + if self.test5 is not None: + MonsterStartTest5Vector(builder, len(self.test5)) + for i in reversed(range(len(self.test5))): + self.test5[i].Pack(builder) + test5 = builder.EndVector() + if self.vectorOfLongs is not None: + if np is not None and type(self.vectorOfLongs) is np.ndarray: + vectorOfLongs = builder.CreateNumpyVector(self.vectorOfLongs) + else: + MonsterStartVectorOfLongsVector(builder, len(self.vectorOfLongs)) + for i in reversed(range(len(self.vectorOfLongs))): + builder.PrependInt64(self.vectorOfLongs[i]) + vectorOfLongs = builder.EndVector() + if self.vectorOfDoubles is not None: + if np is not None and type(self.vectorOfDoubles) is np.ndarray: + vectorOfDoubles = builder.CreateNumpyVector(self.vectorOfDoubles) + else: + MonsterStartVectorOfDoublesVector(builder, len(self.vectorOfDoubles)) + for i in reversed(range(len(self.vectorOfDoubles))): + builder.PrependFloat64(self.vectorOfDoubles[i]) + vectorOfDoubles = builder.EndVector() + if self.parentNamespaceTest is not None: + parentNamespaceTest = self.parentNamespaceTest.Pack(builder) + if self.vectorOfReferrables is not None: + vectorOfReferrableslist = [] + for i in range(len(self.vectorOfReferrables)): + vectorOfReferrableslist.append(self.vectorOfReferrables[i].Pack(builder)) + MonsterStartVectorOfReferrablesVector(builder, len(self.vectorOfReferrables)) + for i in reversed(range(len(self.vectorOfReferrables))): + builder.PrependUOffsetTRelative(vectorOfReferrableslist[i]) + vectorOfReferrables = builder.EndVector() + if self.vectorOfWeakReferences is not None: + if np is not None and type(self.vectorOfWeakReferences) is np.ndarray: + vectorOfWeakReferences = builder.CreateNumpyVector(self.vectorOfWeakReferences) + else: + MonsterStartVectorOfWeakReferencesVector(builder, len(self.vectorOfWeakReferences)) + for i in reversed(range(len(self.vectorOfWeakReferences))): + builder.PrependUint64(self.vectorOfWeakReferences[i]) + vectorOfWeakReferences = builder.EndVector() + if self.vectorOfStrongReferrables is not None: + vectorOfStrongReferrableslist = [] + for i in range(len(self.vectorOfStrongReferrables)): + vectorOfStrongReferrableslist.append(self.vectorOfStrongReferrables[i].Pack(builder)) + MonsterStartVectorOfStrongReferrablesVector(builder, len(self.vectorOfStrongReferrables)) + for i in reversed(range(len(self.vectorOfStrongReferrables))): + builder.PrependUOffsetTRelative(vectorOfStrongReferrableslist[i]) + vectorOfStrongReferrables = builder.EndVector() + if self.vectorOfCoOwningReferences is not None: + if np is not None and type(self.vectorOfCoOwningReferences) is np.ndarray: + vectorOfCoOwningReferences = builder.CreateNumpyVector(self.vectorOfCoOwningReferences) + else: + MonsterStartVectorOfCoOwningReferencesVector(builder, len(self.vectorOfCoOwningReferences)) + for i in reversed(range(len(self.vectorOfCoOwningReferences))): + builder.PrependUint64(self.vectorOfCoOwningReferences[i]) + vectorOfCoOwningReferences = builder.EndVector() + if self.vectorOfNonOwningReferences is not None: + if np is not None and type(self.vectorOfNonOwningReferences) is np.ndarray: + vectorOfNonOwningReferences = builder.CreateNumpyVector(self.vectorOfNonOwningReferences) + else: + MonsterStartVectorOfNonOwningReferencesVector(builder, len(self.vectorOfNonOwningReferences)) + for i in reversed(range(len(self.vectorOfNonOwningReferences))): + builder.PrependUint64(self.vectorOfNonOwningReferences[i]) + vectorOfNonOwningReferences = builder.EndVector() + if self.anyUnique is not None: + anyUnique = self.anyUnique.Pack(builder) + if self.anyAmbiguous is not None: + anyAmbiguous = self.anyAmbiguous.Pack(builder) + if self.vectorOfEnums is not None: + if np is not None and type(self.vectorOfEnums) is np.ndarray: + vectorOfEnums = builder.CreateNumpyVector(self.vectorOfEnums) + else: + MonsterStartVectorOfEnumsVector(builder, len(self.vectorOfEnums)) + for i in reversed(range(len(self.vectorOfEnums))): + builder.PrependUint8(self.vectorOfEnums[i]) + vectorOfEnums = builder.EndVector() + if self.testrequirednestedflatbuffer is not None: + if np is not None and type(self.testrequirednestedflatbuffer) is np.ndarray: + testrequirednestedflatbuffer = builder.CreateNumpyVector(self.testrequirednestedflatbuffer) + else: + MonsterStartTestrequirednestedflatbufferVector(builder, len(self.testrequirednestedflatbuffer)) + for i in reversed(range(len(self.testrequirednestedflatbuffer))): + builder.PrependUint8(self.testrequirednestedflatbuffer[i]) + testrequirednestedflatbuffer = builder.EndVector() + if self.scalarKeySortedTables is not None: + scalarKeySortedTableslist = [] + for i in range(len(self.scalarKeySortedTables)): + scalarKeySortedTableslist.append(self.scalarKeySortedTables[i].Pack(builder)) + MonsterStartScalarKeySortedTablesVector(builder, len(self.scalarKeySortedTables)) + for i in reversed(range(len(self.scalarKeySortedTables))): + builder.PrependUOffsetTRelative(scalarKeySortedTableslist[i]) + scalarKeySortedTables = builder.EndVector() + MonsterStart(builder) + if self.pos is not None: + pos = self.pos.Pack(builder) + MonsterAddPos(builder, pos) + MonsterAddMana(builder, self.mana) + MonsterAddHp(builder, self.hp) + if self.name is not None: + MonsterAddName(builder, name) + if self.inventory is not None: + MonsterAddInventory(builder, inventory) + MonsterAddColor(builder, self.color) + MonsterAddTestType(builder, self.testType) + if self.test is not None: + MonsterAddTest(builder, test) + if self.test4 is not None: + MonsterAddTest4(builder, test4) + if self.testarrayofstring is not None: + MonsterAddTestarrayofstring(builder, testarrayofstring) + if self.testarrayoftables is not None: + MonsterAddTestarrayoftables(builder, testarrayoftables) + if self.enemy is not None: + MonsterAddEnemy(builder, enemy) + if self.testnestedflatbuffer is not None: + MonsterAddTestnestedflatbuffer(builder, testnestedflatbuffer) + if self.testempty is not None: + MonsterAddTestempty(builder, testempty) + MonsterAddTestbool(builder, self.testbool) + MonsterAddTesthashs32Fnv1(builder, self.testhashs32Fnv1) + MonsterAddTesthashu32Fnv1(builder, self.testhashu32Fnv1) + MonsterAddTesthashs64Fnv1(builder, self.testhashs64Fnv1) + MonsterAddTesthashu64Fnv1(builder, self.testhashu64Fnv1) + MonsterAddTesthashs32Fnv1a(builder, self.testhashs32Fnv1a) + MonsterAddTesthashu32Fnv1a(builder, self.testhashu32Fnv1a) + MonsterAddTesthashs64Fnv1a(builder, self.testhashs64Fnv1a) + MonsterAddTesthashu64Fnv1a(builder, self.testhashu64Fnv1a) + if self.testarrayofbools is not None: + MonsterAddTestarrayofbools(builder, testarrayofbools) + MonsterAddTestf(builder, self.testf) + MonsterAddTestf2(builder, self.testf2) + MonsterAddTestf3(builder, self.testf3) + if self.testarrayofstring2 is not None: + MonsterAddTestarrayofstring2(builder, testarrayofstring2) + if self.testarrayofsortedstruct is not None: + MonsterAddTestarrayofsortedstruct(builder, testarrayofsortedstruct) + if self.flex is not None: + MonsterAddFlex(builder, flex) + if self.test5 is not None: + MonsterAddTest5(builder, test5) + if self.vectorOfLongs is not None: + MonsterAddVectorOfLongs(builder, vectorOfLongs) + if self.vectorOfDoubles is not None: + MonsterAddVectorOfDoubles(builder, vectorOfDoubles) + if self.parentNamespaceTest is not None: + MonsterAddParentNamespaceTest(builder, parentNamespaceTest) + if self.vectorOfReferrables is not None: + MonsterAddVectorOfReferrables(builder, vectorOfReferrables) + MonsterAddSingleWeakReference(builder, self.singleWeakReference) + if self.vectorOfWeakReferences is not None: + MonsterAddVectorOfWeakReferences(builder, vectorOfWeakReferences) + if self.vectorOfStrongReferrables is not None: + MonsterAddVectorOfStrongReferrables(builder, vectorOfStrongReferrables) + MonsterAddCoOwningReference(builder, self.coOwningReference) + if self.vectorOfCoOwningReferences is not None: + MonsterAddVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences) + MonsterAddNonOwningReference(builder, self.nonOwningReference) + if self.vectorOfNonOwningReferences is not None: + MonsterAddVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences) + MonsterAddAnyUniqueType(builder, self.anyUniqueType) + if self.anyUnique is not None: + MonsterAddAnyUnique(builder, anyUnique) + MonsterAddAnyAmbiguousType(builder, self.anyAmbiguousType) + if self.anyAmbiguous is not None: + MonsterAddAnyAmbiguous(builder, anyAmbiguous) + if self.vectorOfEnums is not None: + MonsterAddVectorOfEnums(builder, vectorOfEnums) + MonsterAddSignedEnum(builder, self.signedEnum) + if self.testrequirednestedflatbuffer is not None: + MonsterAddTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer) + if self.scalarKeySortedTables is not None: + MonsterAddScalarKeySortedTables(builder, scalarKeySortedTables) + if self.nativeInline is not None: + nativeInline = self.nativeInline.Pack(builder) + MonsterAddNativeInline(builder, nativeInline) + MonsterAddLongEnumNonEnumDefault(builder, self.longEnumNonEnumDefault) + MonsterAddLongEnumNormalDefault(builder, self.longEnumNormalDefault) + MonsterAddNanDefault(builder, self.nanDefault) + MonsterAddInfDefault(builder, self.infDefault) + MonsterAddPositiveInfDefault(builder, self.positiveInfDefault) + MonsterAddInfinityDefault(builder, self.infinityDefault) + MonsterAddPositiveInfinityDefault(builder, self.positiveInfinityDefault) + MonsterAddNegativeInfDefault(builder, self.negativeInfDefault) + MonsterAddNegativeInfinityDefault(builder, self.negativeInfinityDefault) + MonsterAddDoubleInfDefault(builder, self.doubleInfDefault) + monster = MonsterEnd(builder) + return monster + + +class TypeAliases(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TypeAliases() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTypeAliases(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def TypeAliasesBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4D\x4F\x4E\x53", size_prefixed=size_prefixed) + + # TypeAliases + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TypeAliases + def I8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def I16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def I32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def I64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def U64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # TypeAliases + def F32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # TypeAliases + def F64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # TypeAliases + def V8(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Int8Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 1)) + return 0 + + # TypeAliases + def V8AsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Int8Flags, o) + return 0 + + # TypeAliases + def V8Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # TypeAliases + def V8IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + return o == 0 + + # TypeAliases + def Vf64(self, j): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + a = self._tab.Vector(o) + return self._tab.Get(flatbuffers.number_types.Float64Flags, a + flatbuffers.number_types.UOffsetTFlags.py_type(j * 8)) + return 0 + + # TypeAliases + def Vf64AsNumpy(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.GetVectorAsNumpy(flatbuffers.number_types.Float64Flags, o) + return 0 + + # TypeAliases + def Vf64Length(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.VectorLen(o) + return 0 + + # TypeAliases + def Vf64IsNone(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + return o == 0 + +def TypeAliasesStart(builder): + builder.StartObject(12) + +def TypeAliasesAddI8(builder, i8): + builder.PrependInt8Slot(0, i8, 0) + +def TypeAliasesAddU8(builder, u8): + builder.PrependUint8Slot(1, u8, 0) + +def TypeAliasesAddI16(builder, i16): + builder.PrependInt16Slot(2, i16, 0) + +def TypeAliasesAddU16(builder, u16): + builder.PrependUint16Slot(3, u16, 0) + +def TypeAliasesAddI32(builder, i32): + builder.PrependInt32Slot(4, i32, 0) + +def TypeAliasesAddU32(builder, u32): + builder.PrependUint32Slot(5, u32, 0) + +def TypeAliasesAddI64(builder, i64): + builder.PrependInt64Slot(6, i64, 0) + +def TypeAliasesAddU64(builder, u64): + builder.PrependUint64Slot(7, u64, 0) + +def TypeAliasesAddF32(builder, f32): + builder.PrependFloat32Slot(8, f32, 0.0) + +def TypeAliasesAddF64(builder, f64): + builder.PrependFloat64Slot(9, f64, 0.0) + +def TypeAliasesAddV8(builder, v8): + builder.PrependUOffsetTRelativeSlot(10, flatbuffers.number_types.UOffsetTFlags.py_type(v8), 0) + +def TypeAliasesStartV8Vector(builder, numElems): + return builder.StartVector(1, numElems, 1) + +def TypeAliasesAddVf64(builder, vf64): + builder.PrependUOffsetTRelativeSlot(11, flatbuffers.number_types.UOffsetTFlags.py_type(vf64), 0) + +def TypeAliasesStartVf64Vector(builder, numElems): + return builder.StartVector(8, numElems, 8) + +def TypeAliasesEnd(builder): + return builder.EndObject() + + +try: + from typing import List +except: + pass + +class TypeAliasesT(object): + + # TypeAliasesT + def __init__(self): + self.i8 = 0 # type: int + self.u8 = 0 # type: int + self.i16 = 0 # type: int + self.u16 = 0 # type: int + self.i32 = 0 # type: int + self.u32 = 0 # type: int + self.i64 = 0 # type: int + self.u64 = 0 # type: int + self.f32 = 0.0 # type: float + self.f64 = 0.0 # type: float + self.v8 = None # type: List[int] + self.vf64 = None # type: List[float] + + @classmethod + def InitFromBuf(cls, buf, pos): + typeAliases = TypeAliases() + typeAliases.Init(buf, pos) + return cls.InitFromObj(typeAliases) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, typeAliases): + x = TypeAliasesT() + x._UnPack(typeAliases) + return x + + # TypeAliasesT + def _UnPack(self, typeAliases): + if typeAliases is None: + return + self.i8 = typeAliases.I8() + self.u8 = typeAliases.U8() + self.i16 = typeAliases.I16() + self.u16 = typeAliases.U16() + self.i32 = typeAliases.I32() + self.u32 = typeAliases.U32() + self.i64 = typeAliases.I64() + self.u64 = typeAliases.U64() + self.f32 = typeAliases.F32() + self.f64 = typeAliases.F64() + if not typeAliases.V8IsNone(): + if np is None: + self.v8 = [] + for i in range(typeAliases.V8Length()): + self.v8.append(typeAliases.V8(i)) + else: + self.v8 = typeAliases.V8AsNumpy() + if not typeAliases.Vf64IsNone(): + if np is None: + self.vf64 = [] + for i in range(typeAliases.Vf64Length()): + self.vf64.append(typeAliases.Vf64(i)) + else: + self.vf64 = typeAliases.Vf64AsNumpy() + + # TypeAliasesT + def Pack(self, builder): + if self.v8 is not None: + if np is not None and type(self.v8) is np.ndarray: + v8 = builder.CreateNumpyVector(self.v8) + else: + TypeAliasesStartV8Vector(builder, len(self.v8)) + for i in reversed(range(len(self.v8))): + builder.PrependByte(self.v8[i]) + v8 = builder.EndVector() + if self.vf64 is not None: + if np is not None and type(self.vf64) is np.ndarray: + vf64 = builder.CreateNumpyVector(self.vf64) + else: + TypeAliasesStartVf64Vector(builder, len(self.vf64)) + for i in reversed(range(len(self.vf64))): + builder.PrependFloat64(self.vf64[i]) + vf64 = builder.EndVector() + TypeAliasesStart(builder) + TypeAliasesAddI8(builder, self.i8) + TypeAliasesAddU8(builder, self.u8) + TypeAliasesAddI16(builder, self.i16) + TypeAliasesAddU16(builder, self.u16) + TypeAliasesAddI32(builder, self.i32) + TypeAliasesAddU32(builder, self.u32) + TypeAliasesAddI64(builder, self.i64) + TypeAliasesAddU64(builder, self.u64) + TypeAliasesAddF32(builder, self.f32) + TypeAliasesAddF64(builder, self.f64) + if self.v8 is not None: + TypeAliasesAddV8(builder, v8) + if self.vf64 is not None: + TypeAliasesAddVf64(builder, vf64) + typeAliases = TypeAliasesEnd(builder) + return typeAliases + + diff --git a/third_party/flatbuffers/tests/monster_test_generated.ts b/third_party/flatbuffers/tests/monster_test_generated.ts new file mode 100644 index 00000000000..5fd080eb4cd --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_generated.ts @@ -0,0 +1,19 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +export { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from './my-game/example2/monster'; +export { Ability, AbilityT } from './my-game/example/ability'; +export { Any, unionToAny, unionListToAny } from './my-game/example/any'; +export { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from './my-game/example/any-ambiguous-aliases'; +export { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from './my-game/example/any-unique-aliases'; +export { Color } from './my-game/example/color'; +export { Monster, MonsterT } from './my-game/example/monster'; +export { Race } from './my-game/example/race'; +export { Referrable, ReferrableT } from './my-game/example/referrable'; +export { Stat, StatT } from './my-game/example/stat'; +export { StructOfStructs, StructOfStructsT } from './my-game/example/struct-of-structs'; +export { StructOfStructsOfStructs, StructOfStructsOfStructsT } from './my-game/example/struct-of-structs-of-structs'; +export { Test, TestT } from './my-game/example/test'; +export { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './my-game/example/test-simple-table-with-enum'; +export { TypeAliases, TypeAliasesT } from './my-game/example/type-aliases'; +export { Vec3, Vec3T } from './my-game/example/vec3'; +export { InParentNamespace, InParentNamespaceT } from './my-game/in-parent-namespace'; diff --git a/third_party/flatbuffers/tests/monster_test_my_game.example2_generated.dart b/third_party/flatbuffers/tests/monster_test_my_game.example2_generated.dart new file mode 100644 index 00000000000..c266f9ce72b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_my_game.example2_generated.dart @@ -0,0 +1,79 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.example2; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './monster_test_my_game_generated.dart' as my_game; +import './monster_test_my_game.example_generated.dart' as my_game_example; + +import './include_test1_generated.dart'; + +class Monster { + Monster._(this._bc, this._bcOffset); + factory Monster(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MonsterReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + + @override + String toString() { + return 'Monster{}'; + } + + MonsterT unpack() => MonsterT(); + + static int pack(fb.Builder fbBuilder, MonsterT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class MonsterT implements fb.Packable { + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'MonsterT{}'; + } +} + +class _MonsterReader extends fb.TableReader { + const _MonsterReader(); + + @override + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); +} + +class MonsterObjectBuilder extends fb.ObjectBuilder { + + MonsterObjectBuilder(); + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/monster_test_my_game.example_generated.dart b/third_party/flatbuffers/tests/monster_test_my_game.example_generated.dart new file mode 100644 index 00000000000..5554c4c4b1d --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_my_game.example_generated.dart @@ -0,0 +1,2371 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game.example; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './monster_test_my_game_generated.dart' as my_game; +import './monster_test_my_game.example2_generated.dart' as my_game_example2; + +import './include_test1_generated.dart'; + +/// Composite components of Monster color. +enum Color { + Red(1), + Green(2), + Blue(8), + _default(0); + + final int value; + const Color(this.value); + + factory Color.fromValue(int value) { + switch (value) { + case 1: return Color.Red; + case 2: return Color.Green; + case 8: return Color.Blue; + case 0: return Color._default; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static Color? _createOrNull(int? value) => + value == null ? null : Color.fromValue(value); + + static const fb.Reader reader = _ColorReader(); +} + +class _ColorReader extends fb.Reader { + const _ColorReader(); + + @override + int get size => 1; + + @override + Color read(fb.BufferContext bc, int offset) => + Color.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +enum Race { + None(-1), + Human(0), + Dwarf(1), + Elf(2); + + final int value; + const Race(this.value); + + factory Race.fromValue(int value) { + switch (value) { + case -1: return Race.None; + case 0: return Race.Human; + case 1: return Race.Dwarf; + case 2: return Race.Elf; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static Race? _createOrNull(int? value) => + value == null ? null : Race.fromValue(value); + + static const int minValue = -1; + static const int maxValue = 2; + static const fb.Reader reader = _RaceReader(); +} + +class _RaceReader extends fb.Reader { + const _RaceReader(); + + @override + int get size => 1; + + @override + Race read(fb.BufferContext bc, int offset) => + Race.fromValue(const fb.Int8Reader().read(bc, offset)); +} + +enum LongEnum { + LongOne(2), + LongTwo(4), + LongBig(1099511627776), + _default(0); + + final int value; + const LongEnum(this.value); + + factory LongEnum.fromValue(int value) { + switch (value) { + case 2: return LongEnum.LongOne; + case 4: return LongEnum.LongTwo; + case 1099511627776: return LongEnum.LongBig; + case 0: return LongEnum._default; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static LongEnum? _createOrNull(int? value) => + value == null ? null : LongEnum.fromValue(value); + + static const fb.Reader reader = _LongEnumReader(); +} + +class _LongEnumReader extends fb.Reader { + const _LongEnumReader(); + + @override + int get size => 8; + + @override + LongEnum read(fb.BufferContext bc, int offset) => + LongEnum.fromValue(const fb.Uint64Reader().read(bc, offset)); +} + +enum AnyTypeId { + NONE(0), + Monster(1), + TestSimpleTableWithEnum(2), + MyGame_Example2_Monster(3); + + final int value; + const AnyTypeId(this.value); + + factory AnyTypeId.fromValue(int value) { + switch (value) { + case 0: return AnyTypeId.NONE; + case 1: return AnyTypeId.Monster; + case 2: return AnyTypeId.TestSimpleTableWithEnum; + case 3: return AnyTypeId.MyGame_Example2_Monster; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static AnyTypeId? _createOrNull(int? value) => + value == null ? null : AnyTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 3; + static const fb.Reader reader = _AnyTypeIdReader(); +} + +class _AnyTypeIdReader extends fb.Reader { + const _AnyTypeIdReader(); + + @override + int get size => 1; + + @override + AnyTypeId read(fb.BufferContext bc, int offset) => + AnyTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +enum AnyUniqueAliasesTypeId { + NONE(0), + M(1), + TS(2), + M2(3); + + final int value; + const AnyUniqueAliasesTypeId(this.value); + + factory AnyUniqueAliasesTypeId.fromValue(int value) { + switch (value) { + case 0: return AnyUniqueAliasesTypeId.NONE; + case 1: return AnyUniqueAliasesTypeId.M; + case 2: return AnyUniqueAliasesTypeId.TS; + case 3: return AnyUniqueAliasesTypeId.M2; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static AnyUniqueAliasesTypeId? _createOrNull(int? value) => + value == null ? null : AnyUniqueAliasesTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 3; + static const fb.Reader reader = _AnyUniqueAliasesTypeIdReader(); +} + +class _AnyUniqueAliasesTypeIdReader extends fb.Reader { + const _AnyUniqueAliasesTypeIdReader(); + + @override + int get size => 1; + + @override + AnyUniqueAliasesTypeId read(fb.BufferContext bc, int offset) => + AnyUniqueAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +enum AnyAmbiguousAliasesTypeId { + NONE(0), + M1(1), + M2(2), + M3(3); + + final int value; + const AnyAmbiguousAliasesTypeId(this.value); + + factory AnyAmbiguousAliasesTypeId.fromValue(int value) { + switch (value) { + case 0: return AnyAmbiguousAliasesTypeId.NONE; + case 1: return AnyAmbiguousAliasesTypeId.M1; + case 2: return AnyAmbiguousAliasesTypeId.M2; + case 3: return AnyAmbiguousAliasesTypeId.M3; + default: throw StateError('Invalid value $value for bit flag enum'); + } + } + + static AnyAmbiguousAliasesTypeId? _createOrNull(int? value) => + value == null ? null : AnyAmbiguousAliasesTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 3; + static const fb.Reader reader = _AnyAmbiguousAliasesTypeIdReader(); +} + +class _AnyAmbiguousAliasesTypeIdReader extends fb.Reader { + const _AnyAmbiguousAliasesTypeIdReader(); + + @override + int get size => 1; + + @override + AnyAmbiguousAliasesTypeId read(fb.BufferContext bc, int offset) => + AnyAmbiguousAliasesTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +class Test { + Test._(this._bc, this._bcOffset); + + static const fb.Reader reader = _TestReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get a => const fb.Int16Reader().read(_bc, _bcOffset + 0); + int get b => const fb.Int8Reader().read(_bc, _bcOffset + 2); + + @override + String toString() { + return 'Test{a: ${a}, b: ${b}}'; + } + + TestT unpack() => TestT( + a: a, + b: b); + + static int pack(fb.Builder fbBuilder, TestT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TestT implements fb.Packable { + int a; + int b; + + TestT({ + required this.a, + required this.b}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.pad(1); + fbBuilder.putInt8(b); + fbBuilder.putInt16(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'TestT{a: ${a}, b: ${b}}'; + } +} + +class _TestReader extends fb.StructReader { + const _TestReader(); + + @override + int get size => 4; + + @override + Test createObject(fb.BufferContext bc, int offset) => + Test._(bc, offset); +} + +class TestBuilder { + TestBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int a, int b) { + fbBuilder.pad(1); + fbBuilder.putInt8(b); + fbBuilder.putInt16(a); + return fbBuilder.offset; + } + +} + +class TestObjectBuilder extends fb.ObjectBuilder { + final int _a; + final int _b; + + TestObjectBuilder({ + required int a, + required int b, + }) + : _a = a, + _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.pad(1); + fbBuilder.putInt8(_b); + fbBuilder.putInt16(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class TestSimpleTableWithEnum { + TestSimpleTableWithEnum._(this._bc, this._bcOffset); + factory TestSimpleTableWithEnum(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TestSimpleTableWithEnumReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 4, 2)); + + @override + String toString() { + return 'TestSimpleTableWithEnum{color: ${color}}'; + } + + TestSimpleTableWithEnumT unpack() => TestSimpleTableWithEnumT( + color: color); + + static int pack(fb.Builder fbBuilder, TestSimpleTableWithEnumT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TestSimpleTableWithEnumT implements fb.Packable { + Color color; + + TestSimpleTableWithEnumT({ + this.color = Color.Green}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint8(0, color.value); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TestSimpleTableWithEnumT{color: ${color}}'; + } +} + +class _TestSimpleTableWithEnumReader extends fb.TableReader { + const _TestSimpleTableWithEnumReader(); + + @override + TestSimpleTableWithEnum createObject(fb.BufferContext bc, int offset) => + TestSimpleTableWithEnum._(bc, offset); +} + +class TestSimpleTableWithEnumBuilder { + TestSimpleTableWithEnumBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addColor(Color? color) { + fbBuilder.addUint8(0, color?.value); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TestSimpleTableWithEnumObjectBuilder extends fb.ObjectBuilder { + final Color? _color; + + TestSimpleTableWithEnumObjectBuilder({ + Color? color, + }) + : _color = color; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint8(0, _color?.value); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Vec3 { + Vec3._(this._bc, this._bcOffset); + + static const fb.Reader reader = _Vec3Reader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + double get x => const fb.Float32Reader().read(_bc, _bcOffset + 0); + double get y => const fb.Float32Reader().read(_bc, _bcOffset + 4); + double get z => const fb.Float32Reader().read(_bc, _bcOffset + 8); + double get test1 => const fb.Float64Reader().read(_bc, _bcOffset + 16); + Color get test2 => Color.fromValue(const fb.Uint8Reader().read(_bc, _bcOffset + 24)); + Test get test3 => Test.reader.read(_bc, _bcOffset + 26); + + @override + String toString() { + return 'Vec3{x: ${x}, y: ${y}, z: ${z}, test1: ${test1}, test2: ${test2}, test3: ${test3}}'; + } + + Vec3T unpack() => Vec3T( + x: x, + y: y, + z: z, + test1: test1, + test2: test2, + test3: test3.unpack()); + + static int pack(fb.Builder fbBuilder, Vec3T? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class Vec3T implements fb.Packable { + double x; + double y; + double z; + double test1; + Color test2; + TestT test3; + + Vec3T({ + required this.x, + required this.y, + required this.z, + required this.test1, + required this.test2, + required this.test3}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.pad(2); + test3.pack(fbBuilder); + fbBuilder.pad(1); + fbBuilder.putUint8(test2.value); + fbBuilder.putFloat64(test1); + fbBuilder.pad(4); + fbBuilder.putFloat32(z); + fbBuilder.putFloat32(y); + fbBuilder.putFloat32(x); + return fbBuilder.offset; + } + + @override + String toString() { + return 'Vec3T{x: ${x}, y: ${y}, z: ${z}, test1: ${test1}, test2: ${test2}, test3: ${test3}}'; + } +} + +class _Vec3Reader extends fb.StructReader { + const _Vec3Reader(); + + @override + int get size => 32; + + @override + Vec3 createObject(fb.BufferContext bc, int offset) => + Vec3._(bc, offset); +} + +class Vec3Builder { + Vec3Builder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(double x, double y, double z, double test1, Color test2, fb.StructBuilder test3) { + fbBuilder.pad(2); + test3(); + fbBuilder.pad(1); + fbBuilder.putUint8(test2.value); + fbBuilder.putFloat64(test1); + fbBuilder.pad(4); + fbBuilder.putFloat32(z); + fbBuilder.putFloat32(y); + fbBuilder.putFloat32(x); + return fbBuilder.offset; + } + +} + +class Vec3ObjectBuilder extends fb.ObjectBuilder { + final double _x; + final double _y; + final double _z; + final double _test1; + final Color _test2; + final TestObjectBuilder _test3; + + Vec3ObjectBuilder({ + required double x, + required double y, + required double z, + required double test1, + required Color test2, + required TestObjectBuilder test3, + }) + : _x = x, + _y = y, + _z = z, + _test1 = test1, + _test2 = test2, + _test3 = test3; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.pad(2); + _test3.finish(fbBuilder); + fbBuilder.pad(1); + fbBuilder.putUint8(_test2.value); + fbBuilder.putFloat64(_test1); + fbBuilder.pad(4); + fbBuilder.putFloat32(_z); + fbBuilder.putFloat32(_y); + fbBuilder.putFloat32(_x); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Ability { + Ability._(this._bc, this._bcOffset); + + static const fb.Reader reader = _AbilityReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get id => const fb.Uint32Reader().read(_bc, _bcOffset + 0); + int get distance => const fb.Uint32Reader().read(_bc, _bcOffset + 4); + + @override + String toString() { + return 'Ability{id: ${id}, distance: ${distance}}'; + } + + AbilityT unpack() => AbilityT( + id: id, + distance: distance); + + static int pack(fb.Builder fbBuilder, AbilityT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class AbilityT implements fb.Packable { + int id; + int distance; + + AbilityT({ + required this.id, + required this.distance}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putUint32(distance); + fbBuilder.putUint32(id); + return fbBuilder.offset; + } + + @override + String toString() { + return 'AbilityT{id: ${id}, distance: ${distance}}'; + } +} + +class _AbilityReader extends fb.StructReader { + const _AbilityReader(); + + @override + int get size => 8; + + @override + Ability createObject(fb.BufferContext bc, int offset) => + Ability._(bc, offset); +} + +class AbilityBuilder { + AbilityBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int id, int distance) { + fbBuilder.putUint32(distance); + fbBuilder.putUint32(id); + return fbBuilder.offset; + } + +} + +class AbilityObjectBuilder extends fb.ObjectBuilder { + final int _id; + final int _distance; + + AbilityObjectBuilder({ + required int id, + required int distance, + }) + : _id = id, + _distance = distance; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putUint32(_distance); + fbBuilder.putUint32(_id); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class StructOfStructs { + StructOfStructs._(this._bc, this._bcOffset); + + static const fb.Reader reader = _StructOfStructsReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Ability get a => Ability.reader.read(_bc, _bcOffset + 0); + Test get b => Test.reader.read(_bc, _bcOffset + 8); + Ability get c => Ability.reader.read(_bc, _bcOffset + 12); + + @override + String toString() { + return 'StructOfStructs{a: ${a}, b: ${b}, c: ${c}}'; + } + + StructOfStructsT unpack() => StructOfStructsT( + a: a.unpack(), + b: b.unpack(), + c: c.unpack()); + + static int pack(fb.Builder fbBuilder, StructOfStructsT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StructOfStructsT implements fb.Packable { + AbilityT a; + TestT b; + AbilityT c; + + StructOfStructsT({ + required this.a, + required this.b, + required this.c}); + + @override + int pack(fb.Builder fbBuilder) { + c.pack(fbBuilder); + b.pack(fbBuilder); + a.pack(fbBuilder); + return fbBuilder.offset; + } + + @override + String toString() { + return 'StructOfStructsT{a: ${a}, b: ${b}, c: ${c}}'; + } +} + +class _StructOfStructsReader extends fb.StructReader { + const _StructOfStructsReader(); + + @override + int get size => 20; + + @override + StructOfStructs createObject(fb.BufferContext bc, int offset) => + StructOfStructs._(bc, offset); +} + +class StructOfStructsBuilder { + StructOfStructsBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(fb.StructBuilder a, fb.StructBuilder b, fb.StructBuilder c) { + c(); + b(); + a(); + return fbBuilder.offset; + } + +} + +class StructOfStructsObjectBuilder extends fb.ObjectBuilder { + final AbilityObjectBuilder _a; + final TestObjectBuilder _b; + final AbilityObjectBuilder _c; + + StructOfStructsObjectBuilder({ + required AbilityObjectBuilder a, + required TestObjectBuilder b, + required AbilityObjectBuilder c, + }) + : _a = a, + _b = b, + _c = c; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + _c.finish(fbBuilder); + _b.finish(fbBuilder); + _a.finish(fbBuilder); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class StructOfStructsOfStructs { + StructOfStructsOfStructs._(this._bc, this._bcOffset); + + static const fb.Reader reader = _StructOfStructsOfStructsReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + StructOfStructs get a => StructOfStructs.reader.read(_bc, _bcOffset + 0); + + @override + String toString() { + return 'StructOfStructsOfStructs{a: ${a}}'; + } + + StructOfStructsOfStructsT unpack() => StructOfStructsOfStructsT( + a: a.unpack()); + + static int pack(fb.Builder fbBuilder, StructOfStructsOfStructsT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StructOfStructsOfStructsT implements fb.Packable { + StructOfStructsT a; + + StructOfStructsOfStructsT({ + required this.a}); + + @override + int pack(fb.Builder fbBuilder) { + a.pack(fbBuilder); + return fbBuilder.offset; + } + + @override + String toString() { + return 'StructOfStructsOfStructsT{a: ${a}}'; + } +} + +class _StructOfStructsOfStructsReader extends fb.StructReader { + const _StructOfStructsOfStructsReader(); + + @override + int get size => 20; + + @override + StructOfStructsOfStructs createObject(fb.BufferContext bc, int offset) => + StructOfStructsOfStructs._(bc, offset); +} + +class StructOfStructsOfStructsBuilder { + StructOfStructsOfStructsBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(fb.StructBuilder a) { + a(); + return fbBuilder.offset; + } + +} + +class StructOfStructsOfStructsObjectBuilder extends fb.ObjectBuilder { + final StructOfStructsObjectBuilder _a; + + StructOfStructsOfStructsObjectBuilder({ + required StructOfStructsObjectBuilder a, + }) + : _a = a; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + _a.finish(fbBuilder); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Stat { + Stat._(this._bc, this._bcOffset); + factory Stat(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _StatReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + String? get id => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 4); + int get val => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 6, 0); + int get count => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 8, 0); + + @override + String toString() { + return 'Stat{id: ${id}, val: ${val}, count: ${count}}'; + } + + StatT unpack() => StatT( + id: id, + val: val, + count: count); + + static int pack(fb.Builder fbBuilder, StatT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StatT implements fb.Packable { + String? id; + int val; + int count; + + StatT({ + this.id, + this.val = 0, + this.count = 0}); + + @override + int pack(fb.Builder fbBuilder) { + final int? idOffset = id == null ? null + : fbBuilder.writeString(id!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, idOffset); + fbBuilder.addInt64(1, val); + fbBuilder.addUint16(2, count); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'StatT{id: ${id}, val: ${val}, count: ${count}}'; + } +} + +class _StatReader extends fb.TableReader { + const _StatReader(); + + @override + Stat createObject(fb.BufferContext bc, int offset) => + Stat._(bc, offset); +} + +class StatBuilder { + StatBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(3); + } + + int addIdOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + int addVal(int? val) { + fbBuilder.addInt64(1, val); + return fbBuilder.offset; + } + int addCount(int? count) { + fbBuilder.addUint16(2, count); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class StatObjectBuilder extends fb.ObjectBuilder { + final String? _id; + final int? _val; + final int? _count; + + StatObjectBuilder({ + String? id, + int? val, + int? count, + }) + : _id = id, + _val = val, + _count = count; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? idOffset = _id == null ? null + : fbBuilder.writeString(_id!); + fbBuilder.startTable(3); + fbBuilder.addOffset(0, idOffset); + fbBuilder.addInt64(1, _val); + fbBuilder.addUint16(2, _count); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class Referrable { + Referrable._(this._bc, this._bcOffset); + factory Referrable(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _ReferrableReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get id => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 4, 0); + + @override + String toString() { + return 'Referrable{id: ${id}}'; + } + + ReferrableT unpack() => ReferrableT( + id: id); + + static int pack(fb.Builder fbBuilder, ReferrableT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class ReferrableT implements fb.Packable { + int id; + + ReferrableT({ + this.id = 0}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint64(0, id); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'ReferrableT{id: ${id}}'; + } +} + +class _ReferrableReader extends fb.TableReader { + const _ReferrableReader(); + + @override + Referrable createObject(fb.BufferContext bc, int offset) => + Referrable._(bc, offset); +} + +class ReferrableBuilder { + ReferrableBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addId(int? id) { + fbBuilder.addUint64(0, id); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class ReferrableObjectBuilder extends fb.ObjectBuilder { + final int? _id; + + ReferrableObjectBuilder({ + int? id, + }) + : _id = id; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addUint64(0, _id); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +/// an example documentation comment: "monster object" +class Monster { + Monster._(this._bc, this._bcOffset); + factory Monster(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _MonsterReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + Vec3? get pos => Vec3.reader.vTableGetNullable(_bc, _bcOffset, 4); + int get mana => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 6, 150); + int get hp => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 100); + String? get name => const fb.StringReader().vTableGetNullable(_bc, _bcOffset, 10); + List? get inventory => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 14); + Color get color => Color.fromValue(const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 16, 8)); + AnyTypeId? get testType => AnyTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 18)); + dynamic get test { + switch (testType?.value) { + case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); + case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 20); + case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 20); + default: return null; + } + } + List? get test4 => const fb.ListReader(Test.reader).vTableGetNullable(_bc, _bcOffset, 22); + List? get testarrayofstring => const fb.ListReader(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 24); + /// an example documentation comment: this will end up in the generated code + /// multiline too + List? get testarrayoftables => const fb.ListReader(Monster.reader).vTableGetNullable(_bc, _bcOffset, 26); + Monster? get enemy => Monster.reader.vTableGetNullable(_bc, _bcOffset, 28); + List? get testnestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 30); + Stat? get testempty => Stat.reader.vTableGetNullable(_bc, _bcOffset, 32); + bool get testbool => const fb.BoolReader().vTableGet(_bc, _bcOffset, 34, false); + int get testhashs32Fnv1 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 36, 0); + int get testhashu32Fnv1 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 38, 0); + int get testhashs64Fnv1 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 40, 0); + int get testhashu64Fnv1 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 42, 0); + int get testhashs32Fnv1a => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 44, 0); + int get testhashu32Fnv1a => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 46, 0); + int get testhashs64Fnv1a => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 48, 0); + int get testhashu64Fnv1a => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 50, 0); + List? get testarrayofbools => const fb.ListReader(fb.BoolReader()).vTableGetNullable(_bc, _bcOffset, 52); + double get testf => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 54, 3.14159); + double get testf2 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 56, 3.0); + double get testf3 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 58, 0.0); + List? get testarrayofstring2 => const fb.ListReader(fb.StringReader()).vTableGetNullable(_bc, _bcOffset, 60); + List? get testarrayofsortedstruct => const fb.ListReader(Ability.reader).vTableGetNullable(_bc, _bcOffset, 62); + List? get flex => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 64); + List? get test5 => const fb.ListReader(Test.reader).vTableGetNullable(_bc, _bcOffset, 66); + List? get vectorOfLongs => const fb.ListReader(fb.Int64Reader()).vTableGetNullable(_bc, _bcOffset, 68); + List? get vectorOfDoubles => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 70); + my_game.InParentNamespace? get parentNamespaceTest => my_game.InParentNamespace.reader.vTableGetNullable(_bc, _bcOffset, 72); + List? get vectorOfReferrables => const fb.ListReader(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 74); + int get singleWeakReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 76, 0); + List? get vectorOfWeakReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 78); + List? get vectorOfStrongReferrables => const fb.ListReader(Referrable.reader).vTableGetNullable(_bc, _bcOffset, 80); + int get coOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 82, 0); + List? get vectorOfCoOwningReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 84); + int get nonOwningReference => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 86, 0); + List? get vectorOfNonOwningReferences => const fb.ListReader(fb.Uint64Reader()).vTableGetNullable(_bc, _bcOffset, 88); + AnyUniqueAliasesTypeId? get anyUniqueType => AnyUniqueAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 90)); + dynamic get anyUnique { + switch (anyUniqueType?.value) { + case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); + case 2: return TestSimpleTableWithEnum.reader.vTableGetNullable(_bc, _bcOffset, 92); + case 3: return my_game_example2.Monster.reader.vTableGetNullable(_bc, _bcOffset, 92); + default: return null; + } + } + AnyAmbiguousAliasesTypeId? get anyAmbiguousType => AnyAmbiguousAliasesTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 94)); + dynamic get anyAmbiguous { + switch (anyAmbiguousType?.value) { + case 1: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + case 2: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + case 3: return Monster.reader.vTableGetNullable(_bc, _bcOffset, 96); + default: return null; + } + } + List? get vectorOfEnums => const fb.ListReader(Color.reader).vTableGetNullable(_bc, _bcOffset, 98); + Race get signedEnum => Race.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 100, -1)); + List? get testrequirednestedflatbuffer => const fb.Uint8ListReader().vTableGetNullable(_bc, _bcOffset, 102); + List? get scalarKeySortedTables => const fb.ListReader(Stat.reader).vTableGetNullable(_bc, _bcOffset, 104); + Test? get nativeInline => Test.reader.vTableGetNullable(_bc, _bcOffset, 106); + LongEnum get longEnumNonEnumDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 108, 0)); + LongEnum get longEnumNormalDefault => LongEnum.fromValue(const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 110, 2)); + double get nanDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 112, double.nan); + double get infDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 114, double.infinity); + double get positiveInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 116, double.infinity); + double get infinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 118, double.infinity); + double get positiveInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 120, double.infinity); + double get negativeInfDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 122, double.negativeInfinity); + double get negativeInfinityDefault => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 124, double.negativeInfinity); + double get doubleInfDefault => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 126, double.infinity); + + @override + String toString() { + return 'Monster{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}'; + } + + MonsterT unpack() => MonsterT( + pos: pos?.unpack(), + mana: mana, + hp: hp, + name: name, + inventory: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 14), + color: color, + testType: testType, + test: test, + test4: test4?.map((e) => e.unpack()).toList(), + testarrayofstring: const fb.ListReader(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 24), + testarrayoftables: testarrayoftables?.map((e) => e.unpack()).toList(), + enemy: enemy?.unpack(), + testnestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 30), + testempty: testempty?.unpack(), + testbool: testbool, + testhashs32Fnv1: testhashs32Fnv1, + testhashu32Fnv1: testhashu32Fnv1, + testhashs64Fnv1: testhashs64Fnv1, + testhashu64Fnv1: testhashu64Fnv1, + testhashs32Fnv1a: testhashs32Fnv1a, + testhashu32Fnv1a: testhashu32Fnv1a, + testhashs64Fnv1a: testhashs64Fnv1a, + testhashu64Fnv1a: testhashu64Fnv1a, + testarrayofbools: const fb.ListReader(fb.BoolReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 52), + testf: testf, + testf2: testf2, + testf3: testf3, + testarrayofstring2: const fb.ListReader(fb.StringReader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 60), + testarrayofsortedstruct: testarrayofsortedstruct?.map((e) => e.unpack()).toList(), + flex: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 64), + test5: test5?.map((e) => e.unpack()).toList(), + vectorOfLongs: const fb.ListReader(fb.Int64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 68), + vectorOfDoubles: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 70), + parentNamespaceTest: parentNamespaceTest?.unpack(), + vectorOfReferrables: vectorOfReferrables?.map((e) => e.unpack()).toList(), + singleWeakReference: singleWeakReference, + vectorOfWeakReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 78), + vectorOfStrongReferrables: vectorOfStrongReferrables?.map((e) => e.unpack()).toList(), + coOwningReference: coOwningReference, + vectorOfCoOwningReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 84), + nonOwningReference: nonOwningReference, + vectorOfNonOwningReferences: const fb.ListReader(fb.Uint64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 88), + anyUniqueType: anyUniqueType, + anyUnique: anyUnique, + anyAmbiguousType: anyAmbiguousType, + anyAmbiguous: anyAmbiguous, + vectorOfEnums: const fb.ListReader(Color.reader, lazy: false).vTableGetNullable(_bc, _bcOffset, 98), + signedEnum: signedEnum, + testrequirednestedflatbuffer: const fb.Uint8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 102), + scalarKeySortedTables: scalarKeySortedTables?.map((e) => e.unpack()).toList(), + nativeInline: nativeInline?.unpack(), + longEnumNonEnumDefault: longEnumNonEnumDefault, + longEnumNormalDefault: longEnumNormalDefault, + nanDefault: nanDefault, + infDefault: infDefault, + positiveInfDefault: positiveInfDefault, + infinityDefault: infinityDefault, + positiveInfinityDefault: positiveInfinityDefault, + negativeInfDefault: negativeInfDefault, + negativeInfinityDefault: negativeInfinityDefault, + doubleInfDefault: doubleInfDefault); + + static int pack(fb.Builder fbBuilder, MonsterT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +/// an example documentation comment: "monster object" +class MonsterT implements fb.Packable { + Vec3T? pos; + int mana; + int hp; + String? name; + List? inventory; + Color color; + AnyTypeId? testType; + dynamic test; + List? test4; + List? testarrayofstring; + /// an example documentation comment: this will end up in the generated code + /// multiline too + List? testarrayoftables; + MonsterT? enemy; + List? testnestedflatbuffer; + StatT? testempty; + bool testbool; + int testhashs32Fnv1; + int testhashu32Fnv1; + int testhashs64Fnv1; + int testhashu64Fnv1; + int testhashs32Fnv1a; + int testhashu32Fnv1a; + int testhashs64Fnv1a; + int testhashu64Fnv1a; + List? testarrayofbools; + double testf; + double testf2; + double testf3; + List? testarrayofstring2; + List? testarrayofsortedstruct; + List? flex; + List? test5; + List? vectorOfLongs; + List? vectorOfDoubles; + my_game.InParentNamespaceT? parentNamespaceTest; + List? vectorOfReferrables; + int singleWeakReference; + List? vectorOfWeakReferences; + List? vectorOfStrongReferrables; + int coOwningReference; + List? vectorOfCoOwningReferences; + int nonOwningReference; + List? vectorOfNonOwningReferences; + AnyUniqueAliasesTypeId? anyUniqueType; + dynamic anyUnique; + AnyAmbiguousAliasesTypeId? anyAmbiguousType; + dynamic anyAmbiguous; + List? vectorOfEnums; + Race signedEnum; + List? testrequirednestedflatbuffer; + List? scalarKeySortedTables; + TestT? nativeInline; + LongEnum longEnumNonEnumDefault; + LongEnum longEnumNormalDefault; + double nanDefault; + double infDefault; + double positiveInfDefault; + double infinityDefault; + double positiveInfinityDefault; + double negativeInfDefault; + double negativeInfinityDefault; + double doubleInfDefault; + + MonsterT({ + this.pos, + this.mana = 150, + this.hp = 100, + this.name, + this.inventory, + this.color = Color.Blue, + this.testType, + this.test, + this.test4, + this.testarrayofstring, + this.testarrayoftables, + this.enemy, + this.testnestedflatbuffer, + this.testempty, + this.testbool = false, + this.testhashs32Fnv1 = 0, + this.testhashu32Fnv1 = 0, + this.testhashs64Fnv1 = 0, + this.testhashu64Fnv1 = 0, + this.testhashs32Fnv1a = 0, + this.testhashu32Fnv1a = 0, + this.testhashs64Fnv1a = 0, + this.testhashu64Fnv1a = 0, + this.testarrayofbools, + this.testf = 3.14159, + this.testf2 = 3.0, + this.testf3 = 0.0, + this.testarrayofstring2, + this.testarrayofsortedstruct, + this.flex, + this.test5, + this.vectorOfLongs, + this.vectorOfDoubles, + this.parentNamespaceTest, + this.vectorOfReferrables, + this.singleWeakReference = 0, + this.vectorOfWeakReferences, + this.vectorOfStrongReferrables, + this.coOwningReference = 0, + this.vectorOfCoOwningReferences, + this.nonOwningReference = 0, + this.vectorOfNonOwningReferences, + this.anyUniqueType, + this.anyUnique, + this.anyAmbiguousType, + this.anyAmbiguous, + this.vectorOfEnums, + this.signedEnum = Race.None, + this.testrequirednestedflatbuffer, + this.scalarKeySortedTables, + this.nativeInline, + this.longEnumNonEnumDefault = LongEnum._default, + this.longEnumNormalDefault = LongEnum.LongOne, + this.nanDefault = double.nan, + this.infDefault = double.infinity, + this.positiveInfDefault = double.infinity, + this.infinityDefault = double.infinity, + this.positiveInfinityDefault = double.infinity, + this.negativeInfDefault = double.negativeInfinity, + this.negativeInfinityDefault = double.negativeInfinity, + this.doubleInfDefault = double.infinity}); + + @override + int pack(fb.Builder fbBuilder) { + final int? nameOffset = name == null ? null + : fbBuilder.writeString(name!); + final int? inventoryOffset = inventory == null ? null + : fbBuilder.writeListUint8(inventory!); + final int? testOffset = test?.pack(fbBuilder); + int? test4Offset; + if (test4 != null) { + for (var e in test4!) { e.pack(fbBuilder); } + test4Offset = fbBuilder.endStructVector(test4!.length); + } + final int? testarrayofstringOffset = testarrayofstring == null ? null + : fbBuilder.writeList(testarrayofstring!.map(fbBuilder.writeString).toList()); + final int? testarrayoftablesOffset = testarrayoftables == null ? null + : fbBuilder.writeList(testarrayoftables!.map((b) => b.pack(fbBuilder)).toList()); + final int? enemyOffset = enemy?.pack(fbBuilder); + final int? testnestedflatbufferOffset = testnestedflatbuffer == null ? null + : fbBuilder.writeListUint8(testnestedflatbuffer!); + final int? testemptyOffset = testempty?.pack(fbBuilder); + final int? testarrayofboolsOffset = testarrayofbools == null ? null + : fbBuilder.writeListBool(testarrayofbools!); + final int? testarrayofstring2Offset = testarrayofstring2 == null ? null + : fbBuilder.writeList(testarrayofstring2!.map(fbBuilder.writeString).toList()); + int? testarrayofsortedstructOffset; + if (testarrayofsortedstruct != null) { + for (var e in testarrayofsortedstruct!) { e.pack(fbBuilder); } + testarrayofsortedstructOffset = fbBuilder.endStructVector(testarrayofsortedstruct!.length); + } + final int? flexOffset = flex == null ? null + : fbBuilder.writeListUint8(flex!); + int? test5Offset; + if (test5 != null) { + for (var e in test5!) { e.pack(fbBuilder); } + test5Offset = fbBuilder.endStructVector(test5!.length); + } + final int? vectorOfLongsOffset = vectorOfLongs == null ? null + : fbBuilder.writeListInt64(vectorOfLongs!); + final int? vectorOfDoublesOffset = vectorOfDoubles == null ? null + : fbBuilder.writeListFloat64(vectorOfDoubles!); + final int? parentNamespaceTestOffset = parentNamespaceTest?.pack(fbBuilder); + final int? vectorOfReferrablesOffset = vectorOfReferrables == null ? null + : fbBuilder.writeList(vectorOfReferrables!.map((b) => b.pack(fbBuilder)).toList()); + final int? vectorOfWeakReferencesOffset = vectorOfWeakReferences == null ? null + : fbBuilder.writeListUint64(vectorOfWeakReferences!); + final int? vectorOfStrongReferrablesOffset = vectorOfStrongReferrables == null ? null + : fbBuilder.writeList(vectorOfStrongReferrables!.map((b) => b.pack(fbBuilder)).toList()); + final int? vectorOfCoOwningReferencesOffset = vectorOfCoOwningReferences == null ? null + : fbBuilder.writeListUint64(vectorOfCoOwningReferences!); + final int? vectorOfNonOwningReferencesOffset = vectorOfNonOwningReferences == null ? null + : fbBuilder.writeListUint64(vectorOfNonOwningReferences!); + final int? anyUniqueOffset = anyUnique?.pack(fbBuilder); + final int? anyAmbiguousOffset = anyAmbiguous?.pack(fbBuilder); + final int? vectorOfEnumsOffset = vectorOfEnums == null ? null + : fbBuilder.writeListUint8(vectorOfEnums!.map((f) => f.value).toList()); + final int? testrequirednestedflatbufferOffset = testrequirednestedflatbuffer == null ? null + : fbBuilder.writeListUint8(testrequirednestedflatbuffer!); + final int? scalarKeySortedTablesOffset = scalarKeySortedTables == null ? null + : fbBuilder.writeList(scalarKeySortedTables!.map((b) => b.pack(fbBuilder)).toList()); + fbBuilder.startTable(62); + if (pos != null) { + fbBuilder.addStruct(0, pos!.pack(fbBuilder)); + } + fbBuilder.addInt16(1, mana); + fbBuilder.addInt16(2, hp); + fbBuilder.addOffset(3, nameOffset); + fbBuilder.addOffset(5, inventoryOffset); + fbBuilder.addUint8(6, color.value); + fbBuilder.addUint8(7, testType?.value); + fbBuilder.addOffset(8, testOffset); + fbBuilder.addOffset(9, test4Offset); + fbBuilder.addOffset(10, testarrayofstringOffset); + fbBuilder.addOffset(11, testarrayoftablesOffset); + fbBuilder.addOffset(12, enemyOffset); + fbBuilder.addOffset(13, testnestedflatbufferOffset); + fbBuilder.addOffset(14, testemptyOffset); + fbBuilder.addBool(15, testbool); + fbBuilder.addInt32(16, testhashs32Fnv1); + fbBuilder.addUint32(17, testhashu32Fnv1); + fbBuilder.addInt64(18, testhashs64Fnv1); + fbBuilder.addUint64(19, testhashu64Fnv1); + fbBuilder.addInt32(20, testhashs32Fnv1a); + fbBuilder.addUint32(21, testhashu32Fnv1a); + fbBuilder.addInt64(22, testhashs64Fnv1a); + fbBuilder.addUint64(23, testhashu64Fnv1a); + fbBuilder.addOffset(24, testarrayofboolsOffset); + fbBuilder.addFloat32(25, testf); + fbBuilder.addFloat32(26, testf2); + fbBuilder.addFloat32(27, testf3); + fbBuilder.addOffset(28, testarrayofstring2Offset); + fbBuilder.addOffset(29, testarrayofsortedstructOffset); + fbBuilder.addOffset(30, flexOffset); + fbBuilder.addOffset(31, test5Offset); + fbBuilder.addOffset(32, vectorOfLongsOffset); + fbBuilder.addOffset(33, vectorOfDoublesOffset); + fbBuilder.addOffset(34, parentNamespaceTestOffset); + fbBuilder.addOffset(35, vectorOfReferrablesOffset); + fbBuilder.addUint64(36, singleWeakReference); + fbBuilder.addOffset(37, vectorOfWeakReferencesOffset); + fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset); + fbBuilder.addUint64(39, coOwningReference); + fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset); + fbBuilder.addUint64(41, nonOwningReference); + fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset); + fbBuilder.addUint8(43, anyUniqueType?.value); + fbBuilder.addOffset(44, anyUniqueOffset); + fbBuilder.addUint8(45, anyAmbiguousType?.value); + fbBuilder.addOffset(46, anyAmbiguousOffset); + fbBuilder.addOffset(47, vectorOfEnumsOffset); + fbBuilder.addInt8(48, signedEnum.value); + fbBuilder.addOffset(49, testrequirednestedflatbufferOffset); + fbBuilder.addOffset(50, scalarKeySortedTablesOffset); + if (nativeInline != null) { + fbBuilder.addStruct(51, nativeInline!.pack(fbBuilder)); + } + fbBuilder.addUint64(52, longEnumNonEnumDefault.value); + fbBuilder.addUint64(53, longEnumNormalDefault.value); + fbBuilder.addFloat32(54, nanDefault); + fbBuilder.addFloat32(55, infDefault); + fbBuilder.addFloat32(56, positiveInfDefault); + fbBuilder.addFloat32(57, infinityDefault); + fbBuilder.addFloat32(58, positiveInfinityDefault); + fbBuilder.addFloat32(59, negativeInfDefault); + fbBuilder.addFloat32(60, negativeInfinityDefault); + fbBuilder.addFloat64(61, doubleInfDefault); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'MonsterT{pos: ${pos}, mana: ${mana}, hp: ${hp}, name: ${name}, inventory: ${inventory}, color: ${color}, testType: ${testType}, test: ${test}, test4: ${test4}, testarrayofstring: ${testarrayofstring}, testarrayoftables: ${testarrayoftables}, enemy: ${enemy}, testnestedflatbuffer: ${testnestedflatbuffer}, testempty: ${testempty}, testbool: ${testbool}, testhashs32Fnv1: ${testhashs32Fnv1}, testhashu32Fnv1: ${testhashu32Fnv1}, testhashs64Fnv1: ${testhashs64Fnv1}, testhashu64Fnv1: ${testhashu64Fnv1}, testhashs32Fnv1a: ${testhashs32Fnv1a}, testhashu32Fnv1a: ${testhashu32Fnv1a}, testhashs64Fnv1a: ${testhashs64Fnv1a}, testhashu64Fnv1a: ${testhashu64Fnv1a}, testarrayofbools: ${testarrayofbools}, testf: ${testf}, testf2: ${testf2}, testf3: ${testf3}, testarrayofstring2: ${testarrayofstring2}, testarrayofsortedstruct: ${testarrayofsortedstruct}, flex: ${flex}, test5: ${test5}, vectorOfLongs: ${vectorOfLongs}, vectorOfDoubles: ${vectorOfDoubles}, parentNamespaceTest: ${parentNamespaceTest}, vectorOfReferrables: ${vectorOfReferrables}, singleWeakReference: ${singleWeakReference}, vectorOfWeakReferences: ${vectorOfWeakReferences}, vectorOfStrongReferrables: ${vectorOfStrongReferrables}, coOwningReference: ${coOwningReference}, vectorOfCoOwningReferences: ${vectorOfCoOwningReferences}, nonOwningReference: ${nonOwningReference}, vectorOfNonOwningReferences: ${vectorOfNonOwningReferences}, anyUniqueType: ${anyUniqueType}, anyUnique: ${anyUnique}, anyAmbiguousType: ${anyAmbiguousType}, anyAmbiguous: ${anyAmbiguous}, vectorOfEnums: ${vectorOfEnums}, signedEnum: ${signedEnum}, testrequirednestedflatbuffer: ${testrequirednestedflatbuffer}, scalarKeySortedTables: ${scalarKeySortedTables}, nativeInline: ${nativeInline}, longEnumNonEnumDefault: ${longEnumNonEnumDefault}, longEnumNormalDefault: ${longEnumNormalDefault}, nanDefault: ${nanDefault}, infDefault: ${infDefault}, positiveInfDefault: ${positiveInfDefault}, infinityDefault: ${infinityDefault}, positiveInfinityDefault: ${positiveInfinityDefault}, negativeInfDefault: ${negativeInfDefault}, negativeInfinityDefault: ${negativeInfinityDefault}, doubleInfDefault: ${doubleInfDefault}}'; + } +} + +class _MonsterReader extends fb.TableReader { + const _MonsterReader(); + + @override + Monster createObject(fb.BufferContext bc, int offset) => + Monster._(bc, offset); +} + +class MonsterBuilder { + MonsterBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(62); + } + + int addPos(int offset) { + fbBuilder.addStruct(0, offset); + return fbBuilder.offset; + } + int addMana(int? mana) { + fbBuilder.addInt16(1, mana); + return fbBuilder.offset; + } + int addHp(int? hp) { + fbBuilder.addInt16(2, hp); + return fbBuilder.offset; + } + int addNameOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + int addInventoryOffset(int? offset) { + fbBuilder.addOffset(5, offset); + return fbBuilder.offset; + } + int addColor(Color? color) { + fbBuilder.addUint8(6, color?.value); + return fbBuilder.offset; + } + int addTestType(AnyTypeId? testType) { + fbBuilder.addUint8(7, testType?.value); + return fbBuilder.offset; + } + int addTestOffset(int? offset) { + fbBuilder.addOffset(8, offset); + return fbBuilder.offset; + } + int addTest4Offset(int? offset) { + fbBuilder.addOffset(9, offset); + return fbBuilder.offset; + } + int addTestarrayofstringOffset(int? offset) { + fbBuilder.addOffset(10, offset); + return fbBuilder.offset; + } + int addTestarrayoftablesOffset(int? offset) { + fbBuilder.addOffset(11, offset); + return fbBuilder.offset; + } + int addEnemyOffset(int? offset) { + fbBuilder.addOffset(12, offset); + return fbBuilder.offset; + } + int addTestnestedflatbufferOffset(int? offset) { + fbBuilder.addOffset(13, offset); + return fbBuilder.offset; + } + int addTestemptyOffset(int? offset) { + fbBuilder.addOffset(14, offset); + return fbBuilder.offset; + } + int addTestbool(bool? testbool) { + fbBuilder.addBool(15, testbool); + return fbBuilder.offset; + } + int addTesthashs32Fnv1(int? testhashs32Fnv1) { + fbBuilder.addInt32(16, testhashs32Fnv1); + return fbBuilder.offset; + } + int addTesthashu32Fnv1(int? testhashu32Fnv1) { + fbBuilder.addUint32(17, testhashu32Fnv1); + return fbBuilder.offset; + } + int addTesthashs64Fnv1(int? testhashs64Fnv1) { + fbBuilder.addInt64(18, testhashs64Fnv1); + return fbBuilder.offset; + } + int addTesthashu64Fnv1(int? testhashu64Fnv1) { + fbBuilder.addUint64(19, testhashu64Fnv1); + return fbBuilder.offset; + } + int addTesthashs32Fnv1a(int? testhashs32Fnv1a) { + fbBuilder.addInt32(20, testhashs32Fnv1a); + return fbBuilder.offset; + } + int addTesthashu32Fnv1a(int? testhashu32Fnv1a) { + fbBuilder.addUint32(21, testhashu32Fnv1a); + return fbBuilder.offset; + } + int addTesthashs64Fnv1a(int? testhashs64Fnv1a) { + fbBuilder.addInt64(22, testhashs64Fnv1a); + return fbBuilder.offset; + } + int addTesthashu64Fnv1a(int? testhashu64Fnv1a) { + fbBuilder.addUint64(23, testhashu64Fnv1a); + return fbBuilder.offset; + } + int addTestarrayofboolsOffset(int? offset) { + fbBuilder.addOffset(24, offset); + return fbBuilder.offset; + } + int addTestf(double? testf) { + fbBuilder.addFloat32(25, testf); + return fbBuilder.offset; + } + int addTestf2(double? testf2) { + fbBuilder.addFloat32(26, testf2); + return fbBuilder.offset; + } + int addTestf3(double? testf3) { + fbBuilder.addFloat32(27, testf3); + return fbBuilder.offset; + } + int addTestarrayofstring2Offset(int? offset) { + fbBuilder.addOffset(28, offset); + return fbBuilder.offset; + } + int addTestarrayofsortedstructOffset(int? offset) { + fbBuilder.addOffset(29, offset); + return fbBuilder.offset; + } + int addFlexOffset(int? offset) { + fbBuilder.addOffset(30, offset); + return fbBuilder.offset; + } + int addTest5Offset(int? offset) { + fbBuilder.addOffset(31, offset); + return fbBuilder.offset; + } + int addVectorOfLongsOffset(int? offset) { + fbBuilder.addOffset(32, offset); + return fbBuilder.offset; + } + int addVectorOfDoublesOffset(int? offset) { + fbBuilder.addOffset(33, offset); + return fbBuilder.offset; + } + int addParentNamespaceTestOffset(int? offset) { + fbBuilder.addOffset(34, offset); + return fbBuilder.offset; + } + int addVectorOfReferrablesOffset(int? offset) { + fbBuilder.addOffset(35, offset); + return fbBuilder.offset; + } + int addSingleWeakReference(int? singleWeakReference) { + fbBuilder.addUint64(36, singleWeakReference); + return fbBuilder.offset; + } + int addVectorOfWeakReferencesOffset(int? offset) { + fbBuilder.addOffset(37, offset); + return fbBuilder.offset; + } + int addVectorOfStrongReferrablesOffset(int? offset) { + fbBuilder.addOffset(38, offset); + return fbBuilder.offset; + } + int addCoOwningReference(int? coOwningReference) { + fbBuilder.addUint64(39, coOwningReference); + return fbBuilder.offset; + } + int addVectorOfCoOwningReferencesOffset(int? offset) { + fbBuilder.addOffset(40, offset); + return fbBuilder.offset; + } + int addNonOwningReference(int? nonOwningReference) { + fbBuilder.addUint64(41, nonOwningReference); + return fbBuilder.offset; + } + int addVectorOfNonOwningReferencesOffset(int? offset) { + fbBuilder.addOffset(42, offset); + return fbBuilder.offset; + } + int addAnyUniqueType(AnyUniqueAliasesTypeId? anyUniqueType) { + fbBuilder.addUint8(43, anyUniqueType?.value); + return fbBuilder.offset; + } + int addAnyUniqueOffset(int? offset) { + fbBuilder.addOffset(44, offset); + return fbBuilder.offset; + } + int addAnyAmbiguousType(AnyAmbiguousAliasesTypeId? anyAmbiguousType) { + fbBuilder.addUint8(45, anyAmbiguousType?.value); + return fbBuilder.offset; + } + int addAnyAmbiguousOffset(int? offset) { + fbBuilder.addOffset(46, offset); + return fbBuilder.offset; + } + int addVectorOfEnumsOffset(int? offset) { + fbBuilder.addOffset(47, offset); + return fbBuilder.offset; + } + int addSignedEnum(Race? signedEnum) { + fbBuilder.addInt8(48, signedEnum?.value); + return fbBuilder.offset; + } + int addTestrequirednestedflatbufferOffset(int? offset) { + fbBuilder.addOffset(49, offset); + return fbBuilder.offset; + } + int addScalarKeySortedTablesOffset(int? offset) { + fbBuilder.addOffset(50, offset); + return fbBuilder.offset; + } + int addNativeInline(int offset) { + fbBuilder.addStruct(51, offset); + return fbBuilder.offset; + } + int addLongEnumNonEnumDefault(LongEnum? longEnumNonEnumDefault) { + fbBuilder.addUint64(52, longEnumNonEnumDefault?.value); + return fbBuilder.offset; + } + int addLongEnumNormalDefault(LongEnum? longEnumNormalDefault) { + fbBuilder.addUint64(53, longEnumNormalDefault?.value); + return fbBuilder.offset; + } + int addNanDefault(double? nanDefault) { + fbBuilder.addFloat32(54, nanDefault); + return fbBuilder.offset; + } + int addInfDefault(double? infDefault) { + fbBuilder.addFloat32(55, infDefault); + return fbBuilder.offset; + } + int addPositiveInfDefault(double? positiveInfDefault) { + fbBuilder.addFloat32(56, positiveInfDefault); + return fbBuilder.offset; + } + int addInfinityDefault(double? infinityDefault) { + fbBuilder.addFloat32(57, infinityDefault); + return fbBuilder.offset; + } + int addPositiveInfinityDefault(double? positiveInfinityDefault) { + fbBuilder.addFloat32(58, positiveInfinityDefault); + return fbBuilder.offset; + } + int addNegativeInfDefault(double? negativeInfDefault) { + fbBuilder.addFloat32(59, negativeInfDefault); + return fbBuilder.offset; + } + int addNegativeInfinityDefault(double? negativeInfinityDefault) { + fbBuilder.addFloat32(60, negativeInfinityDefault); + return fbBuilder.offset; + } + int addDoubleInfDefault(double? doubleInfDefault) { + fbBuilder.addFloat64(61, doubleInfDefault); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class MonsterObjectBuilder extends fb.ObjectBuilder { + final Vec3ObjectBuilder? _pos; + final int? _mana; + final int? _hp; + final String? _name; + final List? _inventory; + final Color? _color; + final AnyTypeId? _testType; + final dynamic _test; + final List? _test4; + final List? _testarrayofstring; + final List? _testarrayoftables; + final MonsterObjectBuilder? _enemy; + final List? _testnestedflatbuffer; + final StatObjectBuilder? _testempty; + final bool? _testbool; + final int? _testhashs32Fnv1; + final int? _testhashu32Fnv1; + final int? _testhashs64Fnv1; + final int? _testhashu64Fnv1; + final int? _testhashs32Fnv1a; + final int? _testhashu32Fnv1a; + final int? _testhashs64Fnv1a; + final int? _testhashu64Fnv1a; + final List? _testarrayofbools; + final double? _testf; + final double? _testf2; + final double? _testf3; + final List? _testarrayofstring2; + final List? _testarrayofsortedstruct; + final List? _flex; + final List? _test5; + final List? _vectorOfLongs; + final List? _vectorOfDoubles; + final my_game.InParentNamespaceObjectBuilder? _parentNamespaceTest; + final List? _vectorOfReferrables; + final int? _singleWeakReference; + final List? _vectorOfWeakReferences; + final List? _vectorOfStrongReferrables; + final int? _coOwningReference; + final List? _vectorOfCoOwningReferences; + final int? _nonOwningReference; + final List? _vectorOfNonOwningReferences; + final AnyUniqueAliasesTypeId? _anyUniqueType; + final dynamic _anyUnique; + final AnyAmbiguousAliasesTypeId? _anyAmbiguousType; + final dynamic _anyAmbiguous; + final List? _vectorOfEnums; + final Race? _signedEnum; + final List? _testrequirednestedflatbuffer; + final List? _scalarKeySortedTables; + final TestObjectBuilder? _nativeInline; + final LongEnum? _longEnumNonEnumDefault; + final LongEnum? _longEnumNormalDefault; + final double? _nanDefault; + final double? _infDefault; + final double? _positiveInfDefault; + final double? _infinityDefault; + final double? _positiveInfinityDefault; + final double? _negativeInfDefault; + final double? _negativeInfinityDefault; + final double? _doubleInfDefault; + + MonsterObjectBuilder({ + Vec3ObjectBuilder? pos, + int? mana, + int? hp, + String? name, + List? inventory, + Color? color, + AnyTypeId? testType, + dynamic test, + List? test4, + List? testarrayofstring, + List? testarrayoftables, + MonsterObjectBuilder? enemy, + List? testnestedflatbuffer, + StatObjectBuilder? testempty, + bool? testbool, + int? testhashs32Fnv1, + int? testhashu32Fnv1, + int? testhashs64Fnv1, + int? testhashu64Fnv1, + int? testhashs32Fnv1a, + int? testhashu32Fnv1a, + int? testhashs64Fnv1a, + int? testhashu64Fnv1a, + List? testarrayofbools, + double? testf, + double? testf2, + double? testf3, + List? testarrayofstring2, + List? testarrayofsortedstruct, + List? flex, + List? test5, + List? vectorOfLongs, + List? vectorOfDoubles, + my_game.InParentNamespaceObjectBuilder? parentNamespaceTest, + List? vectorOfReferrables, + int? singleWeakReference, + List? vectorOfWeakReferences, + List? vectorOfStrongReferrables, + int? coOwningReference, + List? vectorOfCoOwningReferences, + int? nonOwningReference, + List? vectorOfNonOwningReferences, + AnyUniqueAliasesTypeId? anyUniqueType, + dynamic anyUnique, + AnyAmbiguousAliasesTypeId? anyAmbiguousType, + dynamic anyAmbiguous, + List? vectorOfEnums, + Race? signedEnum, + List? testrequirednestedflatbuffer, + List? scalarKeySortedTables, + TestObjectBuilder? nativeInline, + LongEnum? longEnumNonEnumDefault, + LongEnum? longEnumNormalDefault, + double? nanDefault, + double? infDefault, + double? positiveInfDefault, + double? infinityDefault, + double? positiveInfinityDefault, + double? negativeInfDefault, + double? negativeInfinityDefault, + double? doubleInfDefault, + }) + : _pos = pos, + _mana = mana, + _hp = hp, + _name = name, + _inventory = inventory, + _color = color, + _testType = testType, + _test = test, + _test4 = test4, + _testarrayofstring = testarrayofstring, + _testarrayoftables = testarrayoftables, + _enemy = enemy, + _testnestedflatbuffer = testnestedflatbuffer, + _testempty = testempty, + _testbool = testbool, + _testhashs32Fnv1 = testhashs32Fnv1, + _testhashu32Fnv1 = testhashu32Fnv1, + _testhashs64Fnv1 = testhashs64Fnv1, + _testhashu64Fnv1 = testhashu64Fnv1, + _testhashs32Fnv1a = testhashs32Fnv1a, + _testhashu32Fnv1a = testhashu32Fnv1a, + _testhashs64Fnv1a = testhashs64Fnv1a, + _testhashu64Fnv1a = testhashu64Fnv1a, + _testarrayofbools = testarrayofbools, + _testf = testf, + _testf2 = testf2, + _testf3 = testf3, + _testarrayofstring2 = testarrayofstring2, + _testarrayofsortedstruct = testarrayofsortedstruct, + _flex = flex, + _test5 = test5, + _vectorOfLongs = vectorOfLongs, + _vectorOfDoubles = vectorOfDoubles, + _parentNamespaceTest = parentNamespaceTest, + _vectorOfReferrables = vectorOfReferrables, + _singleWeakReference = singleWeakReference, + _vectorOfWeakReferences = vectorOfWeakReferences, + _vectorOfStrongReferrables = vectorOfStrongReferrables, + _coOwningReference = coOwningReference, + _vectorOfCoOwningReferences = vectorOfCoOwningReferences, + _nonOwningReference = nonOwningReference, + _vectorOfNonOwningReferences = vectorOfNonOwningReferences, + _anyUniqueType = anyUniqueType, + _anyUnique = anyUnique, + _anyAmbiguousType = anyAmbiguousType, + _anyAmbiguous = anyAmbiguous, + _vectorOfEnums = vectorOfEnums, + _signedEnum = signedEnum, + _testrequirednestedflatbuffer = testrequirednestedflatbuffer, + _scalarKeySortedTables = scalarKeySortedTables, + _nativeInline = nativeInline, + _longEnumNonEnumDefault = longEnumNonEnumDefault, + _longEnumNormalDefault = longEnumNormalDefault, + _nanDefault = nanDefault, + _infDefault = infDefault, + _positiveInfDefault = positiveInfDefault, + _infinityDefault = infinityDefault, + _positiveInfinityDefault = positiveInfinityDefault, + _negativeInfDefault = negativeInfDefault, + _negativeInfinityDefault = negativeInfinityDefault, + _doubleInfDefault = doubleInfDefault; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? nameOffset = _name == null ? null + : fbBuilder.writeString(_name!); + final int? inventoryOffset = _inventory == null ? null + : fbBuilder.writeListUint8(_inventory!); + final int? testOffset = _test?.getOrCreateOffset(fbBuilder); + final int? test4Offset = _test4 == null ? null + : fbBuilder.writeListOfStructs(_test4!); + final int? testarrayofstringOffset = _testarrayofstring == null ? null + : fbBuilder.writeList(_testarrayofstring!.map(fbBuilder.writeString).toList()); + final int? testarrayoftablesOffset = _testarrayoftables == null ? null + : fbBuilder.writeList(_testarrayoftables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? enemyOffset = _enemy?.getOrCreateOffset(fbBuilder); + final int? testnestedflatbufferOffset = _testnestedflatbuffer == null ? null + : fbBuilder.writeListUint8(_testnestedflatbuffer!); + final int? testemptyOffset = _testempty?.getOrCreateOffset(fbBuilder); + final int? testarrayofboolsOffset = _testarrayofbools == null ? null + : fbBuilder.writeListBool(_testarrayofbools!); + final int? testarrayofstring2Offset = _testarrayofstring2 == null ? null + : fbBuilder.writeList(_testarrayofstring2!.map(fbBuilder.writeString).toList()); + final int? testarrayofsortedstructOffset = _testarrayofsortedstruct == null ? null + : fbBuilder.writeListOfStructs(_testarrayofsortedstruct!); + final int? flexOffset = _flex == null ? null + : fbBuilder.writeListUint8(_flex!); + final int? test5Offset = _test5 == null ? null + : fbBuilder.writeListOfStructs(_test5!); + final int? vectorOfLongsOffset = _vectorOfLongs == null ? null + : fbBuilder.writeListInt64(_vectorOfLongs!); + final int? vectorOfDoublesOffset = _vectorOfDoubles == null ? null + : fbBuilder.writeListFloat64(_vectorOfDoubles!); + final int? parentNamespaceTestOffset = _parentNamespaceTest?.getOrCreateOffset(fbBuilder); + final int? vectorOfReferrablesOffset = _vectorOfReferrables == null ? null + : fbBuilder.writeList(_vectorOfReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? vectorOfWeakReferencesOffset = _vectorOfWeakReferences == null ? null + : fbBuilder.writeListUint64(_vectorOfWeakReferences!); + final int? vectorOfStrongReferrablesOffset = _vectorOfStrongReferrables == null ? null + : fbBuilder.writeList(_vectorOfStrongReferrables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + final int? vectorOfCoOwningReferencesOffset = _vectorOfCoOwningReferences == null ? null + : fbBuilder.writeListUint64(_vectorOfCoOwningReferences!); + final int? vectorOfNonOwningReferencesOffset = _vectorOfNonOwningReferences == null ? null + : fbBuilder.writeListUint64(_vectorOfNonOwningReferences!); + final int? anyUniqueOffset = _anyUnique?.getOrCreateOffset(fbBuilder); + final int? anyAmbiguousOffset = _anyAmbiguous?.getOrCreateOffset(fbBuilder); + final int? vectorOfEnumsOffset = _vectorOfEnums == null ? null + : fbBuilder.writeListUint8(_vectorOfEnums!.map((f) => f.value).toList()); + final int? testrequirednestedflatbufferOffset = _testrequirednestedflatbuffer == null ? null + : fbBuilder.writeListUint8(_testrequirednestedflatbuffer!); + final int? scalarKeySortedTablesOffset = _scalarKeySortedTables == null ? null + : fbBuilder.writeList(_scalarKeySortedTables!.map((b) => b.getOrCreateOffset(fbBuilder)).toList()); + fbBuilder.startTable(62); + if (_pos != null) { + fbBuilder.addStruct(0, _pos!.finish(fbBuilder)); + } + fbBuilder.addInt16(1, _mana); + fbBuilder.addInt16(2, _hp); + fbBuilder.addOffset(3, nameOffset); + fbBuilder.addOffset(5, inventoryOffset); + fbBuilder.addUint8(6, _color?.value); + fbBuilder.addUint8(7, _testType?.value); + fbBuilder.addOffset(8, testOffset); + fbBuilder.addOffset(9, test4Offset); + fbBuilder.addOffset(10, testarrayofstringOffset); + fbBuilder.addOffset(11, testarrayoftablesOffset); + fbBuilder.addOffset(12, enemyOffset); + fbBuilder.addOffset(13, testnestedflatbufferOffset); + fbBuilder.addOffset(14, testemptyOffset); + fbBuilder.addBool(15, _testbool); + fbBuilder.addInt32(16, _testhashs32Fnv1); + fbBuilder.addUint32(17, _testhashu32Fnv1); + fbBuilder.addInt64(18, _testhashs64Fnv1); + fbBuilder.addUint64(19, _testhashu64Fnv1); + fbBuilder.addInt32(20, _testhashs32Fnv1a); + fbBuilder.addUint32(21, _testhashu32Fnv1a); + fbBuilder.addInt64(22, _testhashs64Fnv1a); + fbBuilder.addUint64(23, _testhashu64Fnv1a); + fbBuilder.addOffset(24, testarrayofboolsOffset); + fbBuilder.addFloat32(25, _testf); + fbBuilder.addFloat32(26, _testf2); + fbBuilder.addFloat32(27, _testf3); + fbBuilder.addOffset(28, testarrayofstring2Offset); + fbBuilder.addOffset(29, testarrayofsortedstructOffset); + fbBuilder.addOffset(30, flexOffset); + fbBuilder.addOffset(31, test5Offset); + fbBuilder.addOffset(32, vectorOfLongsOffset); + fbBuilder.addOffset(33, vectorOfDoublesOffset); + fbBuilder.addOffset(34, parentNamespaceTestOffset); + fbBuilder.addOffset(35, vectorOfReferrablesOffset); + fbBuilder.addUint64(36, _singleWeakReference); + fbBuilder.addOffset(37, vectorOfWeakReferencesOffset); + fbBuilder.addOffset(38, vectorOfStrongReferrablesOffset); + fbBuilder.addUint64(39, _coOwningReference); + fbBuilder.addOffset(40, vectorOfCoOwningReferencesOffset); + fbBuilder.addUint64(41, _nonOwningReference); + fbBuilder.addOffset(42, vectorOfNonOwningReferencesOffset); + fbBuilder.addUint8(43, _anyUniqueType?.value); + fbBuilder.addOffset(44, anyUniqueOffset); + fbBuilder.addUint8(45, _anyAmbiguousType?.value); + fbBuilder.addOffset(46, anyAmbiguousOffset); + fbBuilder.addOffset(47, vectorOfEnumsOffset); + fbBuilder.addInt8(48, _signedEnum?.value); + fbBuilder.addOffset(49, testrequirednestedflatbufferOffset); + fbBuilder.addOffset(50, scalarKeySortedTablesOffset); + if (_nativeInline != null) { + fbBuilder.addStruct(51, _nativeInline!.finish(fbBuilder)); + } + fbBuilder.addUint64(52, _longEnumNonEnumDefault?.value); + fbBuilder.addUint64(53, _longEnumNormalDefault?.value); + fbBuilder.addFloat32(54, _nanDefault); + fbBuilder.addFloat32(55, _infDefault); + fbBuilder.addFloat32(56, _positiveInfDefault); + fbBuilder.addFloat32(57, _infinityDefault); + fbBuilder.addFloat32(58, _positiveInfinityDefault); + fbBuilder.addFloat32(59, _negativeInfDefault); + fbBuilder.addFloat32(60, _negativeInfinityDefault); + fbBuilder.addFloat64(61, _doubleInfDefault); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class TypeAliases { + TypeAliases._(this._bc, this._bcOffset); + factory TypeAliases(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TypeAliasesReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get i8 => const fb.Int8Reader().vTableGet(_bc, _bcOffset, 4, 0); + int get u8 => const fb.Uint8Reader().vTableGet(_bc, _bcOffset, 6, 0); + int get i16 => const fb.Int16Reader().vTableGet(_bc, _bcOffset, 8, 0); + int get u16 => const fb.Uint16Reader().vTableGet(_bc, _bcOffset, 10, 0); + int get i32 => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 12, 0); + int get u32 => const fb.Uint32Reader().vTableGet(_bc, _bcOffset, 14, 0); + int get i64 => const fb.Int64Reader().vTableGet(_bc, _bcOffset, 16, 0); + int get u64 => const fb.Uint64Reader().vTableGet(_bc, _bcOffset, 18, 0); + double get f32 => const fb.Float32Reader().vTableGet(_bc, _bcOffset, 20, 0.0); + double get f64 => const fb.Float64Reader().vTableGet(_bc, _bcOffset, 22, 0.0); + List? get v8 => const fb.Int8ListReader().vTableGetNullable(_bc, _bcOffset, 24); + List? get vf64 => const fb.ListReader(fb.Float64Reader()).vTableGetNullable(_bc, _bcOffset, 26); + + @override + String toString() { + return 'TypeAliases{i8: ${i8}, u8: ${u8}, i16: ${i16}, u16: ${u16}, i32: ${i32}, u32: ${u32}, i64: ${i64}, u64: ${u64}, f32: ${f32}, f64: ${f64}, v8: ${v8}, vf64: ${vf64}}'; + } + + TypeAliasesT unpack() => TypeAliasesT( + i8: i8, + u8: u8, + i16: i16, + u16: u16, + i32: i32, + u32: u32, + i64: i64, + u64: u64, + f32: f32, + f64: f64, + v8: const fb.Int8ListReader(lazy: false).vTableGetNullable(_bc, _bcOffset, 24), + vf64: const fb.ListReader(fb.Float64Reader(), lazy: false).vTableGetNullable(_bc, _bcOffset, 26)); + + static int pack(fb.Builder fbBuilder, TypeAliasesT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TypeAliasesT implements fb.Packable { + int i8; + int u8; + int i16; + int u16; + int i32; + int u32; + int i64; + int u64; + double f32; + double f64; + List? v8; + List? vf64; + + TypeAliasesT({ + this.i8 = 0, + this.u8 = 0, + this.i16 = 0, + this.u16 = 0, + this.i32 = 0, + this.u32 = 0, + this.i64 = 0, + this.u64 = 0, + this.f32 = 0.0, + this.f64 = 0.0, + this.v8, + this.vf64}); + + @override + int pack(fb.Builder fbBuilder) { + final int? v8Offset = v8 == null ? null + : fbBuilder.writeListInt8(v8!); + final int? vf64Offset = vf64 == null ? null + : fbBuilder.writeListFloat64(vf64!); + fbBuilder.startTable(12); + fbBuilder.addInt8(0, i8); + fbBuilder.addUint8(1, u8); + fbBuilder.addInt16(2, i16); + fbBuilder.addUint16(3, u16); + fbBuilder.addInt32(4, i32); + fbBuilder.addUint32(5, u32); + fbBuilder.addInt64(6, i64); + fbBuilder.addUint64(7, u64); + fbBuilder.addFloat32(8, f32); + fbBuilder.addFloat64(9, f64); + fbBuilder.addOffset(10, v8Offset); + fbBuilder.addOffset(11, vf64Offset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TypeAliasesT{i8: ${i8}, u8: ${u8}, i16: ${i16}, u16: ${u16}, i32: ${i32}, u32: ${u32}, i64: ${i64}, u64: ${u64}, f32: ${f32}, f64: ${f64}, v8: ${v8}, vf64: ${vf64}}'; + } +} + +class _TypeAliasesReader extends fb.TableReader { + const _TypeAliasesReader(); + + @override + TypeAliases createObject(fb.BufferContext bc, int offset) => + TypeAliases._(bc, offset); +} + +class TypeAliasesBuilder { + TypeAliasesBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(12); + } + + int addI8(int? i8) { + fbBuilder.addInt8(0, i8); + return fbBuilder.offset; + } + int addU8(int? u8) { + fbBuilder.addUint8(1, u8); + return fbBuilder.offset; + } + int addI16(int? i16) { + fbBuilder.addInt16(2, i16); + return fbBuilder.offset; + } + int addU16(int? u16) { + fbBuilder.addUint16(3, u16); + return fbBuilder.offset; + } + int addI32(int? i32) { + fbBuilder.addInt32(4, i32); + return fbBuilder.offset; + } + int addU32(int? u32) { + fbBuilder.addUint32(5, u32); + return fbBuilder.offset; + } + int addI64(int? i64) { + fbBuilder.addInt64(6, i64); + return fbBuilder.offset; + } + int addU64(int? u64) { + fbBuilder.addUint64(7, u64); + return fbBuilder.offset; + } + int addF32(double? f32) { + fbBuilder.addFloat32(8, f32); + return fbBuilder.offset; + } + int addF64(double? f64) { + fbBuilder.addFloat64(9, f64); + return fbBuilder.offset; + } + int addV8Offset(int? offset) { + fbBuilder.addOffset(10, offset); + return fbBuilder.offset; + } + int addVf64Offset(int? offset) { + fbBuilder.addOffset(11, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TypeAliasesObjectBuilder extends fb.ObjectBuilder { + final int? _i8; + final int? _u8; + final int? _i16; + final int? _u16; + final int? _i32; + final int? _u32; + final int? _i64; + final int? _u64; + final double? _f32; + final double? _f64; + final List? _v8; + final List? _vf64; + + TypeAliasesObjectBuilder({ + int? i8, + int? u8, + int? i16, + int? u16, + int? i32, + int? u32, + int? i64, + int? u64, + double? f32, + double? f64, + List? v8, + List? vf64, + }) + : _i8 = i8, + _u8 = u8, + _i16 = i16, + _u16 = u16, + _i32 = i32, + _u32 = u32, + _i64 = i64, + _u64 = u64, + _f32 = f32, + _f64 = f64, + _v8 = v8, + _vf64 = vf64; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? v8Offset = _v8 == null ? null + : fbBuilder.writeListInt8(_v8!); + final int? vf64Offset = _vf64 == null ? null + : fbBuilder.writeListFloat64(_vf64!); + fbBuilder.startTable(12); + fbBuilder.addInt8(0, _i8); + fbBuilder.addUint8(1, _u8); + fbBuilder.addInt16(2, _i16); + fbBuilder.addUint16(3, _u16); + fbBuilder.addInt32(4, _i32); + fbBuilder.addUint32(5, _u32); + fbBuilder.addInt64(6, _i64); + fbBuilder.addUint64(7, _u64); + fbBuilder.addFloat32(8, _f32); + fbBuilder.addFloat64(9, _f64); + fbBuilder.addOffset(10, v8Offset); + fbBuilder.addOffset(11, vf64Offset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/monster_test_my_game_generated.dart b/third_party/flatbuffers/tests/monster_test_my_game_generated.dart new file mode 100644 index 00000000000..461d06dfa85 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_my_game_generated.dart @@ -0,0 +1,79 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable, constant_identifier_names + +library my_game; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './monster_test_my_game.example_generated.dart' as my_game_example; +import './monster_test_my_game.example2_generated.dart' as my_game_example2; + +import './include_test1_generated.dart'; + +class InParentNamespace { + InParentNamespace._(this._bc, this._bcOffset); + factory InParentNamespace(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _InParentNamespaceReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + + @override + String toString() { + return 'InParentNamespace{}'; + } + + InParentNamespaceT unpack() => InParentNamespaceT(); + + static int pack(fb.Builder fbBuilder, InParentNamespaceT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class InParentNamespaceT implements fb.Packable { + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'InParentNamespaceT{}'; + } +} + +class _InParentNamespaceReader extends fb.TableReader { + const _InParentNamespaceReader(); + + @override + InParentNamespace createObject(fb.BufferContext bc, int offset) => + InParentNamespace._(bc, offset); +} + +class InParentNamespaceObjectBuilder extends fb.ObjectBuilder { + + InParentNamespaceObjectBuilder(); + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(0); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/mod.rs b/third_party/flatbuffers/tests/monster_test_serialize/mod.rs new file mode 100644 index 00000000000..7f1fab13624 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/mod.rs @@ -0,0 +1,58 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod my_game { + use super::*; + pub mod example { + use super::*; + mod color_generated; + pub use self::color_generated::*; + mod race_generated; + pub use self::race_generated::*; + mod long_enum_generated; + pub use self::long_enum_generated::*; + mod any_generated; + pub use self::any_generated::*; + mod any_unique_aliases_generated; + pub use self::any_unique_aliases_generated::*; + mod any_ambiguous_aliases_generated; + pub use self::any_ambiguous_aliases_generated::*; + mod test_generated; + pub use self::test_generated::*; + mod test_simple_table_with_enum_generated; + pub use self::test_simple_table_with_enum_generated::*; + mod vec_3_generated; + pub use self::vec_3_generated::*; + mod ability_generated; + pub use self::ability_generated::*; + mod struct_of_structs_generated; + pub use self::struct_of_structs_generated::*; + mod struct_of_structs_of_structs_generated; + pub use self::struct_of_structs_of_structs_generated::*; + mod stat_generated; + pub use self::stat_generated::*; + mod referrable_generated; + pub use self::referrable_generated::*; + mod monster_generated; + pub use self::monster_generated::*; + mod type_aliases_generated; + pub use self::type_aliases_generated::*; + } // example + pub mod example_2 { + use super::*; + mod monster_generated; + pub use self::monster_generated::*; + } // example_2 + pub mod other_name_space { + use super::*; + mod from_include_generated; + pub use self::from_include_generated::*; + mod unused_generated; + pub use self::unused_generated::*; + mod table_b_generated; + pub use self::table_b_generated::*; + } // other_name_space + mod in_parent_namespace_generated; + pub use self::in_parent_namespace_generated::*; +} // my_game +mod table_a_generated; +pub use self::table_a_generated::*; diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/ability_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/ability_generated.rs new file mode 100644 index 00000000000..88f380206c1 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/ability_generated.rs @@ -0,0 +1,187 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Ability, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Ability(pub [u8; 8]); +impl Default for Ability { + fn default() -> Self { + Self([0; 8]) + } +} +impl core::fmt::Debug for Ability { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Ability") + .field("id", &self.id()) + .field("distance", &self.distance()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Ability {} +impl<'a> flatbuffers::Follow<'a> for Ability { + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Ability>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Ability { + type Inner = &'a Ability; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Ability { + type Output = Ability; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Ability as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Ability { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl Serialize for Ability { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Ability", 2)?; + s.serialize_field("id", &self.id())?; + s.serialize_field("distance", &self.distance())?; + s.end() + } +} + +impl<'a> Ability { + #[allow(clippy::too_many_arguments)] + pub fn new( + id: u32, + distance: u32, + ) -> Self { + let mut s = Self([0; 8]); + s.set_id(id); + s.set_distance(distance); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Ability" + } + + pub fn id(&self) -> u32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_id(&mut self, x: u32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + #[inline] + pub fn key_compare_less_than(&self, o: &Ability) -> bool { + self.id() < o.id() + } + + #[inline] + pub fn key_compare_with_value(&self, val: u32) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } + pub fn distance(&self) -> u32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_distance(&mut self, x: u32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> AbilityT { + AbilityT { + id: self.id(), + distance: self.distance(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct AbilityT { + pub id: u32, + pub distance: u32, +} +impl AbilityT { + pub fn pack(&self) -> Ability { + Ability::new( + self.id, + self.distance, + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs new file mode 100644 index 00000000000..a8e25b6b54d --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_ambiguous_aliases_generated.rs @@ -0,0 +1,212 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY_AMBIGUOUS_ALIASES: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY_AMBIGUOUS_ALIASES: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY_AMBIGUOUS_ALIASES: [AnyAmbiguousAliases; 4] = [ + AnyAmbiguousAliases::NONE, + AnyAmbiguousAliases::M1, + AnyAmbiguousAliases::M2, + AnyAmbiguousAliases::M3, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct AnyAmbiguousAliases(pub u8); +#[allow(non_upper_case_globals)] +impl AnyAmbiguousAliases { + pub const NONE: Self = Self(0); + pub const M1: Self = Self(1); + pub const M2: Self = Self(2); + pub const M3: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M1, + Self::M2, + Self::M3, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M1 => Some("M1"), + Self::M2 => Some("M2"), + Self::M3 => Some("M3"), + _ => None, + } + } +} +impl core::fmt::Debug for AnyAmbiguousAliases { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl Serialize for AnyAmbiguousAliases { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("AnyAmbiguousAliases", self.0 as u32, self.variant_name().unwrap()) + } +} + +impl<'a> flatbuffers::Follow<'a> for AnyAmbiguousAliases { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for AnyAmbiguousAliases { + type Output = AnyAmbiguousAliases; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for AnyAmbiguousAliases { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for AnyAmbiguousAliases { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for AnyAmbiguousAliases {} +pub struct AnyAmbiguousAliasesUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum AnyAmbiguousAliasesT { + NONE, + M1(Box), + M2(Box), + M3(Box), +} +impl Default for AnyAmbiguousAliasesT { + fn default() -> Self { + Self::NONE + } +} +impl AnyAmbiguousAliasesT { + pub fn any_ambiguous_aliases_type(&self) -> AnyAmbiguousAliases { + match self { + Self::NONE => AnyAmbiguousAliases::NONE, + Self::M1(_) => AnyAmbiguousAliases::M1, + Self::M2(_) => AnyAmbiguousAliases::M2, + Self::M3(_) => AnyAmbiguousAliases::M3, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::M1(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), + Self::M3(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m1(&mut self) -> Option> { + if let Self::M1(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M1(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m1(&self) -> Option<&MonsterT> { + if let Self::M1(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m1_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M1(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m2(&self) -> Option<&MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m3(&mut self) -> Option> { + if let Self::M3(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M3(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m3(&self) -> Option<&MonsterT> { + if let Self::M3(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m3_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M3(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_generated.rs new file mode 100644 index 00000000000..b4c49a3ce93 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_generated.rs @@ -0,0 +1,212 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY: [Any; 4] = [ + Any::NONE, + Any::Monster, + Any::TestSimpleTableWithEnum, + Any::MyGame_Example2_Monster, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct Any(pub u8); +#[allow(non_upper_case_globals)] +impl Any { + pub const NONE: Self = Self(0); + pub const Monster: Self = Self(1); + pub const TestSimpleTableWithEnum: Self = Self(2); + pub const MyGame_Example2_Monster: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::Monster, + Self::TestSimpleTableWithEnum, + Self::MyGame_Example2_Monster, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::Monster => Some("Monster"), + Self::TestSimpleTableWithEnum => Some("TestSimpleTableWithEnum"), + Self::MyGame_Example2_Monster => Some("MyGame_Example2_Monster"), + _ => None, + } + } +} +impl core::fmt::Debug for Any { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl Serialize for Any { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("Any", self.0 as u32, self.variant_name().unwrap()) + } +} + +impl<'a> flatbuffers::Follow<'a> for Any { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for Any { + type Output = Any; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for Any { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for Any { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Any {} +pub struct AnyUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum AnyT { + NONE, + Monster(Box), + TestSimpleTableWithEnum(Box), + MyGameExample2Monster(Box), +} +impl Default for AnyT { + fn default() -> Self { + Self::NONE + } +} +impl AnyT { + pub fn any_type(&self) -> Any { + match self { + Self::NONE => Any::NONE, + Self::Monster(_) => Any::Monster, + Self::TestSimpleTableWithEnum(_) => Any::TestSimpleTableWithEnum, + Self::MyGameExample2Monster(_) => Any::MyGame_Example2_Monster, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::Monster(v) => Some(v.pack(fbb).as_union_value()), + Self::TestSimpleTableWithEnum(v) => Some(v.pack(fbb).as_union_value()), + Self::MyGameExample2Monster(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_monster(&mut self) -> Option> { + if let Self::Monster(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_monster(&self) -> Option<&MonsterT> { + if let Self::Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_monster_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::Monster(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_test_simple_table_with_enum(&mut self) -> Option> { + if let Self::TestSimpleTableWithEnum(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::TestSimpleTableWithEnum(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_test_simple_table_with_enum_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TestSimpleTableWithEnum(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_my_game_example_2_monster(&mut self) -> Option> { + if let Self::MyGameExample2Monster(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::MyGameExample2Monster(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster(&self) -> Option<&super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_my_game_example_2_monster_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::MyGameExample2Monster(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs new file mode 100644 index 00000000000..389cee9b433 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/any_unique_aliases_generated.rs @@ -0,0 +1,212 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY_UNIQUE_ALIASES: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY_UNIQUE_ALIASES: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY_UNIQUE_ALIASES: [AnyUniqueAliases; 4] = [ + AnyUniqueAliases::NONE, + AnyUniqueAliases::M, + AnyUniqueAliases::TS, + AnyUniqueAliases::M2, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct AnyUniqueAliases(pub u8); +#[allow(non_upper_case_globals)] +impl AnyUniqueAliases { + pub const NONE: Self = Self(0); + pub const M: Self = Self(1); + pub const TS: Self = Self(2); + pub const M2: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::M, + Self::TS, + Self::M2, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::M => Some("M"), + Self::TS => Some("TS"), + Self::M2 => Some("M2"), + _ => None, + } + } +} +impl core::fmt::Debug for AnyUniqueAliases { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl Serialize for AnyUniqueAliases { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("AnyUniqueAliases", self.0 as u32, self.variant_name().unwrap()) + } +} + +impl<'a> flatbuffers::Follow<'a> for AnyUniqueAliases { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for AnyUniqueAliases { + type Output = AnyUniqueAliases; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for AnyUniqueAliases { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for AnyUniqueAliases { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for AnyUniqueAliases {} +pub struct AnyUniqueAliasesUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum AnyUniqueAliasesT { + NONE, + M(Box), + TS(Box), + M2(Box), +} +impl Default for AnyUniqueAliasesT { + fn default() -> Self { + Self::NONE + } +} +impl AnyUniqueAliasesT { + pub fn any_unique_aliases_type(&self) -> AnyUniqueAliases { + match self { + Self::NONE => AnyUniqueAliases::NONE, + Self::M(_) => AnyUniqueAliases::M, + Self::TS(_) => AnyUniqueAliases::TS, + Self::M2(_) => AnyUniqueAliases::M2, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::M(v) => Some(v.pack(fbb).as_union_value()), + Self::TS(v) => Some(v.pack(fbb).as_union_value()), + Self::M2(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned MonsterT, setting the union to NONE. + pub fn take_m(&mut self) -> Option> { + if let Self::M(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the MonsterT. + pub fn as_m(&self) -> Option<&MonsterT> { + if let Self::M(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the MonsterT. + pub fn as_m_mut(&mut self) -> Option<&mut MonsterT> { + if let Self::M(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned TestSimpleTableWithEnumT, setting the union to NONE. + pub fn take_ts(&mut self) -> Option> { + if let Self::TS(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::TS(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the TestSimpleTableWithEnumT. + pub fn as_ts(&self) -> Option<&TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TestSimpleTableWithEnumT. + pub fn as_ts_mut(&mut self) -> Option<&mut TestSimpleTableWithEnumT> { + if let Self::TS(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned super::example_2::MonsterT, setting the union to NONE. + pub fn take_m2(&mut self) -> Option> { + if let Self::M2(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::M2(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the super::example_2::MonsterT. + pub fn as_m2(&self) -> Option<&super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the super::example_2::MonsterT. + pub fn as_m2_mut(&mut self) -> Option<&mut super::example_2::MonsterT> { + if let Self::M2(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/color_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/color_generated.rs new file mode 100644 index 00000000000..d6879de592c --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/color_generated.rs @@ -0,0 +1,81 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[allow(non_upper_case_globals)] +mod bitflags_color { + flatbuffers::bitflags::bitflags! { + /// Composite components of Monster color. + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct Color: u8 { + const Red = 1; + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + const Green = 2; + /// \brief color Blue (1u << 3) + const Blue = 8; + } + } +} +pub use self::bitflags_color::Color; + +impl Serialize for Color { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_u32(self.bits() as u32) + } +} + +impl<'a> flatbuffers::Follow<'a> for Color { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self::from_bits_retain(b) + } +} + +impl flatbuffers::Push for Color { + type Output = Color; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.bits()); + } +} + +impl flatbuffers::EndianScalar for Color { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self::from_bits_retain(b) + } +} + +impl<'a> flatbuffers::Verifiable for Color { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Color {} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/long_enum_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/long_enum_generated.rs new file mode 100644 index 00000000000..e588ae0e4af --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/long_enum_generated.rs @@ -0,0 +1,77 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[allow(non_upper_case_globals)] +mod bitflags_long_enum { + flatbuffers::bitflags::bitflags! { + #[derive(Default, Debug, Clone, Copy, PartialEq)] + pub struct LongEnum: u64 { + const LongOne = 2; + const LongTwo = 4; + const LongBig = 1099511627776; + } + } +} +pub use self::bitflags_long_enum::LongEnum; + +impl Serialize for LongEnum { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_u32(self.bits() as u32) + } +} + +impl<'a> flatbuffers::Follow<'a> for LongEnum { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self::from_bits_retain(b) + } +} + +impl flatbuffers::Push for LongEnum { + type Output = LongEnum; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.bits()); + } +} + +impl flatbuffers::EndianScalar for LongEnum { + type Scalar = u64; + #[inline] + fn to_little_endian(self) -> u64 { + self.bits().to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u64) -> Self { + let b = u64::from_le(v); + Self::from_bits_retain(b) + } +} + +impl<'a> flatbuffers::Verifiable for LongEnum { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for LongEnum {} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/monster_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/monster_generated.rs new file mode 100644 index 00000000000..5457507dd6b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/monster_generated.rs @@ -0,0 +1,2242 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum MonsterOffset {} +#[derive(Copy, Clone, PartialEq)] + +/// an example documentation comment: "monster object" +pub struct Monster<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Monster<'a> { + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Monster<'a> { + pub const VT_POS: flatbuffers::VOffsetT = 4; + pub const VT_MANA: flatbuffers::VOffsetT = 6; + pub const VT_HP: flatbuffers::VOffsetT = 8; + pub const VT_NAME: flatbuffers::VOffsetT = 10; + pub const VT_INVENTORY: flatbuffers::VOffsetT = 14; + pub const VT_COLOR: flatbuffers::VOffsetT = 16; + pub const VT_TEST_TYPE: flatbuffers::VOffsetT = 18; + pub const VT_TEST: flatbuffers::VOffsetT = 20; + pub const VT_TEST4: flatbuffers::VOffsetT = 22; + pub const VT_TESTARRAYOFSTRING: flatbuffers::VOffsetT = 24; + pub const VT_TESTARRAYOFTABLES: flatbuffers::VOffsetT = 26; + pub const VT_ENEMY: flatbuffers::VOffsetT = 28; + pub const VT_TESTNESTEDFLATBUFFER: flatbuffers::VOffsetT = 30; + pub const VT_TESTEMPTY: flatbuffers::VOffsetT = 32; + pub const VT_TESTBOOL: flatbuffers::VOffsetT = 34; + pub const VT_TESTHASHS32_FNV1: flatbuffers::VOffsetT = 36; + pub const VT_TESTHASHU32_FNV1: flatbuffers::VOffsetT = 38; + pub const VT_TESTHASHS64_FNV1: flatbuffers::VOffsetT = 40; + pub const VT_TESTHASHU64_FNV1: flatbuffers::VOffsetT = 42; + pub const VT_TESTHASHS32_FNV1A: flatbuffers::VOffsetT = 44; + pub const VT_TESTHASHU32_FNV1A: flatbuffers::VOffsetT = 46; + pub const VT_TESTHASHS64_FNV1A: flatbuffers::VOffsetT = 48; + pub const VT_TESTHASHU64_FNV1A: flatbuffers::VOffsetT = 50; + pub const VT_TESTARRAYOFBOOLS: flatbuffers::VOffsetT = 52; + pub const VT_TESTF: flatbuffers::VOffsetT = 54; + pub const VT_TESTF2: flatbuffers::VOffsetT = 56; + pub const VT_TESTF3: flatbuffers::VOffsetT = 58; + pub const VT_TESTARRAYOFSTRING2: flatbuffers::VOffsetT = 60; + pub const VT_TESTARRAYOFSORTEDSTRUCT: flatbuffers::VOffsetT = 62; + pub const VT_FLEX: flatbuffers::VOffsetT = 64; + pub const VT_TEST5: flatbuffers::VOffsetT = 66; + pub const VT_VECTOR_OF_LONGS: flatbuffers::VOffsetT = 68; + pub const VT_VECTOR_OF_DOUBLES: flatbuffers::VOffsetT = 70; + pub const VT_PARENT_NAMESPACE_TEST: flatbuffers::VOffsetT = 72; + pub const VT_VECTOR_OF_REFERRABLES: flatbuffers::VOffsetT = 74; + pub const VT_SINGLE_WEAK_REFERENCE: flatbuffers::VOffsetT = 76; + pub const VT_VECTOR_OF_WEAK_REFERENCES: flatbuffers::VOffsetT = 78; + pub const VT_VECTOR_OF_STRONG_REFERRABLES: flatbuffers::VOffsetT = 80; + pub const VT_CO_OWNING_REFERENCE: flatbuffers::VOffsetT = 82; + pub const VT_VECTOR_OF_CO_OWNING_REFERENCES: flatbuffers::VOffsetT = 84; + pub const VT_NON_OWNING_REFERENCE: flatbuffers::VOffsetT = 86; + pub const VT_VECTOR_OF_NON_OWNING_REFERENCES: flatbuffers::VOffsetT = 88; + pub const VT_ANY_UNIQUE_TYPE: flatbuffers::VOffsetT = 90; + pub const VT_ANY_UNIQUE: flatbuffers::VOffsetT = 92; + pub const VT_ANY_AMBIGUOUS_TYPE: flatbuffers::VOffsetT = 94; + pub const VT_ANY_AMBIGUOUS: flatbuffers::VOffsetT = 96; + pub const VT_VECTOR_OF_ENUMS: flatbuffers::VOffsetT = 98; + pub const VT_SIGNED_ENUM: flatbuffers::VOffsetT = 100; + pub const VT_TESTREQUIREDNESTEDFLATBUFFER: flatbuffers::VOffsetT = 102; + pub const VT_SCALAR_KEY_SORTED_TABLES: flatbuffers::VOffsetT = 104; + pub const VT_NATIVE_INLINE: flatbuffers::VOffsetT = 106; + pub const VT_LONG_ENUM_NON_ENUM_DEFAULT: flatbuffers::VOffsetT = 108; + pub const VT_LONG_ENUM_NORMAL_DEFAULT: flatbuffers::VOffsetT = 110; + pub const VT_NAN_DEFAULT: flatbuffers::VOffsetT = 112; + pub const VT_INF_DEFAULT: flatbuffers::VOffsetT = 114; + pub const VT_POSITIVE_INF_DEFAULT: flatbuffers::VOffsetT = 116; + pub const VT_INFINITY_DEFAULT: flatbuffers::VOffsetT = 118; + pub const VT_POSITIVE_INFINITY_DEFAULT: flatbuffers::VOffsetT = 120; + pub const VT_NEGATIVE_INF_DEFAULT: flatbuffers::VOffsetT = 122; + pub const VT_NEGATIVE_INFINITY_DEFAULT: flatbuffers::VOffsetT = 124; + pub const VT_DOUBLE_INF_DEFAULT: flatbuffers::VOffsetT = 126; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Monster" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Monster { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MonsterArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.add_double_inf_default(args.double_inf_default); + builder.add_long_enum_normal_default(args.long_enum_normal_default); + builder.add_long_enum_non_enum_default(args.long_enum_non_enum_default); + builder.add_non_owning_reference(args.non_owning_reference); + builder.add_co_owning_reference(args.co_owning_reference); + builder.add_single_weak_reference(args.single_weak_reference); + builder.add_testhashu64_fnv1a(args.testhashu64_fnv1a); + builder.add_testhashs64_fnv1a(args.testhashs64_fnv1a); + builder.add_testhashu64_fnv1(args.testhashu64_fnv1); + builder.add_testhashs64_fnv1(args.testhashs64_fnv1); + builder.add_negative_infinity_default(args.negative_infinity_default); + builder.add_negative_inf_default(args.negative_inf_default); + builder.add_positive_infinity_default(args.positive_infinity_default); + builder.add_infinity_default(args.infinity_default); + builder.add_positive_inf_default(args.positive_inf_default); + builder.add_inf_default(args.inf_default); + builder.add_nan_default(args.nan_default); + if let Some(x) = args.native_inline { builder.add_native_inline(x); } + if let Some(x) = args.scalar_key_sorted_tables { builder.add_scalar_key_sorted_tables(x); } + if let Some(x) = args.testrequirednestedflatbuffer { builder.add_testrequirednestedflatbuffer(x); } + if let Some(x) = args.vector_of_enums { builder.add_vector_of_enums(x); } + if let Some(x) = args.any_ambiguous { builder.add_any_ambiguous(x); } + if let Some(x) = args.any_unique { builder.add_any_unique(x); } + if let Some(x) = args.vector_of_non_owning_references { builder.add_vector_of_non_owning_references(x); } + if let Some(x) = args.vector_of_co_owning_references { builder.add_vector_of_co_owning_references(x); } + if let Some(x) = args.vector_of_strong_referrables { builder.add_vector_of_strong_referrables(x); } + if let Some(x) = args.vector_of_weak_references { builder.add_vector_of_weak_references(x); } + if let Some(x) = args.vector_of_referrables { builder.add_vector_of_referrables(x); } + if let Some(x) = args.parent_namespace_test { builder.add_parent_namespace_test(x); } + if let Some(x) = args.vector_of_doubles { builder.add_vector_of_doubles(x); } + if let Some(x) = args.vector_of_longs { builder.add_vector_of_longs(x); } + if let Some(x) = args.test5 { builder.add_test5(x); } + if let Some(x) = args.flex { builder.add_flex(x); } + if let Some(x) = args.testarrayofsortedstruct { builder.add_testarrayofsortedstruct(x); } + if let Some(x) = args.testarrayofstring2 { builder.add_testarrayofstring2(x); } + builder.add_testf3(args.testf3); + builder.add_testf2(args.testf2); + builder.add_testf(args.testf); + if let Some(x) = args.testarrayofbools { builder.add_testarrayofbools(x); } + builder.add_testhashu32_fnv1a(args.testhashu32_fnv1a); + builder.add_testhashs32_fnv1a(args.testhashs32_fnv1a); + builder.add_testhashu32_fnv1(args.testhashu32_fnv1); + builder.add_testhashs32_fnv1(args.testhashs32_fnv1); + if let Some(x) = args.testempty { builder.add_testempty(x); } + if let Some(x) = args.testnestedflatbuffer { builder.add_testnestedflatbuffer(x); } + if let Some(x) = args.enemy { builder.add_enemy(x); } + if let Some(x) = args.testarrayoftables { builder.add_testarrayoftables(x); } + if let Some(x) = args.testarrayofstring { builder.add_testarrayofstring(x); } + if let Some(x) = args.test4 { builder.add_test4(x); } + if let Some(x) = args.test { builder.add_test(x); } + if let Some(x) = args.inventory { builder.add_inventory(x); } + if let Some(x) = args.name { builder.add_name(x); } + if let Some(x) = args.pos { builder.add_pos(x); } + builder.add_hp(args.hp); + builder.add_mana(args.mana); + builder.add_signed_enum(args.signed_enum); + builder.add_any_ambiguous_type(args.any_ambiguous_type); + builder.add_any_unique_type(args.any_unique_type); + builder.add_testbool(args.testbool); + builder.add_test_type(args.test_type); + builder.add_color(args.color); + builder.finish() + } + + pub fn unpack(&self) -> MonsterT { + let pos = self.pos().map(|x| { + x.unpack() + }); + let mana = self.mana(); + let hp = self.hp(); + let name = { + let x = self.name(); + x.to_string() + }; + let inventory = self.inventory().map(|x| { + x.into_iter().collect() + }); + let color = self.color(); + let test = match self.test_type() { + Any::NONE => AnyT::NONE, + Any::Monster => AnyT::Monster(Box::new( + self.test_as_monster() + .expect("Invalid union table, expected `Any::Monster`.") + .unpack() + )), + Any::TestSimpleTableWithEnum => AnyT::TestSimpleTableWithEnum(Box::new( + self.test_as_test_simple_table_with_enum() + .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`.") + .unpack() + )), + Any::MyGame_Example2_Monster => AnyT::MyGameExample2Monster(Box::new( + self.test_as_my_game_example_2_monster() + .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`.") + .unpack() + )), + _ => AnyT::NONE, + }; + let test4 = self.test4().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let testarrayofstring = self.testarrayofstring().map(|x| { + x.iter().map(|s| s.to_string()).collect() + }); + let testarrayoftables = self.testarrayoftables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let enemy = self.enemy().map(|x| { + Box::new(x.unpack()) + }); + let testnestedflatbuffer = self.testnestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let testempty = self.testempty().map(|x| { + Box::new(x.unpack()) + }); + let testbool = self.testbool(); + let testhashs32_fnv1 = self.testhashs32_fnv1(); + let testhashu32_fnv1 = self.testhashu32_fnv1(); + let testhashs64_fnv1 = self.testhashs64_fnv1(); + let testhashu64_fnv1 = self.testhashu64_fnv1(); + let testhashs32_fnv1a = self.testhashs32_fnv1a(); + let testhashu32_fnv1a = self.testhashu32_fnv1a(); + let testhashs64_fnv1a = self.testhashs64_fnv1a(); + let testhashu64_fnv1a = self.testhashu64_fnv1a(); + let testarrayofbools = self.testarrayofbools().map(|x| { + x.into_iter().collect() + }); + let testf = self.testf(); + let testf2 = self.testf2(); + let testf3 = self.testf3(); + let testarrayofstring2 = self.testarrayofstring2().map(|x| { + x.iter().map(|s| s.to_string()).collect() + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let flex = self.flex().map(|x| { + x.into_iter().collect() + }); + let test5 = self.test5().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let vector_of_longs = self.vector_of_longs().map(|x| { + x.into_iter().collect() + }); + let vector_of_doubles = self.vector_of_doubles().map(|x| { + x.into_iter().collect() + }); + let parent_namespace_test = self.parent_namespace_test().map(|x| { + Box::new(x.unpack()) + }); + let vector_of_referrables = self.vector_of_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let single_weak_reference = self.single_weak_reference(); + let vector_of_weak_references = self.vector_of_weak_references().map(|x| { + x.into_iter().collect() + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let co_owning_reference = self.co_owning_reference(); + let vector_of_co_owning_references = self.vector_of_co_owning_references().map(|x| { + x.into_iter().collect() + }); + let non_owning_reference = self.non_owning_reference(); + let vector_of_non_owning_references = self.vector_of_non_owning_references().map(|x| { + x.into_iter().collect() + }); + let any_unique = match self.any_unique_type() { + AnyUniqueAliases::NONE => AnyUniqueAliasesT::NONE, + AnyUniqueAliases::M => AnyUniqueAliasesT::M(Box::new( + self.any_unique_as_m() + .expect("Invalid union table, expected `AnyUniqueAliases::M`.") + .unpack() + )), + AnyUniqueAliases::TS => AnyUniqueAliasesT::TS(Box::new( + self.any_unique_as_ts() + .expect("Invalid union table, expected `AnyUniqueAliases::TS`.") + .unpack() + )), + AnyUniqueAliases::M2 => AnyUniqueAliasesT::M2(Box::new( + self.any_unique_as_m2() + .expect("Invalid union table, expected `AnyUniqueAliases::M2`.") + .unpack() + )), + _ => AnyUniqueAliasesT::NONE, + }; + let any_ambiguous = match self.any_ambiguous_type() { + AnyAmbiguousAliases::NONE => AnyAmbiguousAliasesT::NONE, + AnyAmbiguousAliases::M1 => AnyAmbiguousAliasesT::M1(Box::new( + self.any_ambiguous_as_m1() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`.") + .unpack() + )), + AnyAmbiguousAliases::M2 => AnyAmbiguousAliasesT::M2(Box::new( + self.any_ambiguous_as_m2() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`.") + .unpack() + )), + AnyAmbiguousAliases::M3 => AnyAmbiguousAliasesT::M3(Box::new( + self.any_ambiguous_as_m3() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`.") + .unpack() + )), + _ => AnyAmbiguousAliasesT::NONE, + }; + let vector_of_enums = self.vector_of_enums().map(|x| { + x.into_iter().collect() + }); + let signed_enum = self.signed_enum(); + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer().map(|x| { + x.into_iter().collect() + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables().map(|x| { + x.iter().map(|t| t.unpack()).collect() + }); + let native_inline = self.native_inline().map(|x| { + x.unpack() + }); + let long_enum_non_enum_default = self.long_enum_non_enum_default(); + let long_enum_normal_default = self.long_enum_normal_default(); + let nan_default = self.nan_default(); + let inf_default = self.inf_default(); + let positive_inf_default = self.positive_inf_default(); + let infinity_default = self.infinity_default(); + let positive_infinity_default = self.positive_infinity_default(); + let negative_inf_default = self.negative_inf_default(); + let negative_infinity_default = self.negative_infinity_default(); + let double_inf_default = self.double_inf_default(); + MonsterT { + pos, + mana, + hp, + name, + inventory, + color, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + } + } + + #[inline] + pub fn pos(&self) -> Option<&'a Vec3> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POS, None)} + } + #[inline] + pub fn mana(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_MANA, Some(150)).unwrap()} + } + #[inline] + pub fn hp(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_HP, Some(100)).unwrap()} + } + #[inline] + pub fn name(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_NAME, None).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Monster) -> bool { + self.name() < o.name() + } + + #[inline] + pub fn key_compare_with_value(&self, val: & str) -> ::core::cmp::Ordering { + let key = self.name(); + key.cmp(val) + } + #[inline] + pub fn inventory(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_INVENTORY, None)} + } + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_COLOR, Some(Color::Blue)).unwrap()} + } + #[inline] + pub fn test_type(&self) -> Any { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TEST_TYPE, Some(Any::NONE)).unwrap()} + } + #[inline] + pub fn test(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TEST, None)} + } + #[inline] + pub fn test4(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TEST4, None)} + } + #[inline] + pub fn testarrayofstring(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_TESTARRAYOFSTRING, None)} + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + #[inline] + pub fn testarrayoftables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_TESTARRAYOFTABLES, None)} + } + #[inline] + pub fn enemy(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_ENEMY, None)} + } + #[inline] + pub fn testnestedflatbuffer(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTNESTEDFLATBUFFER, None)} + } + pub fn testnestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testnestedflatbuffer().map(|data| { + use flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { >>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn testempty(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_TESTEMPTY, None)} + } + #[inline] + pub fn testbool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTBOOL, Some(false)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs32_fnv1a(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu32_fnv1a(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU32_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashs64_fnv1a(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHS64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testhashu64_fnv1a(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTHASHU64_FNV1A, Some(0)).unwrap()} + } + #[inline] + pub fn testarrayofbools(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTARRAYOFBOOLS, None)} + } + #[inline] + pub fn testf(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF, Some(3.14159)).unwrap()} + } + #[inline] + pub fn testf2(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF2, Some(3.0)).unwrap()} + } + #[inline] + pub fn testf3(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_TESTF3, Some(0.0)).unwrap()} + } + #[inline] + pub fn testarrayofstring2(&self) -> Option>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_TESTARRAYOFSTRING2, None)} + } + #[inline] + pub fn testarrayofsortedstruct(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, None)} + } + #[inline] + pub fn flex(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_FLEX, None)} + } + #[inline] + pub fn test5(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TEST5, None)} + } + #[inline] + pub fn vector_of_longs(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_LONGS, None)} + } + #[inline] + pub fn vector_of_doubles(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_DOUBLES, None)} + } + #[inline] + pub fn parent_namespace_test(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Monster::VT_PARENT_NAMESPACE_TEST, None)} + } + #[inline] + pub fn vector_of_referrables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_VECTOR_OF_REFERRABLES, None)} + } + #[inline] + pub fn single_weak_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SINGLE_WEAK_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_weak_references(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, None)} + } + #[inline] + pub fn vector_of_strong_referrables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, None)} + } + #[inline] + pub fn co_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_CO_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_co_owning_references(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, None)} + } + #[inline] + pub fn non_owning_reference(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NON_OWNING_REFERENCE, Some(0)).unwrap()} + } + #[inline] + pub fn vector_of_non_owning_references(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, None)} + } + #[inline] + pub fn any_unique_type(&self) -> AnyUniqueAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_UNIQUE_TYPE, Some(AnyUniqueAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_unique(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_ANY_UNIQUE, None)} + } + #[inline] + pub fn any_ambiguous_type(&self) -> AnyAmbiguousAliases { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_ANY_AMBIGUOUS_TYPE, Some(AnyAmbiguousAliases::NONE)).unwrap()} + } + #[inline] + pub fn any_ambiguous(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_ANY_AMBIGUOUS, None)} + } + #[inline] + pub fn vector_of_enums(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_VECTOR_OF_ENUMS, None)} + } + #[inline] + pub fn signed_enum(&self) -> Race { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_SIGNED_ENUM, Some(Race::None)).unwrap()} + } + #[inline] + pub fn testrequirednestedflatbuffer(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, None)} + } + pub fn testrequirednestedflatbuffer_nested_flatbuffer(&'a self) -> Option> { + self.testrequirednestedflatbuffer().map(|data| { + use flatbuffers::Follow; + // Safety: + // Created from a valid Table for this object + // Which contains a valid flatbuffer in this slot + unsafe { >>::follow(data.bytes(), 0) } + }) + } + #[inline] + pub fn scalar_key_sorted_tables(&self) -> Option>>> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>>(Monster::VT_SCALAR_KEY_SORTED_TABLES, None)} + } + #[inline] + pub fn native_inline(&self) -> Option<&'a Test> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NATIVE_INLINE, None)} + } + #[inline] + pub fn long_enum_non_enum_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, Some(Default::default())).unwrap()} + } + #[inline] + pub fn long_enum_normal_default(&self) -> LongEnum { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, Some(LongEnum::LongOne)).unwrap()} + } + #[inline] + pub fn nan_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NAN_DEFAULT, Some(f32::NAN)).unwrap()} + } + #[inline] + pub fn inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INF_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn positive_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_POSITIVE_INFINITY_DEFAULT, Some(f32::INFINITY)).unwrap()} + } + #[inline] + pub fn negative_inf_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INF_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn negative_infinity_default(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, Some(f32::NEG_INFINITY)).unwrap()} + } + #[inline] + pub fn double_inf_default(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Monster::VT_DOUBLE_INF_DEFAULT, Some(f64::INFINITY)).unwrap()} + } + #[inline] + #[allow(non_snake_case)] + pub fn test_as_monster(&self) -> Option> { + if self.test_type() == Any::Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_test_simple_table_with_enum(&self) -> Option> { + if self.test_type() == Any::TestSimpleTableWithEnum { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn test_as_my_game_example_2_monster(&self) -> Option> { + if self.test_type() == Any::MyGame_Example2_Monster { + self.test().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_ts(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::TS { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { TestSimpleTableWithEnum::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_unique_as_m2(&self) -> Option> { + if self.any_unique_type() == AnyUniqueAliases::M2 { + self.any_unique().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { super::example_2::Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m1(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M1 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m2(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M2 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn any_ambiguous_as_m3(&self) -> Option> { + if self.any_ambiguous_type() == AnyAmbiguousAliases::M3 { + self.any_ambiguous().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { Monster::init_from_table(t) } + }) + } else { + None + } + } + +} + +impl flatbuffers::Verifiable for Monster<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("pos", Self::VT_POS, false)? + .visit_field::("mana", Self::VT_MANA, false)? + .visit_field::("hp", Self::VT_HP, false)? + .visit_field::>("name", Self::VT_NAME, true)? + .visit_field::>>("inventory", Self::VT_INVENTORY, false)? + .visit_field::("color", Self::VT_COLOR, false)? + .visit_union::("test_type", Self::VT_TEST_TYPE, "test", Self::VT_TEST, false, |key, v, pos| { + match key { + Any::Monster => v.verify_union_variant::>("Any::Monster", pos), + Any::TestSimpleTableWithEnum => v.verify_union_variant::>("Any::TestSimpleTableWithEnum", pos), + Any::MyGame_Example2_Monster => v.verify_union_variant::>("Any::MyGame_Example2_Monster", pos), + _ => Ok(()), + } + })? + .visit_field::>>("test4", Self::VT_TEST4, false)? + .visit_field::>>>("testarrayofstring", Self::VT_TESTARRAYOFSTRING, false)? + .visit_field::>>>("testarrayoftables", Self::VT_TESTARRAYOFTABLES, false)? + .visit_field::>("enemy", Self::VT_ENEMY, false)? + .visit_field::>>("testnestedflatbuffer", Self::VT_TESTNESTEDFLATBUFFER, false)? + .visit_field::>("testempty", Self::VT_TESTEMPTY, false)? + .visit_field::("testbool", Self::VT_TESTBOOL, false)? + .visit_field::("testhashs32_fnv1", Self::VT_TESTHASHS32_FNV1, false)? + .visit_field::("testhashu32_fnv1", Self::VT_TESTHASHU32_FNV1, false)? + .visit_field::("testhashs64_fnv1", Self::VT_TESTHASHS64_FNV1, false)? + .visit_field::("testhashu64_fnv1", Self::VT_TESTHASHU64_FNV1, false)? + .visit_field::("testhashs32_fnv1a", Self::VT_TESTHASHS32_FNV1A, false)? + .visit_field::("testhashu32_fnv1a", Self::VT_TESTHASHU32_FNV1A, false)? + .visit_field::("testhashs64_fnv1a", Self::VT_TESTHASHS64_FNV1A, false)? + .visit_field::("testhashu64_fnv1a", Self::VT_TESTHASHU64_FNV1A, false)? + .visit_field::>>("testarrayofbools", Self::VT_TESTARRAYOFBOOLS, false)? + .visit_field::("testf", Self::VT_TESTF, false)? + .visit_field::("testf2", Self::VT_TESTF2, false)? + .visit_field::("testf3", Self::VT_TESTF3, false)? + .visit_field::>>>("testarrayofstring2", Self::VT_TESTARRAYOFSTRING2, false)? + .visit_field::>>("testarrayofsortedstruct", Self::VT_TESTARRAYOFSORTEDSTRUCT, false)? + .visit_field::>>("flex", Self::VT_FLEX, false)? + .visit_field::>>("test5", Self::VT_TEST5, false)? + .visit_field::>>("vector_of_longs", Self::VT_VECTOR_OF_LONGS, false)? + .visit_field::>>("vector_of_doubles", Self::VT_VECTOR_OF_DOUBLES, false)? + .visit_field::>("parent_namespace_test", Self::VT_PARENT_NAMESPACE_TEST, false)? + .visit_field::>>>("vector_of_referrables", Self::VT_VECTOR_OF_REFERRABLES, false)? + .visit_field::("single_weak_reference", Self::VT_SINGLE_WEAK_REFERENCE, false)? + .visit_field::>>("vector_of_weak_references", Self::VT_VECTOR_OF_WEAK_REFERENCES, false)? + .visit_field::>>>("vector_of_strong_referrables", Self::VT_VECTOR_OF_STRONG_REFERRABLES, false)? + .visit_field::("co_owning_reference", Self::VT_CO_OWNING_REFERENCE, false)? + .visit_field::>>("vector_of_co_owning_references", Self::VT_VECTOR_OF_CO_OWNING_REFERENCES, false)? + .visit_field::("non_owning_reference", Self::VT_NON_OWNING_REFERENCE, false)? + .visit_field::>>("vector_of_non_owning_references", Self::VT_VECTOR_OF_NON_OWNING_REFERENCES, false)? + .visit_union::("any_unique_type", Self::VT_ANY_UNIQUE_TYPE, "any_unique", Self::VT_ANY_UNIQUE, false, |key, v, pos| { + match key { + AnyUniqueAliases::M => v.verify_union_variant::>("AnyUniqueAliases::M", pos), + AnyUniqueAliases::TS => v.verify_union_variant::>("AnyUniqueAliases::TS", pos), + AnyUniqueAliases::M2 => v.verify_union_variant::>("AnyUniqueAliases::M2", pos), + _ => Ok(()), + } + })? + .visit_union::("any_ambiguous_type", Self::VT_ANY_AMBIGUOUS_TYPE, "any_ambiguous", Self::VT_ANY_AMBIGUOUS, false, |key, v, pos| { + match key { + AnyAmbiguousAliases::M1 => v.verify_union_variant::>("AnyAmbiguousAliases::M1", pos), + AnyAmbiguousAliases::M2 => v.verify_union_variant::>("AnyAmbiguousAliases::M2", pos), + AnyAmbiguousAliases::M3 => v.verify_union_variant::>("AnyAmbiguousAliases::M3", pos), + _ => Ok(()), + } + })? + .visit_field::>>("vector_of_enums", Self::VT_VECTOR_OF_ENUMS, false)? + .visit_field::("signed_enum", Self::VT_SIGNED_ENUM, false)? + .visit_field::>>("testrequirednestedflatbuffer", Self::VT_TESTREQUIREDNESTEDFLATBUFFER, false)? + .visit_field::>>>("scalar_key_sorted_tables", Self::VT_SCALAR_KEY_SORTED_TABLES, false)? + .visit_field::("native_inline", Self::VT_NATIVE_INLINE, false)? + .visit_field::("long_enum_non_enum_default", Self::VT_LONG_ENUM_NON_ENUM_DEFAULT, false)? + .visit_field::("long_enum_normal_default", Self::VT_LONG_ENUM_NORMAL_DEFAULT, false)? + .visit_field::("nan_default", Self::VT_NAN_DEFAULT, false)? + .visit_field::("inf_default", Self::VT_INF_DEFAULT, false)? + .visit_field::("positive_inf_default", Self::VT_POSITIVE_INF_DEFAULT, false)? + .visit_field::("infinity_default", Self::VT_INFINITY_DEFAULT, false)? + .visit_field::("positive_infinity_default", Self::VT_POSITIVE_INFINITY_DEFAULT, false)? + .visit_field::("negative_inf_default", Self::VT_NEGATIVE_INF_DEFAULT, false)? + .visit_field::("negative_infinity_default", Self::VT_NEGATIVE_INFINITY_DEFAULT, false)? + .visit_field::("double_inf_default", Self::VT_DOUBLE_INF_DEFAULT, false)? + .finish(); + Ok(()) + } +} +pub struct MonsterArgs<'a> { + pub pos: Option<&'a Vec3>, + pub mana: i16, + pub hp: i16, + pub name: Option>, + pub inventory: Option>>, + pub color: Color, + pub test_type: Any, + pub test: Option>, + pub test4: Option>>, + pub testarrayofstring: Option>>>, + pub testarrayoftables: Option>>>>, + pub enemy: Option>>, + pub testnestedflatbuffer: Option>>, + pub testempty: Option>>, + pub testbool: bool, + pub testhashs32_fnv1: i32, + pub testhashu32_fnv1: u32, + pub testhashs64_fnv1: i64, + pub testhashu64_fnv1: u64, + pub testhashs32_fnv1a: i32, + pub testhashu32_fnv1a: u32, + pub testhashs64_fnv1a: i64, + pub testhashu64_fnv1a: u64, + pub testarrayofbools: Option>>, + pub testf: f32, + pub testf2: f32, + pub testf3: f32, + pub testarrayofstring2: Option>>>, + pub testarrayofsortedstruct: Option>>, + pub flex: Option>>, + pub test5: Option>>, + pub vector_of_longs: Option>>, + pub vector_of_doubles: Option>>, + pub parent_namespace_test: Option>>, + pub vector_of_referrables: Option>>>>, + pub single_weak_reference: u64, + pub vector_of_weak_references: Option>>, + pub vector_of_strong_referrables: Option>>>>, + pub co_owning_reference: u64, + pub vector_of_co_owning_references: Option>>, + pub non_owning_reference: u64, + pub vector_of_non_owning_references: Option>>, + pub any_unique_type: AnyUniqueAliases, + pub any_unique: Option>, + pub any_ambiguous_type: AnyAmbiguousAliases, + pub any_ambiguous: Option>, + pub vector_of_enums: Option>>, + pub signed_enum: Race, + pub testrequirednestedflatbuffer: Option>>, + pub scalar_key_sorted_tables: Option>>>>, + pub native_inline: Option<&'a Test>, + pub long_enum_non_enum_default: LongEnum, + pub long_enum_normal_default: LongEnum, + pub nan_default: f32, + pub inf_default: f32, + pub positive_inf_default: f32, + pub infinity_default: f32, + pub positive_infinity_default: f32, + pub negative_inf_default: f32, + pub negative_infinity_default: f32, + pub double_inf_default: f64, +} +impl<'a> Default for MonsterArgs<'a> { + #[inline] + fn default() -> Self { + MonsterArgs { + pos: None, + mana: 150, + hp: 100, + name: None, // required field + inventory: None, + color: Color::Blue, + test_type: Any::NONE, + test: None, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique_type: AnyUniqueAliases::NONE, + any_unique: None, + any_ambiguous_type: AnyAmbiguousAliases::NONE, + any_ambiguous: None, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, + } + } +} + +impl Serialize for Monster<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Monster", 62)?; + if let Some(f) = self.pos() { + s.serialize_field("pos", &f)?; + } else { + s.skip_field("pos")?; + } + s.serialize_field("mana", &self.mana())?; + s.serialize_field("hp", &self.hp())?; + s.serialize_field("name", &self.name())?; + if let Some(f) = self.inventory() { + s.serialize_field("inventory", &f)?; + } else { + s.skip_field("inventory")?; + } + s.serialize_field("color", &self.color())?; + s.serialize_field("test_type", &self.test_type())?; + match self.test_type() { + Any::NONE => (), + Any::Monster => { + let f = self.test_as_monster() + .expect("Invalid union table, expected `Any::Monster`."); + s.serialize_field("test", &f)?; + } + Any::TestSimpleTableWithEnum => { + let f = self.test_as_test_simple_table_with_enum() + .expect("Invalid union table, expected `Any::TestSimpleTableWithEnum`."); + s.serialize_field("test", &f)?; + } + Any::MyGame_Example2_Monster => { + let f = self.test_as_my_game_example_2_monster() + .expect("Invalid union table, expected `Any::MyGame_Example2_Monster`."); + s.serialize_field("test", &f)?; + } + _ => unimplemented!(), + } + if let Some(f) = self.test4() { + s.serialize_field("test4", &f)?; + } else { + s.skip_field("test4")?; + } + if let Some(f) = self.testarrayofstring() { + s.serialize_field("testarrayofstring", &f)?; + } else { + s.skip_field("testarrayofstring")?; + } + if let Some(f) = self.testarrayoftables() { + s.serialize_field("testarrayoftables", &f)?; + } else { + s.skip_field("testarrayoftables")?; + } + if let Some(f) = self.enemy() { + s.serialize_field("enemy", &f)?; + } else { + s.skip_field("enemy")?; + } + if let Some(f) = self.testnestedflatbuffer() { + s.serialize_field("testnestedflatbuffer", &f)?; + } else { + s.skip_field("testnestedflatbuffer")?; + } + if let Some(f) = self.testempty() { + s.serialize_field("testempty", &f)?; + } else { + s.skip_field("testempty")?; + } + s.serialize_field("testbool", &self.testbool())?; + s.serialize_field("testhashs32_fnv1", &self.testhashs32_fnv1())?; + s.serialize_field("testhashu32_fnv1", &self.testhashu32_fnv1())?; + s.serialize_field("testhashs64_fnv1", &self.testhashs64_fnv1())?; + s.serialize_field("testhashu64_fnv1", &self.testhashu64_fnv1())?; + s.serialize_field("testhashs32_fnv1a", &self.testhashs32_fnv1a())?; + s.serialize_field("testhashu32_fnv1a", &self.testhashu32_fnv1a())?; + s.serialize_field("testhashs64_fnv1a", &self.testhashs64_fnv1a())?; + s.serialize_field("testhashu64_fnv1a", &self.testhashu64_fnv1a())?; + if let Some(f) = self.testarrayofbools() { + s.serialize_field("testarrayofbools", &f)?; + } else { + s.skip_field("testarrayofbools")?; + } + s.serialize_field("testf", &self.testf())?; + s.serialize_field("testf2", &self.testf2())?; + s.serialize_field("testf3", &self.testf3())?; + if let Some(f) = self.testarrayofstring2() { + s.serialize_field("testarrayofstring2", &f)?; + } else { + s.skip_field("testarrayofstring2")?; + } + if let Some(f) = self.testarrayofsortedstruct() { + s.serialize_field("testarrayofsortedstruct", &f)?; + } else { + s.skip_field("testarrayofsortedstruct")?; + } + if let Some(f) = self.flex() { + s.serialize_field("flex", &f)?; + } else { + s.skip_field("flex")?; + } + if let Some(f) = self.test5() { + s.serialize_field("test5", &f)?; + } else { + s.skip_field("test5")?; + } + if let Some(f) = self.vector_of_longs() { + s.serialize_field("vector_of_longs", &f)?; + } else { + s.skip_field("vector_of_longs")?; + } + if let Some(f) = self.vector_of_doubles() { + s.serialize_field("vector_of_doubles", &f)?; + } else { + s.skip_field("vector_of_doubles")?; + } + if let Some(f) = self.parent_namespace_test() { + s.serialize_field("parent_namespace_test", &f)?; + } else { + s.skip_field("parent_namespace_test")?; + } + if let Some(f) = self.vector_of_referrables() { + s.serialize_field("vector_of_referrables", &f)?; + } else { + s.skip_field("vector_of_referrables")?; + } + s.serialize_field("single_weak_reference", &self.single_weak_reference())?; + if let Some(f) = self.vector_of_weak_references() { + s.serialize_field("vector_of_weak_references", &f)?; + } else { + s.skip_field("vector_of_weak_references")?; + } + if let Some(f) = self.vector_of_strong_referrables() { + s.serialize_field("vector_of_strong_referrables", &f)?; + } else { + s.skip_field("vector_of_strong_referrables")?; + } + s.serialize_field("co_owning_reference", &self.co_owning_reference())?; + if let Some(f) = self.vector_of_co_owning_references() { + s.serialize_field("vector_of_co_owning_references", &f)?; + } else { + s.skip_field("vector_of_co_owning_references")?; + } + s.serialize_field("non_owning_reference", &self.non_owning_reference())?; + if let Some(f) = self.vector_of_non_owning_references() { + s.serialize_field("vector_of_non_owning_references", &f)?; + } else { + s.skip_field("vector_of_non_owning_references")?; + } + s.serialize_field("any_unique_type", &self.any_unique_type())?; + match self.any_unique_type() { + AnyUniqueAliases::NONE => (), + AnyUniqueAliases::M => { + let f = self.any_unique_as_m() + .expect("Invalid union table, expected `AnyUniqueAliases::M`."); + s.serialize_field("any_unique", &f)?; + } + AnyUniqueAliases::TS => { + let f = self.any_unique_as_ts() + .expect("Invalid union table, expected `AnyUniqueAliases::TS`."); + s.serialize_field("any_unique", &f)?; + } + AnyUniqueAliases::M2 => { + let f = self.any_unique_as_m2() + .expect("Invalid union table, expected `AnyUniqueAliases::M2`."); + s.serialize_field("any_unique", &f)?; + } + _ => unimplemented!(), + } + s.serialize_field("any_ambiguous_type", &self.any_ambiguous_type())?; + match self.any_ambiguous_type() { + AnyAmbiguousAliases::NONE => (), + AnyAmbiguousAliases::M1 => { + let f = self.any_ambiguous_as_m1() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M1`."); + s.serialize_field("any_ambiguous", &f)?; + } + AnyAmbiguousAliases::M2 => { + let f = self.any_ambiguous_as_m2() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M2`."); + s.serialize_field("any_ambiguous", &f)?; + } + AnyAmbiguousAliases::M3 => { + let f = self.any_ambiguous_as_m3() + .expect("Invalid union table, expected `AnyAmbiguousAliases::M3`."); + s.serialize_field("any_ambiguous", &f)?; + } + _ => unimplemented!(), + } + if let Some(f) = self.vector_of_enums() { + s.serialize_field("vector_of_enums", &f)?; + } else { + s.skip_field("vector_of_enums")?; + } + s.serialize_field("signed_enum", &self.signed_enum())?; + if let Some(f) = self.testrequirednestedflatbuffer() { + s.serialize_field("testrequirednestedflatbuffer", &f)?; + } else { + s.skip_field("testrequirednestedflatbuffer")?; + } + if let Some(f) = self.scalar_key_sorted_tables() { + s.serialize_field("scalar_key_sorted_tables", &f)?; + } else { + s.skip_field("scalar_key_sorted_tables")?; + } + if let Some(f) = self.native_inline() { + s.serialize_field("native_inline", &f)?; + } else { + s.skip_field("native_inline")?; + } + s.serialize_field("long_enum_non_enum_default", &self.long_enum_non_enum_default())?; + s.serialize_field("long_enum_normal_default", &self.long_enum_normal_default())?; + s.serialize_field("nan_default", &self.nan_default())?; + s.serialize_field("inf_default", &self.inf_default())?; + s.serialize_field("positive_inf_default", &self.positive_inf_default())?; + s.serialize_field("infinity_default", &self.infinity_default())?; + s.serialize_field("positive_infinity_default", &self.positive_infinity_default())?; + s.serialize_field("negative_inf_default", &self.negative_inf_default())?; + s.serialize_field("negative_infinity_default", &self.negative_infinity_default())?; + s.serialize_field("double_inf_default", &self.double_inf_default())?; + s.end() + } +} + +pub struct MonsterBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { + #[inline] + pub fn add_pos(&mut self, pos: &Vec3) { + self.fbb_.push_slot_always::<&Vec3>(Monster::VT_POS, pos); + } + #[inline] + pub fn add_mana(&mut self, mana: i16) { + self.fbb_.push_slot::(Monster::VT_MANA, mana, 150); + } + #[inline] + pub fn add_hp(&mut self, hp: i16) { + self.fbb_.push_slot::(Monster::VT_HP, hp, 100); + } + #[inline] + pub fn add_name(&mut self, name: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Monster::VT_NAME, name); + } + #[inline] + pub fn add_inventory(&mut self, inventory: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_INVENTORY, inventory); + } + #[inline] + pub fn add_color(&mut self, color: Color) { + self.fbb_.push_slot::(Monster::VT_COLOR, color, Color::Blue); + } + #[inline] + pub fn add_test_type(&mut self, test_type: Any) { + self.fbb_.push_slot::(Monster::VT_TEST_TYPE, test_type, Any::NONE); + } + #[inline] + pub fn add_test(&mut self, test: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Monster::VT_TEST, test); + } + #[inline] + pub fn add_test4(&mut self, test4: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TEST4, test4); + } + #[inline] + pub fn add_testarrayofstring(&mut self, testarrayofstring: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + #[inline] + pub fn add_testarrayoftables(&mut self, testarrayoftables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + #[inline] + pub fn add_enemy(&mut self, enemy: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_ENEMY, enemy); + } + #[inline] + pub fn add_testnestedflatbuffer(&mut self, testnestedflatbuffer: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + #[inline] + pub fn add_testempty(&mut self, testempty: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTEMPTY, testempty); + } + #[inline] + pub fn add_testbool(&mut self, testbool: bool) { + self.fbb_.push_slot::(Monster::VT_TESTBOOL, testbool, false); + } + #[inline] + pub fn add_testhashs32_fnv1(&mut self, testhashs32_fnv1: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + #[inline] + pub fn add_testhashu32_fnv1(&mut self, testhashu32_fnv1: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + #[inline] + pub fn add_testhashs64_fnv1(&mut self, testhashs64_fnv1: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + #[inline] + pub fn add_testhashu64_fnv1(&mut self, testhashu64_fnv1: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + #[inline] + pub fn add_testhashs32_fnv1a(&mut self, testhashs32_fnv1a: i32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + #[inline] + pub fn add_testhashu32_fnv1a(&mut self, testhashu32_fnv1a: u32) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + #[inline] + pub fn add_testhashs64_fnv1a(&mut self, testhashs64_fnv1a: i64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + #[inline] + pub fn add_testhashu64_fnv1a(&mut self, testhashu64_fnv1a: u64) { + self.fbb_.push_slot::(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + #[inline] + pub fn add_testarrayofbools(&mut self, testarrayofbools: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + #[inline] + pub fn add_testf(&mut self, testf: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF, testf, 3.14159); + } + #[inline] + pub fn add_testf2(&mut self, testf2: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF2, testf2, 3.0); + } + #[inline] + pub fn add_testf3(&mut self, testf3: f32) { + self.fbb_.push_slot::(Monster::VT_TESTF3, testf3, 0.0); + } + #[inline] + pub fn add_testarrayofstring2(&mut self, testarrayofstring2: flatbuffers::WIPOffset>>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + #[inline] + pub fn add_testarrayofsortedstruct(&mut self, testarrayofsortedstruct: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + #[inline] + pub fn add_flex(&mut self, flex: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_FLEX, flex); + } + #[inline] + pub fn add_test5(&mut self, test5: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TEST5, test5); + } + #[inline] + pub fn add_vector_of_longs(&mut self, vector_of_longs: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + #[inline] + pub fn add_vector_of_doubles(&mut self, vector_of_doubles: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + #[inline] + pub fn add_parent_namespace_test(&mut self, parent_namespace_test: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + #[inline] + pub fn add_vector_of_referrables(&mut self, vector_of_referrables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + #[inline] + pub fn add_single_weak_reference(&mut self, single_weak_reference: u64) { + self.fbb_.push_slot::(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + #[inline] + pub fn add_vector_of_weak_references(&mut self, vector_of_weak_references: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + #[inline] + pub fn add_vector_of_strong_referrables(&mut self, vector_of_strong_referrables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + #[inline] + pub fn add_co_owning_reference(&mut self, co_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_co_owning_references(&mut self, vector_of_co_owning_references: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + #[inline] + pub fn add_non_owning_reference(&mut self, non_owning_reference: u64) { + self.fbb_.push_slot::(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + #[inline] + pub fn add_vector_of_non_owning_references(&mut self, vector_of_non_owning_references: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + #[inline] + pub fn add_any_unique_type(&mut self, any_unique_type: AnyUniqueAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_UNIQUE_TYPE, any_unique_type, AnyUniqueAliases::NONE); + } + #[inline] + pub fn add_any_unique(&mut self, any_unique: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Monster::VT_ANY_UNIQUE, any_unique); + } + #[inline] + pub fn add_any_ambiguous_type(&mut self, any_ambiguous_type: AnyAmbiguousAliases) { + self.fbb_.push_slot::(Monster::VT_ANY_AMBIGUOUS_TYPE, any_ambiguous_type, AnyAmbiguousAliases::NONE); + } + #[inline] + pub fn add_any_ambiguous(&mut self, any_ambiguous: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + #[inline] + pub fn add_vector_of_enums(&mut self, vector_of_enums: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + #[inline] + pub fn add_signed_enum(&mut self, signed_enum: Race) { + self.fbb_.push_slot::(Monster::VT_SIGNED_ENUM, signed_enum, Race::None); + } + #[inline] + pub fn add_testrequirednestedflatbuffer(&mut self, testrequirednestedflatbuffer: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + #[inline] + pub fn add_scalar_key_sorted_tables(&mut self, scalar_key_sorted_tables: flatbuffers::WIPOffset>>>) { + self.fbb_.push_slot_always::>(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + #[inline] + pub fn add_native_inline(&mut self, native_inline: &Test) { + self.fbb_.push_slot_always::<&Test>(Monster::VT_NATIVE_INLINE, native_inline); + } + #[inline] + pub fn add_long_enum_non_enum_default(&mut self, long_enum_non_enum_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, long_enum_non_enum_default, Default::default()); + } + #[inline] + pub fn add_long_enum_normal_default(&mut self, long_enum_normal_default: LongEnum) { + self.fbb_.push_slot::(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, long_enum_normal_default, LongEnum::LongOne); + } + #[inline] + pub fn add_nan_default(&mut self, nan_default: f32) { + self.fbb_.push_slot::(Monster::VT_NAN_DEFAULT, nan_default, f32::NAN); + } + #[inline] + pub fn add_inf_default(&mut self, inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_INF_DEFAULT, inf_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_inf_default(&mut self, positive_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, f32::INFINITY); + } + #[inline] + pub fn add_infinity_default(&mut self, infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_INFINITY_DEFAULT, infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_positive_infinity_default(&mut self, positive_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, f32::INFINITY); + } + #[inline] + pub fn add_negative_inf_default(&mut self, negative_inf_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_negative_infinity_default(&mut self, negative_infinity_default: f32) { + self.fbb_.push_slot::(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, f32::NEG_INFINITY); + } + #[inline] + pub fn add_double_inf_default(&mut self, double_inf_default: f64) { + self.fbb_.push_slot::(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, f64::INFINITY); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + self.fbb_.required(o, Monster::VT_NAME,"name"); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Monster<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.field("pos", &self.pos()); + ds.field("mana", &self.mana()); + ds.field("hp", &self.hp()); + ds.field("name", &self.name()); + ds.field("inventory", &self.inventory()); + ds.field("color", &self.color()); + ds.field("test_type", &self.test_type()); + match self.test_type() { + Any::Monster => { + if let Some(x) = self.test_as_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::TestSimpleTableWithEnum => { + if let Some(x) = self.test_as_test_simple_table_with_enum() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + Any::MyGame_Example2_Monster => { + if let Some(x) = self.test_as_my_game_example_2_monster() { + ds.field("test", &x) + } else { + ds.field("test", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("test", &x) + }, + }; + ds.field("test4", &self.test4()); + ds.field("testarrayofstring", &self.testarrayofstring()); + ds.field("testarrayoftables", &self.testarrayoftables()); + ds.field("enemy", &self.enemy()); + ds.field("testnestedflatbuffer", &self.testnestedflatbuffer()); + ds.field("testempty", &self.testempty()); + ds.field("testbool", &self.testbool()); + ds.field("testhashs32_fnv1", &self.testhashs32_fnv1()); + ds.field("testhashu32_fnv1", &self.testhashu32_fnv1()); + ds.field("testhashs64_fnv1", &self.testhashs64_fnv1()); + ds.field("testhashu64_fnv1", &self.testhashu64_fnv1()); + ds.field("testhashs32_fnv1a", &self.testhashs32_fnv1a()); + ds.field("testhashu32_fnv1a", &self.testhashu32_fnv1a()); + ds.field("testhashs64_fnv1a", &self.testhashs64_fnv1a()); + ds.field("testhashu64_fnv1a", &self.testhashu64_fnv1a()); + ds.field("testarrayofbools", &self.testarrayofbools()); + ds.field("testf", &self.testf()); + ds.field("testf2", &self.testf2()); + ds.field("testf3", &self.testf3()); + ds.field("testarrayofstring2", &self.testarrayofstring2()); + ds.field("testarrayofsortedstruct", &self.testarrayofsortedstruct()); + ds.field("flex", &self.flex()); + ds.field("test5", &self.test5()); + ds.field("vector_of_longs", &self.vector_of_longs()); + ds.field("vector_of_doubles", &self.vector_of_doubles()); + ds.field("parent_namespace_test", &self.parent_namespace_test()); + ds.field("vector_of_referrables", &self.vector_of_referrables()); + ds.field("single_weak_reference", &self.single_weak_reference()); + ds.field("vector_of_weak_references", &self.vector_of_weak_references()); + ds.field("vector_of_strong_referrables", &self.vector_of_strong_referrables()); + ds.field("co_owning_reference", &self.co_owning_reference()); + ds.field("vector_of_co_owning_references", &self.vector_of_co_owning_references()); + ds.field("non_owning_reference", &self.non_owning_reference()); + ds.field("vector_of_non_owning_references", &self.vector_of_non_owning_references()); + ds.field("any_unique_type", &self.any_unique_type()); + match self.any_unique_type() { + AnyUniqueAliases::M => { + if let Some(x) = self.any_unique_as_m() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::TS => { + if let Some(x) = self.any_unique_as_ts() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyUniqueAliases::M2 => { + if let Some(x) = self.any_unique_as_m2() { + ds.field("any_unique", &x) + } else { + ds.field("any_unique", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_unique", &x) + }, + }; + ds.field("any_ambiguous_type", &self.any_ambiguous_type()); + match self.any_ambiguous_type() { + AnyAmbiguousAliases::M1 => { + if let Some(x) = self.any_ambiguous_as_m1() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M2 => { + if let Some(x) = self.any_ambiguous_as_m2() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + AnyAmbiguousAliases::M3 => { + if let Some(x) = self.any_ambiguous_as_m3() { + ds.field("any_ambiguous", &x) + } else { + ds.field("any_ambiguous", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("any_ambiguous", &x) + }, + }; + ds.field("vector_of_enums", &self.vector_of_enums()); + ds.field("signed_enum", &self.signed_enum()); + ds.field("testrequirednestedflatbuffer", &self.testrequirednestedflatbuffer()); + ds.field("scalar_key_sorted_tables", &self.scalar_key_sorted_tables()); + ds.field("native_inline", &self.native_inline()); + ds.field("long_enum_non_enum_default", &self.long_enum_non_enum_default()); + ds.field("long_enum_normal_default", &self.long_enum_normal_default()); + ds.field("nan_default", &self.nan_default()); + ds.field("inf_default", &self.inf_default()); + ds.field("positive_inf_default", &self.positive_inf_default()); + ds.field("infinity_default", &self.infinity_default()); + ds.field("positive_infinity_default", &self.positive_infinity_default()); + ds.field("negative_inf_default", &self.negative_inf_default()); + ds.field("negative_infinity_default", &self.negative_infinity_default()); + ds.field("double_inf_default", &self.double_inf_default()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct MonsterT { + pub pos: Option, + pub mana: i16, + pub hp: i16, + pub name: String, + pub inventory: Option>, + pub color: Color, + pub test: AnyT, + pub test4: Option>, + pub testarrayofstring: Option>, + pub testarrayoftables: Option>, + pub enemy: Option>, + pub testnestedflatbuffer: Option>, + pub testempty: Option>, + pub testbool: bool, + pub testhashs32_fnv1: i32, + pub testhashu32_fnv1: u32, + pub testhashs64_fnv1: i64, + pub testhashu64_fnv1: u64, + pub testhashs32_fnv1a: i32, + pub testhashu32_fnv1a: u32, + pub testhashs64_fnv1a: i64, + pub testhashu64_fnv1a: u64, + pub testarrayofbools: Option>, + pub testf: f32, + pub testf2: f32, + pub testf3: f32, + pub testarrayofstring2: Option>, + pub testarrayofsortedstruct: Option>, + pub flex: Option>, + pub test5: Option>, + pub vector_of_longs: Option>, + pub vector_of_doubles: Option>, + pub parent_namespace_test: Option>, + pub vector_of_referrables: Option>, + pub single_weak_reference: u64, + pub vector_of_weak_references: Option>, + pub vector_of_strong_referrables: Option>, + pub co_owning_reference: u64, + pub vector_of_co_owning_references: Option>, + pub non_owning_reference: u64, + pub vector_of_non_owning_references: Option>, + pub any_unique: AnyUniqueAliasesT, + pub any_ambiguous: AnyAmbiguousAliasesT, + pub vector_of_enums: Option>, + pub signed_enum: Race, + pub testrequirednestedflatbuffer: Option>, + pub scalar_key_sorted_tables: Option>, + pub native_inline: Option, + pub long_enum_non_enum_default: LongEnum, + pub long_enum_normal_default: LongEnum, + pub nan_default: f32, + pub inf_default: f32, + pub positive_inf_default: f32, + pub infinity_default: f32, + pub positive_infinity_default: f32, + pub negative_inf_default: f32, + pub negative_infinity_default: f32, + pub double_inf_default: f64, +} +impl Default for MonsterT { + fn default() -> Self { + Self { + pos: None, + mana: 150, + hp: 100, + name: "".to_string(), + inventory: None, + color: Color::Blue, + test: AnyT::NONE, + test4: None, + testarrayofstring: None, + testarrayoftables: None, + enemy: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testarrayofbools: None, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + testarrayofstring2: None, + testarrayofsortedstruct: None, + flex: None, + test5: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique: AnyUniqueAliasesT::NONE, + any_ambiguous: AnyAmbiguousAliasesT::NONE, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: f32::NAN, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, + } + } +} +impl MonsterT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let pos_tmp = self.pos.as_ref().map(|x| x.pack()); + let pos = pos_tmp.as_ref(); + let mana = self.mana; + let hp = self.hp; + let name = Some({ + let x = &self.name; + _fbb.create_string(x) + }); + let inventory = self.inventory.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let color = self.color; + let test_type = self.test.any_type(); + let test = self.test.pack(_fbb); + let test4 = self.test4.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let testarrayofstring = self.testarrayofstring.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayoftables = self.testarrayoftables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let enemy = self.enemy.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testnestedflatbuffer = self.testnestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testempty = self.testempty.as_ref().map(|x|{ + x.pack(_fbb) + }); + let testbool = self.testbool; + let testhashs32_fnv1 = self.testhashs32_fnv1; + let testhashu32_fnv1 = self.testhashu32_fnv1; + let testhashs64_fnv1 = self.testhashs64_fnv1; + let testhashu64_fnv1 = self.testhashu64_fnv1; + let testhashs32_fnv1a = self.testhashs32_fnv1a; + let testhashu32_fnv1a = self.testhashu32_fnv1a; + let testhashs64_fnv1a = self.testhashs64_fnv1a; + let testhashu64_fnv1a = self.testhashu64_fnv1a; + let testarrayofbools = self.testarrayofbools.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let testf = self.testf; + let testf2 = self.testf2; + let testf3 = self.testf3; + let testarrayofstring2 = self.testarrayofstring2.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|s| _fbb.create_string(s)).collect();_fbb.create_vector(&w) + }); + let testarrayofsortedstruct = self.testarrayofsortedstruct.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let flex = self.flex.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let test5 = self.test5.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack()).collect();_fbb.create_vector(&w) + }); + let vector_of_longs = self.vector_of_longs.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_doubles = self.vector_of_doubles.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let parent_namespace_test = self.parent_namespace_test.as_ref().map(|x|{ + x.pack(_fbb) + }); + let vector_of_referrables = self.vector_of_referrables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let single_weak_reference = self.single_weak_reference; + let vector_of_weak_references = self.vector_of_weak_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vector_of_strong_referrables = self.vector_of_strong_referrables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let co_owning_reference = self.co_owning_reference; + let vector_of_co_owning_references = self.vector_of_co_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let non_owning_reference = self.non_owning_reference; + let vector_of_non_owning_references = self.vector_of_non_owning_references.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let any_unique_type = self.any_unique.any_unique_aliases_type(); + let any_unique = self.any_unique.pack(_fbb); + let any_ambiguous_type = self.any_ambiguous.any_ambiguous_aliases_type(); + let any_ambiguous = self.any_ambiguous.pack(_fbb); + let vector_of_enums = self.vector_of_enums.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let signed_enum = self.signed_enum; + let testrequirednestedflatbuffer = self.testrequirednestedflatbuffer.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let scalar_key_sorted_tables = self.scalar_key_sorted_tables.as_ref().map(|x|{ + let w: Vec<_> = x.iter().map(|t| t.pack(_fbb)).collect();_fbb.create_vector(&w) + }); + let native_inline_tmp = self.native_inline.as_ref().map(|x| x.pack()); + let native_inline = native_inline_tmp.as_ref(); + let long_enum_non_enum_default = self.long_enum_non_enum_default; + let long_enum_normal_default = self.long_enum_normal_default; + let nan_default = self.nan_default; + let inf_default = self.inf_default; + let positive_inf_default = self.positive_inf_default; + let infinity_default = self.infinity_default; + let positive_infinity_default = self.positive_infinity_default; + let negative_inf_default = self.negative_inf_default; + let negative_infinity_default = self.negative_infinity_default; + let double_inf_default = self.double_inf_default; + Monster::create(_fbb, &MonsterArgs{ + pos, + mana, + hp, + name, + inventory, + color, + test_type, + test, + test4, + testarrayofstring, + testarrayoftables, + enemy, + testnestedflatbuffer, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools, + testf, + testf2, + testf3, + testarrayofstring2, + testarrayofsortedstruct, + flex, + test5, + vector_of_longs, + vector_of_doubles, + parent_namespace_test, + vector_of_referrables, + single_weak_reference, + vector_of_weak_references, + vector_of_strong_referrables, + co_owning_reference, + vector_of_co_owning_references, + non_owning_reference, + vector_of_non_owning_references, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums, + signed_enum, + testrequirednestedflatbuffer, + scalar_key_sorted_tables, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default, + }) + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `Monster` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_monster_unchecked`. +pub fn root_as_monster(buf: &[u8]) -> Result { + flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `Monster` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_monster_unchecked`. +pub fn size_prefixed_root_as_monster(buf: &[u8]) -> Result { + flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `Monster` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_monster_unchecked`. +pub fn root_as_monster_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `Monster` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_monster_unchecked`. +pub fn size_prefixed_root_as_monster_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a Monster and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `Monster`. +pub unsafe fn root_as_monster_unchecked(buf: &[u8]) -> Monster { + flatbuffers::root_unchecked::(buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed Monster and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `Monster`. +pub unsafe fn size_prefixed_root_as_monster_unchecked(buf: &[u8]) -> Monster { + flatbuffers::size_prefixed_root_unchecked::(buf) +} +pub const MONSTER_IDENTIFIER: &str = "MONS"; + +#[inline] +pub fn monster_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, false) +} + +#[inline] +pub fn monster_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, MONSTER_IDENTIFIER, true) +} + +pub const MONSTER_EXTENSION: &str = "mon"; + +#[inline] +pub fn finish_monster_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( + fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + root: flatbuffers::WIPOffset>) { + fbb.finish(root, Some(MONSTER_IDENTIFIER)); +} + +#[inline] +pub fn finish_size_prefixed_monster_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(MONSTER_IDENTIFIER)); +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/race_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/race_generated.rs new file mode 100644 index 00000000000..fe57ce0a048 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/race_generated.rs @@ -0,0 +1,115 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_RACE: i8 = -1; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_RACE: i8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_RACE: [Race; 4] = [ + Race::None, + Race::Human, + Race::Dwarf, + Race::Elf, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct Race(pub i8); +#[allow(non_upper_case_globals)] +impl Race { + pub const None: Self = Self(-1); + pub const Human: Self = Self(0); + pub const Dwarf: Self = Self(1); + pub const Elf: Self = Self(2); + + pub const ENUM_MIN: i8 = -1; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::Human, + Self::Dwarf, + Self::Elf, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::Human => Some("Human"), + Self::Dwarf => Some("Dwarf"), + Self::Elf => Some("Elf"), + _ => None, + } + } +} +impl core::fmt::Debug for Race { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl Serialize for Race { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("Race", self.0 as u32, self.variant_name().unwrap()) + } +} + +impl<'a> flatbuffers::Follow<'a> for Race { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for Race { + type Output = Race; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for Race { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for Race { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Race {} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/referrable_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/referrable_generated.rs new file mode 100644 index 00000000000..681cc13232f --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/referrable_generated.rs @@ -0,0 +1,164 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum ReferrableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Referrable<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Referrable<'a> { + type Inner = Referrable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Referrable<'a> { + pub const VT_ID: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Referrable" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Referrable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ReferrableArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = ReferrableBuilder::new(_fbb); + builder.add_id(args.id); + builder.finish() + } + + pub fn unpack(&self) -> ReferrableT { + let id = self.id(); + ReferrableT { + id, + } + } + + #[inline] + pub fn id(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Referrable::VT_ID, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Referrable) -> bool { + self.id() < o.id() + } + + #[inline] + pub fn key_compare_with_value(&self, val: u64) -> ::core::cmp::Ordering { + let key = self.id(); + key.cmp(&val) + } +} + +impl flatbuffers::Verifiable for Referrable<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("id", Self::VT_ID, false)? + .finish(); + Ok(()) + } +} +pub struct ReferrableArgs { + pub id: u64, +} +impl<'a> Default for ReferrableArgs { + #[inline] + fn default() -> Self { + ReferrableArgs { + id: 0, + } + } +} + +impl Serialize for Referrable<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Referrable", 1)?; + s.serialize_field("id", &self.id())?; + s.end() + } +} + +pub struct ReferrableBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ReferrableBuilder<'a, 'b, A> { + #[inline] + pub fn add_id(&mut self, id: u64) { + self.fbb_.push_slot::(Referrable::VT_ID, id, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ReferrableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ReferrableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Referrable<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Referrable"); + ds.field("id", &self.id()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct ReferrableT { + pub id: u64, +} +impl Default for ReferrableT { + fn default() -> Self { + Self { + id: 0, + } + } +} +impl ReferrableT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let id = self.id; + Referrable::create(_fbb, &ReferrableArgs{ + id, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/stat_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/stat_generated.rs new file mode 100644 index 00000000000..f864c6f828b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/stat_generated.rs @@ -0,0 +1,220 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum StatOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Stat<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Stat<'a> { + type Inner = Stat<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Stat<'a> { + pub const VT_ID: flatbuffers::VOffsetT = 4; + pub const VT_VAL: flatbuffers::VOffsetT = 6; + pub const VT_COUNT: flatbuffers::VOffsetT = 8; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Stat" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Stat { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args StatArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = StatBuilder::new(_fbb); + builder.add_val(args.val); + if let Some(x) = args.id { builder.add_id(x); } + builder.add_count(args.count); + builder.finish() + } + + pub fn unpack(&self) -> StatT { + let id = self.id().map(|x| { + x.to_string() + }); + let val = self.val(); + let count = self.count(); + StatT { + id, + val, + count, + } + } + + #[inline] + pub fn id(&self) -> Option<&'a str> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(Stat::VT_ID, None)} + } + #[inline] + pub fn val(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_VAL, Some(0)).unwrap()} + } + #[inline] + pub fn count(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Stat::VT_COUNT, Some(0)).unwrap()} + } + #[inline] + pub fn key_compare_less_than(&self, o: &Stat) -> bool { + self.count() < o.count() + } + + #[inline] + pub fn key_compare_with_value(&self, val: u16) -> ::core::cmp::Ordering { + let key = self.count(); + key.cmp(&val) + } +} + +impl flatbuffers::Verifiable for Stat<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("id", Self::VT_ID, false)? + .visit_field::("val", Self::VT_VAL, false)? + .visit_field::("count", Self::VT_COUNT, false)? + .finish(); + Ok(()) + } +} +pub struct StatArgs<'a> { + pub id: Option>, + pub val: i64, + pub count: u16, +} +impl<'a> Default for StatArgs<'a> { + #[inline] + fn default() -> Self { + StatArgs { + id: None, + val: 0, + count: 0, + } + } +} + +impl Serialize for Stat<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Stat", 3)?; + if let Some(f) = self.id() { + s.serialize_field("id", &f)?; + } else { + s.skip_field("id")?; + } + s.serialize_field("val", &self.val())?; + s.serialize_field("count", &self.count())?; + s.end() + } +} + +pub struct StatBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> StatBuilder<'a, 'b, A> { + #[inline] + pub fn add_id(&mut self, id: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(Stat::VT_ID, id); + } + #[inline] + pub fn add_val(&mut self, val: i64) { + self.fbb_.push_slot::(Stat::VT_VAL, val, 0); + } + #[inline] + pub fn add_count(&mut self, count: u16) { + self.fbb_.push_slot::(Stat::VT_COUNT, count, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> StatBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + StatBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Stat<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Stat"); + ds.field("id", &self.id()); + ds.field("val", &self.val()); + ds.field("count", &self.count()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct StatT { + pub id: Option, + pub val: i64, + pub count: u16, +} +impl Default for StatT { + fn default() -> Self { + Self { + id: None, + val: 0, + count: 0, + } + } +} +impl StatT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let id = self.id.as_ref().map(|x|{ + _fbb.create_string(x) + }); + let val = self.val; + let count = self.count; + Stat::create(_fbb, &StatArgs{ + id, + val, + count, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs new file mode 100644 index 00000000000..e524059f807 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/struct_of_structs_generated.rs @@ -0,0 +1,162 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct StructOfStructs, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct StructOfStructs(pub [u8; 20]); +impl Default for StructOfStructs { + fn default() -> Self { + Self([0; 20]) + } +} +impl core::fmt::Debug for StructOfStructs { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("StructOfStructs") + .field("a", &self.a()) + .field("b", &self.b()) + .field("c", &self.c()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for StructOfStructs {} +impl<'a> flatbuffers::Follow<'a> for StructOfStructs { + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a StructOfStructs>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a StructOfStructs { + type Inner = &'a StructOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for StructOfStructs { + type Output = StructOfStructs; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const StructOfStructs as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for StructOfStructs { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl Serialize for StructOfStructs { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("StructOfStructs", 3)?; + s.serialize_field("a", &self.a())?; + s.serialize_field("b", &self.b())?; + s.serialize_field("c", &self.c())?; + s.end() + } +} + +impl<'a> StructOfStructs { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &Ability, + b: &Test, + c: &Ability, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s.set_b(b); + s.set_c(c); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructs" + } + + pub fn a(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const Ability) } + } + + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &Ability) { + self.0[0..0 + 8].copy_from_slice(&x.0) + } + + pub fn b(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[8..].as_ptr() as *const Test) } + } + + #[allow(clippy::identity_op)] + pub fn set_b(&mut self, x: &Test) { + self.0[8..8 + 4].copy_from_slice(&x.0) + } + + pub fn c(&self) -> &Ability { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[12..].as_ptr() as *const Ability) } + } + + #[allow(clippy::identity_op)] + pub fn set_c(&mut self, x: &Ability) { + self.0[12..12 + 8].copy_from_slice(&x.0) + } + + pub fn unpack(&self) -> StructOfStructsT { + StructOfStructsT { + a: self.a().unpack(), + b: self.b().unpack(), + c: self.c().unpack(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct StructOfStructsT { + pub a: AbilityT, + pub b: TestT, + pub c: AbilityT, +} +impl StructOfStructsT { + pub fn pack(&self) -> StructOfStructs { + StructOfStructs::new( + &self.a.pack(), + &self.b.pack(), + &self.c.pack(), + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs new file mode 100644 index 00000000000..b7fd8cd7cf9 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/struct_of_structs_of_structs_generated.rs @@ -0,0 +1,124 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct StructOfStructsOfStructs, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct StructOfStructsOfStructs(pub [u8; 20]); +impl Default for StructOfStructsOfStructs { + fn default() -> Self { + Self([0; 20]) + } +} +impl core::fmt::Debug for StructOfStructsOfStructs { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("StructOfStructsOfStructs") + .field("a", &self.a()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for StructOfStructsOfStructs {} +impl<'a> flatbuffers::Follow<'a> for StructOfStructsOfStructs { + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a StructOfStructsOfStructs>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a StructOfStructsOfStructs { + type Inner = &'a StructOfStructsOfStructs; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for StructOfStructsOfStructs { + type Output = StructOfStructsOfStructs; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const StructOfStructsOfStructs as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for StructOfStructsOfStructs { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl Serialize for StructOfStructsOfStructs { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("StructOfStructsOfStructs", 1)?; + s.serialize_field("a", &self.a())?; + s.end() + } +} + +impl<'a> StructOfStructsOfStructs { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: &StructOfStructs, + ) -> Self { + let mut s = Self([0; 20]); + s.set_a(a); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.StructOfStructsOfStructs" + } + + pub fn a(&self) -> &StructOfStructs { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[0..].as_ptr() as *const StructOfStructs) } + } + + #[allow(clippy::identity_op)] + pub fn set_a(&mut self, x: &StructOfStructs) { + self.0[0..0 + 20].copy_from_slice(&x.0) + } + + pub fn unpack(&self) -> StructOfStructsOfStructsT { + StructOfStructsOfStructsT { + a: self.a().unpack(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct StructOfStructsOfStructsT { + pub a: StructOfStructsT, +} +impl StructOfStructsOfStructsT { + pub fn pack(&self) -> StructOfStructsOfStructs { + StructOfStructsOfStructs::new( + &self.a.pack(), + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/test_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/test_generated.rs new file mode 100644 index 00000000000..0a0a48c7dbe --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/test_generated.rs @@ -0,0 +1,177 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Test, aligned to 2 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Test(pub [u8; 4]); +impl Default for Test { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Test { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Test") + .field("a", &self.a()) + .field("b", &self.b()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Test {} +impl<'a> flatbuffers::Follow<'a> for Test { + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Test>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Test { + type Inner = &'a Test; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Test { + type Output = Test; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Test as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(2) + } +} + +impl<'a> flatbuffers::Verifiable for Test { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl Serialize for Test { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Test", 2)?; + s.serialize_field("a", &self.a())?; + s.serialize_field("b", &self.b())?; + s.end() + } +} + +impl<'a> Test { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i16, + b: i8, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s.set_b(b); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Test" + } + + pub fn a(&self) -> i16 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i16) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn b(&self) -> i8 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[2..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_b(&mut self, x: i8) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[2..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> TestT { + TestT { + a: self.a(), + b: self.b(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct TestT { + pub a: i16, + pub b: i8, +} +impl TestT { + pub fn pack(&self) -> Test { + Test::new( + self.a, + self.b, + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs new file mode 100644 index 00000000000..2db2b0bccdc --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/test_simple_table_with_enum_generated.rs @@ -0,0 +1,154 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TestSimpleTableWithEnumOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TestSimpleTableWithEnum<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TestSimpleTableWithEnum<'a> { + type Inner = TestSimpleTableWithEnum<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TestSimpleTableWithEnum<'a> { + pub const VT_COLOR: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TestSimpleTableWithEnum" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TestSimpleTableWithEnum { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TestSimpleTableWithEnumArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = TestSimpleTableWithEnumBuilder::new(_fbb); + builder.add_color(args.color); + builder.finish() + } + + pub fn unpack(&self) -> TestSimpleTableWithEnumT { + let color = self.color(); + TestSimpleTableWithEnumT { + color, + } + } + + #[inline] + pub fn color(&self) -> Color { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TestSimpleTableWithEnum::VT_COLOR, Some(Color::Green)).unwrap()} + } +} + +impl flatbuffers::Verifiable for TestSimpleTableWithEnum<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("color", Self::VT_COLOR, false)? + .finish(); + Ok(()) + } +} +pub struct TestSimpleTableWithEnumArgs { + pub color: Color, +} +impl<'a> Default for TestSimpleTableWithEnumArgs { + #[inline] + fn default() -> Self { + TestSimpleTableWithEnumArgs { + color: Color::Green, + } + } +} + +impl Serialize for TestSimpleTableWithEnum<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TestSimpleTableWithEnum", 1)?; + s.serialize_field("color", &self.color())?; + s.end() + } +} + +pub struct TestSimpleTableWithEnumBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TestSimpleTableWithEnumBuilder<'a, 'b, A> { + #[inline] + pub fn add_color(&mut self, color: Color) { + self.fbb_.push_slot::(TestSimpleTableWithEnum::VT_COLOR, color, Color::Green); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TestSimpleTableWithEnumBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TestSimpleTableWithEnumBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TestSimpleTableWithEnum<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TestSimpleTableWithEnum"); + ds.field("color", &self.color()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TestSimpleTableWithEnumT { + pub color: Color, +} +impl Default for TestSimpleTableWithEnumT { + fn default() -> Self { + Self { + color: Color::Green, + } + } +} +impl TestSimpleTableWithEnumT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let color = self.color; + TestSimpleTableWithEnum::create(_fbb, &TestSimpleTableWithEnumArgs{ + color, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs new file mode 100644 index 00000000000..fb9d1a1c431 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/type_aliases_generated.rs @@ -0,0 +1,434 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TypeAliasesOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TypeAliases<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TypeAliases<'a> { + type Inner = TypeAliases<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TypeAliases<'a> { + pub const VT_I8_: flatbuffers::VOffsetT = 4; + pub const VT_U8_: flatbuffers::VOffsetT = 6; + pub const VT_I16_: flatbuffers::VOffsetT = 8; + pub const VT_U16_: flatbuffers::VOffsetT = 10; + pub const VT_I32_: flatbuffers::VOffsetT = 12; + pub const VT_U32_: flatbuffers::VOffsetT = 14; + pub const VT_I64_: flatbuffers::VOffsetT = 16; + pub const VT_U64_: flatbuffers::VOffsetT = 18; + pub const VT_F32_: flatbuffers::VOffsetT = 20; + pub const VT_F64_: flatbuffers::VOffsetT = 22; + pub const VT_V8: flatbuffers::VOffsetT = 24; + pub const VT_VF64: flatbuffers::VOffsetT = 26; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.TypeAliases" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TypeAliases { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TypeAliasesArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TypeAliasesBuilder::new(_fbb); + builder.add_f64_(args.f64_); + builder.add_u64_(args.u64_); + builder.add_i64_(args.i64_); + if let Some(x) = args.vf64 { builder.add_vf64(x); } + if let Some(x) = args.v8 { builder.add_v8(x); } + builder.add_f32_(args.f32_); + builder.add_u32_(args.u32_); + builder.add_i32_(args.i32_); + builder.add_u16_(args.u16_); + builder.add_i16_(args.i16_); + builder.add_u8_(args.u8_); + builder.add_i8_(args.i8_); + builder.finish() + } + + pub fn unpack(&self) -> TypeAliasesT { + let i8_ = self.i8_(); + let u8_ = self.u8_(); + let i16_ = self.i16_(); + let u16_ = self.u16_(); + let i32_ = self.i32_(); + let u32_ = self.u32_(); + let i64_ = self.i64_(); + let u64_ = self.u64_(); + let f32_ = self.f32_(); + let f64_ = self.f64_(); + let v8 = self.v8().map(|x| { + x.into_iter().collect() + }); + let vf64 = self.vf64().map(|x| { + x.into_iter().collect() + }); + TypeAliasesT { + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, + } + } + + #[inline] + pub fn i8_(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I8_, Some(0)).unwrap()} + } + #[inline] + pub fn u8_(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U8_, Some(0)).unwrap()} + } + #[inline] + pub fn i16_(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I16_, Some(0)).unwrap()} + } + #[inline] + pub fn u16_(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U16_, Some(0)).unwrap()} + } + #[inline] + pub fn i32_(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I32_, Some(0)).unwrap()} + } + #[inline] + pub fn u32_(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U32_, Some(0)).unwrap()} + } + #[inline] + pub fn i64_(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_I64_, Some(0)).unwrap()} + } + #[inline] + pub fn u64_(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_U64_, Some(0)).unwrap()} + } + #[inline] + pub fn f32_(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F32_, Some(0.0)).unwrap()} + } + #[inline] + pub fn f64_(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TypeAliases::VT_F64_, Some(0.0)).unwrap()} + } + #[inline] + pub fn v8(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(TypeAliases::VT_V8, None)} + } + #[inline] + pub fn vf64(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(TypeAliases::VT_VF64, None)} + } +} + +impl flatbuffers::Verifiable for TypeAliases<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("i8_", Self::VT_I8_, false)? + .visit_field::("u8_", Self::VT_U8_, false)? + .visit_field::("i16_", Self::VT_I16_, false)? + .visit_field::("u16_", Self::VT_U16_, false)? + .visit_field::("i32_", Self::VT_I32_, false)? + .visit_field::("u32_", Self::VT_U32_, false)? + .visit_field::("i64_", Self::VT_I64_, false)? + .visit_field::("u64_", Self::VT_U64_, false)? + .visit_field::("f32_", Self::VT_F32_, false)? + .visit_field::("f64_", Self::VT_F64_, false)? + .visit_field::>>("v8", Self::VT_V8, false)? + .visit_field::>>("vf64", Self::VT_VF64, false)? + .finish(); + Ok(()) + } +} +pub struct TypeAliasesArgs<'a> { + pub i8_: i8, + pub u8_: u8, + pub i16_: i16, + pub u16_: u16, + pub i32_: i32, + pub u32_: u32, + pub i64_: i64, + pub u64_: u64, + pub f32_: f32, + pub f64_: f64, + pub v8: Option>>, + pub vf64: Option>>, +} +impl<'a> Default for TypeAliasesArgs<'a> { + #[inline] + fn default() -> Self { + TypeAliasesArgs { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, + } + } +} + +impl Serialize for TypeAliases<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TypeAliases", 12)?; + s.serialize_field("i8_", &self.i8_())?; + s.serialize_field("u8_", &self.u8_())?; + s.serialize_field("i16_", &self.i16_())?; + s.serialize_field("u16_", &self.u16_())?; + s.serialize_field("i32_", &self.i32_())?; + s.serialize_field("u32_", &self.u32_())?; + s.serialize_field("i64_", &self.i64_())?; + s.serialize_field("u64_", &self.u64_())?; + s.serialize_field("f32_", &self.f32_())?; + s.serialize_field("f64_", &self.f64_())?; + if let Some(f) = self.v8() { + s.serialize_field("v8", &f)?; + } else { + s.skip_field("v8")?; + } + if let Some(f) = self.vf64() { + s.serialize_field("vf64", &f)?; + } else { + s.skip_field("vf64")?; + } + s.end() + } +} + +pub struct TypeAliasesBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TypeAliasesBuilder<'a, 'b, A> { + #[inline] + pub fn add_i8_(&mut self, i8_: i8) { + self.fbb_.push_slot::(TypeAliases::VT_I8_, i8_, 0); + } + #[inline] + pub fn add_u8_(&mut self, u8_: u8) { + self.fbb_.push_slot::(TypeAliases::VT_U8_, u8_, 0); + } + #[inline] + pub fn add_i16_(&mut self, i16_: i16) { + self.fbb_.push_slot::(TypeAliases::VT_I16_, i16_, 0); + } + #[inline] + pub fn add_u16_(&mut self, u16_: u16) { + self.fbb_.push_slot::(TypeAliases::VT_U16_, u16_, 0); + } + #[inline] + pub fn add_i32_(&mut self, i32_: i32) { + self.fbb_.push_slot::(TypeAliases::VT_I32_, i32_, 0); + } + #[inline] + pub fn add_u32_(&mut self, u32_: u32) { + self.fbb_.push_slot::(TypeAliases::VT_U32_, u32_, 0); + } + #[inline] + pub fn add_i64_(&mut self, i64_: i64) { + self.fbb_.push_slot::(TypeAliases::VT_I64_, i64_, 0); + } + #[inline] + pub fn add_u64_(&mut self, u64_: u64) { + self.fbb_.push_slot::(TypeAliases::VT_U64_, u64_, 0); + } + #[inline] + pub fn add_f32_(&mut self, f32_: f32) { + self.fbb_.push_slot::(TypeAliases::VT_F32_, f32_, 0.0); + } + #[inline] + pub fn add_f64_(&mut self, f64_: f64) { + self.fbb_.push_slot::(TypeAliases::VT_F64_, f64_, 0.0); + } + #[inline] + pub fn add_v8(&mut self, v8: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TypeAliases::VT_V8, v8); + } + #[inline] + pub fn add_vf64(&mut self, vf64: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TypeAliases::VT_VF64, vf64); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TypeAliasesBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TypeAliasesBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TypeAliases<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TypeAliases"); + ds.field("i8_", &self.i8_()); + ds.field("u8_", &self.u8_()); + ds.field("i16_", &self.i16_()); + ds.field("u16_", &self.u16_()); + ds.field("i32_", &self.i32_()); + ds.field("u32_", &self.u32_()); + ds.field("i64_", &self.i64_()); + ds.field("u64_", &self.u64_()); + ds.field("f32_", &self.f32_()); + ds.field("f64_", &self.f64_()); + ds.field("v8", &self.v8()); + ds.field("vf64", &self.vf64()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TypeAliasesT { + pub i8_: i8, + pub u8_: u8, + pub i16_: i16, + pub u16_: u16, + pub i32_: i32, + pub u32_: u32, + pub i64_: i64, + pub u64_: u64, + pub f32_: f32, + pub f64_: f64, + pub v8: Option>, + pub vf64: Option>, +} +impl Default for TypeAliasesT { + fn default() -> Self { + Self { + i8_: 0, + u8_: 0, + i16_: 0, + u16_: 0, + i32_: 0, + u32_: 0, + i64_: 0, + u64_: 0, + f32_: 0.0, + f64_: 0.0, + v8: None, + vf64: None, + } + } +} +impl TypeAliasesT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let i8_ = self.i8_; + let u8_ = self.u8_; + let i16_ = self.i16_; + let u16_ = self.u16_; + let i32_ = self.i32_; + let u32_ = self.u32_; + let i64_ = self.i64_; + let u64_ = self.u64_; + let f32_ = self.f32_; + let f64_ = self.f64_; + let v8 = self.v8.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + let vf64 = self.vf64.as_ref().map(|x|{ + _fbb.create_vector(x) + }); + TypeAliases::create(_fbb, &TypeAliasesArgs{ + i8_, + u8_, + i16_, + u16_, + i32_, + u32_, + i64_, + u64_, + f32_, + f64_, + v8, + vf64, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/vec_3_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/vec_3_generated.rs new file mode 100644 index 00000000000..e4ff8f2a2a7 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example/vec_3_generated.rs @@ -0,0 +1,304 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Vec3, aligned to 8 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Vec3(pub [u8; 32]); +impl Default for Vec3 { + fn default() -> Self { + Self([0; 32]) + } +} +impl core::fmt::Debug for Vec3 { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Vec3") + .field("x", &self.x()) + .field("y", &self.y()) + .field("z", &self.z()) + .field("test1", &self.test1()) + .field("test2", &self.test2()) + .field("test3", &self.test3()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Vec3 {} +impl<'a> flatbuffers::Follow<'a> for Vec3 { + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Vec3>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Vec3 { + type Inner = &'a Vec3; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Vec3 { + type Output = Vec3; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Vec3 as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(8) + } +} + +impl<'a> flatbuffers::Verifiable for Vec3 { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl Serialize for Vec3 { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Vec3", 6)?; + s.serialize_field("x", &self.x())?; + s.serialize_field("y", &self.y())?; + s.serialize_field("z", &self.z())?; + s.serialize_field("test1", &self.test1())?; + s.serialize_field("test2", &self.test2())?; + s.serialize_field("test3", &self.test3())?; + s.end() + } +} + +impl<'a> Vec3 { + #[allow(clippy::too_many_arguments)] + pub fn new( + x: f32, + y: f32, + z: f32, + test1: f64, + test2: Color, + test3: &Test, + ) -> Self { + let mut s = Self([0; 32]); + s.set_x(x); + s.set_y(y); + s.set_z(z); + s.set_test1(test1); + s.set_test2(test2); + s.set_test3(test3); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example.Vec3" + } + + pub fn x(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_x(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn y(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_y(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn z(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_z(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn test1(&self) -> f64 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[16..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_test1(&mut self, x: f64) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[16..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn test2(&self) -> Color { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[24..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_test2(&mut self, x: Color) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[24..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn test3(&self) -> &Test { + // Safety: + // Created from a valid Table for this object + // Which contains a valid struct in this slot + unsafe { &*(self.0[26..].as_ptr() as *const Test) } + } + + #[allow(clippy::identity_op)] + pub fn set_test3(&mut self, x: &Test) { + self.0[26..26 + 4].copy_from_slice(&x.0) + } + + pub fn unpack(&self) -> Vec3T { + Vec3T { + x: self.x(), + y: self.y(), + z: self.z(), + test1: self.test1(), + test2: self.test2(), + test3: self.test3().unpack(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct Vec3T { + pub x: f32, + pub y: f32, + pub z: f32, + pub test1: f64, + pub test2: Color, + pub test3: TestT, +} +impl Vec3T { + pub fn pack(&self) -> Vec3 { + Vec3::new( + self.x, + self.y, + self.z, + self.test1, + self.test2, + &self.test3.pack(), + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/example_2/monster_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example_2/monster_generated.rs new file mode 100644 index 00000000000..96f2d17a17b --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/example_2/monster_generated.rs @@ -0,0 +1,129 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum MonsterOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct Monster<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Monster<'a> { + type Inner = Monster<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Monster<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.Example2.Monster" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Monster { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args MonsterArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = MonsterBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> MonsterT { + MonsterT { + } + } +} + +impl flatbuffers::Verifiable for Monster<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct MonsterArgs { +} +impl<'a> Default for MonsterArgs { + #[inline] + fn default() -> Self { + MonsterArgs { + } + } +} + +impl Serialize for Monster<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let s = serializer.serialize_struct("Monster", 0)?; + s.end() + } +} + +pub struct MonsterBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> MonsterBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> MonsterBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MonsterBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Monster<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Monster"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct MonsterT { +} +impl Default for MonsterT { + fn default() -> Self { + Self { + } + } +} +impl MonsterT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + Monster::create(_fbb, &MonsterArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs new file mode 100644 index 00000000000..7f9324342c6 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/in_parent_namespace_generated.rs @@ -0,0 +1,129 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum InParentNamespaceOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct InParentNamespace<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for InParentNamespace<'a> { + type Inner = InParentNamespace<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> InParentNamespace<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.InParentNamespace" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + InParentNamespace { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args InParentNamespaceArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = InParentNamespaceBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> InParentNamespaceT { + InParentNamespaceT { + } + } +} + +impl flatbuffers::Verifiable for InParentNamespace<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct InParentNamespaceArgs { +} +impl<'a> Default for InParentNamespaceArgs { + #[inline] + fn default() -> Self { + InParentNamespaceArgs { + } + } +} + +impl Serialize for InParentNamespace<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let s = serializer.serialize_struct("InParentNamespace", 0)?; + s.end() + } +} + +pub struct InParentNamespaceBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> InParentNamespaceBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> InParentNamespaceBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + InParentNamespaceBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for InParentNamespace<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("InParentNamespace"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct InParentNamespaceT { +} +impl Default for InParentNamespaceT { + fn default() -> Self { + Self { + } + } +} +impl InParentNamespaceT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + InParentNamespace::create(_fbb, &InParentNamespaceArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs new file mode 100644 index 00000000000..15366440143 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/from_include_generated.rs @@ -0,0 +1,103 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FROM_INCLUDE: i64 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FROM_INCLUDE: [FromInclude; 1] = [ + FromInclude::IncludeVal, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FromInclude(pub i64); +#[allow(non_upper_case_globals)] +impl FromInclude { + pub const IncludeVal: Self = Self(0); + + pub const ENUM_MIN: i64 = 0; + pub const ENUM_MAX: i64 = 0; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::IncludeVal, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::IncludeVal => Some("IncludeVal"), + _ => None, + } + } +} +impl core::fmt::Debug for FromInclude { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl Serialize for FromInclude { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + serializer.serialize_unit_variant("FromInclude", self.0 as u32, self.variant_name().unwrap()) + } +} + +impl<'a> flatbuffers::Follow<'a> for FromInclude { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for FromInclude { + type Output = FromInclude; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for FromInclude { + type Scalar = i64; + #[inline] + fn to_little_endian(self) -> i64 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i64) -> Self { + let b = i64::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for FromInclude { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i64::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for FromInclude {} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs new file mode 100644 index 00000000000..83ed1a9fbe6 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/table_b_generated.rs @@ -0,0 +1,162 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableBOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableB<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableB<'a> { + type Inner = TableB<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableB<'a> { + pub const VT_A: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.TableB" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableB { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableBArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableBBuilder::new(_fbb); + if let Some(x) = args.a { builder.add_a(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableBT { + let a = self.a().map(|x| { + Box::new(x.unpack()) + }); + TableBT { + a, + } + } + + #[inline] + pub fn a(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableB::VT_A, None)} + } +} + +impl flatbuffers::Verifiable for TableB<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("a", Self::VT_A, false)? + .finish(); + Ok(()) + } +} +pub struct TableBArgs<'a> { + pub a: Option>>, +} +impl<'a> Default for TableBArgs<'a> { + #[inline] + fn default() -> Self { + TableBArgs { + a: None, + } + } +} + +impl Serialize for TableB<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TableB", 1)?; + if let Some(f) = self.a() { + s.serialize_field("a", &f)?; + } else { + s.skip_field("a")?; + } + s.end() + } +} + +pub struct TableBBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableBBuilder<'a, 'b, A> { + #[inline] + pub fn add_a(&mut self, a: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableB::VT_A, a); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableBBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableBBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableB<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableB"); + ds.field("a", &self.a()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableBT { + pub a: Option>, +} +impl Default for TableBT { + fn default() -> Self { + Self { + a: None, + } + } +} +impl TableBT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let a = self.a.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableB::create(_fbb, &TableBArgs{ + a, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs new file mode 100644 index 00000000000..c89fab4ef78 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/my_game/other_name_space/unused_generated.rs @@ -0,0 +1,141 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Unused, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct Unused(pub [u8; 4]); +impl Default for Unused { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Unused { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Unused") + .field("a", &self.a()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Unused {} +impl<'a> flatbuffers::Follow<'a> for Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Unused>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Unused { + type Inner = &'a Unused; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Unused { + type Output = Unused; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Unused as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Unused { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl Serialize for Unused { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("Unused", 1)?; + s.serialize_field("a", &self.a())?; + s.end() + } +} + +impl<'a> Unused { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_a(a); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "MyGame.OtherNameSpace.Unused" + } + + pub fn a(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> UnusedT { + UnusedT { + a: self.a(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct UnusedT { + pub a: i32, +} +impl UnusedT { + pub fn pack(&self) -> Unused { + Unused::new( + self.a, + ) + } +} + diff --git a/third_party/flatbuffers/tests/monster_test_serialize/table_a_generated.rs b/third_party/flatbuffers/tests/monster_test_serialize/table_a_generated.rs new file mode 100644 index 00000000000..c0d8f65b154 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_serialize/table_a_generated.rs @@ -0,0 +1,162 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +extern crate serde; +use self::serde::ser::{Serialize, Serializer, SerializeStruct}; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableAOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableA<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableA<'a> { + type Inner = TableA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableA<'a> { + pub const VT_B: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "TableA" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableAArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableABuilder::new(_fbb); + if let Some(x) = args.b { builder.add_b(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableAT { + let b = self.b().map(|x| { + Box::new(x.unpack()) + }); + TableAT { + b, + } + } + + #[inline] + pub fn b(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableA::VT_B, None)} + } +} + +impl flatbuffers::Verifiable for TableA<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("b", Self::VT_B, false)? + .finish(); + Ok(()) + } +} +pub struct TableAArgs<'a> { + pub b: Option>>, +} +impl<'a> Default for TableAArgs<'a> { + #[inline] + fn default() -> Self { + TableAArgs { + b: None, + } + } +} + +impl Serialize for TableA<'_> { + fn serialize(&self, serializer: S) -> Result + where + S: Serializer, + { + let mut s = serializer.serialize_struct("TableA", 1)?; + if let Some(f) = self.b() { + s.serialize_field("b", &f)?; + } else { + s.skip_field("b")?; + } + s.end() + } +} + +pub struct TableABuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableABuilder<'a, 'b, A> { + #[inline] + pub fn add_b(&mut self, b: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableA::VT_B, b); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableABuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableA<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableA"); + ds.field("b", &self.b()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableAT { + pub b: Option>, +} +impl Default for TableAT { + fn default() -> Self { + Self { + b: None, + } + } +} +impl TableAT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let b = self.b.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableA::create(_fbb, &TableAArgs{ + b, + }) + } +} diff --git a/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test.grpc.fb.cc b/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test.grpc.fb.cc new file mode 100644 index 00000000000..3cc72ed6325 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test.grpc.fb.cc @@ -0,0 +1,131 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test + +#include "monster_test_generated.hpp" +#include "monster_test.grpc.fb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +namespace MyGame { +namespace Example { + +static const char* MonsterStorage_method_names[] = { + "/MyGame.Example.MonsterStorage/Store", + "/MyGame.Example.MonsterStorage/Retrieve", + "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", +}; + +std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) { + std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel)); + return stub; +} + +MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) + : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) + , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) + , rpcmethod_GetMaxHitPoint_(MonsterStorage_method_names[2], ::grpc::internal::RpcMethod::CLIENT_STREAMING, channel) + , rpcmethod_GetMinMaxHitPoints_(MonsterStorage_method_names[3], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel) + {} + +::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) { + return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false); +} + +::grpc::ClientReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_Retrieve_, context, request); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr); +} + +::grpc::ClientWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return ::grpc::internal::ClientWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMaxHitPoint_, context, response); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, true, tag); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, false, nullptr); +} + +::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMinMaxHitPointsRaw(::grpc::ClientContext* context) { + return ::grpc::internal::ClientReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMinMaxHitPoints_, context); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, true, tag); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, false, nullptr); +} + +MonsterStorage::Service::Service() { + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[0], + ::grpc::internal::RpcMethod::NORMAL_RPC, + new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Store), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[1], + ::grpc::internal::RpcMethod::SERVER_STREAMING, + new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Retrieve), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[2], + ::grpc::internal::RpcMethod::CLIENT_STREAMING, + new ::grpc::internal::ClientStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMaxHitPoint), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[3], + ::grpc::internal::RpcMethod::BIDI_STREAMING, + new ::grpc::internal::BidiStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMinMaxHitPoints), this))); +} + +MonsterStorage::Service::~Service() { +} + +::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + + +} // namespace MyGame +} // namespace Example + diff --git a/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test.grpc.fb.h b/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test.grpc.fb.h new file mode 100644 index 00000000000..530504e1045 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test.grpc.fb.h @@ -0,0 +1,350 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test +#ifndef GRPC_monster_5ftest__INCLUDED +#define GRPC_monster_5ftest__INCLUDED + +#include "monster_test_generated.hpp" +#include "flatbuffers/grpc.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class Channel; +class ServerCompletionQueue; +class ServerContext; +} // namespace grpc + +namespace MyGame { +namespace Example { + +class MonsterStorage final { + public: + static constexpr char const* service_full_name() { + return "MyGame.Example.MonsterStorage"; + } + class StubInterface { + public: + virtual ~StubInterface() {} + virtual ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + private: + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReader< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientWriter< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override; + const ::grpc::internal::RpcMethod rpcmethod_Store_; + const ::grpc::internal::RpcMethod rpcmethod_Retrieve_; + const ::grpc::internal::RpcMethod rpcmethod_GetMaxHitPoint_; + const ::grpc::internal::RpcMethod rpcmethod_GetMinMaxHitPoints_; + }; + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class Service : public ::grpc::Service { + public: + Service(); + virtual ~Service(); + virtual ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, flatbuffers::grpc::Message* response); + virtual ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, ::grpc::ServerWriter< flatbuffers::grpc::Message>* writer); + virtual ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message>* reader, flatbuffers::grpc::Message* response); + virtual ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream); + }; + template + class WithAsyncMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Store() { + ::grpc::Service::MarkMethodAsync(0); + } + ~WithAsyncMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestStore(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncResponseWriter< flatbuffers::grpc::Message>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Retrieve() { + ::grpc::Service::MarkMethodAsync(1); + } + ~WithAsyncMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestRetrieve(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncWriter< flatbuffers::grpc::Message>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncServerStreaming(1, context, request, writer, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodAsync(2); + } + ~WithAsyncMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* reader, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncClientStreaming(2, context, reader, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodAsync(3); + } + ~WithAsyncMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(3, context, stream, new_call_cq, notification_cq, tag); + } + }; + typedef WithAsyncMethod_Store< WithAsyncMethod_Retrieve< WithAsyncMethod_GetMaxHitPoint< WithAsyncMethod_GetMinMaxHitPoints< Service > > > > AsyncService; + template + class WithGenericMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Store() { + ::grpc::Service::MarkMethodGeneric(0); + } + ~WithGenericMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Retrieve() { + ::grpc::Service::MarkMethodGeneric(1); + } + ~WithGenericMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodGeneric(2); + } + ~WithGenericMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodGeneric(3); + } + ~WithGenericMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithStreamedUnaryMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithStreamedUnaryMethod_Store() { + ::grpc::Service::MarkMethodStreamed(0, + new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithStreamedUnaryMethod_Store::StreamedStore, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedStore(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_unary_streamer) = 0; + }; + typedef WithStreamedUnaryMethod_Store< Service > StreamedUnaryService; + template + class WithSplitStreamingMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) { } + public: + WithSplitStreamingMethod_Retrieve() { + ::grpc::Service::MarkMethodStreamed(1, + new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithSplitStreamingMethod_Retrieve::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithSplitStreamingMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with split streamed + virtual ::grpc::Status StreamedRetrieve(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_split_streamer) = 0; + }; + typedef WithSplitStreamingMethod_Retrieve< Service > SplitStreamedService; + typedef WithStreamedUnaryMethod_Store< WithSplitStreamingMethod_Retrieve< Service > > StreamedService; +}; + +} // namespace Example +} // namespace MyGame + + +#endif // GRPC_monster_5ftest__INCLUDED diff --git a/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test_generated.hpp b/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test_generated.hpp new file mode 100644 index 00000000000..fd292b0f327 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/ext_only/monster_test_generated.hpp @@ -0,0 +1,4238 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ +#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/flex_flat_util.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace MyGame { + +struct InParentNamespace; +struct InParentNamespaceBuilder; +struct InParentNamespaceT; + +namespace Example2 { + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +} // namespace Example2 + +namespace Example { + +struct Test; + +struct TestSimpleTableWithEnum; +struct TestSimpleTableWithEnumBuilder; +struct TestSimpleTableWithEnumT; + +struct Vec3; + +struct Ability; + +struct StructOfStructs; + +struct StructOfStructsOfStructs; + +struct Stat; +struct StatBuilder; +struct StatT; + +struct Referrable; +struct ReferrableBuilder; +struct ReferrableT; + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +struct TypeAliases; +struct TypeAliasesBuilder; +struct TypeAliasesT; + +} // namespace Example + +bool operator==(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +namespace Example2 { + +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +} // namespace Example2 + +namespace Example { + +bool operator==(const Test &lhs, const Test &rhs); +bool operator!=(const Test &lhs, const Test &rhs); +bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator==(const Vec3 &lhs, const Vec3 &rhs); +bool operator!=(const Vec3 &lhs, const Vec3 &rhs); +bool operator==(const Ability &lhs, const Ability &rhs); +bool operator!=(const Ability &lhs, const Ability &rhs); +bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator==(const StatT &lhs, const StatT &rhs); +bool operator!=(const StatT &lhs, const StatT &rhs); +bool operator==(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs); +bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs); + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable(); + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable(); + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable(); + +inline const ::flatbuffers::TypeTable *Vec3TypeTable(); + +inline const ::flatbuffers::TypeTable *AbilityTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StatTypeTable(); + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable(); + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable(); + +/// Composite components of Monster color. +enum Color : uint8_t { + Color_Red = 1, + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Color_Green = 2, + /// \brief color Blue (1u << 3) + Color_Blue = 8, + Color_NONE = 0, + Color_ANY = 11 +}; + +inline const Color (&EnumValuesColor())[3] { + static const Color values[] = { + Color_Red, + Color_Green, + Color_Blue + }; + return values; +} + +inline const char * const *EnumNamesColor() { + static const char * const names[9] = { + "Red", + "Green", + "", + "", + "", + "", + "", + "Blue", + nullptr + }; + return names; +} + +inline const char *EnumNameColor(Color e) { + if (::flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return ""; + const size_t index = static_cast(e) - static_cast(Color_Red); + return EnumNamesColor()[index]; +} + +enum Race : int8_t { + Race_None = -1, + Race_Human = 0, + Race_Dwarf = 1, + Race_Elf = 2, + Race_MIN = Race_None, + Race_MAX = Race_Elf +}; + +inline const Race (&EnumValuesRace())[4] { + static const Race values[] = { + Race_None, + Race_Human, + Race_Dwarf, + Race_Elf + }; + return values; +} + +inline const char * const *EnumNamesRace() { + static const char * const names[5] = { + "None", + "Human", + "Dwarf", + "Elf", + nullptr + }; + return names; +} + +inline const char *EnumNameRace(Race e) { + if (::flatbuffers::IsOutRange(e, Race_None, Race_Elf)) return ""; + const size_t index = static_cast(e) - static_cast(Race_None); + return EnumNamesRace()[index]; +} + +enum LongEnum : uint64_t { + LongEnum_LongOne = 2ULL, + LongEnum_LongTwo = 4ULL, + LongEnum_LongBig = 1099511627776ULL, + LongEnum_NONE = 0, + LongEnum_ANY = 1099511627782ULL +}; + +inline const LongEnum (&EnumValuesLongEnum())[3] { + static const LongEnum values[] = { + LongEnum_LongOne, + LongEnum_LongTwo, + LongEnum_LongBig + }; + return values; +} + +inline const char *EnumNameLongEnum(LongEnum e) { + switch (e) { + case LongEnum_LongOne: return "LongOne"; + case LongEnum_LongTwo: return "LongTwo"; + case LongEnum_LongBig: return "LongBig"; + default: return ""; + } +} + +enum Any : uint8_t { + Any_NONE = 0, + Any_Monster = 1, + Any_TestSimpleTableWithEnum = 2, + Any_MyGame_Example2_Monster = 3, + Any_MIN = Any_NONE, + Any_MAX = Any_MyGame_Example2_Monster +}; + +inline const Any (&EnumValuesAny())[4] { + static const Any values[] = { + Any_NONE, + Any_Monster, + Any_TestSimpleTableWithEnum, + Any_MyGame_Example2_Monster + }; + return values; +} + +inline const char * const *EnumNamesAny() { + static const char * const names[5] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster", + nullptr + }; + return names; +} + +inline const char *EnumNameAny(Any e) { + if (::flatbuffers::IsOutRange(e, Any_NONE, Any_MyGame_Example2_Monster)) return ""; + const size_t index = static_cast(e); + return EnumNamesAny()[index]; +} + +template struct AnyTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +template struct AnyUnionTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +struct AnyUnion { + Any type; + void *value; + + AnyUnion() : type(Any_NONE), value(nullptr) {} + AnyUnion(AnyUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Any_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUnion(const AnyUnion &); + AnyUnion &operator=(const AnyUnion &u) + { AnyUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUnion &operator=(AnyUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUnionTraits::enum_value; + if (type != Any_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsMonster() { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsMonster() const { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() const { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() const { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUnion &lhs, const AnyUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_TestSimpleTableWithEnum: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_MyGame_Example2_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUnion &lhs, const AnyUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type); +bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyUniqueAliases : uint8_t { + AnyUniqueAliases_NONE = 0, + AnyUniqueAliases_M = 1, + AnyUniqueAliases_TS = 2, + AnyUniqueAliases_M2 = 3, + AnyUniqueAliases_MIN = AnyUniqueAliases_NONE, + AnyUniqueAliases_MAX = AnyUniqueAliases_M2 +}; + +inline const AnyUniqueAliases (&EnumValuesAnyUniqueAliases())[4] { + static const AnyUniqueAliases values[] = { + AnyUniqueAliases_NONE, + AnyUniqueAliases_M, + AnyUniqueAliases_TS, + AnyUniqueAliases_M2 + }; + return values; +} + +inline const char * const *EnumNamesAnyUniqueAliases() { + static const char * const names[5] = { + "NONE", + "M", + "TS", + "M2", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyUniqueAliases(AnyUniqueAliases e) { + if (::flatbuffers::IsOutRange(e, AnyUniqueAliases_NONE, AnyUniqueAliases_M2)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyUniqueAliases()[index]; +} + +template struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +template struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +struct AnyUniqueAliasesUnion { + AnyUniqueAliases type; + void *value; + + AnyUniqueAliasesUnion() : type(AnyUniqueAliases_NONE), value(nullptr) {} + AnyUniqueAliasesUnion(AnyUniqueAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyUniqueAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &); + AnyUniqueAliasesUnion &operator=(const AnyUniqueAliasesUnion &u) + { AnyUniqueAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUniqueAliasesUnion &operator=(AnyUniqueAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUniqueAliasesUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUniqueAliasesUnionTraits::enum_value; + if (type != AnyUniqueAliases_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM() { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM() const { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTS() { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTS() const { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsM2() { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsM2() const { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_TS: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type); +bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyAmbiguousAliases : uint8_t { + AnyAmbiguousAliases_NONE = 0, + AnyAmbiguousAliases_M1 = 1, + AnyAmbiguousAliases_M2 = 2, + AnyAmbiguousAliases_M3 = 3, + AnyAmbiguousAliases_MIN = AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_MAX = AnyAmbiguousAliases_M3 +}; + +inline const AnyAmbiguousAliases (&EnumValuesAnyAmbiguousAliases())[4] { + static const AnyAmbiguousAliases values[] = { + AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_M1, + AnyAmbiguousAliases_M2, + AnyAmbiguousAliases_M3 + }; + return values; +} + +inline const char * const *EnumNamesAnyAmbiguousAliases() { + static const char * const names[5] = { + "NONE", + "M1", + "M2", + "M3", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyAmbiguousAliases(AnyAmbiguousAliases e) { + if (::flatbuffers::IsOutRange(e, AnyAmbiguousAliases_NONE, AnyAmbiguousAliases_M3)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyAmbiguousAliases()[index]; +} + +struct AnyAmbiguousAliasesUnion { + AnyAmbiguousAliases type; + void *value; + + AnyAmbiguousAliasesUnion() : type(AnyAmbiguousAliases_NONE), value(nullptr) {} + AnyAmbiguousAliasesUnion(AnyAmbiguousAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyAmbiguousAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &); + AnyAmbiguousAliasesUnion &operator=(const AnyAmbiguousAliasesUnion &u) + { AnyAmbiguousAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyAmbiguousAliasesUnion &operator=(AnyAmbiguousAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyAmbiguousAliasesUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM1() { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM1() const { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM2() { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM2() const { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM3() { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM3() const { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M3: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type); +bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS { + private: + int16_t a_; + int8_t b_; + int8_t padding0__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestTypeTable(); + } + Test() + : a_(0), + b_(0), + padding0__(0) { + (void)padding0__; + } + Test(int16_t _a, int8_t _b) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0) { + (void)padding0__; + } + int16_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int16_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + int8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(int8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Test, 4); + +inline bool operator==(const Test &lhs, const Test &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Test &lhs, const Test &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Vec3 FLATBUFFERS_FINAL_CLASS { + private: + float x_; + float y_; + float z_; + int32_t padding0__; + double test1_; + uint8_t test2_; + int8_t padding1__; + MyGame::Example::Test test3_; + int16_t padding2__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vec3TypeTable(); + } + Vec3() + : x_(0), + y_(0), + z_(0), + padding0__(0), + test1_(0), + test2_(0), + padding1__(0), + test3_(), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + Vec3(float _x, float _y, float _z, double _test1, MyGame::Example::Color _test2, const MyGame::Example::Test &_test3) + : x_(::flatbuffers::EndianScalar(_x)), + y_(::flatbuffers::EndianScalar(_y)), + z_(::flatbuffers::EndianScalar(_z)), + padding0__(0), + test1_(::flatbuffers::EndianScalar(_test1)), + test2_(::flatbuffers::EndianScalar(static_cast(_test2))), + padding1__(0), + test3_(_test3), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + float x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(float _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } + float y() const { + return ::flatbuffers::EndianScalar(y_); + } + void mutate_y(float _y) { + ::flatbuffers::WriteScalar(&y_, _y); + } + float z() const { + return ::flatbuffers::EndianScalar(z_); + } + void mutate_z(float _z) { + ::flatbuffers::WriteScalar(&z_, _z); + } + double test1() const { + return ::flatbuffers::EndianScalar(test1_); + } + void mutate_test1(double _test1) { + ::flatbuffers::WriteScalar(&test1_, _test1); + } + MyGame::Example::Color test2() const { + return static_cast(::flatbuffers::EndianScalar(test2_)); + } + void mutate_test2(MyGame::Example::Color _test2) { + ::flatbuffers::WriteScalar(&test2_, static_cast(_test2)); + } + const MyGame::Example::Test &test3() const { + return test3_; + } + MyGame::Example::Test &mutable_test3() { + return test3_; + } +}; +FLATBUFFERS_STRUCT_END(Vec3, 32); + +inline bool operator==(const Vec3 &lhs, const Vec3 &rhs) { + return + (lhs.x() == rhs.x()) && + (lhs.y() == rhs.y()) && + (lhs.z() == rhs.z()) && + (lhs.test1() == rhs.test1()) && + (lhs.test2() == rhs.test2()) && + (lhs.test3() == rhs.test3()); +} + +inline bool operator!=(const Vec3 &lhs, const Vec3 &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Ability FLATBUFFERS_FINAL_CLASS { + private: + uint32_t id_; + uint32_t distance_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AbilityTypeTable(); + } + Ability() + : id_(0), + distance_(0) { + } + Ability(uint32_t _id, uint32_t _distance) + : id_(::flatbuffers::EndianScalar(_id)), + distance_(::flatbuffers::EndianScalar(_distance)) { + } + uint32_t id() const { + return ::flatbuffers::EndianScalar(id_); + } + void mutate_id(uint32_t _id) { + ::flatbuffers::WriteScalar(&id_, _id); + } + bool KeyCompareLessThan(const Ability * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint32_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + uint32_t distance() const { + return ::flatbuffers::EndianScalar(distance_); + } + void mutate_distance(uint32_t _distance) { + ::flatbuffers::WriteScalar(&distance_, _distance); + } +}; +FLATBUFFERS_STRUCT_END(Ability, 8); + +inline bool operator==(const Ability &lhs, const Ability &rhs) { + return + (lhs.id() == rhs.id()) && + (lhs.distance() == rhs.distance()); +} + +inline bool operator!=(const Ability &lhs, const Ability &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::Ability a_; + MyGame::Example::Test b_; + MyGame::Example::Ability c_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsTypeTable(); + } + StructOfStructs() + : a_(), + b_(), + c_() { + } + StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c) + : a_(_a), + b_(_b), + c_(_c) { + } + const MyGame::Example::Ability &a() const { + return a_; + } + MyGame::Example::Ability &mutable_a() { + return a_; + } + const MyGame::Example::Test &b() const { + return b_; + } + MyGame::Example::Test &mutable_b() { + return b_; + } + const MyGame::Example::Ability &c() const { + return c_; + } + MyGame::Example::Ability &mutable_c() { + return c_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructs, 20); + +inline bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()) && + (lhs.c() == rhs.c()); +} + +inline bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructsOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::StructOfStructs a_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsOfStructsTypeTable(); + } + StructOfStructsOfStructs() + : a_() { + } + StructOfStructsOfStructs(const MyGame::Example::StructOfStructs &_a) + : a_(_a) { + } + const MyGame::Example::StructOfStructs &a() const { + return a_; + } + MyGame::Example::StructOfStructs &mutable_a() { + return a_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructsOfStructs, 20); + +inline bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return + (lhs.a() == rhs.a()); +} + +inline bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return !(lhs == rhs); +} + + +} // namespace Example + +struct InParentNamespaceT : public ::flatbuffers::NativeTable { + typedef InParentNamespace TableType; +}; + +struct InParentNamespace FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef InParentNamespaceT NativeTableType; + typedef InParentNamespaceBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return InParentNamespaceTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + InParentNamespaceT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct InParentNamespaceBuilder { + typedef InParentNamespace Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit InParentNamespaceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateInParentNamespace( + ::flatbuffers::FlatBufferBuilder &_fbb) { + InParentNamespaceBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +namespace Example2 { + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; +}; + +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb) { + MonsterBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example2 + +namespace Example { + +struct TestSimpleTableWithEnumT : public ::flatbuffers::NativeTable { + typedef TestSimpleTableWithEnum TableType; + MyGame::Example::Color color = MyGame::Example::Color_Green; +}; + +struct TestSimpleTableWithEnum FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TestSimpleTableWithEnumT NativeTableType; + typedef TestSimpleTableWithEnumBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestSimpleTableWithEnumTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_COLOR = 4 + }; + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 2)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(2)) { + return SetField(VT_COLOR, static_cast(_color), 2); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_COLOR, 1) && + verifier.EndTable(); + } + TestSimpleTableWithEnumT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TestSimpleTableWithEnumBuilder { + typedef TestSimpleTableWithEnum Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(TestSimpleTableWithEnum::VT_COLOR, static_cast(color), 2); + } + explicit TestSimpleTableWithEnumBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum( + ::flatbuffers::FlatBufferBuilder &_fbb, + MyGame::Example::Color color = MyGame::Example::Color_Green) { + TestSimpleTableWithEnumBuilder builder_(_fbb); + builder_.add_color(color); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct StatT : public ::flatbuffers::NativeTable { + typedef Stat TableType; + std::string id{}; + int64_t val = 0; + uint16_t count = 0; +}; + +struct Stat FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StatT NativeTableType; + typedef StatBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StatTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4, + VT_VAL = 6, + VT_COUNT = 8 + }; + const ::flatbuffers::String *id() const { + return GetPointer(VT_ID); + } + ::flatbuffers::String *mutable_id() { + return GetPointer<::flatbuffers::String *>(VT_ID); + } + int64_t val() const { + return GetField(VT_VAL, 0); + } + bool mutate_val(int64_t _val = 0) { + return SetField(VT_VAL, _val, 0); + } + uint16_t count() const { + return GetField(VT_COUNT, 0); + } + bool mutate_count(uint16_t _count = 0) { + return SetField(VT_COUNT, _count, 0); + } + bool KeyCompareLessThan(const Stat * const o) const { + return count() < o->count(); + } + int KeyCompareWithValue(uint16_t _count) const { + return static_cast(count() > _count) - static_cast(count() < _count); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ID) && + verifier.VerifyString(id()) && + VerifyField(verifier, VT_VAL, 8) && + VerifyField(verifier, VT_COUNT, 2) && + verifier.EndTable(); + } + StatT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct StatBuilder { + typedef Stat Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(::flatbuffers::Offset<::flatbuffers::String> id) { + fbb_.AddOffset(Stat::VT_ID, id); + } + void add_val(int64_t val) { + fbb_.AddElement(Stat::VT_VAL, val, 0); + } + void add_count(uint16_t count) { + fbb_.AddElement(Stat::VT_COUNT, count, 0); + } + explicit StatBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStat( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> id = 0, + int64_t val = 0, + uint16_t count = 0) { + StatBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_id(id); + builder_.add_count(count); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStatDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *id = nullptr, + int64_t val = 0, + uint16_t count = 0) { + auto id__ = id ? _fbb.CreateString(id) : 0; + return MyGame::Example::CreateStat( + _fbb, + id__, + val, + count); +} + +::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct ReferrableT : public ::flatbuffers::NativeTable { + typedef Referrable TableType; + uint64_t id = 0; +}; + +struct Referrable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ReferrableT NativeTableType; + typedef ReferrableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ReferrableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4 + }; + uint64_t id() const { + return GetField(VT_ID, 0); + } + bool mutate_id(uint64_t _id = 0) { + return SetField(VT_ID, _id, 0); + } + bool KeyCompareLessThan(const Referrable * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint64_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_ID, 8) && + verifier.EndTable(); + } + ReferrableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ReferrableBuilder { + typedef Referrable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(uint64_t id) { + fbb_.AddElement(Referrable::VT_ID, id, 0); + } + explicit ReferrableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateReferrable( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint64_t id = 0) { + ReferrableBuilder builder_(_fbb); + builder_.add_id(id); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; + std::unique_ptr pos{}; + int16_t mana = 150; + int16_t hp = 100; + std::string name{}; + std::vector inventory{}; + MyGame::Example::Color color = MyGame::Example::Color_Blue; + MyGame::Example::AnyUnion test{}; + std::vector test4{}; + std::vector testarrayofstring{}; + std::vector> testarrayoftables{}; + std::unique_ptr enemy{}; + std::vector testnestedflatbuffer{}; + std::unique_ptr testempty{}; + bool testbool = false; + int32_t testhashs32_fnv1 = 0; + uint32_t testhashu32_fnv1 = 0; + int64_t testhashs64_fnv1 = 0; + uint64_t testhashu64_fnv1 = 0; + int32_t testhashs32_fnv1a = 0; + Stat *testhashu32_fnv1a = nullptr; + int64_t testhashs64_fnv1a = 0; + uint64_t testhashu64_fnv1a = 0; + std::vector testarrayofbools{}; + float testf = 3.14159f; + float testf2 = 3.0f; + float testf3 = 0.0f; + std::vector testarrayofstring2{}; + std::vector testarrayofsortedstruct{}; + std::vector flex{}; + std::vector test5{}; + std::vector vector_of_longs{}; + std::vector vector_of_doubles{}; + std::unique_ptr parent_namespace_test{}; + std::vector> vector_of_referrables{}; + ReferrableT *single_weak_reference = nullptr; + std::vector vector_of_weak_references{}; + std::vector> vector_of_strong_referrables{}; + ReferrableT *co_owning_reference = nullptr; + std::vector> vector_of_co_owning_references{}; + ReferrableT *non_owning_reference = nullptr; + std::vector vector_of_non_owning_references{}; + MyGame::Example::AnyUniqueAliasesUnion any_unique{}; + MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous{}; + std::vector vector_of_enums{}; + MyGame::Example::Race signed_enum = MyGame::Example::Race_None; + std::vector testrequirednestedflatbuffer{}; + std::vector> scalar_key_sorted_tables{}; + MyGame::Example::Test native_inline{}; + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0); + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne; + float nan_default = std::numeric_limits::quiet_NaN(); + float inf_default = std::numeric_limits::infinity(); + float positive_inf_default = std::numeric_limits::infinity(); + float infinity_default = std::numeric_limits::infinity(); + float positive_infinity_default = std::numeric_limits::infinity(); + float negative_inf_default = -std::numeric_limits::infinity(); + float negative_infinity_default = -std::numeric_limits::infinity(); + double double_inf_default = std::numeric_limits::infinity(); + MonsterT() = default; + MonsterT(const MonsterT &o); + MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default; + MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT; +}; + +/// an example documentation comment: "monster object" +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_POS = 4, + VT_MANA = 6, + VT_HP = 8, + VT_NAME = 10, + VT_INVENTORY = 14, + VT_COLOR = 16, + VT_TEST_TYPE = 18, + VT_TEST = 20, + VT_TEST4 = 22, + VT_TESTARRAYOFSTRING = 24, + VT_TESTARRAYOFTABLES = 26, + VT_ENEMY = 28, + VT_TESTNESTEDFLATBUFFER = 30, + VT_TESTEMPTY = 32, + VT_TESTBOOL = 34, + VT_TESTHASHS32_FNV1 = 36, + VT_TESTHASHU32_FNV1 = 38, + VT_TESTHASHS64_FNV1 = 40, + VT_TESTHASHU64_FNV1 = 42, + VT_TESTHASHS32_FNV1A = 44, + VT_TESTHASHU32_FNV1A = 46, + VT_TESTHASHS64_FNV1A = 48, + VT_TESTHASHU64_FNV1A = 50, + VT_TESTARRAYOFBOOLS = 52, + VT_TESTF = 54, + VT_TESTF2 = 56, + VT_TESTF3 = 58, + VT_TESTARRAYOFSTRING2 = 60, + VT_TESTARRAYOFSORTEDSTRUCT = 62, + VT_FLEX = 64, + VT_TEST5 = 66, + VT_VECTOR_OF_LONGS = 68, + VT_VECTOR_OF_DOUBLES = 70, + VT_PARENT_NAMESPACE_TEST = 72, + VT_VECTOR_OF_REFERRABLES = 74, + VT_SINGLE_WEAK_REFERENCE = 76, + VT_VECTOR_OF_WEAK_REFERENCES = 78, + VT_VECTOR_OF_STRONG_REFERRABLES = 80, + VT_CO_OWNING_REFERENCE = 82, + VT_VECTOR_OF_CO_OWNING_REFERENCES = 84, + VT_NON_OWNING_REFERENCE = 86, + VT_VECTOR_OF_NON_OWNING_REFERENCES = 88, + VT_ANY_UNIQUE_TYPE = 90, + VT_ANY_UNIQUE = 92, + VT_ANY_AMBIGUOUS_TYPE = 94, + VT_ANY_AMBIGUOUS = 96, + VT_VECTOR_OF_ENUMS = 98, + VT_SIGNED_ENUM = 100, + VT_TESTREQUIREDNESTEDFLATBUFFER = 102, + VT_SCALAR_KEY_SORTED_TABLES = 104, + VT_NATIVE_INLINE = 106, + VT_LONG_ENUM_NON_ENUM_DEFAULT = 108, + VT_LONG_ENUM_NORMAL_DEFAULT = 110, + VT_NAN_DEFAULT = 112, + VT_INF_DEFAULT = 114, + VT_POSITIVE_INF_DEFAULT = 116, + VT_INFINITY_DEFAULT = 118, + VT_POSITIVE_INFINITY_DEFAULT = 120, + VT_NEGATIVE_INF_DEFAULT = 122, + VT_NEGATIVE_INFINITY_DEFAULT = 124, + VT_DOUBLE_INF_DEFAULT = 126 + }; + const MyGame::Example::Vec3 *pos() const { + return GetStruct(VT_POS); + } + MyGame::Example::Vec3 *mutable_pos() { + return GetStruct(VT_POS); + } + int16_t mana() const { + return GetField(VT_MANA, 150); + } + bool mutate_mana(int16_t _mana = 150) { + return SetField(VT_MANA, _mana, 150); + } + int16_t hp() const { + return GetField(VT_HP, 100); + } + bool mutate_hp(int16_t _hp = 100) { + return SetField(VT_HP, _hp, 100); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + bool KeyCompareLessThan(const Monster * const o) const { + return *name() < *o->name(); + } + int KeyCompareWithValue(const char *_name) const { + return strcmp(name()->c_str(), _name); + } + template + int KeyCompareWithValue(const StringType& _name) const { + if (name()->c_str() < _name) return -1; + if (_name < name()->c_str()) return 1; + return 0; + } + const ::flatbuffers::Vector *inventory() const { + return GetPointer *>(VT_INVENTORY); + } + ::flatbuffers::Vector *mutable_inventory() { + return GetPointer<::flatbuffers::Vector *>(VT_INVENTORY); + } + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 8)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(8)) { + return SetField(VT_COLOR, static_cast(_color), 8); + } + MyGame::Example::Any test_type() const { + return static_cast(GetField(VT_TEST_TYPE, 0)); + } + const void *test() const { + return GetPointer(VT_TEST); + } + template const T *test_as() const; + const MyGame::Example::Monster *test_as_Monster() const { + return test_type() == MyGame::Example::Any_Monster ? static_cast(test()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *test_as_TestSimpleTableWithEnum() const { + return test_type() == MyGame::Example::Any_TestSimpleTableWithEnum ? static_cast(test()) : nullptr; + } + const MyGame::Example2::Monster *test_as_MyGame_Example2_Monster() const { + return test_type() == MyGame::Example::Any_MyGame_Example2_Monster ? static_cast(test()) : nullptr; + } + void *mutable_test() { + return GetPointer(VT_TEST); + } + const ::flatbuffers::Vector *test4() const { + return GetPointer *>(VT_TEST4); + } + ::flatbuffers::Vector *mutable_test4() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST4); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING); + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + const ::flatbuffers::Vector<::flatbuffers::Offset> *testarrayoftables() const { + return GetPointer> *>(VT_TESTARRAYOFTABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_testarrayoftables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_TESTARRAYOFTABLES); + } + const MyGame::Example::Monster *enemy() const { + return GetPointer(VT_ENEMY); + } + MyGame::Example::Monster *mutable_enemy() { + return GetPointer(VT_ENEMY); + } + const ::flatbuffers::Vector *testnestedflatbuffer() const { + return GetPointer *>(VT_TESTNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testnestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testnestedflatbuffer_nested_root() const { + const auto _f = testnestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const MyGame::Example::Stat *testempty() const { + return GetPointer(VT_TESTEMPTY); + } + MyGame::Example::Stat *mutable_testempty() { + return GetPointer(VT_TESTEMPTY); + } + bool testbool() const { + return GetField(VT_TESTBOOL, 0) != 0; + } + bool mutate_testbool(bool _testbool = 0) { + return SetField(VT_TESTBOOL, static_cast(_testbool), 0); + } + int32_t testhashs32_fnv1() const { + return GetField(VT_TESTHASHS32_FNV1, 0); + } + bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) { + return SetField(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0); + } + uint32_t testhashu32_fnv1() const { + return GetField(VT_TESTHASHU32_FNV1, 0); + } + bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) { + return SetField(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0); + } + int64_t testhashs64_fnv1() const { + return GetField(VT_TESTHASHS64_FNV1, 0); + } + bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) { + return SetField(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0); + } + uint64_t testhashu64_fnv1() const { + return GetField(VT_TESTHASHU64_FNV1, 0); + } + bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) { + return SetField(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0); + } + int32_t testhashs32_fnv1a() const { + return GetField(VT_TESTHASHS32_FNV1A, 0); + } + bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) { + return SetField(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0); + } + uint32_t testhashu32_fnv1a() const { + return GetField(VT_TESTHASHU32_FNV1A, 0); + } + bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) { + return SetField(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0); + } + int64_t testhashs64_fnv1a() const { + return GetField(VT_TESTHASHS64_FNV1A, 0); + } + bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) { + return SetField(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0); + } + uint64_t testhashu64_fnv1a() const { + return GetField(VT_TESTHASHU64_FNV1A, 0); + } + bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) { + return SetField(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0); + } + const ::flatbuffers::Vector *testarrayofbools() const { + return GetPointer *>(VT_TESTARRAYOFBOOLS); + } + ::flatbuffers::Vector *mutable_testarrayofbools() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFBOOLS); + } + float testf() const { + return GetField(VT_TESTF, 3.14159f); + } + bool mutate_testf(float _testf = 3.14159f) { + return SetField(VT_TESTF, _testf, 3.14159f); + } + float testf2() const { + return GetField(VT_TESTF2, 3.0f); + } + bool mutate_testf2(float _testf2 = 3.0f) { + return SetField(VT_TESTF2, _testf2, 3.0f); + } + float testf3() const { + return GetField(VT_TESTF3, 0.0f); + } + bool mutate_testf3(float _testf3 = 0.0f) { + return SetField(VT_TESTF3, _testf3, 0.0f); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING2); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring2() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING2); + } + const ::flatbuffers::Vector *testarrayofsortedstruct() const { + return GetPointer *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + ::flatbuffers::Vector *mutable_testarrayofsortedstruct() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + const ::flatbuffers::Vector *flex() const { + return GetPointer *>(VT_FLEX); + } + ::flatbuffers::Vector *mutable_flex() { + return GetPointer<::flatbuffers::Vector *>(VT_FLEX); + } + flexbuffers::Reference flex_flexbuffer_root() const { + const auto _f = flex(); + return _f ? flexbuffers::GetRoot(_f->Data(), _f->size()) + : flexbuffers::Reference(); + } + const ::flatbuffers::Vector *test5() const { + return GetPointer *>(VT_TEST5); + } + ::flatbuffers::Vector *mutable_test5() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST5); + } + const ::flatbuffers::Vector *vector_of_longs() const { + return GetPointer *>(VT_VECTOR_OF_LONGS); + } + ::flatbuffers::Vector *mutable_vector_of_longs() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_LONGS); + } + const ::flatbuffers::Vector *vector_of_doubles() const { + return GetPointer *>(VT_VECTOR_OF_DOUBLES); + } + ::flatbuffers::Vector *mutable_vector_of_doubles() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_DOUBLES); + } + const MyGame::InParentNamespace *parent_namespace_test() const { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + MyGame::InParentNamespace *mutable_parent_namespace_test() { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_REFERRABLES); + } + uint64_t single_weak_reference() const { + return GetField(VT_SINGLE_WEAK_REFERENCE, 0); + } + bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) { + return SetField(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0); + } + const ::flatbuffers::Vector *vector_of_weak_references() const { + return GetPointer *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_weak_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_strong_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_strong_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + uint64_t co_owning_reference() const { + return GetField(VT_CO_OWNING_REFERENCE, 0); + } + bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) { + return SetField(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_co_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_co_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + uint64_t non_owning_reference() const { + return GetField(VT_NON_OWNING_REFERENCE, 0); + } + bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) { + return SetField(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_non_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_non_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + MyGame::Example::AnyUniqueAliases any_unique_type() const { + return static_cast(GetField(VT_ANY_UNIQUE_TYPE, 0)); + } + const void *any_unique() const { + return GetPointer(VT_ANY_UNIQUE); + } + template const T *any_unique_as() const; + const MyGame::Example::Monster *any_unique_as_M() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *any_unique_as_TS() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_TS ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example2::Monster *any_unique_as_M2() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M2 ? static_cast(any_unique()) : nullptr; + } + void *mutable_any_unique() { + return GetPointer(VT_ANY_UNIQUE); + } + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type() const { + return static_cast(GetField(VT_ANY_AMBIGUOUS_TYPE, 0)); + } + const void *any_ambiguous() const { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const MyGame::Example::Monster *any_ambiguous_as_M1() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M1 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M2() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M2 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M3() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M3 ? static_cast(any_ambiguous()) : nullptr; + } + void *mutable_any_ambiguous() { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const ::flatbuffers::Vector *vector_of_enums() const { + return GetPointer *>(VT_VECTOR_OF_ENUMS); + } + ::flatbuffers::Vector *mutable_vector_of_enums() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_ENUMS); + } + MyGame::Example::Race signed_enum() const { + return static_cast(GetField(VT_SIGNED_ENUM, -1)); + } + bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast(-1)) { + return SetField(VT_SIGNED_ENUM, static_cast(_signed_enum), -1); + } + const ::flatbuffers::Vector *testrequirednestedflatbuffer() const { + return GetPointer *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testrequirednestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const { + const auto _f = testrequirednestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *scalar_key_sorted_tables() const { + return GetPointer> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_scalar_key_sorted_tables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + const MyGame::Example::Test *native_inline() const { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::Test *mutable_native_inline() { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::LongEnum long_enum_non_enum_default() const { + return static_cast(GetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0)); + } + bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast(0)) { + return SetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(_long_enum_non_enum_default), 0); + } + MyGame::Example::LongEnum long_enum_normal_default() const { + return static_cast(GetField(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL)); + } + bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast(2ULL)) { + return SetField(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(_long_enum_normal_default), 2ULL); + } + float nan_default() const { + return GetField(VT_NAN_DEFAULT, std::numeric_limits::quiet_NaN()); + } + bool mutate_nan_default(float _nan_default = std::numeric_limits::quiet_NaN()) { + return SetField(VT_NAN_DEFAULT, _nan_default, std::numeric_limits::quiet_NaN()); + } + float inf_default() const { + return GetField(VT_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_inf_default(float _inf_default = std::numeric_limits::infinity()) { + return SetField(VT_INF_DEFAULT, _inf_default, std::numeric_limits::infinity()); + } + float positive_inf_default() const { + return GetField(VT_POSITIVE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_inf_default(float _positive_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INF_DEFAULT, _positive_inf_default, std::numeric_limits::infinity()); + } + float infinity_default() const { + return GetField(VT_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_infinity_default(float _infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_INFINITY_DEFAULT, _infinity_default, std::numeric_limits::infinity()); + } + float positive_infinity_default() const { + return GetField(VT_POSITIVE_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_infinity_default(float _positive_infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INFINITY_DEFAULT, _positive_infinity_default, std::numeric_limits::infinity()); + } + float negative_inf_default() const { + return GetField(VT_NEGATIVE_INF_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_inf_default(float _negative_inf_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INF_DEFAULT, _negative_inf_default, -std::numeric_limits::infinity()); + } + float negative_infinity_default() const { + return GetField(VT_NEGATIVE_INFINITY_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_infinity_default(float _negative_infinity_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INFINITY_DEFAULT, _negative_infinity_default, -std::numeric_limits::infinity()); + } + double double_inf_default() const { + return GetField(VT_DOUBLE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_double_inf_default(double _double_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_DOUBLE_INF_DEFAULT, _double_inf_default, std::numeric_limits::infinity()); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_POS, 8) && + VerifyField(verifier, VT_MANA, 2) && + VerifyField(verifier, VT_HP, 2) && + VerifyOffsetRequired(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_INVENTORY) && + verifier.VerifyVector(inventory()) && + VerifyField(verifier, VT_COLOR, 1) && + VerifyField(verifier, VT_TEST_TYPE, 1) && + VerifyOffset(verifier, VT_TEST) && + VerifyAny(verifier, test(), test_type()) && + VerifyOffset(verifier, VT_TEST4) && + verifier.VerifyVector(test4()) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING) && + verifier.VerifyVector(testarrayofstring()) && + verifier.VerifyVectorOfStrings(testarrayofstring()) && + VerifyOffset(verifier, VT_TESTARRAYOFTABLES) && + verifier.VerifyVector(testarrayoftables()) && + verifier.VerifyVectorOfTables(testarrayoftables()) && + VerifyOffset(verifier, VT_ENEMY) && + verifier.VerifyTable(enemy()) && + VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) && + verifier.VerifyVector(testnestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testnestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_TESTEMPTY) && + verifier.VerifyTable(testempty()) && + VerifyField(verifier, VT_TESTBOOL, 1) && + VerifyField(verifier, VT_TESTHASHS32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHS32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1A, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1A, 8) && + VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) && + verifier.VerifyVector(testarrayofbools()) && + VerifyField(verifier, VT_TESTF, 4) && + VerifyField(verifier, VT_TESTF2, 4) && + VerifyField(verifier, VT_TESTF3, 4) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) && + verifier.VerifyVector(testarrayofstring2()) && + verifier.VerifyVectorOfStrings(testarrayofstring2()) && + VerifyOffset(verifier, VT_TESTARRAYOFSORTEDSTRUCT) && + verifier.VerifyVector(testarrayofsortedstruct()) && + VerifyOffset(verifier, VT_FLEX) && + verifier.VerifyVector(flex()) && + flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) && + VerifyOffset(verifier, VT_TEST5) && + verifier.VerifyVector(test5()) && + VerifyOffset(verifier, VT_VECTOR_OF_LONGS) && + verifier.VerifyVector(vector_of_longs()) && + VerifyOffset(verifier, VT_VECTOR_OF_DOUBLES) && + verifier.VerifyVector(vector_of_doubles()) && + VerifyOffset(verifier, VT_PARENT_NAMESPACE_TEST) && + verifier.VerifyTable(parent_namespace_test()) && + VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) && + verifier.VerifyVector(vector_of_referrables()) && + verifier.VerifyVectorOfTables(vector_of_referrables()) && + VerifyField(verifier, VT_SINGLE_WEAK_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) && + verifier.VerifyVector(vector_of_weak_references()) && + VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) && + verifier.VerifyVector(vector_of_strong_referrables()) && + verifier.VerifyVectorOfTables(vector_of_strong_referrables()) && + VerifyField(verifier, VT_CO_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_co_owning_references()) && + VerifyField(verifier, VT_NON_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_non_owning_references()) && + VerifyField(verifier, VT_ANY_UNIQUE_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_UNIQUE) && + VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) && + VerifyField(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_AMBIGUOUS) && + VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) && + VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) && + verifier.VerifyVector(vector_of_enums()) && + VerifyField(verifier, VT_SIGNED_ENUM, 1) && + VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) && + verifier.VerifyVector(testrequirednestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testrequirednestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) && + verifier.VerifyVector(scalar_key_sorted_tables()) && + verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) && + VerifyField(verifier, VT_NATIVE_INLINE, 2) && + VerifyField(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) && + VerifyField(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) && + VerifyField(verifier, VT_NAN_DEFAULT, 4) && + VerifyField(verifier, VT_INF_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_DOUBLE_INF_DEFAULT, 8) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const MyGame::Example::Monster *Monster::test_as() const { + return test_as_Monster(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::test_as() const { + return test_as_TestSimpleTableWithEnum(); +} + +template<> inline const MyGame::Example2::Monster *Monster::test_as() const { + return test_as_MyGame_Example2_Monster(); +} + +template<> inline const MyGame::Example::Monster *Monster::any_unique_as() const { + return any_unique_as_M(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::any_unique_as() const { + return any_unique_as_TS(); +} + +template<> inline const MyGame::Example2::Monster *Monster::any_unique_as() const { + return any_unique_as_M2(); +} + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_pos(const MyGame::Example::Vec3 *pos) { + fbb_.AddStruct(Monster::VT_POS, pos); + } + void add_mana(int16_t mana) { + fbb_.AddElement(Monster::VT_MANA, mana, 150); + } + void add_hp(int16_t hp) { + fbb_.AddElement(Monster::VT_HP, hp, 100); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Monster::VT_NAME, name); + } + void add_inventory(::flatbuffers::Offset<::flatbuffers::Vector> inventory) { + fbb_.AddOffset(Monster::VT_INVENTORY, inventory); + } + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(Monster::VT_COLOR, static_cast(color), 8); + } + void add_test_type(MyGame::Example::Any test_type) { + fbb_.AddElement(Monster::VT_TEST_TYPE, static_cast(test_type), 0); + } + void add_test(::flatbuffers::Offset test) { + fbb_.AddOffset(Monster::VT_TEST, test); + } + void add_test4(::flatbuffers::Offset<::flatbuffers::Vector> test4) { + fbb_.AddOffset(Monster::VT_TEST4, test4); + } + void add_testarrayofstring(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + void add_testarrayoftables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + void add_enemy(::flatbuffers::Offset enemy) { + fbb_.AddOffset(Monster::VT_ENEMY, enemy); + } + void add_testnestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + void add_testempty(::flatbuffers::Offset testempty) { + fbb_.AddOffset(Monster::VT_TESTEMPTY, testempty); + } + void add_testbool(bool testbool) { + fbb_.AddElement(Monster::VT_TESTBOOL, static_cast(testbool), 0); + } + void add_testhashs32_fnv1(int32_t testhashs32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + void add_testhashu32_fnv1(uint32_t testhashu32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + void add_testhashs64_fnv1(int64_t testhashs64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + void add_testhashu64_fnv1(uint64_t testhashu64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + void add_testhashs32_fnv1a(int32_t testhashs32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + void add_testhashu32_fnv1a(uint32_t testhashu32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + void add_testhashs64_fnv1a(int64_t testhashs64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + void add_testhashu64_fnv1a(uint64_t testhashu64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + void add_testarrayofbools(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + void add_testf(float testf) { + fbb_.AddElement(Monster::VT_TESTF, testf, 3.14159f); + } + void add_testf2(float testf2) { + fbb_.AddElement(Monster::VT_TESTF2, testf2, 3.0f); + } + void add_testf3(float testf3) { + fbb_.AddElement(Monster::VT_TESTF3, testf3, 0.0f); + } + void add_testarrayofstring2(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + void add_testarrayofsortedstruct(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + void add_flex(::flatbuffers::Offset<::flatbuffers::Vector> flex) { + fbb_.AddOffset(Monster::VT_FLEX, flex); + } + void add_test5(::flatbuffers::Offset<::flatbuffers::Vector> test5) { + fbb_.AddOffset(Monster::VT_TEST5, test5); + } + void add_vector_of_longs(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + void add_vector_of_doubles(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + void add_parent_namespace_test(::flatbuffers::Offset parent_namespace_test) { + fbb_.AddOffset(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + void add_vector_of_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + void add_single_weak_reference(uint64_t single_weak_reference) { + fbb_.AddElement(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + void add_vector_of_weak_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + void add_vector_of_strong_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + void add_co_owning_reference(uint64_t co_owning_reference) { + fbb_.AddElement(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + void add_vector_of_co_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + void add_non_owning_reference(uint64_t non_owning_reference) { + fbb_.AddElement(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + void add_vector_of_non_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + void add_any_unique_type(MyGame::Example::AnyUniqueAliases any_unique_type) { + fbb_.AddElement(Monster::VT_ANY_UNIQUE_TYPE, static_cast(any_unique_type), 0); + } + void add_any_unique(::flatbuffers::Offset any_unique) { + fbb_.AddOffset(Monster::VT_ANY_UNIQUE, any_unique); + } + void add_any_ambiguous_type(MyGame::Example::AnyAmbiguousAliases any_ambiguous_type) { + fbb_.AddElement(Monster::VT_ANY_AMBIGUOUS_TYPE, static_cast(any_ambiguous_type), 0); + } + void add_any_ambiguous(::flatbuffers::Offset any_ambiguous) { + fbb_.AddOffset(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + void add_vector_of_enums(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + void add_signed_enum(MyGame::Example::Race signed_enum) { + fbb_.AddElement(Monster::VT_SIGNED_ENUM, static_cast(signed_enum), -1); + } + void add_testrequirednestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + void add_scalar_key_sorted_tables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables) { + fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + void add_native_inline(const MyGame::Example::Test *native_inline) { + fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline); + } + void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(long_enum_non_enum_default), 0); + } + void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(long_enum_normal_default), 2ULL); + } + void add_nan_default(float nan_default) { + fbb_.AddElement(Monster::VT_NAN_DEFAULT, nan_default, std::numeric_limits::quiet_NaN()); + } + void add_inf_default(float inf_default) { + fbb_.AddElement(Monster::VT_INF_DEFAULT, inf_default, std::numeric_limits::infinity()); + } + void add_positive_inf_default(float positive_inf_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, std::numeric_limits::infinity()); + } + void add_infinity_default(float infinity_default) { + fbb_.AddElement(Monster::VT_INFINITY_DEFAULT, infinity_default, std::numeric_limits::infinity()); + } + void add_positive_infinity_default(float positive_infinity_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, std::numeric_limits::infinity()); + } + void add_negative_inf_default(float negative_inf_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, -std::numeric_limits::infinity()); + } + void add_negative_infinity_default(float negative_infinity_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, -std::numeric_limits::infinity()); + } + void add_double_inf_default(double double_inf_default) { + fbb_.AddElement(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, std::numeric_limits::infinity()); + } + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + fbb_.Required(o, Monster::VT_NAME); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> inventory = 0, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test4 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables = 0, + ::flatbuffers::Offset enemy = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer = 0, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools = 0, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> flex = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test5 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles = 0, + ::flatbuffers::Offset parent_namespace_test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables = 0, + uint64_t single_weak_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables = 0, + uint64_t co_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references = 0, + uint64_t non_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references = 0, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums = 0, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + ::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables = 0, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + MonsterBuilder builder_(_fbb); + builder_.add_double_inf_default(double_inf_default); + builder_.add_long_enum_normal_default(long_enum_normal_default); + builder_.add_long_enum_non_enum_default(long_enum_non_enum_default); + builder_.add_non_owning_reference(non_owning_reference); + builder_.add_co_owning_reference(co_owning_reference); + builder_.add_single_weak_reference(single_weak_reference); + builder_.add_testhashu64_fnv1a(testhashu64_fnv1a); + builder_.add_testhashs64_fnv1a(testhashs64_fnv1a); + builder_.add_testhashu64_fnv1(testhashu64_fnv1); + builder_.add_testhashs64_fnv1(testhashs64_fnv1); + builder_.add_negative_infinity_default(negative_infinity_default); + builder_.add_negative_inf_default(negative_inf_default); + builder_.add_positive_infinity_default(positive_infinity_default); + builder_.add_infinity_default(infinity_default); + builder_.add_positive_inf_default(positive_inf_default); + builder_.add_inf_default(inf_default); + builder_.add_nan_default(nan_default); + builder_.add_native_inline(native_inline); + builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables); + builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer); + builder_.add_vector_of_enums(vector_of_enums); + builder_.add_any_ambiguous(any_ambiguous); + builder_.add_any_unique(any_unique); + builder_.add_vector_of_non_owning_references(vector_of_non_owning_references); + builder_.add_vector_of_co_owning_references(vector_of_co_owning_references); + builder_.add_vector_of_strong_referrables(vector_of_strong_referrables); + builder_.add_vector_of_weak_references(vector_of_weak_references); + builder_.add_vector_of_referrables(vector_of_referrables); + builder_.add_parent_namespace_test(parent_namespace_test); + builder_.add_vector_of_doubles(vector_of_doubles); + builder_.add_vector_of_longs(vector_of_longs); + builder_.add_test5(test5); + builder_.add_flex(flex); + builder_.add_testarrayofsortedstruct(testarrayofsortedstruct); + builder_.add_testarrayofstring2(testarrayofstring2); + builder_.add_testf3(testf3); + builder_.add_testf2(testf2); + builder_.add_testf(testf); + builder_.add_testarrayofbools(testarrayofbools); + builder_.add_testhashu32_fnv1a(testhashu32_fnv1a); + builder_.add_testhashs32_fnv1a(testhashs32_fnv1a); + builder_.add_testhashu32_fnv1(testhashu32_fnv1); + builder_.add_testhashs32_fnv1(testhashs32_fnv1); + builder_.add_testempty(testempty); + builder_.add_testnestedflatbuffer(testnestedflatbuffer); + builder_.add_enemy(enemy); + builder_.add_testarrayoftables(testarrayoftables); + builder_.add_testarrayofstring(testarrayofstring); + builder_.add_test4(test4); + builder_.add_test(test); + builder_.add_inventory(inventory); + builder_.add_name(name); + builder_.add_pos(pos); + builder_.add_hp(hp); + builder_.add_mana(mana); + builder_.add_signed_enum(signed_enum); + builder_.add_any_ambiguous_type(any_ambiguous_type); + builder_.add_any_unique_type(any_unique_type); + builder_.add_testbool(testbool); + builder_.add_test_type(test_type); + builder_.add_color(color); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMonsterDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + const char *name = nullptr, + const std::vector *inventory = nullptr, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + const std::vector *test4 = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring = nullptr, + std::vector<::flatbuffers::Offset> *testarrayoftables = nullptr, + ::flatbuffers::Offset enemy = 0, + const std::vector *testnestedflatbuffer = nullptr, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + const std::vector *testarrayofbools = nullptr, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2 = nullptr, + std::vector *testarrayofsortedstruct = nullptr, + const std::vector *flex = nullptr, + const std::vector *test5 = nullptr, + const std::vector *vector_of_longs = nullptr, + const std::vector *vector_of_doubles = nullptr, + ::flatbuffers::Offset parent_namespace_test = 0, + std::vector<::flatbuffers::Offset> *vector_of_referrables = nullptr, + uint64_t single_weak_reference = 0, + const std::vector *vector_of_weak_references = nullptr, + std::vector<::flatbuffers::Offset> *vector_of_strong_referrables = nullptr, + uint64_t co_owning_reference = 0, + const std::vector *vector_of_co_owning_references = nullptr, + uint64_t non_owning_reference = 0, + const std::vector *vector_of_non_owning_references = nullptr, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + const std::vector *vector_of_enums = nullptr, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + const std::vector *testrequirednestedflatbuffer = nullptr, + std::vector<::flatbuffers::Offset> *scalar_key_sorted_tables = nullptr, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto inventory__ = inventory ? _fbb.CreateVector(*inventory) : 0; + auto test4__ = test4 ? _fbb.CreateVectorOfStructs(*test4) : 0; + auto testarrayofstring__ = testarrayofstring ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring) : 0; + auto testarrayoftables__ = testarrayoftables ? _fbb.CreateVectorOfSortedTables(testarrayoftables) : 0; + auto testnestedflatbuffer__ = testnestedflatbuffer ? _fbb.CreateVector(*testnestedflatbuffer) : 0; + auto testarrayofbools__ = testarrayofbools ? _fbb.CreateVector(*testarrayofbools) : 0; + auto testarrayofstring2__ = testarrayofstring2 ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring2) : 0; + auto testarrayofsortedstruct__ = testarrayofsortedstruct ? _fbb.CreateVectorOfSortedStructs(testarrayofsortedstruct) : 0; + auto flex__ = flex ? _fbb.CreateVector(*flex) : 0; + auto test5__ = test5 ? _fbb.CreateVectorOfStructs(*test5) : 0; + auto vector_of_longs__ = vector_of_longs ? _fbb.CreateVector(*vector_of_longs) : 0; + auto vector_of_doubles__ = vector_of_doubles ? _fbb.CreateVector(*vector_of_doubles) : 0; + auto vector_of_referrables__ = vector_of_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_referrables) : 0; + auto vector_of_weak_references__ = vector_of_weak_references ? _fbb.CreateVector(*vector_of_weak_references) : 0; + auto vector_of_strong_referrables__ = vector_of_strong_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_strong_referrables) : 0; + auto vector_of_co_owning_references__ = vector_of_co_owning_references ? _fbb.CreateVector(*vector_of_co_owning_references) : 0; + auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector(*vector_of_non_owning_references) : 0; + auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector(*vector_of_enums) : 0; + auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector(*testrequirednestedflatbuffer) : 0; + auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables(scalar_key_sorted_tables) : 0; + return MyGame::Example::CreateMonster( + _fbb, + pos, + mana, + hp, + name__, + inventory__, + color, + test_type, + test, + test4__, + testarrayofstring__, + testarrayoftables__, + enemy, + testnestedflatbuffer__, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools__, + testf, + testf2, + testf3, + testarrayofstring2__, + testarrayofsortedstruct__, + flex__, + test5__, + vector_of_longs__, + vector_of_doubles__, + parent_namespace_test, + vector_of_referrables__, + single_weak_reference, + vector_of_weak_references__, + vector_of_strong_referrables__, + co_owning_reference, + vector_of_co_owning_references__, + non_owning_reference, + vector_of_non_owning_references__, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums__, + signed_enum, + testrequirednestedflatbuffer__, + scalar_key_sorted_tables__, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct TypeAliasesT : public ::flatbuffers::NativeTable { + typedef TypeAliases TableType; + int8_t i8 = 0; + uint8_t u8 = 0; + int16_t i16 = 0; + uint16_t u16 = 0; + int32_t i32 = 0; + uint32_t u32 = 0; + int64_t i64 = 0; + uint64_t u64 = 0; + float f32 = 0.0f; + double f64 = 0.0; + std::vector v8{}; + std::vector vf64{}; +}; + +struct TypeAliases FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TypeAliasesT NativeTableType; + typedef TypeAliasesBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TypeAliasesTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_I8 = 4, + VT_U8 = 6, + VT_I16 = 8, + VT_U16 = 10, + VT_I32 = 12, + VT_U32 = 14, + VT_I64 = 16, + VT_U64 = 18, + VT_F32 = 20, + VT_F64 = 22, + VT_V8 = 24, + VT_VF64 = 26 + }; + int8_t i8() const { + return GetField(VT_I8, 0); + } + bool mutate_i8(int8_t _i8 = 0) { + return SetField(VT_I8, _i8, 0); + } + uint8_t u8() const { + return GetField(VT_U8, 0); + } + bool mutate_u8(uint8_t _u8 = 0) { + return SetField(VT_U8, _u8, 0); + } + int16_t i16() const { + return GetField(VT_I16, 0); + } + bool mutate_i16(int16_t _i16 = 0) { + return SetField(VT_I16, _i16, 0); + } + uint16_t u16() const { + return GetField(VT_U16, 0); + } + bool mutate_u16(uint16_t _u16 = 0) { + return SetField(VT_U16, _u16, 0); + } + int32_t i32() const { + return GetField(VT_I32, 0); + } + bool mutate_i32(int32_t _i32 = 0) { + return SetField(VT_I32, _i32, 0); + } + uint32_t u32() const { + return GetField(VT_U32, 0); + } + bool mutate_u32(uint32_t _u32 = 0) { + return SetField(VT_U32, _u32, 0); + } + int64_t i64() const { + return GetField(VT_I64, 0); + } + bool mutate_i64(int64_t _i64 = 0) { + return SetField(VT_I64, _i64, 0); + } + uint64_t u64() const { + return GetField(VT_U64, 0); + } + bool mutate_u64(uint64_t _u64 = 0) { + return SetField(VT_U64, _u64, 0); + } + float f32() const { + return GetField(VT_F32, 0.0f); + } + bool mutate_f32(float _f32 = 0.0f) { + return SetField(VT_F32, _f32, 0.0f); + } + double f64() const { + return GetField(VT_F64, 0.0); + } + bool mutate_f64(double _f64 = 0.0) { + return SetField(VT_F64, _f64, 0.0); + } + const ::flatbuffers::Vector *v8() const { + return GetPointer *>(VT_V8); + } + ::flatbuffers::Vector *mutable_v8() { + return GetPointer<::flatbuffers::Vector *>(VT_V8); + } + const ::flatbuffers::Vector *vf64() const { + return GetPointer *>(VT_VF64); + } + ::flatbuffers::Vector *mutable_vf64() { + return GetPointer<::flatbuffers::Vector *>(VT_VF64); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_I8, 1) && + VerifyField(verifier, VT_U8, 1) && + VerifyField(verifier, VT_I16, 2) && + VerifyField(verifier, VT_U16, 2) && + VerifyField(verifier, VT_I32, 4) && + VerifyField(verifier, VT_U32, 4) && + VerifyField(verifier, VT_I64, 8) && + VerifyField(verifier, VT_U64, 8) && + VerifyField(verifier, VT_F32, 4) && + VerifyField(verifier, VT_F64, 8) && + VerifyOffset(verifier, VT_V8) && + verifier.VerifyVector(v8()) && + VerifyOffset(verifier, VT_VF64) && + verifier.VerifyVector(vf64()) && + verifier.EndTable(); + } + TypeAliasesT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TypeAliasesBuilder { + typedef TypeAliases Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_i8(int8_t i8) { + fbb_.AddElement(TypeAliases::VT_I8, i8, 0); + } + void add_u8(uint8_t u8) { + fbb_.AddElement(TypeAliases::VT_U8, u8, 0); + } + void add_i16(int16_t i16) { + fbb_.AddElement(TypeAliases::VT_I16, i16, 0); + } + void add_u16(uint16_t u16) { + fbb_.AddElement(TypeAliases::VT_U16, u16, 0); + } + void add_i32(int32_t i32) { + fbb_.AddElement(TypeAliases::VT_I32, i32, 0); + } + void add_u32(uint32_t u32) { + fbb_.AddElement(TypeAliases::VT_U32, u32, 0); + } + void add_i64(int64_t i64) { + fbb_.AddElement(TypeAliases::VT_I64, i64, 0); + } + void add_u64(uint64_t u64) { + fbb_.AddElement(TypeAliases::VT_U64, u64, 0); + } + void add_f32(float f32) { + fbb_.AddElement(TypeAliases::VT_F32, f32, 0.0f); + } + void add_f64(double f64) { + fbb_.AddElement(TypeAliases::VT_F64, f64, 0.0); + } + void add_v8(::flatbuffers::Offset<::flatbuffers::Vector> v8) { + fbb_.AddOffset(TypeAliases::VT_V8, v8); + } + void add_vf64(::flatbuffers::Offset<::flatbuffers::Vector> vf64) { + fbb_.AddOffset(TypeAliases::VT_VF64, vf64); + } + explicit TypeAliasesBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTypeAliases( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + ::flatbuffers::Offset<::flatbuffers::Vector> v8 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vf64 = 0) { + TypeAliasesBuilder builder_(_fbb); + builder_.add_f64(f64); + builder_.add_u64(u64); + builder_.add_i64(i64); + builder_.add_vf64(vf64); + builder_.add_v8(v8); + builder_.add_f32(f32); + builder_.add_u32(u32); + builder_.add_i32(i32); + builder_.add_u16(u16); + builder_.add_i16(i16); + builder_.add_u8(u8); + builder_.add_i8(i8); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTypeAliasesDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + const std::vector *v8 = nullptr, + const std::vector *vf64 = nullptr) { + auto v8__ = v8 ? _fbb.CreateVector(*v8) : 0; + auto vf64__ = vf64 ? _fbb.CreateVector(*vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + i8, + u8, + i16, + u16, + i32, + u32, + i64, + u64, + f32, + f64, + v8__, + vf64__); +} + +::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example + + +inline bool operator==(const InParentNamespaceT &, const InParentNamespaceT &) { + return true; +} + +inline bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs) { + return !(lhs == rhs); +} + + +inline InParentNamespaceT *InParentNamespace::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new InParentNamespaceT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void InParentNamespace::UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset InParentNamespace::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateInParentNamespace(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const InParentNamespaceT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::CreateInParentNamespace( + _fbb); +} + +namespace Example2 { + + +inline bool operator==(const MonsterT &, const MonsterT &) { + return true; +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::Example2::CreateMonster( + _fbb); +} + +} // namespace Example2 + +namespace Example { + + +inline bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return + (lhs.color == rhs.color); +} + +inline bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return !(lhs == rhs); +} + + +inline TestSimpleTableWithEnumT *TestSimpleTableWithEnum::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TestSimpleTableWithEnumT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TestSimpleTableWithEnum::UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = color(); _o->color = _e; } +} + +inline ::flatbuffers::Offset TestSimpleTableWithEnum::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTestSimpleTableWithEnum(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TestSimpleTableWithEnumT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _color = _o->color; + return MyGame::Example::CreateTestSimpleTableWithEnum( + _fbb, + _color); +} + + +inline bool operator==(const StatT &lhs, const StatT &rhs) { + return + (lhs.id == rhs.id) && + (lhs.val == rhs.val) && + (lhs.count == rhs.count); +} + +inline bool operator!=(const StatT &lhs, const StatT &rhs) { + return !(lhs == rhs); +} + + +inline StatT *Stat::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new StatT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Stat::UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); if (_e) _o->id = _e->str(); } + { auto _e = val(); _o->val = _e; } + { auto _e = count(); _o->count = _e; } +} + +inline ::flatbuffers::Offset Stat::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateStat(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const StatT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id.empty() ? 0 : _fbb.CreateString(_o->id); + auto _val = _o->val; + auto _count = _o->count; + return MyGame::Example::CreateStat( + _fbb, + _id, + _val, + _count); +} + + +inline bool operator==(const ReferrableT &lhs, const ReferrableT &rhs) { + return + (lhs.id == rhs.id); +} + +inline bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs) { + return !(lhs == rhs); +} + + +inline ReferrableT *Referrable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new ReferrableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Referrable::UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); _o->id = _e; } +} + +inline ::flatbuffers::Offset Referrable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateReferrable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ReferrableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id; + return MyGame::Example::CreateReferrable( + _fbb, + _id); +} + + +inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) { + return + ((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) && + (lhs.mana == rhs.mana) && + (lhs.hp == rhs.hp) && + (lhs.name == rhs.name) && + (lhs.inventory == rhs.inventory) && + (lhs.color == rhs.color) && + (lhs.test == rhs.test) && + (lhs.test4 == rhs.test4) && + (lhs.testarrayofstring == rhs.testarrayofstring) && + (lhs.testarrayoftables.size() == rhs.testarrayoftables.size() && std::equal(lhs.testarrayoftables.cbegin(), lhs.testarrayoftables.cend(), rhs.testarrayoftables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + ((lhs.enemy == rhs.enemy) || (lhs.enemy && rhs.enemy && *lhs.enemy == *rhs.enemy)) && + (lhs.testnestedflatbuffer == rhs.testnestedflatbuffer) && + ((lhs.testempty == rhs.testempty) || (lhs.testempty && rhs.testempty && *lhs.testempty == *rhs.testempty)) && + (lhs.testbool == rhs.testbool) && + (lhs.testhashs32_fnv1 == rhs.testhashs32_fnv1) && + (lhs.testhashu32_fnv1 == rhs.testhashu32_fnv1) && + (lhs.testhashs64_fnv1 == rhs.testhashs64_fnv1) && + (lhs.testhashu64_fnv1 == rhs.testhashu64_fnv1) && + (lhs.testhashs32_fnv1a == rhs.testhashs32_fnv1a) && + (lhs.testhashu32_fnv1a == rhs.testhashu32_fnv1a) && + (lhs.testhashs64_fnv1a == rhs.testhashs64_fnv1a) && + (lhs.testhashu64_fnv1a == rhs.testhashu64_fnv1a) && + (lhs.testarrayofbools == rhs.testarrayofbools) && + (lhs.testf == rhs.testf) && + (lhs.testf2 == rhs.testf2) && + (lhs.testf3 == rhs.testf3) && + (lhs.testarrayofstring2 == rhs.testarrayofstring2) && + (lhs.testarrayofsortedstruct == rhs.testarrayofsortedstruct) && + (lhs.flex == rhs.flex) && + (lhs.test5 == rhs.test5) && + (lhs.vector_of_longs == rhs.vector_of_longs) && + (lhs.vector_of_doubles == rhs.vector_of_doubles) && + ((lhs.parent_namespace_test == rhs.parent_namespace_test) || (lhs.parent_namespace_test && rhs.parent_namespace_test && *lhs.parent_namespace_test == *rhs.parent_namespace_test)) && + (lhs.vector_of_referrables.size() == rhs.vector_of_referrables.size() && std::equal(lhs.vector_of_referrables.cbegin(), lhs.vector_of_referrables.cend(), rhs.vector_of_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.single_weak_reference == rhs.single_weak_reference) && + (lhs.vector_of_weak_references == rhs.vector_of_weak_references) && + (lhs.vector_of_strong_referrables.size() == rhs.vector_of_strong_referrables.size() && std::equal(lhs.vector_of_strong_referrables.cbegin(), lhs.vector_of_strong_referrables.cend(), rhs.vector_of_strong_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.co_owning_reference == rhs.co_owning_reference) && + (lhs.vector_of_co_owning_references == rhs.vector_of_co_owning_references) && + (lhs.non_owning_reference == rhs.non_owning_reference) && + (lhs.vector_of_non_owning_references == rhs.vector_of_non_owning_references) && + (lhs.any_unique == rhs.any_unique) && + (lhs.any_ambiguous == rhs.any_ambiguous) && + (lhs.vector_of_enums == rhs.vector_of_enums) && + (lhs.signed_enum == rhs.signed_enum) && + (lhs.testrequirednestedflatbuffer == rhs.testrequirednestedflatbuffer) && + (lhs.scalar_key_sorted_tables.size() == rhs.scalar_key_sorted_tables.size() && std::equal(lhs.scalar_key_sorted_tables.cbegin(), lhs.scalar_key_sorted_tables.cend(), rhs.scalar_key_sorted_tables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.native_inline == rhs.native_inline) && + (lhs.long_enum_non_enum_default == rhs.long_enum_non_enum_default) && + (lhs.long_enum_normal_default == rhs.long_enum_normal_default) && + (lhs.nan_default == rhs.nan_default) && + (lhs.inf_default == rhs.inf_default) && + (lhs.positive_inf_default == rhs.positive_inf_default) && + (lhs.infinity_default == rhs.infinity_default) && + (lhs.positive_infinity_default == rhs.positive_infinity_default) && + (lhs.negative_inf_default == rhs.negative_inf_default) && + (lhs.negative_infinity_default == rhs.negative_infinity_default) && + (lhs.double_inf_default == rhs.double_inf_default); +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT::MonsterT(const MonsterT &o) + : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr), + mana(o.mana), + hp(o.hp), + name(o.name), + inventory(o.inventory), + color(o.color), + test(o.test), + test4(o.test4), + testarrayofstring(o.testarrayofstring), + enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr), + testnestedflatbuffer(o.testnestedflatbuffer), + testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr), + testbool(o.testbool), + testhashs32_fnv1(o.testhashs32_fnv1), + testhashu32_fnv1(o.testhashu32_fnv1), + testhashs64_fnv1(o.testhashs64_fnv1), + testhashu64_fnv1(o.testhashu64_fnv1), + testhashs32_fnv1a(o.testhashs32_fnv1a), + testhashu32_fnv1a(o.testhashu32_fnv1a), + testhashs64_fnv1a(o.testhashs64_fnv1a), + testhashu64_fnv1a(o.testhashu64_fnv1a), + testarrayofbools(o.testarrayofbools), + testf(o.testf), + testf2(o.testf2), + testf3(o.testf3), + testarrayofstring2(o.testarrayofstring2), + testarrayofsortedstruct(o.testarrayofsortedstruct), + flex(o.flex), + test5(o.test5), + vector_of_longs(o.vector_of_longs), + vector_of_doubles(o.vector_of_doubles), + parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr), + single_weak_reference(o.single_weak_reference), + vector_of_weak_references(o.vector_of_weak_references), + co_owning_reference(o.co_owning_reference), + non_owning_reference(o.non_owning_reference), + vector_of_non_owning_references(o.vector_of_non_owning_references), + any_unique(o.any_unique), + any_ambiguous(o.any_ambiguous), + vector_of_enums(o.vector_of_enums), + signed_enum(o.signed_enum), + testrequirednestedflatbuffer(o.testrequirednestedflatbuffer), + native_inline(o.native_inline), + long_enum_non_enum_default(o.long_enum_non_enum_default), + long_enum_normal_default(o.long_enum_normal_default), + nan_default(o.nan_default), + inf_default(o.inf_default), + positive_inf_default(o.positive_inf_default), + infinity_default(o.infinity_default), + positive_infinity_default(o.positive_infinity_default), + negative_inf_default(o.negative_inf_default), + negative_infinity_default(o.negative_infinity_default), + double_inf_default(o.double_inf_default) { + testarrayoftables.reserve(o.testarrayoftables.size()); + for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); } + vector_of_referrables.reserve(o.vector_of_referrables.size()); + for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); } + vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size()); + for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); } + vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size()); + for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); } + scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size()); + for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); } +} + +inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT { + std::swap(pos, o.pos); + std::swap(mana, o.mana); + std::swap(hp, o.hp); + std::swap(name, o.name); + std::swap(inventory, o.inventory); + std::swap(color, o.color); + std::swap(test, o.test); + std::swap(test4, o.test4); + std::swap(testarrayofstring, o.testarrayofstring); + std::swap(testarrayoftables, o.testarrayoftables); + std::swap(enemy, o.enemy); + std::swap(testnestedflatbuffer, o.testnestedflatbuffer); + std::swap(testempty, o.testempty); + std::swap(testbool, o.testbool); + std::swap(testhashs32_fnv1, o.testhashs32_fnv1); + std::swap(testhashu32_fnv1, o.testhashu32_fnv1); + std::swap(testhashs64_fnv1, o.testhashs64_fnv1); + std::swap(testhashu64_fnv1, o.testhashu64_fnv1); + std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a); + std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a); + std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a); + std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a); + std::swap(testarrayofbools, o.testarrayofbools); + std::swap(testf, o.testf); + std::swap(testf2, o.testf2); + std::swap(testf3, o.testf3); + std::swap(testarrayofstring2, o.testarrayofstring2); + std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct); + std::swap(flex, o.flex); + std::swap(test5, o.test5); + std::swap(vector_of_longs, o.vector_of_longs); + std::swap(vector_of_doubles, o.vector_of_doubles); + std::swap(parent_namespace_test, o.parent_namespace_test); + std::swap(vector_of_referrables, o.vector_of_referrables); + std::swap(single_weak_reference, o.single_weak_reference); + std::swap(vector_of_weak_references, o.vector_of_weak_references); + std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables); + std::swap(co_owning_reference, o.co_owning_reference); + std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references); + std::swap(non_owning_reference, o.non_owning_reference); + std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references); + std::swap(any_unique, o.any_unique); + std::swap(any_ambiguous, o.any_ambiguous); + std::swap(vector_of_enums, o.vector_of_enums); + std::swap(signed_enum, o.signed_enum); + std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer); + std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables); + std::swap(native_inline, o.native_inline); + std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default); + std::swap(long_enum_normal_default, o.long_enum_normal_default); + std::swap(nan_default, o.nan_default); + std::swap(inf_default, o.inf_default); + std::swap(positive_inf_default, o.positive_inf_default); + std::swap(infinity_default, o.infinity_default); + std::swap(positive_infinity_default, o.positive_infinity_default); + std::swap(negative_inf_default, o.negative_inf_default); + std::swap(negative_infinity_default, o.negative_infinity_default); + std::swap(double_inf_default, o.double_inf_default); + return *this; +} + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = pos(); if (_e) _o->pos = std::unique_ptr(new MyGame::Example::Vec3(*_e)); } + { auto _e = mana(); _o->mana = _e; } + { auto _e = hp(); _o->hp = _e; } + { auto _e = name(); if (_e) _o->name = _e->str(); } + { auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } } + { auto _e = color(); _o->color = _e; } + { auto _e = test_type(); _o->test.type = _e; } + { auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); } + { auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } else { _o->test4.resize(0); } } + { auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring.resize(0); } } + { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->testarrayoftables.resize(0); } } + { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->enemy) { _o->enemy.reset(); } } + { auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } } + { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->testempty) { _o->testempty.reset(); } } + { auto _e = testbool(); _o->testbool = _e; } + { auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; } + { auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; } + { auto _e = testhashs64_fnv1(); _o->testhashs64_fnv1 = _e; } + { auto _e = testhashu64_fnv1(); _o->testhashu64_fnv1 = _e; } + { auto _e = testhashs32_fnv1a(); _o->testhashs32_fnv1a = _e; } + { auto _e = testhashu32_fnv1a(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->testhashu32_fnv1a), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->testhashu32_fnv1a = nullptr; } + { auto _e = testhashs64_fnv1a(); _o->testhashs64_fnv1a = _e; } + { auto _e = testhashu64_fnv1a(); _o->testhashu64_fnv1a = _e; } + { auto _e = testarrayofbools(); if (_e) { _o->testarrayofbools.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofbools[_i] = _e->Get(_i) != 0; } } else { _o->testarrayofbools.resize(0); } } + { auto _e = testf(); _o->testf = _e; } + { auto _e = testf2(); _o->testf2 = _e; } + { auto _e = testf3(); _o->testf3 = _e; } + { auto _e = testarrayofstring2(); if (_e) { _o->testarrayofstring2.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring2[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring2.resize(0); } } + { auto _e = testarrayofsortedstruct(); if (_e) { _o->testarrayofsortedstruct.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofsortedstruct[_i] = *_e->Get(_i); } } else { _o->testarrayofsortedstruct.resize(0); } } + { auto _e = flex(); if (_e) { _o->flex.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->flex.begin()); } } + { auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } else { _o->test5.resize(0); } } + { auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } else { _o->vector_of_longs.resize(0); } } + { auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } else { _o->vector_of_doubles.resize(0); } } + { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->parent_namespace_test) { _o->parent_namespace_test.reset(); } } + { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_referrables.resize(0); } } + { auto _e = single_weak_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->single_weak_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; } + { auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_weak_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } else { _o->vector_of_weak_references.resize(0); } } + { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_strong_referrables.resize(0); } } + { auto _e = co_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->co_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; } + { auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, default_ptr_type*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_co_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i)));/* else do nothing */} } else { _o->vector_of_co_owning_references.resize(0); } } + { auto _e = non_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->non_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->non_owning_reference = nullptr; } + { auto _e = vector_of_non_owning_references(); if (_e) { _o->vector_of_non_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_non_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_non_owning_references[_i] = nullptr; } } else { _o->vector_of_non_owning_references.resize(0); } } + { auto _e = any_unique_type(); _o->any_unique.type = _e; } + { auto _e = any_unique(); if (_e) _o->any_unique.value = MyGame::Example::AnyUniqueAliasesUnion::UnPack(_e, any_unique_type(), _resolver); } + { auto _e = any_ambiguous_type(); _o->any_ambiguous.type = _e; } + { auto _e = any_ambiguous(); if (_e) _o->any_ambiguous.value = MyGame::Example::AnyAmbiguousAliasesUnion::UnPack(_e, any_ambiguous_type(), _resolver); } + { auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast(_e->Get(_i)); } } else { _o->vector_of_enums.resize(0); } } + { auto _e = signed_enum(); _o->signed_enum = _e; } + { auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } } + { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->scalar_key_sorted_tables.resize(0); } } + { auto _e = native_inline(); if (_e) _o->native_inline = *_e; } + { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; } + { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; } + { auto _e = nan_default(); _o->nan_default = _e; } + { auto _e = inf_default(); _o->inf_default = _e; } + { auto _e = positive_inf_default(); _o->positive_inf_default = _e; } + { auto _e = infinity_default(); _o->infinity_default = _e; } + { auto _e = positive_infinity_default(); _o->positive_infinity_default = _e; } + { auto _e = negative_inf_default(); _o->negative_inf_default = _e; } + { auto _e = negative_infinity_default(); _o->negative_infinity_default = _e; } + { auto _e = double_inf_default(); _o->double_inf_default = _e; } +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _pos = _o->pos ? _o->pos.get() : nullptr; + auto _mana = _o->mana; + auto _hp = _o->hp; + auto _name = _fbb.CreateString(_o->name); + auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0; + auto _color = _o->color; + auto _test_type = _o->test.type; + auto _test = _o->test.Pack(_fbb); + auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; + auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testbool = _o->testbool; + auto _testhashs32_fnv1 = _o->testhashs32_fnv1; + auto _testhashu32_fnv1 = _o->testhashu32_fnv1; + auto _testhashs64_fnv1 = _o->testhashs64_fnv1; + auto _testhashu64_fnv1 = _o->testhashu64_fnv1; + auto _testhashs32_fnv1a = _o->testhashs32_fnv1a; + auto _testhashu32_fnv1a = _rehasher ? static_cast((*_rehasher)(_o->testhashu32_fnv1a)) : 0; + auto _testhashs64_fnv1a = _o->testhashs64_fnv1a; + auto _testhashu64_fnv1a = _o->testhashu64_fnv1a; + auto _testarrayofbools = _o->testarrayofbools.size() ? _fbb.CreateVector(_o->testarrayofbools) : 0; + auto _testf = _o->testf; + auto _testf2 = _o->testf2; + auto _testf3 = _o->testf3; + auto _testarrayofstring2 = _o->testarrayofstring2.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring2) : 0; + auto _testarrayofsortedstruct = _o->testarrayofsortedstruct.size() ? _fbb.CreateVectorOfStructs(_o->testarrayofsortedstruct) : 0; + auto _flex = _o->flex.size() ? _fbb.CreateVector(_o->flex) : 0; + auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; + auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; + auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; + auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; + auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; + auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; + auto _vector_of_non_owning_references = _o->vector_of_non_owning_references.size() ? _fbb.CreateVector(_o->vector_of_non_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_non_owning_references[i])) : 0; }, &_va ) : 0; + auto _any_unique_type = _o->any_unique.type; + auto _any_unique = _o->any_unique.Pack(_fbb); + auto _any_ambiguous_type = _o->any_ambiguous.type; + auto _any_ambiguous = _o->any_ambiguous.Pack(_fbb); + auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; + auto _signed_enum = _o->signed_enum; + auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _native_inline = &_o->native_inline; + auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; + auto _long_enum_normal_default = _o->long_enum_normal_default; + auto _nan_default = _o->nan_default; + auto _inf_default = _o->inf_default; + auto _positive_inf_default = _o->positive_inf_default; + auto _infinity_default = _o->infinity_default; + auto _positive_infinity_default = _o->positive_infinity_default; + auto _negative_inf_default = _o->negative_inf_default; + auto _negative_infinity_default = _o->negative_infinity_default; + auto _double_inf_default = _o->double_inf_default; + return MyGame::Example::CreateMonster( + _fbb, + _pos, + _mana, + _hp, + _name, + _inventory, + _color, + _test_type, + _test, + _test4, + _testarrayofstring, + _testarrayoftables, + _enemy, + _testnestedflatbuffer, + _testempty, + _testbool, + _testhashs32_fnv1, + _testhashu32_fnv1, + _testhashs64_fnv1, + _testhashu64_fnv1, + _testhashs32_fnv1a, + _testhashu32_fnv1a, + _testhashs64_fnv1a, + _testhashu64_fnv1a, + _testarrayofbools, + _testf, + _testf2, + _testf3, + _testarrayofstring2, + _testarrayofsortedstruct, + _flex, + _test5, + _vector_of_longs, + _vector_of_doubles, + _parent_namespace_test, + _vector_of_referrables, + _single_weak_reference, + _vector_of_weak_references, + _vector_of_strong_referrables, + _co_owning_reference, + _vector_of_co_owning_references, + _non_owning_reference, + _vector_of_non_owning_references, + _any_unique_type, + _any_unique, + _any_ambiguous_type, + _any_ambiguous, + _vector_of_enums, + _signed_enum, + _testrequirednestedflatbuffer, + _scalar_key_sorted_tables, + _native_inline, + _long_enum_non_enum_default, + _long_enum_normal_default, + _nan_default, + _inf_default, + _positive_inf_default, + _infinity_default, + _positive_infinity_default, + _negative_inf_default, + _negative_infinity_default, + _double_inf_default); +} + + +inline bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return + (lhs.i8 == rhs.i8) && + (lhs.u8 == rhs.u8) && + (lhs.i16 == rhs.i16) && + (lhs.u16 == rhs.u16) && + (lhs.i32 == rhs.i32) && + (lhs.u32 == rhs.u32) && + (lhs.i64 == rhs.i64) && + (lhs.u64 == rhs.u64) && + (lhs.f32 == rhs.f32) && + (lhs.f64 == rhs.f64) && + (lhs.v8 == rhs.v8) && + (lhs.vf64 == rhs.vf64); +} + +inline bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return !(lhs == rhs); +} + + +inline TypeAliasesT *TypeAliases::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TypeAliasesT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TypeAliases::UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = i8(); _o->i8 = _e; } + { auto _e = u8(); _o->u8 = _e; } + { auto _e = i16(); _o->i16 = _e; } + { auto _e = u16(); _o->u16 = _e; } + { auto _e = i32(); _o->i32 = _e; } + { auto _e = u32(); _o->u32 = _e; } + { auto _e = i64(); _o->i64 = _e; } + { auto _e = u64(); _o->u64 = _e; } + { auto _e = f32(); _o->f32 = _e; } + { auto _e = f64(); _o->f64 = _e; } + { auto _e = v8(); if (_e) { _o->v8.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->v8.begin()); } } + { auto _e = vf64(); if (_e) { _o->vf64.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vf64[_i] = _e->Get(_i); } } else { _o->vf64.resize(0); } } +} + +inline ::flatbuffers::Offset TypeAliases::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTypeAliases(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TypeAliasesT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _i8 = _o->i8; + auto _u8 = _o->u8; + auto _i16 = _o->i16; + auto _u16 = _o->u16; + auto _i32 = _o->i32; + auto _u32 = _o->u32; + auto _i64 = _o->i64; + auto _u64 = _o->u64; + auto _f32 = _o->f32; + auto _f64 = _o->f64; + auto _v8 = _o->v8.size() ? _fbb.CreateVector(_o->v8) : 0; + auto _vf64 = _o->vf64.size() ? _fbb.CreateVector(_o->vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + _i8, + _u8, + _i16, + _u16, + _i32, + _u32, + _i64, + _u64, + _f32, + _f64, + _v8, + _vf64); +} + +inline bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type) { + switch (type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAny( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUnion::UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Any_Monster: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case Any_TestSimpleTableWithEnum: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case Any_MyGame_Example2_Monster: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUnion::Reset() { + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Any_NONE; +} + +inline bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type) { + switch (type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyUniqueAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUniqueAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyUniqueAliases_M: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_TS: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_M2: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUniqueAliasesUnion::Reset() { + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyUniqueAliases_NONE; +} + +inline bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type) { + switch (type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyAmbiguousAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyAmbiguousAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyAmbiguousAliases_M1: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M2: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M3: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyAmbiguousAliasesUnion::Reset() { + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyAmbiguousAliases_NONE; +} + +inline const ::flatbuffers::TypeTable *ColorTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const int64_t values[] = { 1, 2, 8 }; + static const char * const names[] = { + "Red", + "Green", + "Blue" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RaceTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::RaceTypeTable + }; + static const int64_t values[] = { -1, 0, 1, 2 }; + static const char * const names[] = { + "None", + "Human", + "Dwarf", + "Elf" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 4, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *LongEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::LongEnumTypeTable + }; + static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL }; + static const char * const names[] = { + "LongOne", + "LongTwo", + "LongBig" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyUniqueAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M", + "TS", + "M2" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyAmbiguousAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M1", + "M2", + "M3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 } + }; + static const int64_t values[] = { 0, 2, 4 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const char * const names[] = { + "color" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *Vec3TypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 4, 8, 16, 24, 26, 32 }; + static const char * const names[] = { + "x", + "y", + "z", + "test1", + "test2", + "test3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 6, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AbilityTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "id", + "distance" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::AbilityTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 8, 12, 20 }; + static const char * const names[] = { + "a", + "b", + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::StructOfStructsTypeTable + }; + static const int64_t values[] = { 0, 20 }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StatTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 } + }; + static const char * const names[] = { + "id", + "val", + "count" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, -1 } + }; + static const char * const names[] = { + "id" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 1 }, + { ::flatbuffers::ET_UTYPE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 4 }, + { ::flatbuffers::ET_SEQUENCE, 0, 4 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 5 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_BOOL, 1, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 6 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_LONG, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 7 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_UTYPE, 0, 9 }, + { ::flatbuffers::ET_SEQUENCE, 0, 9 }, + { ::flatbuffers::ET_UTYPE, 0, 10 }, + { ::flatbuffers::ET_SEQUENCE, 0, 10 }, + { ::flatbuffers::ET_UCHAR, 1, 1 }, + { ::flatbuffers::ET_CHAR, 0, 11 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 5 }, + { ::flatbuffers::ET_SEQUENCE, 0, 3 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::Vec3TypeTable, + MyGame::Example::ColorTypeTable, + MyGame::Example::AnyTypeTable, + MyGame::Example::TestTypeTable, + MyGame::Example::MonsterTypeTable, + MyGame::Example::StatTypeTable, + MyGame::Example::AbilityTypeTable, + MyGame::InParentNamespaceTypeTable, + MyGame::Example::ReferrableTypeTable, + MyGame::Example::AnyUniqueAliasesTypeTable, + MyGame::Example::AnyAmbiguousAliasesTypeTable, + MyGame::Example::RaceTypeTable, + MyGame::Example::LongEnumTypeTable + }; + static const char * const names[] = { + "pos", + "mana", + "hp", + "name", + "friendly", + "inventory", + "color", + "test_type", + "test", + "test4", + "testarrayofstring", + "testarrayoftables", + "enemy", + "testnestedflatbuffer", + "testempty", + "testbool", + "testhashs32_fnv1", + "testhashu32_fnv1", + "testhashs64_fnv1", + "testhashu64_fnv1", + "testhashs32_fnv1a", + "testhashu32_fnv1a", + "testhashs64_fnv1a", + "testhashu64_fnv1a", + "testarrayofbools", + "testf", + "testf2", + "testf3", + "testarrayofstring2", + "testarrayofsortedstruct", + "flex", + "test5", + "vector_of_longs", + "vector_of_doubles", + "parent_namespace_test", + "vector_of_referrables", + "single_weak_reference", + "vector_of_weak_references", + "vector_of_strong_referrables", + "co_owning_reference", + "vector_of_co_owning_references", + "non_owning_reference", + "vector_of_non_owning_references", + "any_unique_type", + "any_unique", + "any_ambiguous_type", + "any_ambiguous", + "vector_of_enums", + "signed_enum", + "testrequirednestedflatbuffer", + "scalar_key_sorted_tables", + "native_inline", + "long_enum_non_enum_default", + "long_enum_normal_default", + "nan_default", + "inf_default", + "positive_inf_default", + "infinity_default", + "positive_infinity_default", + "negative_inf_default", + "negative_infinity_default", + "double_inf_default" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 62, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_CHAR, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 } + }; + static const char * const names[] = { + "i8", + "u8", + "i16", + "u16", + "i32", + "u32", + "i64", + "u64", + "f32", + "f64", + "v8", + "vf64" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 12, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const MyGame::Example::Monster *GetMonster(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const MyGame::Example::Monster *GetSizePrefixedMonster(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Monster *GetMutableMonster(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MonsterIdentifier() { + return "MONS"; +} + +inline bool MonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier()); +} + +inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier(), true); +} + +inline bool VerifyMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MonsterIdentifier()); +} + +inline bool VerifySizePrefixedMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MonsterIdentifier()); +} + +inline const char *MonsterExtension() { + return "mon"; +} + +inline void FinishMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MonsterIdentifier()); +} + +inline void FinishSizePrefixedMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MonsterIdentifier()); +} + +inline std::unique_ptr UnPackMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMonster(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMonster(buf)->UnPack(res)); +} + +} // namespace Example +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ diff --git a/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test.grpc.fb.cc b/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test.grpc.fb.cc new file mode 100644 index 00000000000..3ef89ceeba7 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test.grpc.fb.cc @@ -0,0 +1,131 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test + +#include "monster_test_suffix.h" +#include "monster_test.grpc.fb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +namespace MyGame { +namespace Example { + +static const char* MonsterStorage_method_names[] = { + "/MyGame.Example.MonsterStorage/Store", + "/MyGame.Example.MonsterStorage/Retrieve", + "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", +}; + +std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) { + std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel)); + return stub; +} + +MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) + : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) + , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) + , rpcmethod_GetMaxHitPoint_(MonsterStorage_method_names[2], ::grpc::internal::RpcMethod::CLIENT_STREAMING, channel) + , rpcmethod_GetMinMaxHitPoints_(MonsterStorage_method_names[3], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel) + {} + +::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) { + return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false); +} + +::grpc::ClientReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_Retrieve_, context, request); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr); +} + +::grpc::ClientWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return ::grpc::internal::ClientWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMaxHitPoint_, context, response); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, true, tag); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, false, nullptr); +} + +::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMinMaxHitPointsRaw(::grpc::ClientContext* context) { + return ::grpc::internal::ClientReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMinMaxHitPoints_, context); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, true, tag); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, false, nullptr); +} + +MonsterStorage::Service::Service() { + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[0], + ::grpc::internal::RpcMethod::NORMAL_RPC, + new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Store), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[1], + ::grpc::internal::RpcMethod::SERVER_STREAMING, + new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Retrieve), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[2], + ::grpc::internal::RpcMethod::CLIENT_STREAMING, + new ::grpc::internal::ClientStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMaxHitPoint), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[3], + ::grpc::internal::RpcMethod::BIDI_STREAMING, + new ::grpc::internal::BidiStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMinMaxHitPoints), this))); +} + +MonsterStorage::Service::~Service() { +} + +::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + + +} // namespace MyGame +} // namespace Example + diff --git a/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test.grpc.fb.h b/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test.grpc.fb.h new file mode 100644 index 00000000000..a8f4b95ad0d --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test.grpc.fb.h @@ -0,0 +1,350 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test +#ifndef GRPC_monster_5ftest__INCLUDED +#define GRPC_monster_5ftest__INCLUDED + +#include "monster_test_suffix.h" +#include "flatbuffers/grpc.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class Channel; +class ServerCompletionQueue; +class ServerContext; +} // namespace grpc + +namespace MyGame { +namespace Example { + +class MonsterStorage final { + public: + static constexpr char const* service_full_name() { + return "MyGame.Example.MonsterStorage"; + } + class StubInterface { + public: + virtual ~StubInterface() {} + virtual ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + private: + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReader< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientWriter< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override; + const ::grpc::internal::RpcMethod rpcmethod_Store_; + const ::grpc::internal::RpcMethod rpcmethod_Retrieve_; + const ::grpc::internal::RpcMethod rpcmethod_GetMaxHitPoint_; + const ::grpc::internal::RpcMethod rpcmethod_GetMinMaxHitPoints_; + }; + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class Service : public ::grpc::Service { + public: + Service(); + virtual ~Service(); + virtual ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, flatbuffers::grpc::Message* response); + virtual ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, ::grpc::ServerWriter< flatbuffers::grpc::Message>* writer); + virtual ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message>* reader, flatbuffers::grpc::Message* response); + virtual ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream); + }; + template + class WithAsyncMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Store() { + ::grpc::Service::MarkMethodAsync(0); + } + ~WithAsyncMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestStore(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncResponseWriter< flatbuffers::grpc::Message>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Retrieve() { + ::grpc::Service::MarkMethodAsync(1); + } + ~WithAsyncMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestRetrieve(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncWriter< flatbuffers::grpc::Message>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncServerStreaming(1, context, request, writer, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodAsync(2); + } + ~WithAsyncMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* reader, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncClientStreaming(2, context, reader, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodAsync(3); + } + ~WithAsyncMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(3, context, stream, new_call_cq, notification_cq, tag); + } + }; + typedef WithAsyncMethod_Store< WithAsyncMethod_Retrieve< WithAsyncMethod_GetMaxHitPoint< WithAsyncMethod_GetMinMaxHitPoints< Service > > > > AsyncService; + template + class WithGenericMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Store() { + ::grpc::Service::MarkMethodGeneric(0); + } + ~WithGenericMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Retrieve() { + ::grpc::Service::MarkMethodGeneric(1); + } + ~WithGenericMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodGeneric(2); + } + ~WithGenericMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodGeneric(3); + } + ~WithGenericMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithStreamedUnaryMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithStreamedUnaryMethod_Store() { + ::grpc::Service::MarkMethodStreamed(0, + new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithStreamedUnaryMethod_Store::StreamedStore, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedStore(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_unary_streamer) = 0; + }; + typedef WithStreamedUnaryMethod_Store< Service > StreamedUnaryService; + template + class WithSplitStreamingMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) { } + public: + WithSplitStreamingMethod_Retrieve() { + ::grpc::Service::MarkMethodStreamed(1, + new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithSplitStreamingMethod_Retrieve::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithSplitStreamingMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with split streamed + virtual ::grpc::Status StreamedRetrieve(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_split_streamer) = 0; + }; + typedef WithSplitStreamingMethod_Retrieve< Service > SplitStreamedService; + typedef WithStreamedUnaryMethod_Store< WithSplitStreamingMethod_Retrieve< Service > > StreamedService; +}; + +} // namespace Example +} // namespace MyGame + + +#endif // GRPC_monster_5ftest__INCLUDED diff --git a/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h b/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h new file mode 100644 index 00000000000..fd292b0f327 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/filesuffix_only/monster_test_suffix.h @@ -0,0 +1,4238 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ +#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/flex_flat_util.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace MyGame { + +struct InParentNamespace; +struct InParentNamespaceBuilder; +struct InParentNamespaceT; + +namespace Example2 { + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +} // namespace Example2 + +namespace Example { + +struct Test; + +struct TestSimpleTableWithEnum; +struct TestSimpleTableWithEnumBuilder; +struct TestSimpleTableWithEnumT; + +struct Vec3; + +struct Ability; + +struct StructOfStructs; + +struct StructOfStructsOfStructs; + +struct Stat; +struct StatBuilder; +struct StatT; + +struct Referrable; +struct ReferrableBuilder; +struct ReferrableT; + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +struct TypeAliases; +struct TypeAliasesBuilder; +struct TypeAliasesT; + +} // namespace Example + +bool operator==(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +namespace Example2 { + +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +} // namespace Example2 + +namespace Example { + +bool operator==(const Test &lhs, const Test &rhs); +bool operator!=(const Test &lhs, const Test &rhs); +bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator==(const Vec3 &lhs, const Vec3 &rhs); +bool operator!=(const Vec3 &lhs, const Vec3 &rhs); +bool operator==(const Ability &lhs, const Ability &rhs); +bool operator!=(const Ability &lhs, const Ability &rhs); +bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator==(const StatT &lhs, const StatT &rhs); +bool operator!=(const StatT &lhs, const StatT &rhs); +bool operator==(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs); +bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs); + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable(); + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable(); + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable(); + +inline const ::flatbuffers::TypeTable *Vec3TypeTable(); + +inline const ::flatbuffers::TypeTable *AbilityTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StatTypeTable(); + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable(); + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable(); + +/// Composite components of Monster color. +enum Color : uint8_t { + Color_Red = 1, + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Color_Green = 2, + /// \brief color Blue (1u << 3) + Color_Blue = 8, + Color_NONE = 0, + Color_ANY = 11 +}; + +inline const Color (&EnumValuesColor())[3] { + static const Color values[] = { + Color_Red, + Color_Green, + Color_Blue + }; + return values; +} + +inline const char * const *EnumNamesColor() { + static const char * const names[9] = { + "Red", + "Green", + "", + "", + "", + "", + "", + "Blue", + nullptr + }; + return names; +} + +inline const char *EnumNameColor(Color e) { + if (::flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return ""; + const size_t index = static_cast(e) - static_cast(Color_Red); + return EnumNamesColor()[index]; +} + +enum Race : int8_t { + Race_None = -1, + Race_Human = 0, + Race_Dwarf = 1, + Race_Elf = 2, + Race_MIN = Race_None, + Race_MAX = Race_Elf +}; + +inline const Race (&EnumValuesRace())[4] { + static const Race values[] = { + Race_None, + Race_Human, + Race_Dwarf, + Race_Elf + }; + return values; +} + +inline const char * const *EnumNamesRace() { + static const char * const names[5] = { + "None", + "Human", + "Dwarf", + "Elf", + nullptr + }; + return names; +} + +inline const char *EnumNameRace(Race e) { + if (::flatbuffers::IsOutRange(e, Race_None, Race_Elf)) return ""; + const size_t index = static_cast(e) - static_cast(Race_None); + return EnumNamesRace()[index]; +} + +enum LongEnum : uint64_t { + LongEnum_LongOne = 2ULL, + LongEnum_LongTwo = 4ULL, + LongEnum_LongBig = 1099511627776ULL, + LongEnum_NONE = 0, + LongEnum_ANY = 1099511627782ULL +}; + +inline const LongEnum (&EnumValuesLongEnum())[3] { + static const LongEnum values[] = { + LongEnum_LongOne, + LongEnum_LongTwo, + LongEnum_LongBig + }; + return values; +} + +inline const char *EnumNameLongEnum(LongEnum e) { + switch (e) { + case LongEnum_LongOne: return "LongOne"; + case LongEnum_LongTwo: return "LongTwo"; + case LongEnum_LongBig: return "LongBig"; + default: return ""; + } +} + +enum Any : uint8_t { + Any_NONE = 0, + Any_Monster = 1, + Any_TestSimpleTableWithEnum = 2, + Any_MyGame_Example2_Monster = 3, + Any_MIN = Any_NONE, + Any_MAX = Any_MyGame_Example2_Monster +}; + +inline const Any (&EnumValuesAny())[4] { + static const Any values[] = { + Any_NONE, + Any_Monster, + Any_TestSimpleTableWithEnum, + Any_MyGame_Example2_Monster + }; + return values; +} + +inline const char * const *EnumNamesAny() { + static const char * const names[5] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster", + nullptr + }; + return names; +} + +inline const char *EnumNameAny(Any e) { + if (::flatbuffers::IsOutRange(e, Any_NONE, Any_MyGame_Example2_Monster)) return ""; + const size_t index = static_cast(e); + return EnumNamesAny()[index]; +} + +template struct AnyTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +template struct AnyUnionTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +struct AnyUnion { + Any type; + void *value; + + AnyUnion() : type(Any_NONE), value(nullptr) {} + AnyUnion(AnyUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Any_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUnion(const AnyUnion &); + AnyUnion &operator=(const AnyUnion &u) + { AnyUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUnion &operator=(AnyUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUnionTraits::enum_value; + if (type != Any_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsMonster() { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsMonster() const { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() const { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() const { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUnion &lhs, const AnyUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_TestSimpleTableWithEnum: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_MyGame_Example2_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUnion &lhs, const AnyUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type); +bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyUniqueAliases : uint8_t { + AnyUniqueAliases_NONE = 0, + AnyUniqueAliases_M = 1, + AnyUniqueAliases_TS = 2, + AnyUniqueAliases_M2 = 3, + AnyUniqueAliases_MIN = AnyUniqueAliases_NONE, + AnyUniqueAliases_MAX = AnyUniqueAliases_M2 +}; + +inline const AnyUniqueAliases (&EnumValuesAnyUniqueAliases())[4] { + static const AnyUniqueAliases values[] = { + AnyUniqueAliases_NONE, + AnyUniqueAliases_M, + AnyUniqueAliases_TS, + AnyUniqueAliases_M2 + }; + return values; +} + +inline const char * const *EnumNamesAnyUniqueAliases() { + static const char * const names[5] = { + "NONE", + "M", + "TS", + "M2", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyUniqueAliases(AnyUniqueAliases e) { + if (::flatbuffers::IsOutRange(e, AnyUniqueAliases_NONE, AnyUniqueAliases_M2)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyUniqueAliases()[index]; +} + +template struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +template struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +struct AnyUniqueAliasesUnion { + AnyUniqueAliases type; + void *value; + + AnyUniqueAliasesUnion() : type(AnyUniqueAliases_NONE), value(nullptr) {} + AnyUniqueAliasesUnion(AnyUniqueAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyUniqueAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &); + AnyUniqueAliasesUnion &operator=(const AnyUniqueAliasesUnion &u) + { AnyUniqueAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUniqueAliasesUnion &operator=(AnyUniqueAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUniqueAliasesUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUniqueAliasesUnionTraits::enum_value; + if (type != AnyUniqueAliases_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM() { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM() const { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTS() { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTS() const { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsM2() { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsM2() const { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_TS: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type); +bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyAmbiguousAliases : uint8_t { + AnyAmbiguousAliases_NONE = 0, + AnyAmbiguousAliases_M1 = 1, + AnyAmbiguousAliases_M2 = 2, + AnyAmbiguousAliases_M3 = 3, + AnyAmbiguousAliases_MIN = AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_MAX = AnyAmbiguousAliases_M3 +}; + +inline const AnyAmbiguousAliases (&EnumValuesAnyAmbiguousAliases())[4] { + static const AnyAmbiguousAliases values[] = { + AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_M1, + AnyAmbiguousAliases_M2, + AnyAmbiguousAliases_M3 + }; + return values; +} + +inline const char * const *EnumNamesAnyAmbiguousAliases() { + static const char * const names[5] = { + "NONE", + "M1", + "M2", + "M3", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyAmbiguousAliases(AnyAmbiguousAliases e) { + if (::flatbuffers::IsOutRange(e, AnyAmbiguousAliases_NONE, AnyAmbiguousAliases_M3)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyAmbiguousAliases()[index]; +} + +struct AnyAmbiguousAliasesUnion { + AnyAmbiguousAliases type; + void *value; + + AnyAmbiguousAliasesUnion() : type(AnyAmbiguousAliases_NONE), value(nullptr) {} + AnyAmbiguousAliasesUnion(AnyAmbiguousAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyAmbiguousAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &); + AnyAmbiguousAliasesUnion &operator=(const AnyAmbiguousAliasesUnion &u) + { AnyAmbiguousAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyAmbiguousAliasesUnion &operator=(AnyAmbiguousAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyAmbiguousAliasesUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM1() { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM1() const { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM2() { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM2() const { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM3() { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM3() const { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M3: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type); +bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS { + private: + int16_t a_; + int8_t b_; + int8_t padding0__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestTypeTable(); + } + Test() + : a_(0), + b_(0), + padding0__(0) { + (void)padding0__; + } + Test(int16_t _a, int8_t _b) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0) { + (void)padding0__; + } + int16_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int16_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + int8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(int8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Test, 4); + +inline bool operator==(const Test &lhs, const Test &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Test &lhs, const Test &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Vec3 FLATBUFFERS_FINAL_CLASS { + private: + float x_; + float y_; + float z_; + int32_t padding0__; + double test1_; + uint8_t test2_; + int8_t padding1__; + MyGame::Example::Test test3_; + int16_t padding2__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vec3TypeTable(); + } + Vec3() + : x_(0), + y_(0), + z_(0), + padding0__(0), + test1_(0), + test2_(0), + padding1__(0), + test3_(), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + Vec3(float _x, float _y, float _z, double _test1, MyGame::Example::Color _test2, const MyGame::Example::Test &_test3) + : x_(::flatbuffers::EndianScalar(_x)), + y_(::flatbuffers::EndianScalar(_y)), + z_(::flatbuffers::EndianScalar(_z)), + padding0__(0), + test1_(::flatbuffers::EndianScalar(_test1)), + test2_(::flatbuffers::EndianScalar(static_cast(_test2))), + padding1__(0), + test3_(_test3), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + float x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(float _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } + float y() const { + return ::flatbuffers::EndianScalar(y_); + } + void mutate_y(float _y) { + ::flatbuffers::WriteScalar(&y_, _y); + } + float z() const { + return ::flatbuffers::EndianScalar(z_); + } + void mutate_z(float _z) { + ::flatbuffers::WriteScalar(&z_, _z); + } + double test1() const { + return ::flatbuffers::EndianScalar(test1_); + } + void mutate_test1(double _test1) { + ::flatbuffers::WriteScalar(&test1_, _test1); + } + MyGame::Example::Color test2() const { + return static_cast(::flatbuffers::EndianScalar(test2_)); + } + void mutate_test2(MyGame::Example::Color _test2) { + ::flatbuffers::WriteScalar(&test2_, static_cast(_test2)); + } + const MyGame::Example::Test &test3() const { + return test3_; + } + MyGame::Example::Test &mutable_test3() { + return test3_; + } +}; +FLATBUFFERS_STRUCT_END(Vec3, 32); + +inline bool operator==(const Vec3 &lhs, const Vec3 &rhs) { + return + (lhs.x() == rhs.x()) && + (lhs.y() == rhs.y()) && + (lhs.z() == rhs.z()) && + (lhs.test1() == rhs.test1()) && + (lhs.test2() == rhs.test2()) && + (lhs.test3() == rhs.test3()); +} + +inline bool operator!=(const Vec3 &lhs, const Vec3 &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Ability FLATBUFFERS_FINAL_CLASS { + private: + uint32_t id_; + uint32_t distance_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AbilityTypeTable(); + } + Ability() + : id_(0), + distance_(0) { + } + Ability(uint32_t _id, uint32_t _distance) + : id_(::flatbuffers::EndianScalar(_id)), + distance_(::flatbuffers::EndianScalar(_distance)) { + } + uint32_t id() const { + return ::flatbuffers::EndianScalar(id_); + } + void mutate_id(uint32_t _id) { + ::flatbuffers::WriteScalar(&id_, _id); + } + bool KeyCompareLessThan(const Ability * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint32_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + uint32_t distance() const { + return ::flatbuffers::EndianScalar(distance_); + } + void mutate_distance(uint32_t _distance) { + ::flatbuffers::WriteScalar(&distance_, _distance); + } +}; +FLATBUFFERS_STRUCT_END(Ability, 8); + +inline bool operator==(const Ability &lhs, const Ability &rhs) { + return + (lhs.id() == rhs.id()) && + (lhs.distance() == rhs.distance()); +} + +inline bool operator!=(const Ability &lhs, const Ability &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::Ability a_; + MyGame::Example::Test b_; + MyGame::Example::Ability c_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsTypeTable(); + } + StructOfStructs() + : a_(), + b_(), + c_() { + } + StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c) + : a_(_a), + b_(_b), + c_(_c) { + } + const MyGame::Example::Ability &a() const { + return a_; + } + MyGame::Example::Ability &mutable_a() { + return a_; + } + const MyGame::Example::Test &b() const { + return b_; + } + MyGame::Example::Test &mutable_b() { + return b_; + } + const MyGame::Example::Ability &c() const { + return c_; + } + MyGame::Example::Ability &mutable_c() { + return c_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructs, 20); + +inline bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()) && + (lhs.c() == rhs.c()); +} + +inline bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructsOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::StructOfStructs a_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsOfStructsTypeTable(); + } + StructOfStructsOfStructs() + : a_() { + } + StructOfStructsOfStructs(const MyGame::Example::StructOfStructs &_a) + : a_(_a) { + } + const MyGame::Example::StructOfStructs &a() const { + return a_; + } + MyGame::Example::StructOfStructs &mutable_a() { + return a_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructsOfStructs, 20); + +inline bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return + (lhs.a() == rhs.a()); +} + +inline bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return !(lhs == rhs); +} + + +} // namespace Example + +struct InParentNamespaceT : public ::flatbuffers::NativeTable { + typedef InParentNamespace TableType; +}; + +struct InParentNamespace FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef InParentNamespaceT NativeTableType; + typedef InParentNamespaceBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return InParentNamespaceTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + InParentNamespaceT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct InParentNamespaceBuilder { + typedef InParentNamespace Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit InParentNamespaceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateInParentNamespace( + ::flatbuffers::FlatBufferBuilder &_fbb) { + InParentNamespaceBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +namespace Example2 { + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; +}; + +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb) { + MonsterBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example2 + +namespace Example { + +struct TestSimpleTableWithEnumT : public ::flatbuffers::NativeTable { + typedef TestSimpleTableWithEnum TableType; + MyGame::Example::Color color = MyGame::Example::Color_Green; +}; + +struct TestSimpleTableWithEnum FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TestSimpleTableWithEnumT NativeTableType; + typedef TestSimpleTableWithEnumBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestSimpleTableWithEnumTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_COLOR = 4 + }; + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 2)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(2)) { + return SetField(VT_COLOR, static_cast(_color), 2); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_COLOR, 1) && + verifier.EndTable(); + } + TestSimpleTableWithEnumT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TestSimpleTableWithEnumBuilder { + typedef TestSimpleTableWithEnum Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(TestSimpleTableWithEnum::VT_COLOR, static_cast(color), 2); + } + explicit TestSimpleTableWithEnumBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum( + ::flatbuffers::FlatBufferBuilder &_fbb, + MyGame::Example::Color color = MyGame::Example::Color_Green) { + TestSimpleTableWithEnumBuilder builder_(_fbb); + builder_.add_color(color); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct StatT : public ::flatbuffers::NativeTable { + typedef Stat TableType; + std::string id{}; + int64_t val = 0; + uint16_t count = 0; +}; + +struct Stat FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StatT NativeTableType; + typedef StatBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StatTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4, + VT_VAL = 6, + VT_COUNT = 8 + }; + const ::flatbuffers::String *id() const { + return GetPointer(VT_ID); + } + ::flatbuffers::String *mutable_id() { + return GetPointer<::flatbuffers::String *>(VT_ID); + } + int64_t val() const { + return GetField(VT_VAL, 0); + } + bool mutate_val(int64_t _val = 0) { + return SetField(VT_VAL, _val, 0); + } + uint16_t count() const { + return GetField(VT_COUNT, 0); + } + bool mutate_count(uint16_t _count = 0) { + return SetField(VT_COUNT, _count, 0); + } + bool KeyCompareLessThan(const Stat * const o) const { + return count() < o->count(); + } + int KeyCompareWithValue(uint16_t _count) const { + return static_cast(count() > _count) - static_cast(count() < _count); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ID) && + verifier.VerifyString(id()) && + VerifyField(verifier, VT_VAL, 8) && + VerifyField(verifier, VT_COUNT, 2) && + verifier.EndTable(); + } + StatT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct StatBuilder { + typedef Stat Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(::flatbuffers::Offset<::flatbuffers::String> id) { + fbb_.AddOffset(Stat::VT_ID, id); + } + void add_val(int64_t val) { + fbb_.AddElement(Stat::VT_VAL, val, 0); + } + void add_count(uint16_t count) { + fbb_.AddElement(Stat::VT_COUNT, count, 0); + } + explicit StatBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStat( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> id = 0, + int64_t val = 0, + uint16_t count = 0) { + StatBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_id(id); + builder_.add_count(count); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStatDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *id = nullptr, + int64_t val = 0, + uint16_t count = 0) { + auto id__ = id ? _fbb.CreateString(id) : 0; + return MyGame::Example::CreateStat( + _fbb, + id__, + val, + count); +} + +::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct ReferrableT : public ::flatbuffers::NativeTable { + typedef Referrable TableType; + uint64_t id = 0; +}; + +struct Referrable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ReferrableT NativeTableType; + typedef ReferrableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ReferrableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4 + }; + uint64_t id() const { + return GetField(VT_ID, 0); + } + bool mutate_id(uint64_t _id = 0) { + return SetField(VT_ID, _id, 0); + } + bool KeyCompareLessThan(const Referrable * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint64_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_ID, 8) && + verifier.EndTable(); + } + ReferrableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ReferrableBuilder { + typedef Referrable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(uint64_t id) { + fbb_.AddElement(Referrable::VT_ID, id, 0); + } + explicit ReferrableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateReferrable( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint64_t id = 0) { + ReferrableBuilder builder_(_fbb); + builder_.add_id(id); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; + std::unique_ptr pos{}; + int16_t mana = 150; + int16_t hp = 100; + std::string name{}; + std::vector inventory{}; + MyGame::Example::Color color = MyGame::Example::Color_Blue; + MyGame::Example::AnyUnion test{}; + std::vector test4{}; + std::vector testarrayofstring{}; + std::vector> testarrayoftables{}; + std::unique_ptr enemy{}; + std::vector testnestedflatbuffer{}; + std::unique_ptr testempty{}; + bool testbool = false; + int32_t testhashs32_fnv1 = 0; + uint32_t testhashu32_fnv1 = 0; + int64_t testhashs64_fnv1 = 0; + uint64_t testhashu64_fnv1 = 0; + int32_t testhashs32_fnv1a = 0; + Stat *testhashu32_fnv1a = nullptr; + int64_t testhashs64_fnv1a = 0; + uint64_t testhashu64_fnv1a = 0; + std::vector testarrayofbools{}; + float testf = 3.14159f; + float testf2 = 3.0f; + float testf3 = 0.0f; + std::vector testarrayofstring2{}; + std::vector testarrayofsortedstruct{}; + std::vector flex{}; + std::vector test5{}; + std::vector vector_of_longs{}; + std::vector vector_of_doubles{}; + std::unique_ptr parent_namespace_test{}; + std::vector> vector_of_referrables{}; + ReferrableT *single_weak_reference = nullptr; + std::vector vector_of_weak_references{}; + std::vector> vector_of_strong_referrables{}; + ReferrableT *co_owning_reference = nullptr; + std::vector> vector_of_co_owning_references{}; + ReferrableT *non_owning_reference = nullptr; + std::vector vector_of_non_owning_references{}; + MyGame::Example::AnyUniqueAliasesUnion any_unique{}; + MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous{}; + std::vector vector_of_enums{}; + MyGame::Example::Race signed_enum = MyGame::Example::Race_None; + std::vector testrequirednestedflatbuffer{}; + std::vector> scalar_key_sorted_tables{}; + MyGame::Example::Test native_inline{}; + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0); + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne; + float nan_default = std::numeric_limits::quiet_NaN(); + float inf_default = std::numeric_limits::infinity(); + float positive_inf_default = std::numeric_limits::infinity(); + float infinity_default = std::numeric_limits::infinity(); + float positive_infinity_default = std::numeric_limits::infinity(); + float negative_inf_default = -std::numeric_limits::infinity(); + float negative_infinity_default = -std::numeric_limits::infinity(); + double double_inf_default = std::numeric_limits::infinity(); + MonsterT() = default; + MonsterT(const MonsterT &o); + MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default; + MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT; +}; + +/// an example documentation comment: "monster object" +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_POS = 4, + VT_MANA = 6, + VT_HP = 8, + VT_NAME = 10, + VT_INVENTORY = 14, + VT_COLOR = 16, + VT_TEST_TYPE = 18, + VT_TEST = 20, + VT_TEST4 = 22, + VT_TESTARRAYOFSTRING = 24, + VT_TESTARRAYOFTABLES = 26, + VT_ENEMY = 28, + VT_TESTNESTEDFLATBUFFER = 30, + VT_TESTEMPTY = 32, + VT_TESTBOOL = 34, + VT_TESTHASHS32_FNV1 = 36, + VT_TESTHASHU32_FNV1 = 38, + VT_TESTHASHS64_FNV1 = 40, + VT_TESTHASHU64_FNV1 = 42, + VT_TESTHASHS32_FNV1A = 44, + VT_TESTHASHU32_FNV1A = 46, + VT_TESTHASHS64_FNV1A = 48, + VT_TESTHASHU64_FNV1A = 50, + VT_TESTARRAYOFBOOLS = 52, + VT_TESTF = 54, + VT_TESTF2 = 56, + VT_TESTF3 = 58, + VT_TESTARRAYOFSTRING2 = 60, + VT_TESTARRAYOFSORTEDSTRUCT = 62, + VT_FLEX = 64, + VT_TEST5 = 66, + VT_VECTOR_OF_LONGS = 68, + VT_VECTOR_OF_DOUBLES = 70, + VT_PARENT_NAMESPACE_TEST = 72, + VT_VECTOR_OF_REFERRABLES = 74, + VT_SINGLE_WEAK_REFERENCE = 76, + VT_VECTOR_OF_WEAK_REFERENCES = 78, + VT_VECTOR_OF_STRONG_REFERRABLES = 80, + VT_CO_OWNING_REFERENCE = 82, + VT_VECTOR_OF_CO_OWNING_REFERENCES = 84, + VT_NON_OWNING_REFERENCE = 86, + VT_VECTOR_OF_NON_OWNING_REFERENCES = 88, + VT_ANY_UNIQUE_TYPE = 90, + VT_ANY_UNIQUE = 92, + VT_ANY_AMBIGUOUS_TYPE = 94, + VT_ANY_AMBIGUOUS = 96, + VT_VECTOR_OF_ENUMS = 98, + VT_SIGNED_ENUM = 100, + VT_TESTREQUIREDNESTEDFLATBUFFER = 102, + VT_SCALAR_KEY_SORTED_TABLES = 104, + VT_NATIVE_INLINE = 106, + VT_LONG_ENUM_NON_ENUM_DEFAULT = 108, + VT_LONG_ENUM_NORMAL_DEFAULT = 110, + VT_NAN_DEFAULT = 112, + VT_INF_DEFAULT = 114, + VT_POSITIVE_INF_DEFAULT = 116, + VT_INFINITY_DEFAULT = 118, + VT_POSITIVE_INFINITY_DEFAULT = 120, + VT_NEGATIVE_INF_DEFAULT = 122, + VT_NEGATIVE_INFINITY_DEFAULT = 124, + VT_DOUBLE_INF_DEFAULT = 126 + }; + const MyGame::Example::Vec3 *pos() const { + return GetStruct(VT_POS); + } + MyGame::Example::Vec3 *mutable_pos() { + return GetStruct(VT_POS); + } + int16_t mana() const { + return GetField(VT_MANA, 150); + } + bool mutate_mana(int16_t _mana = 150) { + return SetField(VT_MANA, _mana, 150); + } + int16_t hp() const { + return GetField(VT_HP, 100); + } + bool mutate_hp(int16_t _hp = 100) { + return SetField(VT_HP, _hp, 100); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + bool KeyCompareLessThan(const Monster * const o) const { + return *name() < *o->name(); + } + int KeyCompareWithValue(const char *_name) const { + return strcmp(name()->c_str(), _name); + } + template + int KeyCompareWithValue(const StringType& _name) const { + if (name()->c_str() < _name) return -1; + if (_name < name()->c_str()) return 1; + return 0; + } + const ::flatbuffers::Vector *inventory() const { + return GetPointer *>(VT_INVENTORY); + } + ::flatbuffers::Vector *mutable_inventory() { + return GetPointer<::flatbuffers::Vector *>(VT_INVENTORY); + } + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 8)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(8)) { + return SetField(VT_COLOR, static_cast(_color), 8); + } + MyGame::Example::Any test_type() const { + return static_cast(GetField(VT_TEST_TYPE, 0)); + } + const void *test() const { + return GetPointer(VT_TEST); + } + template const T *test_as() const; + const MyGame::Example::Monster *test_as_Monster() const { + return test_type() == MyGame::Example::Any_Monster ? static_cast(test()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *test_as_TestSimpleTableWithEnum() const { + return test_type() == MyGame::Example::Any_TestSimpleTableWithEnum ? static_cast(test()) : nullptr; + } + const MyGame::Example2::Monster *test_as_MyGame_Example2_Monster() const { + return test_type() == MyGame::Example::Any_MyGame_Example2_Monster ? static_cast(test()) : nullptr; + } + void *mutable_test() { + return GetPointer(VT_TEST); + } + const ::flatbuffers::Vector *test4() const { + return GetPointer *>(VT_TEST4); + } + ::flatbuffers::Vector *mutable_test4() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST4); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING); + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + const ::flatbuffers::Vector<::flatbuffers::Offset> *testarrayoftables() const { + return GetPointer> *>(VT_TESTARRAYOFTABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_testarrayoftables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_TESTARRAYOFTABLES); + } + const MyGame::Example::Monster *enemy() const { + return GetPointer(VT_ENEMY); + } + MyGame::Example::Monster *mutable_enemy() { + return GetPointer(VT_ENEMY); + } + const ::flatbuffers::Vector *testnestedflatbuffer() const { + return GetPointer *>(VT_TESTNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testnestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testnestedflatbuffer_nested_root() const { + const auto _f = testnestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const MyGame::Example::Stat *testempty() const { + return GetPointer(VT_TESTEMPTY); + } + MyGame::Example::Stat *mutable_testempty() { + return GetPointer(VT_TESTEMPTY); + } + bool testbool() const { + return GetField(VT_TESTBOOL, 0) != 0; + } + bool mutate_testbool(bool _testbool = 0) { + return SetField(VT_TESTBOOL, static_cast(_testbool), 0); + } + int32_t testhashs32_fnv1() const { + return GetField(VT_TESTHASHS32_FNV1, 0); + } + bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) { + return SetField(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0); + } + uint32_t testhashu32_fnv1() const { + return GetField(VT_TESTHASHU32_FNV1, 0); + } + bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) { + return SetField(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0); + } + int64_t testhashs64_fnv1() const { + return GetField(VT_TESTHASHS64_FNV1, 0); + } + bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) { + return SetField(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0); + } + uint64_t testhashu64_fnv1() const { + return GetField(VT_TESTHASHU64_FNV1, 0); + } + bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) { + return SetField(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0); + } + int32_t testhashs32_fnv1a() const { + return GetField(VT_TESTHASHS32_FNV1A, 0); + } + bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) { + return SetField(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0); + } + uint32_t testhashu32_fnv1a() const { + return GetField(VT_TESTHASHU32_FNV1A, 0); + } + bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) { + return SetField(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0); + } + int64_t testhashs64_fnv1a() const { + return GetField(VT_TESTHASHS64_FNV1A, 0); + } + bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) { + return SetField(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0); + } + uint64_t testhashu64_fnv1a() const { + return GetField(VT_TESTHASHU64_FNV1A, 0); + } + bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) { + return SetField(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0); + } + const ::flatbuffers::Vector *testarrayofbools() const { + return GetPointer *>(VT_TESTARRAYOFBOOLS); + } + ::flatbuffers::Vector *mutable_testarrayofbools() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFBOOLS); + } + float testf() const { + return GetField(VT_TESTF, 3.14159f); + } + bool mutate_testf(float _testf = 3.14159f) { + return SetField(VT_TESTF, _testf, 3.14159f); + } + float testf2() const { + return GetField(VT_TESTF2, 3.0f); + } + bool mutate_testf2(float _testf2 = 3.0f) { + return SetField(VT_TESTF2, _testf2, 3.0f); + } + float testf3() const { + return GetField(VT_TESTF3, 0.0f); + } + bool mutate_testf3(float _testf3 = 0.0f) { + return SetField(VT_TESTF3, _testf3, 0.0f); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING2); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring2() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING2); + } + const ::flatbuffers::Vector *testarrayofsortedstruct() const { + return GetPointer *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + ::flatbuffers::Vector *mutable_testarrayofsortedstruct() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + const ::flatbuffers::Vector *flex() const { + return GetPointer *>(VT_FLEX); + } + ::flatbuffers::Vector *mutable_flex() { + return GetPointer<::flatbuffers::Vector *>(VT_FLEX); + } + flexbuffers::Reference flex_flexbuffer_root() const { + const auto _f = flex(); + return _f ? flexbuffers::GetRoot(_f->Data(), _f->size()) + : flexbuffers::Reference(); + } + const ::flatbuffers::Vector *test5() const { + return GetPointer *>(VT_TEST5); + } + ::flatbuffers::Vector *mutable_test5() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST5); + } + const ::flatbuffers::Vector *vector_of_longs() const { + return GetPointer *>(VT_VECTOR_OF_LONGS); + } + ::flatbuffers::Vector *mutable_vector_of_longs() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_LONGS); + } + const ::flatbuffers::Vector *vector_of_doubles() const { + return GetPointer *>(VT_VECTOR_OF_DOUBLES); + } + ::flatbuffers::Vector *mutable_vector_of_doubles() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_DOUBLES); + } + const MyGame::InParentNamespace *parent_namespace_test() const { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + MyGame::InParentNamespace *mutable_parent_namespace_test() { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_REFERRABLES); + } + uint64_t single_weak_reference() const { + return GetField(VT_SINGLE_WEAK_REFERENCE, 0); + } + bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) { + return SetField(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0); + } + const ::flatbuffers::Vector *vector_of_weak_references() const { + return GetPointer *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_weak_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_strong_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_strong_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + uint64_t co_owning_reference() const { + return GetField(VT_CO_OWNING_REFERENCE, 0); + } + bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) { + return SetField(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_co_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_co_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + uint64_t non_owning_reference() const { + return GetField(VT_NON_OWNING_REFERENCE, 0); + } + bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) { + return SetField(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_non_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_non_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + MyGame::Example::AnyUniqueAliases any_unique_type() const { + return static_cast(GetField(VT_ANY_UNIQUE_TYPE, 0)); + } + const void *any_unique() const { + return GetPointer(VT_ANY_UNIQUE); + } + template const T *any_unique_as() const; + const MyGame::Example::Monster *any_unique_as_M() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *any_unique_as_TS() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_TS ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example2::Monster *any_unique_as_M2() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M2 ? static_cast(any_unique()) : nullptr; + } + void *mutable_any_unique() { + return GetPointer(VT_ANY_UNIQUE); + } + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type() const { + return static_cast(GetField(VT_ANY_AMBIGUOUS_TYPE, 0)); + } + const void *any_ambiguous() const { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const MyGame::Example::Monster *any_ambiguous_as_M1() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M1 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M2() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M2 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M3() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M3 ? static_cast(any_ambiguous()) : nullptr; + } + void *mutable_any_ambiguous() { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const ::flatbuffers::Vector *vector_of_enums() const { + return GetPointer *>(VT_VECTOR_OF_ENUMS); + } + ::flatbuffers::Vector *mutable_vector_of_enums() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_ENUMS); + } + MyGame::Example::Race signed_enum() const { + return static_cast(GetField(VT_SIGNED_ENUM, -1)); + } + bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast(-1)) { + return SetField(VT_SIGNED_ENUM, static_cast(_signed_enum), -1); + } + const ::flatbuffers::Vector *testrequirednestedflatbuffer() const { + return GetPointer *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testrequirednestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const { + const auto _f = testrequirednestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *scalar_key_sorted_tables() const { + return GetPointer> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_scalar_key_sorted_tables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + const MyGame::Example::Test *native_inline() const { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::Test *mutable_native_inline() { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::LongEnum long_enum_non_enum_default() const { + return static_cast(GetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0)); + } + bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast(0)) { + return SetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(_long_enum_non_enum_default), 0); + } + MyGame::Example::LongEnum long_enum_normal_default() const { + return static_cast(GetField(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL)); + } + bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast(2ULL)) { + return SetField(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(_long_enum_normal_default), 2ULL); + } + float nan_default() const { + return GetField(VT_NAN_DEFAULT, std::numeric_limits::quiet_NaN()); + } + bool mutate_nan_default(float _nan_default = std::numeric_limits::quiet_NaN()) { + return SetField(VT_NAN_DEFAULT, _nan_default, std::numeric_limits::quiet_NaN()); + } + float inf_default() const { + return GetField(VT_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_inf_default(float _inf_default = std::numeric_limits::infinity()) { + return SetField(VT_INF_DEFAULT, _inf_default, std::numeric_limits::infinity()); + } + float positive_inf_default() const { + return GetField(VT_POSITIVE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_inf_default(float _positive_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INF_DEFAULT, _positive_inf_default, std::numeric_limits::infinity()); + } + float infinity_default() const { + return GetField(VT_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_infinity_default(float _infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_INFINITY_DEFAULT, _infinity_default, std::numeric_limits::infinity()); + } + float positive_infinity_default() const { + return GetField(VT_POSITIVE_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_infinity_default(float _positive_infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INFINITY_DEFAULT, _positive_infinity_default, std::numeric_limits::infinity()); + } + float negative_inf_default() const { + return GetField(VT_NEGATIVE_INF_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_inf_default(float _negative_inf_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INF_DEFAULT, _negative_inf_default, -std::numeric_limits::infinity()); + } + float negative_infinity_default() const { + return GetField(VT_NEGATIVE_INFINITY_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_infinity_default(float _negative_infinity_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INFINITY_DEFAULT, _negative_infinity_default, -std::numeric_limits::infinity()); + } + double double_inf_default() const { + return GetField(VT_DOUBLE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_double_inf_default(double _double_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_DOUBLE_INF_DEFAULT, _double_inf_default, std::numeric_limits::infinity()); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_POS, 8) && + VerifyField(verifier, VT_MANA, 2) && + VerifyField(verifier, VT_HP, 2) && + VerifyOffsetRequired(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_INVENTORY) && + verifier.VerifyVector(inventory()) && + VerifyField(verifier, VT_COLOR, 1) && + VerifyField(verifier, VT_TEST_TYPE, 1) && + VerifyOffset(verifier, VT_TEST) && + VerifyAny(verifier, test(), test_type()) && + VerifyOffset(verifier, VT_TEST4) && + verifier.VerifyVector(test4()) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING) && + verifier.VerifyVector(testarrayofstring()) && + verifier.VerifyVectorOfStrings(testarrayofstring()) && + VerifyOffset(verifier, VT_TESTARRAYOFTABLES) && + verifier.VerifyVector(testarrayoftables()) && + verifier.VerifyVectorOfTables(testarrayoftables()) && + VerifyOffset(verifier, VT_ENEMY) && + verifier.VerifyTable(enemy()) && + VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) && + verifier.VerifyVector(testnestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testnestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_TESTEMPTY) && + verifier.VerifyTable(testempty()) && + VerifyField(verifier, VT_TESTBOOL, 1) && + VerifyField(verifier, VT_TESTHASHS32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHS32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1A, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1A, 8) && + VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) && + verifier.VerifyVector(testarrayofbools()) && + VerifyField(verifier, VT_TESTF, 4) && + VerifyField(verifier, VT_TESTF2, 4) && + VerifyField(verifier, VT_TESTF3, 4) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) && + verifier.VerifyVector(testarrayofstring2()) && + verifier.VerifyVectorOfStrings(testarrayofstring2()) && + VerifyOffset(verifier, VT_TESTARRAYOFSORTEDSTRUCT) && + verifier.VerifyVector(testarrayofsortedstruct()) && + VerifyOffset(verifier, VT_FLEX) && + verifier.VerifyVector(flex()) && + flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) && + VerifyOffset(verifier, VT_TEST5) && + verifier.VerifyVector(test5()) && + VerifyOffset(verifier, VT_VECTOR_OF_LONGS) && + verifier.VerifyVector(vector_of_longs()) && + VerifyOffset(verifier, VT_VECTOR_OF_DOUBLES) && + verifier.VerifyVector(vector_of_doubles()) && + VerifyOffset(verifier, VT_PARENT_NAMESPACE_TEST) && + verifier.VerifyTable(parent_namespace_test()) && + VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) && + verifier.VerifyVector(vector_of_referrables()) && + verifier.VerifyVectorOfTables(vector_of_referrables()) && + VerifyField(verifier, VT_SINGLE_WEAK_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) && + verifier.VerifyVector(vector_of_weak_references()) && + VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) && + verifier.VerifyVector(vector_of_strong_referrables()) && + verifier.VerifyVectorOfTables(vector_of_strong_referrables()) && + VerifyField(verifier, VT_CO_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_co_owning_references()) && + VerifyField(verifier, VT_NON_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_non_owning_references()) && + VerifyField(verifier, VT_ANY_UNIQUE_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_UNIQUE) && + VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) && + VerifyField(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_AMBIGUOUS) && + VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) && + VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) && + verifier.VerifyVector(vector_of_enums()) && + VerifyField(verifier, VT_SIGNED_ENUM, 1) && + VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) && + verifier.VerifyVector(testrequirednestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testrequirednestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) && + verifier.VerifyVector(scalar_key_sorted_tables()) && + verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) && + VerifyField(verifier, VT_NATIVE_INLINE, 2) && + VerifyField(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) && + VerifyField(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) && + VerifyField(verifier, VT_NAN_DEFAULT, 4) && + VerifyField(verifier, VT_INF_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_DOUBLE_INF_DEFAULT, 8) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const MyGame::Example::Monster *Monster::test_as() const { + return test_as_Monster(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::test_as() const { + return test_as_TestSimpleTableWithEnum(); +} + +template<> inline const MyGame::Example2::Monster *Monster::test_as() const { + return test_as_MyGame_Example2_Monster(); +} + +template<> inline const MyGame::Example::Monster *Monster::any_unique_as() const { + return any_unique_as_M(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::any_unique_as() const { + return any_unique_as_TS(); +} + +template<> inline const MyGame::Example2::Monster *Monster::any_unique_as() const { + return any_unique_as_M2(); +} + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_pos(const MyGame::Example::Vec3 *pos) { + fbb_.AddStruct(Monster::VT_POS, pos); + } + void add_mana(int16_t mana) { + fbb_.AddElement(Monster::VT_MANA, mana, 150); + } + void add_hp(int16_t hp) { + fbb_.AddElement(Monster::VT_HP, hp, 100); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Monster::VT_NAME, name); + } + void add_inventory(::flatbuffers::Offset<::flatbuffers::Vector> inventory) { + fbb_.AddOffset(Monster::VT_INVENTORY, inventory); + } + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(Monster::VT_COLOR, static_cast(color), 8); + } + void add_test_type(MyGame::Example::Any test_type) { + fbb_.AddElement(Monster::VT_TEST_TYPE, static_cast(test_type), 0); + } + void add_test(::flatbuffers::Offset test) { + fbb_.AddOffset(Monster::VT_TEST, test); + } + void add_test4(::flatbuffers::Offset<::flatbuffers::Vector> test4) { + fbb_.AddOffset(Monster::VT_TEST4, test4); + } + void add_testarrayofstring(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + void add_testarrayoftables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + void add_enemy(::flatbuffers::Offset enemy) { + fbb_.AddOffset(Monster::VT_ENEMY, enemy); + } + void add_testnestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + void add_testempty(::flatbuffers::Offset testempty) { + fbb_.AddOffset(Monster::VT_TESTEMPTY, testempty); + } + void add_testbool(bool testbool) { + fbb_.AddElement(Monster::VT_TESTBOOL, static_cast(testbool), 0); + } + void add_testhashs32_fnv1(int32_t testhashs32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + void add_testhashu32_fnv1(uint32_t testhashu32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + void add_testhashs64_fnv1(int64_t testhashs64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + void add_testhashu64_fnv1(uint64_t testhashu64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + void add_testhashs32_fnv1a(int32_t testhashs32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + void add_testhashu32_fnv1a(uint32_t testhashu32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + void add_testhashs64_fnv1a(int64_t testhashs64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + void add_testhashu64_fnv1a(uint64_t testhashu64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + void add_testarrayofbools(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + void add_testf(float testf) { + fbb_.AddElement(Monster::VT_TESTF, testf, 3.14159f); + } + void add_testf2(float testf2) { + fbb_.AddElement(Monster::VT_TESTF2, testf2, 3.0f); + } + void add_testf3(float testf3) { + fbb_.AddElement(Monster::VT_TESTF3, testf3, 0.0f); + } + void add_testarrayofstring2(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + void add_testarrayofsortedstruct(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + void add_flex(::flatbuffers::Offset<::flatbuffers::Vector> flex) { + fbb_.AddOffset(Monster::VT_FLEX, flex); + } + void add_test5(::flatbuffers::Offset<::flatbuffers::Vector> test5) { + fbb_.AddOffset(Monster::VT_TEST5, test5); + } + void add_vector_of_longs(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + void add_vector_of_doubles(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + void add_parent_namespace_test(::flatbuffers::Offset parent_namespace_test) { + fbb_.AddOffset(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + void add_vector_of_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + void add_single_weak_reference(uint64_t single_weak_reference) { + fbb_.AddElement(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + void add_vector_of_weak_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + void add_vector_of_strong_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + void add_co_owning_reference(uint64_t co_owning_reference) { + fbb_.AddElement(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + void add_vector_of_co_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + void add_non_owning_reference(uint64_t non_owning_reference) { + fbb_.AddElement(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + void add_vector_of_non_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + void add_any_unique_type(MyGame::Example::AnyUniqueAliases any_unique_type) { + fbb_.AddElement(Monster::VT_ANY_UNIQUE_TYPE, static_cast(any_unique_type), 0); + } + void add_any_unique(::flatbuffers::Offset any_unique) { + fbb_.AddOffset(Monster::VT_ANY_UNIQUE, any_unique); + } + void add_any_ambiguous_type(MyGame::Example::AnyAmbiguousAliases any_ambiguous_type) { + fbb_.AddElement(Monster::VT_ANY_AMBIGUOUS_TYPE, static_cast(any_ambiguous_type), 0); + } + void add_any_ambiguous(::flatbuffers::Offset any_ambiguous) { + fbb_.AddOffset(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + void add_vector_of_enums(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + void add_signed_enum(MyGame::Example::Race signed_enum) { + fbb_.AddElement(Monster::VT_SIGNED_ENUM, static_cast(signed_enum), -1); + } + void add_testrequirednestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + void add_scalar_key_sorted_tables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables) { + fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + void add_native_inline(const MyGame::Example::Test *native_inline) { + fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline); + } + void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(long_enum_non_enum_default), 0); + } + void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(long_enum_normal_default), 2ULL); + } + void add_nan_default(float nan_default) { + fbb_.AddElement(Monster::VT_NAN_DEFAULT, nan_default, std::numeric_limits::quiet_NaN()); + } + void add_inf_default(float inf_default) { + fbb_.AddElement(Monster::VT_INF_DEFAULT, inf_default, std::numeric_limits::infinity()); + } + void add_positive_inf_default(float positive_inf_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, std::numeric_limits::infinity()); + } + void add_infinity_default(float infinity_default) { + fbb_.AddElement(Monster::VT_INFINITY_DEFAULT, infinity_default, std::numeric_limits::infinity()); + } + void add_positive_infinity_default(float positive_infinity_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, std::numeric_limits::infinity()); + } + void add_negative_inf_default(float negative_inf_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, -std::numeric_limits::infinity()); + } + void add_negative_infinity_default(float negative_infinity_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, -std::numeric_limits::infinity()); + } + void add_double_inf_default(double double_inf_default) { + fbb_.AddElement(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, std::numeric_limits::infinity()); + } + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + fbb_.Required(o, Monster::VT_NAME); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> inventory = 0, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test4 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables = 0, + ::flatbuffers::Offset enemy = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer = 0, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools = 0, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> flex = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test5 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles = 0, + ::flatbuffers::Offset parent_namespace_test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables = 0, + uint64_t single_weak_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables = 0, + uint64_t co_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references = 0, + uint64_t non_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references = 0, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums = 0, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + ::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables = 0, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + MonsterBuilder builder_(_fbb); + builder_.add_double_inf_default(double_inf_default); + builder_.add_long_enum_normal_default(long_enum_normal_default); + builder_.add_long_enum_non_enum_default(long_enum_non_enum_default); + builder_.add_non_owning_reference(non_owning_reference); + builder_.add_co_owning_reference(co_owning_reference); + builder_.add_single_weak_reference(single_weak_reference); + builder_.add_testhashu64_fnv1a(testhashu64_fnv1a); + builder_.add_testhashs64_fnv1a(testhashs64_fnv1a); + builder_.add_testhashu64_fnv1(testhashu64_fnv1); + builder_.add_testhashs64_fnv1(testhashs64_fnv1); + builder_.add_negative_infinity_default(negative_infinity_default); + builder_.add_negative_inf_default(negative_inf_default); + builder_.add_positive_infinity_default(positive_infinity_default); + builder_.add_infinity_default(infinity_default); + builder_.add_positive_inf_default(positive_inf_default); + builder_.add_inf_default(inf_default); + builder_.add_nan_default(nan_default); + builder_.add_native_inline(native_inline); + builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables); + builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer); + builder_.add_vector_of_enums(vector_of_enums); + builder_.add_any_ambiguous(any_ambiguous); + builder_.add_any_unique(any_unique); + builder_.add_vector_of_non_owning_references(vector_of_non_owning_references); + builder_.add_vector_of_co_owning_references(vector_of_co_owning_references); + builder_.add_vector_of_strong_referrables(vector_of_strong_referrables); + builder_.add_vector_of_weak_references(vector_of_weak_references); + builder_.add_vector_of_referrables(vector_of_referrables); + builder_.add_parent_namespace_test(parent_namespace_test); + builder_.add_vector_of_doubles(vector_of_doubles); + builder_.add_vector_of_longs(vector_of_longs); + builder_.add_test5(test5); + builder_.add_flex(flex); + builder_.add_testarrayofsortedstruct(testarrayofsortedstruct); + builder_.add_testarrayofstring2(testarrayofstring2); + builder_.add_testf3(testf3); + builder_.add_testf2(testf2); + builder_.add_testf(testf); + builder_.add_testarrayofbools(testarrayofbools); + builder_.add_testhashu32_fnv1a(testhashu32_fnv1a); + builder_.add_testhashs32_fnv1a(testhashs32_fnv1a); + builder_.add_testhashu32_fnv1(testhashu32_fnv1); + builder_.add_testhashs32_fnv1(testhashs32_fnv1); + builder_.add_testempty(testempty); + builder_.add_testnestedflatbuffer(testnestedflatbuffer); + builder_.add_enemy(enemy); + builder_.add_testarrayoftables(testarrayoftables); + builder_.add_testarrayofstring(testarrayofstring); + builder_.add_test4(test4); + builder_.add_test(test); + builder_.add_inventory(inventory); + builder_.add_name(name); + builder_.add_pos(pos); + builder_.add_hp(hp); + builder_.add_mana(mana); + builder_.add_signed_enum(signed_enum); + builder_.add_any_ambiguous_type(any_ambiguous_type); + builder_.add_any_unique_type(any_unique_type); + builder_.add_testbool(testbool); + builder_.add_test_type(test_type); + builder_.add_color(color); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMonsterDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + const char *name = nullptr, + const std::vector *inventory = nullptr, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + const std::vector *test4 = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring = nullptr, + std::vector<::flatbuffers::Offset> *testarrayoftables = nullptr, + ::flatbuffers::Offset enemy = 0, + const std::vector *testnestedflatbuffer = nullptr, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + const std::vector *testarrayofbools = nullptr, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2 = nullptr, + std::vector *testarrayofsortedstruct = nullptr, + const std::vector *flex = nullptr, + const std::vector *test5 = nullptr, + const std::vector *vector_of_longs = nullptr, + const std::vector *vector_of_doubles = nullptr, + ::flatbuffers::Offset parent_namespace_test = 0, + std::vector<::flatbuffers::Offset> *vector_of_referrables = nullptr, + uint64_t single_weak_reference = 0, + const std::vector *vector_of_weak_references = nullptr, + std::vector<::flatbuffers::Offset> *vector_of_strong_referrables = nullptr, + uint64_t co_owning_reference = 0, + const std::vector *vector_of_co_owning_references = nullptr, + uint64_t non_owning_reference = 0, + const std::vector *vector_of_non_owning_references = nullptr, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + const std::vector *vector_of_enums = nullptr, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + const std::vector *testrequirednestedflatbuffer = nullptr, + std::vector<::flatbuffers::Offset> *scalar_key_sorted_tables = nullptr, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto inventory__ = inventory ? _fbb.CreateVector(*inventory) : 0; + auto test4__ = test4 ? _fbb.CreateVectorOfStructs(*test4) : 0; + auto testarrayofstring__ = testarrayofstring ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring) : 0; + auto testarrayoftables__ = testarrayoftables ? _fbb.CreateVectorOfSortedTables(testarrayoftables) : 0; + auto testnestedflatbuffer__ = testnestedflatbuffer ? _fbb.CreateVector(*testnestedflatbuffer) : 0; + auto testarrayofbools__ = testarrayofbools ? _fbb.CreateVector(*testarrayofbools) : 0; + auto testarrayofstring2__ = testarrayofstring2 ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring2) : 0; + auto testarrayofsortedstruct__ = testarrayofsortedstruct ? _fbb.CreateVectorOfSortedStructs(testarrayofsortedstruct) : 0; + auto flex__ = flex ? _fbb.CreateVector(*flex) : 0; + auto test5__ = test5 ? _fbb.CreateVectorOfStructs(*test5) : 0; + auto vector_of_longs__ = vector_of_longs ? _fbb.CreateVector(*vector_of_longs) : 0; + auto vector_of_doubles__ = vector_of_doubles ? _fbb.CreateVector(*vector_of_doubles) : 0; + auto vector_of_referrables__ = vector_of_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_referrables) : 0; + auto vector_of_weak_references__ = vector_of_weak_references ? _fbb.CreateVector(*vector_of_weak_references) : 0; + auto vector_of_strong_referrables__ = vector_of_strong_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_strong_referrables) : 0; + auto vector_of_co_owning_references__ = vector_of_co_owning_references ? _fbb.CreateVector(*vector_of_co_owning_references) : 0; + auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector(*vector_of_non_owning_references) : 0; + auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector(*vector_of_enums) : 0; + auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector(*testrequirednestedflatbuffer) : 0; + auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables(scalar_key_sorted_tables) : 0; + return MyGame::Example::CreateMonster( + _fbb, + pos, + mana, + hp, + name__, + inventory__, + color, + test_type, + test, + test4__, + testarrayofstring__, + testarrayoftables__, + enemy, + testnestedflatbuffer__, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools__, + testf, + testf2, + testf3, + testarrayofstring2__, + testarrayofsortedstruct__, + flex__, + test5__, + vector_of_longs__, + vector_of_doubles__, + parent_namespace_test, + vector_of_referrables__, + single_weak_reference, + vector_of_weak_references__, + vector_of_strong_referrables__, + co_owning_reference, + vector_of_co_owning_references__, + non_owning_reference, + vector_of_non_owning_references__, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums__, + signed_enum, + testrequirednestedflatbuffer__, + scalar_key_sorted_tables__, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct TypeAliasesT : public ::flatbuffers::NativeTable { + typedef TypeAliases TableType; + int8_t i8 = 0; + uint8_t u8 = 0; + int16_t i16 = 0; + uint16_t u16 = 0; + int32_t i32 = 0; + uint32_t u32 = 0; + int64_t i64 = 0; + uint64_t u64 = 0; + float f32 = 0.0f; + double f64 = 0.0; + std::vector v8{}; + std::vector vf64{}; +}; + +struct TypeAliases FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TypeAliasesT NativeTableType; + typedef TypeAliasesBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TypeAliasesTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_I8 = 4, + VT_U8 = 6, + VT_I16 = 8, + VT_U16 = 10, + VT_I32 = 12, + VT_U32 = 14, + VT_I64 = 16, + VT_U64 = 18, + VT_F32 = 20, + VT_F64 = 22, + VT_V8 = 24, + VT_VF64 = 26 + }; + int8_t i8() const { + return GetField(VT_I8, 0); + } + bool mutate_i8(int8_t _i8 = 0) { + return SetField(VT_I8, _i8, 0); + } + uint8_t u8() const { + return GetField(VT_U8, 0); + } + bool mutate_u8(uint8_t _u8 = 0) { + return SetField(VT_U8, _u8, 0); + } + int16_t i16() const { + return GetField(VT_I16, 0); + } + bool mutate_i16(int16_t _i16 = 0) { + return SetField(VT_I16, _i16, 0); + } + uint16_t u16() const { + return GetField(VT_U16, 0); + } + bool mutate_u16(uint16_t _u16 = 0) { + return SetField(VT_U16, _u16, 0); + } + int32_t i32() const { + return GetField(VT_I32, 0); + } + bool mutate_i32(int32_t _i32 = 0) { + return SetField(VT_I32, _i32, 0); + } + uint32_t u32() const { + return GetField(VT_U32, 0); + } + bool mutate_u32(uint32_t _u32 = 0) { + return SetField(VT_U32, _u32, 0); + } + int64_t i64() const { + return GetField(VT_I64, 0); + } + bool mutate_i64(int64_t _i64 = 0) { + return SetField(VT_I64, _i64, 0); + } + uint64_t u64() const { + return GetField(VT_U64, 0); + } + bool mutate_u64(uint64_t _u64 = 0) { + return SetField(VT_U64, _u64, 0); + } + float f32() const { + return GetField(VT_F32, 0.0f); + } + bool mutate_f32(float _f32 = 0.0f) { + return SetField(VT_F32, _f32, 0.0f); + } + double f64() const { + return GetField(VT_F64, 0.0); + } + bool mutate_f64(double _f64 = 0.0) { + return SetField(VT_F64, _f64, 0.0); + } + const ::flatbuffers::Vector *v8() const { + return GetPointer *>(VT_V8); + } + ::flatbuffers::Vector *mutable_v8() { + return GetPointer<::flatbuffers::Vector *>(VT_V8); + } + const ::flatbuffers::Vector *vf64() const { + return GetPointer *>(VT_VF64); + } + ::flatbuffers::Vector *mutable_vf64() { + return GetPointer<::flatbuffers::Vector *>(VT_VF64); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_I8, 1) && + VerifyField(verifier, VT_U8, 1) && + VerifyField(verifier, VT_I16, 2) && + VerifyField(verifier, VT_U16, 2) && + VerifyField(verifier, VT_I32, 4) && + VerifyField(verifier, VT_U32, 4) && + VerifyField(verifier, VT_I64, 8) && + VerifyField(verifier, VT_U64, 8) && + VerifyField(verifier, VT_F32, 4) && + VerifyField(verifier, VT_F64, 8) && + VerifyOffset(verifier, VT_V8) && + verifier.VerifyVector(v8()) && + VerifyOffset(verifier, VT_VF64) && + verifier.VerifyVector(vf64()) && + verifier.EndTable(); + } + TypeAliasesT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TypeAliasesBuilder { + typedef TypeAliases Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_i8(int8_t i8) { + fbb_.AddElement(TypeAliases::VT_I8, i8, 0); + } + void add_u8(uint8_t u8) { + fbb_.AddElement(TypeAliases::VT_U8, u8, 0); + } + void add_i16(int16_t i16) { + fbb_.AddElement(TypeAliases::VT_I16, i16, 0); + } + void add_u16(uint16_t u16) { + fbb_.AddElement(TypeAliases::VT_U16, u16, 0); + } + void add_i32(int32_t i32) { + fbb_.AddElement(TypeAliases::VT_I32, i32, 0); + } + void add_u32(uint32_t u32) { + fbb_.AddElement(TypeAliases::VT_U32, u32, 0); + } + void add_i64(int64_t i64) { + fbb_.AddElement(TypeAliases::VT_I64, i64, 0); + } + void add_u64(uint64_t u64) { + fbb_.AddElement(TypeAliases::VT_U64, u64, 0); + } + void add_f32(float f32) { + fbb_.AddElement(TypeAliases::VT_F32, f32, 0.0f); + } + void add_f64(double f64) { + fbb_.AddElement(TypeAliases::VT_F64, f64, 0.0); + } + void add_v8(::flatbuffers::Offset<::flatbuffers::Vector> v8) { + fbb_.AddOffset(TypeAliases::VT_V8, v8); + } + void add_vf64(::flatbuffers::Offset<::flatbuffers::Vector> vf64) { + fbb_.AddOffset(TypeAliases::VT_VF64, vf64); + } + explicit TypeAliasesBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTypeAliases( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + ::flatbuffers::Offset<::flatbuffers::Vector> v8 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vf64 = 0) { + TypeAliasesBuilder builder_(_fbb); + builder_.add_f64(f64); + builder_.add_u64(u64); + builder_.add_i64(i64); + builder_.add_vf64(vf64); + builder_.add_v8(v8); + builder_.add_f32(f32); + builder_.add_u32(u32); + builder_.add_i32(i32); + builder_.add_u16(u16); + builder_.add_i16(i16); + builder_.add_u8(u8); + builder_.add_i8(i8); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTypeAliasesDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + const std::vector *v8 = nullptr, + const std::vector *vf64 = nullptr) { + auto v8__ = v8 ? _fbb.CreateVector(*v8) : 0; + auto vf64__ = vf64 ? _fbb.CreateVector(*vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + i8, + u8, + i16, + u16, + i32, + u32, + i64, + u64, + f32, + f64, + v8__, + vf64__); +} + +::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example + + +inline bool operator==(const InParentNamespaceT &, const InParentNamespaceT &) { + return true; +} + +inline bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs) { + return !(lhs == rhs); +} + + +inline InParentNamespaceT *InParentNamespace::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new InParentNamespaceT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void InParentNamespace::UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset InParentNamespace::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateInParentNamespace(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const InParentNamespaceT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::CreateInParentNamespace( + _fbb); +} + +namespace Example2 { + + +inline bool operator==(const MonsterT &, const MonsterT &) { + return true; +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::Example2::CreateMonster( + _fbb); +} + +} // namespace Example2 + +namespace Example { + + +inline bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return + (lhs.color == rhs.color); +} + +inline bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return !(lhs == rhs); +} + + +inline TestSimpleTableWithEnumT *TestSimpleTableWithEnum::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TestSimpleTableWithEnumT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TestSimpleTableWithEnum::UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = color(); _o->color = _e; } +} + +inline ::flatbuffers::Offset TestSimpleTableWithEnum::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTestSimpleTableWithEnum(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TestSimpleTableWithEnumT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _color = _o->color; + return MyGame::Example::CreateTestSimpleTableWithEnum( + _fbb, + _color); +} + + +inline bool operator==(const StatT &lhs, const StatT &rhs) { + return + (lhs.id == rhs.id) && + (lhs.val == rhs.val) && + (lhs.count == rhs.count); +} + +inline bool operator!=(const StatT &lhs, const StatT &rhs) { + return !(lhs == rhs); +} + + +inline StatT *Stat::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new StatT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Stat::UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); if (_e) _o->id = _e->str(); } + { auto _e = val(); _o->val = _e; } + { auto _e = count(); _o->count = _e; } +} + +inline ::flatbuffers::Offset Stat::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateStat(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const StatT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id.empty() ? 0 : _fbb.CreateString(_o->id); + auto _val = _o->val; + auto _count = _o->count; + return MyGame::Example::CreateStat( + _fbb, + _id, + _val, + _count); +} + + +inline bool operator==(const ReferrableT &lhs, const ReferrableT &rhs) { + return + (lhs.id == rhs.id); +} + +inline bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs) { + return !(lhs == rhs); +} + + +inline ReferrableT *Referrable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new ReferrableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Referrable::UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); _o->id = _e; } +} + +inline ::flatbuffers::Offset Referrable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateReferrable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ReferrableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id; + return MyGame::Example::CreateReferrable( + _fbb, + _id); +} + + +inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) { + return + ((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) && + (lhs.mana == rhs.mana) && + (lhs.hp == rhs.hp) && + (lhs.name == rhs.name) && + (lhs.inventory == rhs.inventory) && + (lhs.color == rhs.color) && + (lhs.test == rhs.test) && + (lhs.test4 == rhs.test4) && + (lhs.testarrayofstring == rhs.testarrayofstring) && + (lhs.testarrayoftables.size() == rhs.testarrayoftables.size() && std::equal(lhs.testarrayoftables.cbegin(), lhs.testarrayoftables.cend(), rhs.testarrayoftables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + ((lhs.enemy == rhs.enemy) || (lhs.enemy && rhs.enemy && *lhs.enemy == *rhs.enemy)) && + (lhs.testnestedflatbuffer == rhs.testnestedflatbuffer) && + ((lhs.testempty == rhs.testempty) || (lhs.testempty && rhs.testempty && *lhs.testempty == *rhs.testempty)) && + (lhs.testbool == rhs.testbool) && + (lhs.testhashs32_fnv1 == rhs.testhashs32_fnv1) && + (lhs.testhashu32_fnv1 == rhs.testhashu32_fnv1) && + (lhs.testhashs64_fnv1 == rhs.testhashs64_fnv1) && + (lhs.testhashu64_fnv1 == rhs.testhashu64_fnv1) && + (lhs.testhashs32_fnv1a == rhs.testhashs32_fnv1a) && + (lhs.testhashu32_fnv1a == rhs.testhashu32_fnv1a) && + (lhs.testhashs64_fnv1a == rhs.testhashs64_fnv1a) && + (lhs.testhashu64_fnv1a == rhs.testhashu64_fnv1a) && + (lhs.testarrayofbools == rhs.testarrayofbools) && + (lhs.testf == rhs.testf) && + (lhs.testf2 == rhs.testf2) && + (lhs.testf3 == rhs.testf3) && + (lhs.testarrayofstring2 == rhs.testarrayofstring2) && + (lhs.testarrayofsortedstruct == rhs.testarrayofsortedstruct) && + (lhs.flex == rhs.flex) && + (lhs.test5 == rhs.test5) && + (lhs.vector_of_longs == rhs.vector_of_longs) && + (lhs.vector_of_doubles == rhs.vector_of_doubles) && + ((lhs.parent_namespace_test == rhs.parent_namespace_test) || (lhs.parent_namespace_test && rhs.parent_namespace_test && *lhs.parent_namespace_test == *rhs.parent_namespace_test)) && + (lhs.vector_of_referrables.size() == rhs.vector_of_referrables.size() && std::equal(lhs.vector_of_referrables.cbegin(), lhs.vector_of_referrables.cend(), rhs.vector_of_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.single_weak_reference == rhs.single_weak_reference) && + (lhs.vector_of_weak_references == rhs.vector_of_weak_references) && + (lhs.vector_of_strong_referrables.size() == rhs.vector_of_strong_referrables.size() && std::equal(lhs.vector_of_strong_referrables.cbegin(), lhs.vector_of_strong_referrables.cend(), rhs.vector_of_strong_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.co_owning_reference == rhs.co_owning_reference) && + (lhs.vector_of_co_owning_references == rhs.vector_of_co_owning_references) && + (lhs.non_owning_reference == rhs.non_owning_reference) && + (lhs.vector_of_non_owning_references == rhs.vector_of_non_owning_references) && + (lhs.any_unique == rhs.any_unique) && + (lhs.any_ambiguous == rhs.any_ambiguous) && + (lhs.vector_of_enums == rhs.vector_of_enums) && + (lhs.signed_enum == rhs.signed_enum) && + (lhs.testrequirednestedflatbuffer == rhs.testrequirednestedflatbuffer) && + (lhs.scalar_key_sorted_tables.size() == rhs.scalar_key_sorted_tables.size() && std::equal(lhs.scalar_key_sorted_tables.cbegin(), lhs.scalar_key_sorted_tables.cend(), rhs.scalar_key_sorted_tables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.native_inline == rhs.native_inline) && + (lhs.long_enum_non_enum_default == rhs.long_enum_non_enum_default) && + (lhs.long_enum_normal_default == rhs.long_enum_normal_default) && + (lhs.nan_default == rhs.nan_default) && + (lhs.inf_default == rhs.inf_default) && + (lhs.positive_inf_default == rhs.positive_inf_default) && + (lhs.infinity_default == rhs.infinity_default) && + (lhs.positive_infinity_default == rhs.positive_infinity_default) && + (lhs.negative_inf_default == rhs.negative_inf_default) && + (lhs.negative_infinity_default == rhs.negative_infinity_default) && + (lhs.double_inf_default == rhs.double_inf_default); +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT::MonsterT(const MonsterT &o) + : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr), + mana(o.mana), + hp(o.hp), + name(o.name), + inventory(o.inventory), + color(o.color), + test(o.test), + test4(o.test4), + testarrayofstring(o.testarrayofstring), + enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr), + testnestedflatbuffer(o.testnestedflatbuffer), + testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr), + testbool(o.testbool), + testhashs32_fnv1(o.testhashs32_fnv1), + testhashu32_fnv1(o.testhashu32_fnv1), + testhashs64_fnv1(o.testhashs64_fnv1), + testhashu64_fnv1(o.testhashu64_fnv1), + testhashs32_fnv1a(o.testhashs32_fnv1a), + testhashu32_fnv1a(o.testhashu32_fnv1a), + testhashs64_fnv1a(o.testhashs64_fnv1a), + testhashu64_fnv1a(o.testhashu64_fnv1a), + testarrayofbools(o.testarrayofbools), + testf(o.testf), + testf2(o.testf2), + testf3(o.testf3), + testarrayofstring2(o.testarrayofstring2), + testarrayofsortedstruct(o.testarrayofsortedstruct), + flex(o.flex), + test5(o.test5), + vector_of_longs(o.vector_of_longs), + vector_of_doubles(o.vector_of_doubles), + parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr), + single_weak_reference(o.single_weak_reference), + vector_of_weak_references(o.vector_of_weak_references), + co_owning_reference(o.co_owning_reference), + non_owning_reference(o.non_owning_reference), + vector_of_non_owning_references(o.vector_of_non_owning_references), + any_unique(o.any_unique), + any_ambiguous(o.any_ambiguous), + vector_of_enums(o.vector_of_enums), + signed_enum(o.signed_enum), + testrequirednestedflatbuffer(o.testrequirednestedflatbuffer), + native_inline(o.native_inline), + long_enum_non_enum_default(o.long_enum_non_enum_default), + long_enum_normal_default(o.long_enum_normal_default), + nan_default(o.nan_default), + inf_default(o.inf_default), + positive_inf_default(o.positive_inf_default), + infinity_default(o.infinity_default), + positive_infinity_default(o.positive_infinity_default), + negative_inf_default(o.negative_inf_default), + negative_infinity_default(o.negative_infinity_default), + double_inf_default(o.double_inf_default) { + testarrayoftables.reserve(o.testarrayoftables.size()); + for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); } + vector_of_referrables.reserve(o.vector_of_referrables.size()); + for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); } + vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size()); + for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); } + vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size()); + for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); } + scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size()); + for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); } +} + +inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT { + std::swap(pos, o.pos); + std::swap(mana, o.mana); + std::swap(hp, o.hp); + std::swap(name, o.name); + std::swap(inventory, o.inventory); + std::swap(color, o.color); + std::swap(test, o.test); + std::swap(test4, o.test4); + std::swap(testarrayofstring, o.testarrayofstring); + std::swap(testarrayoftables, o.testarrayoftables); + std::swap(enemy, o.enemy); + std::swap(testnestedflatbuffer, o.testnestedflatbuffer); + std::swap(testempty, o.testempty); + std::swap(testbool, o.testbool); + std::swap(testhashs32_fnv1, o.testhashs32_fnv1); + std::swap(testhashu32_fnv1, o.testhashu32_fnv1); + std::swap(testhashs64_fnv1, o.testhashs64_fnv1); + std::swap(testhashu64_fnv1, o.testhashu64_fnv1); + std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a); + std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a); + std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a); + std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a); + std::swap(testarrayofbools, o.testarrayofbools); + std::swap(testf, o.testf); + std::swap(testf2, o.testf2); + std::swap(testf3, o.testf3); + std::swap(testarrayofstring2, o.testarrayofstring2); + std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct); + std::swap(flex, o.flex); + std::swap(test5, o.test5); + std::swap(vector_of_longs, o.vector_of_longs); + std::swap(vector_of_doubles, o.vector_of_doubles); + std::swap(parent_namespace_test, o.parent_namespace_test); + std::swap(vector_of_referrables, o.vector_of_referrables); + std::swap(single_weak_reference, o.single_weak_reference); + std::swap(vector_of_weak_references, o.vector_of_weak_references); + std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables); + std::swap(co_owning_reference, o.co_owning_reference); + std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references); + std::swap(non_owning_reference, o.non_owning_reference); + std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references); + std::swap(any_unique, o.any_unique); + std::swap(any_ambiguous, o.any_ambiguous); + std::swap(vector_of_enums, o.vector_of_enums); + std::swap(signed_enum, o.signed_enum); + std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer); + std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables); + std::swap(native_inline, o.native_inline); + std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default); + std::swap(long_enum_normal_default, o.long_enum_normal_default); + std::swap(nan_default, o.nan_default); + std::swap(inf_default, o.inf_default); + std::swap(positive_inf_default, o.positive_inf_default); + std::swap(infinity_default, o.infinity_default); + std::swap(positive_infinity_default, o.positive_infinity_default); + std::swap(negative_inf_default, o.negative_inf_default); + std::swap(negative_infinity_default, o.negative_infinity_default); + std::swap(double_inf_default, o.double_inf_default); + return *this; +} + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = pos(); if (_e) _o->pos = std::unique_ptr(new MyGame::Example::Vec3(*_e)); } + { auto _e = mana(); _o->mana = _e; } + { auto _e = hp(); _o->hp = _e; } + { auto _e = name(); if (_e) _o->name = _e->str(); } + { auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } } + { auto _e = color(); _o->color = _e; } + { auto _e = test_type(); _o->test.type = _e; } + { auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); } + { auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } else { _o->test4.resize(0); } } + { auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring.resize(0); } } + { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->testarrayoftables.resize(0); } } + { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->enemy) { _o->enemy.reset(); } } + { auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } } + { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->testempty) { _o->testempty.reset(); } } + { auto _e = testbool(); _o->testbool = _e; } + { auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; } + { auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; } + { auto _e = testhashs64_fnv1(); _o->testhashs64_fnv1 = _e; } + { auto _e = testhashu64_fnv1(); _o->testhashu64_fnv1 = _e; } + { auto _e = testhashs32_fnv1a(); _o->testhashs32_fnv1a = _e; } + { auto _e = testhashu32_fnv1a(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->testhashu32_fnv1a), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->testhashu32_fnv1a = nullptr; } + { auto _e = testhashs64_fnv1a(); _o->testhashs64_fnv1a = _e; } + { auto _e = testhashu64_fnv1a(); _o->testhashu64_fnv1a = _e; } + { auto _e = testarrayofbools(); if (_e) { _o->testarrayofbools.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofbools[_i] = _e->Get(_i) != 0; } } else { _o->testarrayofbools.resize(0); } } + { auto _e = testf(); _o->testf = _e; } + { auto _e = testf2(); _o->testf2 = _e; } + { auto _e = testf3(); _o->testf3 = _e; } + { auto _e = testarrayofstring2(); if (_e) { _o->testarrayofstring2.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring2[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring2.resize(0); } } + { auto _e = testarrayofsortedstruct(); if (_e) { _o->testarrayofsortedstruct.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofsortedstruct[_i] = *_e->Get(_i); } } else { _o->testarrayofsortedstruct.resize(0); } } + { auto _e = flex(); if (_e) { _o->flex.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->flex.begin()); } } + { auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } else { _o->test5.resize(0); } } + { auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } else { _o->vector_of_longs.resize(0); } } + { auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } else { _o->vector_of_doubles.resize(0); } } + { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->parent_namespace_test) { _o->parent_namespace_test.reset(); } } + { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_referrables.resize(0); } } + { auto _e = single_weak_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->single_weak_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; } + { auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_weak_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } else { _o->vector_of_weak_references.resize(0); } } + { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_strong_referrables.resize(0); } } + { auto _e = co_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->co_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; } + { auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, default_ptr_type*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_co_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i)));/* else do nothing */} } else { _o->vector_of_co_owning_references.resize(0); } } + { auto _e = non_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->non_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->non_owning_reference = nullptr; } + { auto _e = vector_of_non_owning_references(); if (_e) { _o->vector_of_non_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_non_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_non_owning_references[_i] = nullptr; } } else { _o->vector_of_non_owning_references.resize(0); } } + { auto _e = any_unique_type(); _o->any_unique.type = _e; } + { auto _e = any_unique(); if (_e) _o->any_unique.value = MyGame::Example::AnyUniqueAliasesUnion::UnPack(_e, any_unique_type(), _resolver); } + { auto _e = any_ambiguous_type(); _o->any_ambiguous.type = _e; } + { auto _e = any_ambiguous(); if (_e) _o->any_ambiguous.value = MyGame::Example::AnyAmbiguousAliasesUnion::UnPack(_e, any_ambiguous_type(), _resolver); } + { auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast(_e->Get(_i)); } } else { _o->vector_of_enums.resize(0); } } + { auto _e = signed_enum(); _o->signed_enum = _e; } + { auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } } + { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->scalar_key_sorted_tables.resize(0); } } + { auto _e = native_inline(); if (_e) _o->native_inline = *_e; } + { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; } + { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; } + { auto _e = nan_default(); _o->nan_default = _e; } + { auto _e = inf_default(); _o->inf_default = _e; } + { auto _e = positive_inf_default(); _o->positive_inf_default = _e; } + { auto _e = infinity_default(); _o->infinity_default = _e; } + { auto _e = positive_infinity_default(); _o->positive_infinity_default = _e; } + { auto _e = negative_inf_default(); _o->negative_inf_default = _e; } + { auto _e = negative_infinity_default(); _o->negative_infinity_default = _e; } + { auto _e = double_inf_default(); _o->double_inf_default = _e; } +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _pos = _o->pos ? _o->pos.get() : nullptr; + auto _mana = _o->mana; + auto _hp = _o->hp; + auto _name = _fbb.CreateString(_o->name); + auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0; + auto _color = _o->color; + auto _test_type = _o->test.type; + auto _test = _o->test.Pack(_fbb); + auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; + auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testbool = _o->testbool; + auto _testhashs32_fnv1 = _o->testhashs32_fnv1; + auto _testhashu32_fnv1 = _o->testhashu32_fnv1; + auto _testhashs64_fnv1 = _o->testhashs64_fnv1; + auto _testhashu64_fnv1 = _o->testhashu64_fnv1; + auto _testhashs32_fnv1a = _o->testhashs32_fnv1a; + auto _testhashu32_fnv1a = _rehasher ? static_cast((*_rehasher)(_o->testhashu32_fnv1a)) : 0; + auto _testhashs64_fnv1a = _o->testhashs64_fnv1a; + auto _testhashu64_fnv1a = _o->testhashu64_fnv1a; + auto _testarrayofbools = _o->testarrayofbools.size() ? _fbb.CreateVector(_o->testarrayofbools) : 0; + auto _testf = _o->testf; + auto _testf2 = _o->testf2; + auto _testf3 = _o->testf3; + auto _testarrayofstring2 = _o->testarrayofstring2.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring2) : 0; + auto _testarrayofsortedstruct = _o->testarrayofsortedstruct.size() ? _fbb.CreateVectorOfStructs(_o->testarrayofsortedstruct) : 0; + auto _flex = _o->flex.size() ? _fbb.CreateVector(_o->flex) : 0; + auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; + auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; + auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; + auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; + auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; + auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; + auto _vector_of_non_owning_references = _o->vector_of_non_owning_references.size() ? _fbb.CreateVector(_o->vector_of_non_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_non_owning_references[i])) : 0; }, &_va ) : 0; + auto _any_unique_type = _o->any_unique.type; + auto _any_unique = _o->any_unique.Pack(_fbb); + auto _any_ambiguous_type = _o->any_ambiguous.type; + auto _any_ambiguous = _o->any_ambiguous.Pack(_fbb); + auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; + auto _signed_enum = _o->signed_enum; + auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _native_inline = &_o->native_inline; + auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; + auto _long_enum_normal_default = _o->long_enum_normal_default; + auto _nan_default = _o->nan_default; + auto _inf_default = _o->inf_default; + auto _positive_inf_default = _o->positive_inf_default; + auto _infinity_default = _o->infinity_default; + auto _positive_infinity_default = _o->positive_infinity_default; + auto _negative_inf_default = _o->negative_inf_default; + auto _negative_infinity_default = _o->negative_infinity_default; + auto _double_inf_default = _o->double_inf_default; + return MyGame::Example::CreateMonster( + _fbb, + _pos, + _mana, + _hp, + _name, + _inventory, + _color, + _test_type, + _test, + _test4, + _testarrayofstring, + _testarrayoftables, + _enemy, + _testnestedflatbuffer, + _testempty, + _testbool, + _testhashs32_fnv1, + _testhashu32_fnv1, + _testhashs64_fnv1, + _testhashu64_fnv1, + _testhashs32_fnv1a, + _testhashu32_fnv1a, + _testhashs64_fnv1a, + _testhashu64_fnv1a, + _testarrayofbools, + _testf, + _testf2, + _testf3, + _testarrayofstring2, + _testarrayofsortedstruct, + _flex, + _test5, + _vector_of_longs, + _vector_of_doubles, + _parent_namespace_test, + _vector_of_referrables, + _single_weak_reference, + _vector_of_weak_references, + _vector_of_strong_referrables, + _co_owning_reference, + _vector_of_co_owning_references, + _non_owning_reference, + _vector_of_non_owning_references, + _any_unique_type, + _any_unique, + _any_ambiguous_type, + _any_ambiguous, + _vector_of_enums, + _signed_enum, + _testrequirednestedflatbuffer, + _scalar_key_sorted_tables, + _native_inline, + _long_enum_non_enum_default, + _long_enum_normal_default, + _nan_default, + _inf_default, + _positive_inf_default, + _infinity_default, + _positive_infinity_default, + _negative_inf_default, + _negative_infinity_default, + _double_inf_default); +} + + +inline bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return + (lhs.i8 == rhs.i8) && + (lhs.u8 == rhs.u8) && + (lhs.i16 == rhs.i16) && + (lhs.u16 == rhs.u16) && + (lhs.i32 == rhs.i32) && + (lhs.u32 == rhs.u32) && + (lhs.i64 == rhs.i64) && + (lhs.u64 == rhs.u64) && + (lhs.f32 == rhs.f32) && + (lhs.f64 == rhs.f64) && + (lhs.v8 == rhs.v8) && + (lhs.vf64 == rhs.vf64); +} + +inline bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return !(lhs == rhs); +} + + +inline TypeAliasesT *TypeAliases::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TypeAliasesT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TypeAliases::UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = i8(); _o->i8 = _e; } + { auto _e = u8(); _o->u8 = _e; } + { auto _e = i16(); _o->i16 = _e; } + { auto _e = u16(); _o->u16 = _e; } + { auto _e = i32(); _o->i32 = _e; } + { auto _e = u32(); _o->u32 = _e; } + { auto _e = i64(); _o->i64 = _e; } + { auto _e = u64(); _o->u64 = _e; } + { auto _e = f32(); _o->f32 = _e; } + { auto _e = f64(); _o->f64 = _e; } + { auto _e = v8(); if (_e) { _o->v8.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->v8.begin()); } } + { auto _e = vf64(); if (_e) { _o->vf64.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vf64[_i] = _e->Get(_i); } } else { _o->vf64.resize(0); } } +} + +inline ::flatbuffers::Offset TypeAliases::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTypeAliases(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TypeAliasesT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _i8 = _o->i8; + auto _u8 = _o->u8; + auto _i16 = _o->i16; + auto _u16 = _o->u16; + auto _i32 = _o->i32; + auto _u32 = _o->u32; + auto _i64 = _o->i64; + auto _u64 = _o->u64; + auto _f32 = _o->f32; + auto _f64 = _o->f64; + auto _v8 = _o->v8.size() ? _fbb.CreateVector(_o->v8) : 0; + auto _vf64 = _o->vf64.size() ? _fbb.CreateVector(_o->vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + _i8, + _u8, + _i16, + _u16, + _i32, + _u32, + _i64, + _u64, + _f32, + _f64, + _v8, + _vf64); +} + +inline bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type) { + switch (type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAny( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUnion::UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Any_Monster: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case Any_TestSimpleTableWithEnum: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case Any_MyGame_Example2_Monster: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUnion::Reset() { + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Any_NONE; +} + +inline bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type) { + switch (type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyUniqueAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUniqueAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyUniqueAliases_M: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_TS: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_M2: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUniqueAliasesUnion::Reset() { + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyUniqueAliases_NONE; +} + +inline bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type) { + switch (type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyAmbiguousAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyAmbiguousAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyAmbiguousAliases_M1: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M2: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M3: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyAmbiguousAliasesUnion::Reset() { + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyAmbiguousAliases_NONE; +} + +inline const ::flatbuffers::TypeTable *ColorTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const int64_t values[] = { 1, 2, 8 }; + static const char * const names[] = { + "Red", + "Green", + "Blue" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RaceTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::RaceTypeTable + }; + static const int64_t values[] = { -1, 0, 1, 2 }; + static const char * const names[] = { + "None", + "Human", + "Dwarf", + "Elf" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 4, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *LongEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::LongEnumTypeTable + }; + static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL }; + static const char * const names[] = { + "LongOne", + "LongTwo", + "LongBig" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyUniqueAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M", + "TS", + "M2" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyAmbiguousAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M1", + "M2", + "M3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 } + }; + static const int64_t values[] = { 0, 2, 4 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const char * const names[] = { + "color" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *Vec3TypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 4, 8, 16, 24, 26, 32 }; + static const char * const names[] = { + "x", + "y", + "z", + "test1", + "test2", + "test3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 6, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AbilityTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "id", + "distance" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::AbilityTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 8, 12, 20 }; + static const char * const names[] = { + "a", + "b", + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::StructOfStructsTypeTable + }; + static const int64_t values[] = { 0, 20 }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StatTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 } + }; + static const char * const names[] = { + "id", + "val", + "count" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, -1 } + }; + static const char * const names[] = { + "id" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 1 }, + { ::flatbuffers::ET_UTYPE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 4 }, + { ::flatbuffers::ET_SEQUENCE, 0, 4 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 5 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_BOOL, 1, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 6 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_LONG, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 7 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_UTYPE, 0, 9 }, + { ::flatbuffers::ET_SEQUENCE, 0, 9 }, + { ::flatbuffers::ET_UTYPE, 0, 10 }, + { ::flatbuffers::ET_SEQUENCE, 0, 10 }, + { ::flatbuffers::ET_UCHAR, 1, 1 }, + { ::flatbuffers::ET_CHAR, 0, 11 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 5 }, + { ::flatbuffers::ET_SEQUENCE, 0, 3 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::Vec3TypeTable, + MyGame::Example::ColorTypeTable, + MyGame::Example::AnyTypeTable, + MyGame::Example::TestTypeTable, + MyGame::Example::MonsterTypeTable, + MyGame::Example::StatTypeTable, + MyGame::Example::AbilityTypeTable, + MyGame::InParentNamespaceTypeTable, + MyGame::Example::ReferrableTypeTable, + MyGame::Example::AnyUniqueAliasesTypeTable, + MyGame::Example::AnyAmbiguousAliasesTypeTable, + MyGame::Example::RaceTypeTable, + MyGame::Example::LongEnumTypeTable + }; + static const char * const names[] = { + "pos", + "mana", + "hp", + "name", + "friendly", + "inventory", + "color", + "test_type", + "test", + "test4", + "testarrayofstring", + "testarrayoftables", + "enemy", + "testnestedflatbuffer", + "testempty", + "testbool", + "testhashs32_fnv1", + "testhashu32_fnv1", + "testhashs64_fnv1", + "testhashu64_fnv1", + "testhashs32_fnv1a", + "testhashu32_fnv1a", + "testhashs64_fnv1a", + "testhashu64_fnv1a", + "testarrayofbools", + "testf", + "testf2", + "testf3", + "testarrayofstring2", + "testarrayofsortedstruct", + "flex", + "test5", + "vector_of_longs", + "vector_of_doubles", + "parent_namespace_test", + "vector_of_referrables", + "single_weak_reference", + "vector_of_weak_references", + "vector_of_strong_referrables", + "co_owning_reference", + "vector_of_co_owning_references", + "non_owning_reference", + "vector_of_non_owning_references", + "any_unique_type", + "any_unique", + "any_ambiguous_type", + "any_ambiguous", + "vector_of_enums", + "signed_enum", + "testrequirednestedflatbuffer", + "scalar_key_sorted_tables", + "native_inline", + "long_enum_non_enum_default", + "long_enum_normal_default", + "nan_default", + "inf_default", + "positive_inf_default", + "infinity_default", + "positive_infinity_default", + "negative_inf_default", + "negative_infinity_default", + "double_inf_default" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 62, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_CHAR, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 } + }; + static const char * const names[] = { + "i8", + "u8", + "i16", + "u16", + "i32", + "u32", + "i64", + "u64", + "f32", + "f64", + "v8", + "vf64" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 12, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const MyGame::Example::Monster *GetMonster(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const MyGame::Example::Monster *GetSizePrefixedMonster(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Monster *GetMutableMonster(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MonsterIdentifier() { + return "MONS"; +} + +inline bool MonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier()); +} + +inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier(), true); +} + +inline bool VerifyMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MonsterIdentifier()); +} + +inline bool VerifySizePrefixedMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MonsterIdentifier()); +} + +inline const char *MonsterExtension() { + return "mon"; +} + +inline void FinishMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MonsterIdentifier()); +} + +inline void FinishSizePrefixedMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MonsterIdentifier()); +} + +inline std::unique_ptr UnPackMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMonster(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMonster(buf)->UnPack(res)); +} + +} // namespace Example +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ diff --git a/third_party/flatbuffers/tests/monster_test_suffix/monster_test.grpc.fb.cc b/third_party/flatbuffers/tests/monster_test_suffix/monster_test.grpc.fb.cc new file mode 100644 index 00000000000..6680f4f7cf5 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/monster_test.grpc.fb.cc @@ -0,0 +1,131 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test + +#include "monster_test_suffix.hpp" +#include "monster_test.grpc.fb.h" + +#include +#include +#include +#include +#include +#include +#include +#include +namespace MyGame { +namespace Example { + +static const char* MonsterStorage_method_names[] = { + "/MyGame.Example.MonsterStorage/Store", + "/MyGame.Example.MonsterStorage/Retrieve", + "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", +}; + +std::unique_ptr< MonsterStorage::Stub> MonsterStorage::NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& /*options*/) { + std::unique_ptr< MonsterStorage::Stub> stub(new MonsterStorage::Stub(channel)); + return stub; +} + +MonsterStorage::Stub::Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel) + : channel_(channel) , rpcmethod_Store_(MonsterStorage_method_names[0], ::grpc::internal::RpcMethod::NORMAL_RPC, channel) + , rpcmethod_Retrieve_(MonsterStorage_method_names[1], ::grpc::internal::RpcMethod::SERVER_STREAMING, channel) + , rpcmethod_GetMaxHitPoint_(MonsterStorage_method_names[2], ::grpc::internal::RpcMethod::CLIENT_STREAMING, channel) + , rpcmethod_GetMinMaxHitPoints_(MonsterStorage_method_names[3], ::grpc::internal::RpcMethod::BIDI_STREAMING, channel) + {} + +::grpc::Status MonsterStorage::Stub::Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) { + return ::grpc::internal::BlockingUnaryCall(channel_.get(), rpcmethod_Store_, context, request, response); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, true); +} + +::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncResponseReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Store_, context, request, false); +} + +::grpc::ClientReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return ::grpc::internal::ClientReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_Retrieve_, context, request); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, true, tag); +} + +::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_Retrieve_, context, request, false, nullptr); +} + +::grpc::ClientWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return ::grpc::internal::ClientWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMaxHitPoint_, context, response); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, true, tag); +} + +::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncWriterFactory< flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMaxHitPoint_, context, response, false, nullptr); +} + +::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::GetMinMaxHitPointsRaw(::grpc::ClientContext* context) { + return ::grpc::internal::ClientReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), rpcmethod_GetMinMaxHitPoints_, context); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, true, tag); +} + +::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* MonsterStorage::Stub::PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return ::grpc::internal::ClientAsyncReaderWriterFactory< flatbuffers::grpc::Message, flatbuffers::grpc::Message>::Create(channel_.get(), cq, rpcmethod_GetMinMaxHitPoints_, context, false, nullptr); +} + +MonsterStorage::Service::Service() { + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[0], + ::grpc::internal::RpcMethod::NORMAL_RPC, + new ::grpc::internal::RpcMethodHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Store), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[1], + ::grpc::internal::RpcMethod::SERVER_STREAMING, + new ::grpc::internal::ServerStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::Retrieve), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[2], + ::grpc::internal::RpcMethod::CLIENT_STREAMING, + new ::grpc::internal::ClientStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMaxHitPoint), this))); + AddMethod(new ::grpc::internal::RpcServiceMethod( + MonsterStorage_method_names[3], + ::grpc::internal::RpcMethod::BIDI_STREAMING, + new ::grpc::internal::BidiStreamingHandler< MonsterStorage::Service, flatbuffers::grpc::Message, flatbuffers::grpc::Message>( + std::mem_fn(&MonsterStorage::Service::GetMinMaxHitPoints), this))); +} + +MonsterStorage::Service::~Service() { +} + +::grpc::Status MonsterStorage::Service::Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + +::grpc::Status MonsterStorage::Service::GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) { + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); +} + + +} // namespace MyGame +} // namespace Example + diff --git a/third_party/flatbuffers/tests/monster_test_suffix/monster_test.grpc.fb.h b/third_party/flatbuffers/tests/monster_test_suffix/monster_test.grpc.fb.h new file mode 100644 index 00000000000..1b6ab6f4c96 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/monster_test.grpc.fb.h @@ -0,0 +1,350 @@ +// Generated by the gRPC C++ plugin. +// If you make any local change, they will be lost. +// source: monster_test +#ifndef GRPC_monster_5ftest__INCLUDED +#define GRPC_monster_5ftest__INCLUDED + +#include "monster_test_suffix.hpp" +#include "flatbuffers/grpc.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace grpc { +class CompletionQueue; +class Channel; +class ServerCompletionQueue; +class ServerContext; +} // namespace grpc + +namespace MyGame { +namespace Example { + +class MonsterStorage final { + public: + static constexpr char const* service_full_name() { + return "MyGame.Example.MonsterStorage"; + } + class StubInterface { + public: + virtual ~StubInterface() {} + virtual ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) = 0; + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + private: + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientAsyncResponseReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderInterface< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderInterface< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientWriterInterface< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncWriterInterface< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) = 0; + virtual ::grpc::ClientReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) = 0; + virtual ::grpc::ClientAsyncReaderWriterInterface< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) = 0; + }; + class Stub final : public StubInterface { + public: + Stub(const std::shared_ptr< ::grpc::ChannelInterface>& channel); + ::grpc::Status Store(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, flatbuffers::grpc::Message* response) override; + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> AsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(AsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>> PrepareAsyncStore(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>>(PrepareAsyncStoreRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>> Retrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) { + return std::unique_ptr< ::grpc::ClientReader< flatbuffers::grpc::Message>>(RetrieveRaw(context, request)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> AsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(AsyncRetrieveRaw(context, request, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>> PrepareAsyncRetrieve(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>>(PrepareAsyncRetrieveRaw(context, request, cq)); + } + std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>> GetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) { + return std::unique_ptr< ::grpc::ClientWriter< flatbuffers::grpc::Message>>(GetMaxHitPointRaw(context, response)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> AsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(AsyncGetMaxHitPointRaw(context, response, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>> PrepareAsyncGetMaxHitPoint(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>>(PrepareAsyncGetMaxHitPointRaw(context, response, cq)); + } + std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> GetMinMaxHitPoints(::grpc::ClientContext* context) { + return std::unique_ptr< ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(GetMinMaxHitPointsRaw(context)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> AsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(AsyncGetMinMaxHitPointsRaw(context, cq, tag)); + } + std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>> PrepareAsyncGetMinMaxHitPoints(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) { + return std::unique_ptr< ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>>(PrepareAsyncGetMinMaxHitPointsRaw(context, cq)); + } + + private: + std::shared_ptr< ::grpc::ChannelInterface> channel_; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* AsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientAsyncResponseReader< flatbuffers::grpc::Message>* PrepareAsyncStoreRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReader< flatbuffers::grpc::Message>* RetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* AsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReader< flatbuffers::grpc::Message>* PrepareAsyncRetrieveRaw(::grpc::ClientContext* context, const flatbuffers::grpc::Message& request, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientWriter< flatbuffers::grpc::Message>* GetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* AsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncWriter< flatbuffers::grpc::Message>* PrepareAsyncGetMaxHitPointRaw(::grpc::ClientContext* context, flatbuffers::grpc::Message* response, ::grpc::CompletionQueue* cq) override; + ::grpc::ClientReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* GetMinMaxHitPointsRaw(::grpc::ClientContext* context) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* AsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq, void* tag) override; + ::grpc::ClientAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* PrepareAsyncGetMinMaxHitPointsRaw(::grpc::ClientContext* context, ::grpc::CompletionQueue* cq) override; + const ::grpc::internal::RpcMethod rpcmethod_Store_; + const ::grpc::internal::RpcMethod rpcmethod_Retrieve_; + const ::grpc::internal::RpcMethod rpcmethod_GetMaxHitPoint_; + const ::grpc::internal::RpcMethod rpcmethod_GetMinMaxHitPoints_; + }; + static std::unique_ptr NewStub(const std::shared_ptr< ::grpc::ChannelInterface>& channel, const ::grpc::StubOptions& options = ::grpc::StubOptions()); + + class Service : public ::grpc::Service { + public: + Service(); + virtual ~Service(); + virtual ::grpc::Status Store(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, flatbuffers::grpc::Message* response); + virtual ::grpc::Status Retrieve(::grpc::ServerContext* context, const flatbuffers::grpc::Message* request, ::grpc::ServerWriter< flatbuffers::grpc::Message>* writer); + virtual ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerReader< flatbuffers::grpc::Message>* reader, flatbuffers::grpc::Message* response); + virtual ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream); + }; + template + class WithAsyncMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Store() { + ::grpc::Service::MarkMethodAsync(0); + } + ~WithAsyncMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestStore(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncResponseWriter< flatbuffers::grpc::Message>* response, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncUnary(0, context, request, response, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_Retrieve() { + ::grpc::Service::MarkMethodAsync(1); + } + ~WithAsyncMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestRetrieve(::grpc::ServerContext* context, flatbuffers::grpc::Message* request, ::grpc::ServerAsyncWriter< flatbuffers::grpc::Message>* writer, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncServerStreaming(1, context, request, writer, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodAsync(2); + } + ~WithAsyncMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMaxHitPoint(::grpc::ServerContext* context, ::grpc::ServerAsyncReader< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* reader, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncClientStreaming(2, context, reader, new_call_cq, notification_cq, tag); + } + }; + template + class WithAsyncMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithAsyncMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodAsync(3); + } + ~WithAsyncMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + void RequestGetMinMaxHitPoints(::grpc::ServerContext* context, ::grpc::ServerAsyncReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* stream, ::grpc::CompletionQueue* new_call_cq, ::grpc::ServerCompletionQueue* notification_cq, void *tag) { + ::grpc::Service::RequestAsyncBidiStreaming(3, context, stream, new_call_cq, notification_cq, tag); + } + }; + typedef WithAsyncMethod_Store< WithAsyncMethod_Retrieve< WithAsyncMethod_GetMaxHitPoint< WithAsyncMethod_GetMinMaxHitPoints< Service > > > > AsyncService; + template + class WithGenericMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Store() { + ::grpc::Service::MarkMethodGeneric(0); + } + ~WithGenericMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_Retrieve() { + ::grpc::Service::MarkMethodGeneric(1); + } + ~WithGenericMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMaxHitPoint : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMaxHitPoint() { + ::grpc::Service::MarkMethodGeneric(2); + } + ~WithGenericMethod_GetMaxHitPoint() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMaxHitPoint(::grpc::ServerContext* /*context*/, ::grpc::ServerReader< flatbuffers::grpc::Message>* /*reader*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithGenericMethod_GetMinMaxHitPoints : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithGenericMethod_GetMinMaxHitPoints() { + ::grpc::Service::MarkMethodGeneric(3); + } + ~WithGenericMethod_GetMinMaxHitPoints() override { + BaseClassMustBeDerivedFromService(this); + } + // disable synchronous version of this method + ::grpc::Status GetMinMaxHitPoints(::grpc::ServerContext* /*context*/, ::grpc::ServerReaderWriter< flatbuffers::grpc::Message, flatbuffers::grpc::Message>* /*stream*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + }; + template + class WithStreamedUnaryMethod_Store : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) {} + public: + WithStreamedUnaryMethod_Store() { + ::grpc::Service::MarkMethodStreamed(0, + new ::grpc::internal::StreamedUnaryHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithStreamedUnaryMethod_Store::StreamedStore, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithStreamedUnaryMethod_Store() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Store(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, flatbuffers::grpc::Message* /*response*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with streamed unary + virtual ::grpc::Status StreamedStore(::grpc::ServerContext* context, ::grpc::ServerUnaryStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_unary_streamer) = 0; + }; + typedef WithStreamedUnaryMethod_Store< Service > StreamedUnaryService; + template + class WithSplitStreamingMethod_Retrieve : public BaseClass { + private: + void BaseClassMustBeDerivedFromService(const Service */*service*/) { } + public: + WithSplitStreamingMethod_Retrieve() { + ::grpc::Service::MarkMethodStreamed(1, + new ::grpc::internal::SplitServerStreamingHandler< flatbuffers::grpc::Message, flatbuffers::grpc::Message>(std::bind(&WithSplitStreamingMethod_Retrieve::StreamedRetrieve, this, std::placeholders::_1, std::placeholders::_2))); + } + ~WithSplitStreamingMethod_Retrieve() override { + BaseClassMustBeDerivedFromService(this); + } + // disable regular version of this method + ::grpc::Status Retrieve(::grpc::ServerContext* /*context*/, const flatbuffers::grpc::Message* /*request*/, ::grpc::ServerWriter< flatbuffers::grpc::Message>* /*writer*/) final override { + abort(); + return ::grpc::Status(::grpc::StatusCode::UNIMPLEMENTED, ""); + } + // replace default version of method with split streamed + virtual ::grpc::Status StreamedRetrieve(::grpc::ServerContext* context, ::grpc::ServerSplitStreamer< flatbuffers::grpc::Message,flatbuffers::grpc::Message>* server_split_streamer) = 0; + }; + typedef WithSplitStreamingMethod_Retrieve< Service > SplitStreamedService; + typedef WithStreamedUnaryMethod_Store< WithSplitStreamingMethod_Retrieve< Service > > StreamedService; +}; + +} // namespace Example +} // namespace MyGame + + +#endif // GRPC_monster_5ftest__INCLUDED diff --git a/third_party/flatbuffers/tests/monster_test_suffix/monster_test_suffix.hpp b/third_party/flatbuffers/tests/monster_test_suffix/monster_test_suffix.hpp new file mode 100644 index 00000000000..fd292b0f327 --- /dev/null +++ b/third_party/flatbuffers/tests/monster_test_suffix/monster_test_suffix.hpp @@ -0,0 +1,4238 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ +#define FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ + +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/flexbuffers.h" +#include "flatbuffers/flex_flat_util.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace MyGame { + +struct InParentNamespace; +struct InParentNamespaceBuilder; +struct InParentNamespaceT; + +namespace Example2 { + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +} // namespace Example2 + +namespace Example { + +struct Test; + +struct TestSimpleTableWithEnum; +struct TestSimpleTableWithEnumBuilder; +struct TestSimpleTableWithEnumT; + +struct Vec3; + +struct Ability; + +struct StructOfStructs; + +struct StructOfStructsOfStructs; + +struct Stat; +struct StatBuilder; +struct StatT; + +struct Referrable; +struct ReferrableBuilder; +struct ReferrableT; + +struct Monster; +struct MonsterBuilder; +struct MonsterT; + +struct TypeAliases; +struct TypeAliasesBuilder; +struct TypeAliasesT; + +} // namespace Example + +bool operator==(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs); +namespace Example2 { + +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +} // namespace Example2 + +namespace Example { + +bool operator==(const Test &lhs, const Test &rhs); +bool operator!=(const Test &lhs, const Test &rhs); +bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs); +bool operator==(const Vec3 &lhs, const Vec3 &rhs); +bool operator!=(const Vec3 &lhs, const Vec3 &rhs); +bool operator==(const Ability &lhs, const Ability &rhs); +bool operator!=(const Ability &lhs, const Ability &rhs); +bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs); +bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs); +bool operator==(const StatT &lhs, const StatT &rhs); +bool operator!=(const StatT &lhs, const StatT &rhs); +bool operator==(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs); +bool operator==(const MonsterT &lhs, const MonsterT &rhs); +bool operator!=(const MonsterT &lhs, const MonsterT &rhs); +bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs); +bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs); + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable(); + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable(); + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable(); + +inline const ::flatbuffers::TypeTable *Vec3TypeTable(); + +inline const ::flatbuffers::TypeTable *AbilityTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable(); + +inline const ::flatbuffers::TypeTable *StatTypeTable(); + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable(); + +inline const ::flatbuffers::TypeTable *MonsterTypeTable(); + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable(); + +/// Composite components of Monster color. +enum Color : uint8_t { + Color_Red = 1, + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Color_Green = 2, + /// \brief color Blue (1u << 3) + Color_Blue = 8, + Color_NONE = 0, + Color_ANY = 11 +}; + +inline const Color (&EnumValuesColor())[3] { + static const Color values[] = { + Color_Red, + Color_Green, + Color_Blue + }; + return values; +} + +inline const char * const *EnumNamesColor() { + static const char * const names[9] = { + "Red", + "Green", + "", + "", + "", + "", + "", + "Blue", + nullptr + }; + return names; +} + +inline const char *EnumNameColor(Color e) { + if (::flatbuffers::IsOutRange(e, Color_Red, Color_Blue)) return ""; + const size_t index = static_cast(e) - static_cast(Color_Red); + return EnumNamesColor()[index]; +} + +enum Race : int8_t { + Race_None = -1, + Race_Human = 0, + Race_Dwarf = 1, + Race_Elf = 2, + Race_MIN = Race_None, + Race_MAX = Race_Elf +}; + +inline const Race (&EnumValuesRace())[4] { + static const Race values[] = { + Race_None, + Race_Human, + Race_Dwarf, + Race_Elf + }; + return values; +} + +inline const char * const *EnumNamesRace() { + static const char * const names[5] = { + "None", + "Human", + "Dwarf", + "Elf", + nullptr + }; + return names; +} + +inline const char *EnumNameRace(Race e) { + if (::flatbuffers::IsOutRange(e, Race_None, Race_Elf)) return ""; + const size_t index = static_cast(e) - static_cast(Race_None); + return EnumNamesRace()[index]; +} + +enum LongEnum : uint64_t { + LongEnum_LongOne = 2ULL, + LongEnum_LongTwo = 4ULL, + LongEnum_LongBig = 1099511627776ULL, + LongEnum_NONE = 0, + LongEnum_ANY = 1099511627782ULL +}; + +inline const LongEnum (&EnumValuesLongEnum())[3] { + static const LongEnum values[] = { + LongEnum_LongOne, + LongEnum_LongTwo, + LongEnum_LongBig + }; + return values; +} + +inline const char *EnumNameLongEnum(LongEnum e) { + switch (e) { + case LongEnum_LongOne: return "LongOne"; + case LongEnum_LongTwo: return "LongTwo"; + case LongEnum_LongBig: return "LongBig"; + default: return ""; + } +} + +enum Any : uint8_t { + Any_NONE = 0, + Any_Monster = 1, + Any_TestSimpleTableWithEnum = 2, + Any_MyGame_Example2_Monster = 3, + Any_MIN = Any_NONE, + Any_MAX = Any_MyGame_Example2_Monster +}; + +inline const Any (&EnumValuesAny())[4] { + static const Any values[] = { + Any_NONE, + Any_Monster, + Any_TestSimpleTableWithEnum, + Any_MyGame_Example2_Monster + }; + return values; +} + +inline const char * const *EnumNamesAny() { + static const char * const names[5] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster", + nullptr + }; + return names; +} + +inline const char *EnumNameAny(Any e) { + if (::flatbuffers::IsOutRange(e, Any_NONE, Any_MyGame_Example2_Monster)) return ""; + const size_t index = static_cast(e); + return EnumNamesAny()[index]; +} + +template struct AnyTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +template struct AnyUnionTraits { + static const Any enum_value = Any_NONE; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_Monster; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_TestSimpleTableWithEnum; +}; + +template<> struct AnyUnionTraits { + static const Any enum_value = Any_MyGame_Example2_Monster; +}; + +struct AnyUnion { + Any type; + void *value; + + AnyUnion() : type(Any_NONE), value(nullptr) {} + AnyUnion(AnyUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Any_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUnion(const AnyUnion &); + AnyUnion &operator=(const AnyUnion &u) + { AnyUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUnion &operator=(AnyUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUnionTraits::enum_value; + if (type != Any_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsMonster() { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsMonster() const { + return type == Any_Monster ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTestSimpleTableWithEnum() const { + return type == Any_TestSimpleTableWithEnum ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsMyGame_Example2_Monster() const { + return type == Any_MyGame_Example2_Monster ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUnion &lhs, const AnyUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_TestSimpleTableWithEnum: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Any_MyGame_Example2_Monster: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUnion &lhs, const AnyUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type); +bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyUniqueAliases : uint8_t { + AnyUniqueAliases_NONE = 0, + AnyUniqueAliases_M = 1, + AnyUniqueAliases_TS = 2, + AnyUniqueAliases_M2 = 3, + AnyUniqueAliases_MIN = AnyUniqueAliases_NONE, + AnyUniqueAliases_MAX = AnyUniqueAliases_M2 +}; + +inline const AnyUniqueAliases (&EnumValuesAnyUniqueAliases())[4] { + static const AnyUniqueAliases values[] = { + AnyUniqueAliases_NONE, + AnyUniqueAliases_M, + AnyUniqueAliases_TS, + AnyUniqueAliases_M2 + }; + return values; +} + +inline const char * const *EnumNamesAnyUniqueAliases() { + static const char * const names[5] = { + "NONE", + "M", + "TS", + "M2", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyUniqueAliases(AnyUniqueAliases e) { + if (::flatbuffers::IsOutRange(e, AnyUniqueAliases_NONE, AnyUniqueAliases_M2)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyUniqueAliases()[index]; +} + +template struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +template struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_NONE; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_TS; +}; + +template<> struct AnyUniqueAliasesUnionTraits { + static const AnyUniqueAliases enum_value = AnyUniqueAliases_M2; +}; + +struct AnyUniqueAliasesUnion { + AnyUniqueAliases type; + void *value; + + AnyUniqueAliasesUnion() : type(AnyUniqueAliases_NONE), value(nullptr) {} + AnyUniqueAliasesUnion(AnyUniqueAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyUniqueAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &); + AnyUniqueAliasesUnion &operator=(const AnyUniqueAliasesUnion &u) + { AnyUniqueAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyUniqueAliasesUnion &operator=(AnyUniqueAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyUniqueAliasesUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = AnyUniqueAliasesUnionTraits::enum_value; + if (type != AnyUniqueAliases_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM() { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM() const { + return type == AnyUniqueAliases_M ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::TestSimpleTableWithEnumT *AsTS() { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnumT *AsTS() const { + return type == AnyUniqueAliases_TS ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example2::MonsterT *AsM2() { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example2::MonsterT *AsM2() const { + return type == AnyUniqueAliases_M2 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_TS: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyUniqueAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyUniqueAliasesUnion &lhs, const AnyUniqueAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type); +bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum AnyAmbiguousAliases : uint8_t { + AnyAmbiguousAliases_NONE = 0, + AnyAmbiguousAliases_M1 = 1, + AnyAmbiguousAliases_M2 = 2, + AnyAmbiguousAliases_M3 = 3, + AnyAmbiguousAliases_MIN = AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_MAX = AnyAmbiguousAliases_M3 +}; + +inline const AnyAmbiguousAliases (&EnumValuesAnyAmbiguousAliases())[4] { + static const AnyAmbiguousAliases values[] = { + AnyAmbiguousAliases_NONE, + AnyAmbiguousAliases_M1, + AnyAmbiguousAliases_M2, + AnyAmbiguousAliases_M3 + }; + return values; +} + +inline const char * const *EnumNamesAnyAmbiguousAliases() { + static const char * const names[5] = { + "NONE", + "M1", + "M2", + "M3", + nullptr + }; + return names; +} + +inline const char *EnumNameAnyAmbiguousAliases(AnyAmbiguousAliases e) { + if (::flatbuffers::IsOutRange(e, AnyAmbiguousAliases_NONE, AnyAmbiguousAliases_M3)) return ""; + const size_t index = static_cast(e); + return EnumNamesAnyAmbiguousAliases()[index]; +} + +struct AnyAmbiguousAliasesUnion { + AnyAmbiguousAliases type; + void *value; + + AnyAmbiguousAliasesUnion() : type(AnyAmbiguousAliases_NONE), value(nullptr) {} + AnyAmbiguousAliasesUnion(AnyAmbiguousAliasesUnion&& u) FLATBUFFERS_NOEXCEPT : + type(AnyAmbiguousAliases_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &); + AnyAmbiguousAliasesUnion &operator=(const AnyAmbiguousAliasesUnion &u) + { AnyAmbiguousAliasesUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + AnyAmbiguousAliasesUnion &operator=(AnyAmbiguousAliasesUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~AnyAmbiguousAliasesUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + MyGame::Example::MonsterT *AsM1() { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM1() const { + return type == AnyAmbiguousAliases_M1 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM2() { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM2() const { + return type == AnyAmbiguousAliases_M2 ? + reinterpret_cast(value) : nullptr; + } + MyGame::Example::MonsterT *AsM3() { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } + const MyGame::Example::MonsterT *AsM3() const { + return type == AnyAmbiguousAliases_M3 ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M2: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case AnyAmbiguousAliases_M3: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const AnyAmbiguousAliasesUnion &lhs, const AnyAmbiguousAliasesUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type); +bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(2) Test FLATBUFFERS_FINAL_CLASS { + private: + int16_t a_; + int8_t b_; + int8_t padding0__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestTypeTable(); + } + Test() + : a_(0), + b_(0), + padding0__(0) { + (void)padding0__; + } + Test(int16_t _a, int8_t _b) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)), + padding0__(0) { + (void)padding0__; + } + int16_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int16_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + int8_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(int8_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(Test, 4); + +inline bool operator==(const Test &lhs, const Test &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const Test &lhs, const Test &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(8) Vec3 FLATBUFFERS_FINAL_CLASS { + private: + float x_; + float y_; + float z_; + int32_t padding0__; + double test1_; + uint8_t test2_; + int8_t padding1__; + MyGame::Example::Test test3_; + int16_t padding2__; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vec3TypeTable(); + } + Vec3() + : x_(0), + y_(0), + z_(0), + padding0__(0), + test1_(0), + test2_(0), + padding1__(0), + test3_(), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + Vec3(float _x, float _y, float _z, double _test1, MyGame::Example::Color _test2, const MyGame::Example::Test &_test3) + : x_(::flatbuffers::EndianScalar(_x)), + y_(::flatbuffers::EndianScalar(_y)), + z_(::flatbuffers::EndianScalar(_z)), + padding0__(0), + test1_(::flatbuffers::EndianScalar(_test1)), + test2_(::flatbuffers::EndianScalar(static_cast(_test2))), + padding1__(0), + test3_(_test3), + padding2__(0) { + (void)padding0__; + (void)padding1__; + (void)padding2__; + } + float x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(float _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } + float y() const { + return ::flatbuffers::EndianScalar(y_); + } + void mutate_y(float _y) { + ::flatbuffers::WriteScalar(&y_, _y); + } + float z() const { + return ::flatbuffers::EndianScalar(z_); + } + void mutate_z(float _z) { + ::flatbuffers::WriteScalar(&z_, _z); + } + double test1() const { + return ::flatbuffers::EndianScalar(test1_); + } + void mutate_test1(double _test1) { + ::flatbuffers::WriteScalar(&test1_, _test1); + } + MyGame::Example::Color test2() const { + return static_cast(::flatbuffers::EndianScalar(test2_)); + } + void mutate_test2(MyGame::Example::Color _test2) { + ::flatbuffers::WriteScalar(&test2_, static_cast(_test2)); + } + const MyGame::Example::Test &test3() const { + return test3_; + } + MyGame::Example::Test &mutable_test3() { + return test3_; + } +}; +FLATBUFFERS_STRUCT_END(Vec3, 32); + +inline bool operator==(const Vec3 &lhs, const Vec3 &rhs) { + return + (lhs.x() == rhs.x()) && + (lhs.y() == rhs.y()) && + (lhs.z() == rhs.z()) && + (lhs.test1() == rhs.test1()) && + (lhs.test2() == rhs.test2()) && + (lhs.test3() == rhs.test3()); +} + +inline bool operator!=(const Vec3 &lhs, const Vec3 &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Ability FLATBUFFERS_FINAL_CLASS { + private: + uint32_t id_; + uint32_t distance_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AbilityTypeTable(); + } + Ability() + : id_(0), + distance_(0) { + } + Ability(uint32_t _id, uint32_t _distance) + : id_(::flatbuffers::EndianScalar(_id)), + distance_(::flatbuffers::EndianScalar(_distance)) { + } + uint32_t id() const { + return ::flatbuffers::EndianScalar(id_); + } + void mutate_id(uint32_t _id) { + ::flatbuffers::WriteScalar(&id_, _id); + } + bool KeyCompareLessThan(const Ability * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint32_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + uint32_t distance() const { + return ::flatbuffers::EndianScalar(distance_); + } + void mutate_distance(uint32_t _distance) { + ::flatbuffers::WriteScalar(&distance_, _distance); + } +}; +FLATBUFFERS_STRUCT_END(Ability, 8); + +inline bool operator==(const Ability &lhs, const Ability &rhs) { + return + (lhs.id() == rhs.id()) && + (lhs.distance() == rhs.distance()); +} + +inline bool operator!=(const Ability &lhs, const Ability &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::Ability a_; + MyGame::Example::Test b_; + MyGame::Example::Ability c_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsTypeTable(); + } + StructOfStructs() + : a_(), + b_(), + c_() { + } + StructOfStructs(const MyGame::Example::Ability &_a, const MyGame::Example::Test &_b, const MyGame::Example::Ability &_c) + : a_(_a), + b_(_b), + c_(_c) { + } + const MyGame::Example::Ability &a() const { + return a_; + } + MyGame::Example::Ability &mutable_a() { + return a_; + } + const MyGame::Example::Test &b() const { + return b_; + } + MyGame::Example::Test &mutable_b() { + return b_; + } + const MyGame::Example::Ability &c() const { + return c_; + } + MyGame::Example::Ability &mutable_c() { + return c_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructs, 20); + +inline bool operator==(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()) && + (lhs.c() == rhs.c()); +} + +inline bool operator!=(const StructOfStructs &lhs, const StructOfStructs &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructOfStructsOfStructs FLATBUFFERS_FINAL_CLASS { + private: + MyGame::Example::StructOfStructs a_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructOfStructsOfStructsTypeTable(); + } + StructOfStructsOfStructs() + : a_() { + } + StructOfStructsOfStructs(const MyGame::Example::StructOfStructs &_a) + : a_(_a) { + } + const MyGame::Example::StructOfStructs &a() const { + return a_; + } + MyGame::Example::StructOfStructs &mutable_a() { + return a_; + } +}; +FLATBUFFERS_STRUCT_END(StructOfStructsOfStructs, 20); + +inline bool operator==(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return + (lhs.a() == rhs.a()); +} + +inline bool operator!=(const StructOfStructsOfStructs &lhs, const StructOfStructsOfStructs &rhs) { + return !(lhs == rhs); +} + + +} // namespace Example + +struct InParentNamespaceT : public ::flatbuffers::NativeTable { + typedef InParentNamespace TableType; +}; + +struct InParentNamespace FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef InParentNamespaceT NativeTableType; + typedef InParentNamespaceBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return InParentNamespaceTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + InParentNamespaceT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct InParentNamespaceBuilder { + typedef InParentNamespace Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit InParentNamespaceBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateInParentNamespace( + ::flatbuffers::FlatBufferBuilder &_fbb) { + InParentNamespaceBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +namespace Example2 { + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; +}; + +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb) { + MonsterBuilder builder_(_fbb); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example2 + +namespace Example { + +struct TestSimpleTableWithEnumT : public ::flatbuffers::NativeTable { + typedef TestSimpleTableWithEnum TableType; + MyGame::Example::Color color = MyGame::Example::Color_Green; +}; + +struct TestSimpleTableWithEnum FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TestSimpleTableWithEnumT NativeTableType; + typedef TestSimpleTableWithEnumBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestSimpleTableWithEnumTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_COLOR = 4 + }; + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 2)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(2)) { + return SetField(VT_COLOR, static_cast(_color), 2); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_COLOR, 1) && + verifier.EndTable(); + } + TestSimpleTableWithEnumT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TestSimpleTableWithEnumBuilder { + typedef TestSimpleTableWithEnum Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(TestSimpleTableWithEnum::VT_COLOR, static_cast(color), 2); + } + explicit TestSimpleTableWithEnumBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum( + ::flatbuffers::FlatBufferBuilder &_fbb, + MyGame::Example::Color color = MyGame::Example::Color_Green) { + TestSimpleTableWithEnumBuilder builder_(_fbb); + builder_.add_color(color); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct StatT : public ::flatbuffers::NativeTable { + typedef Stat TableType; + std::string id{}; + int64_t val = 0; + uint16_t count = 0; +}; + +struct Stat FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef StatT NativeTableType; + typedef StatBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StatTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4, + VT_VAL = 6, + VT_COUNT = 8 + }; + const ::flatbuffers::String *id() const { + return GetPointer(VT_ID); + } + ::flatbuffers::String *mutable_id() { + return GetPointer<::flatbuffers::String *>(VT_ID); + } + int64_t val() const { + return GetField(VT_VAL, 0); + } + bool mutate_val(int64_t _val = 0) { + return SetField(VT_VAL, _val, 0); + } + uint16_t count() const { + return GetField(VT_COUNT, 0); + } + bool mutate_count(uint16_t _count = 0) { + return SetField(VT_COUNT, _count, 0); + } + bool KeyCompareLessThan(const Stat * const o) const { + return count() < o->count(); + } + int KeyCompareWithValue(uint16_t _count) const { + return static_cast(count() > _count) - static_cast(count() < _count); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_ID) && + verifier.VerifyString(id()) && + VerifyField(verifier, VT_VAL, 8) && + VerifyField(verifier, VT_COUNT, 2) && + verifier.EndTable(); + } + StatT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct StatBuilder { + typedef Stat Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(::flatbuffers::Offset<::flatbuffers::String> id) { + fbb_.AddOffset(Stat::VT_ID, id); + } + void add_val(int64_t val) { + fbb_.AddElement(Stat::VT_VAL, val, 0); + } + void add_count(uint16_t count) { + fbb_.AddElement(Stat::VT_COUNT, count, 0); + } + explicit StatBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateStat( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> id = 0, + int64_t val = 0, + uint16_t count = 0) { + StatBuilder builder_(_fbb); + builder_.add_val(val); + builder_.add_id(id); + builder_.add_count(count); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateStatDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *id = nullptr, + int64_t val = 0, + uint16_t count = 0) { + auto id__ = id ? _fbb.CreateString(id) : 0; + return MyGame::Example::CreateStat( + _fbb, + id__, + val, + count); +} + +::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct ReferrableT : public ::flatbuffers::NativeTable { + typedef Referrable TableType; + uint64_t id = 0; +}; + +struct Referrable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ReferrableT NativeTableType; + typedef ReferrableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ReferrableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_ID = 4 + }; + uint64_t id() const { + return GetField(VT_ID, 0); + } + bool mutate_id(uint64_t _id = 0) { + return SetField(VT_ID, _id, 0); + } + bool KeyCompareLessThan(const Referrable * const o) const { + return id() < o->id(); + } + int KeyCompareWithValue(uint64_t _id) const { + return static_cast(id() > _id) - static_cast(id() < _id); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_ID, 8) && + verifier.EndTable(); + } + ReferrableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ReferrableBuilder { + typedef Referrable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_id(uint64_t id) { + fbb_.AddElement(Referrable::VT_ID, id, 0); + } + explicit ReferrableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateReferrable( + ::flatbuffers::FlatBufferBuilder &_fbb, + uint64_t id = 0) { + ReferrableBuilder builder_(_fbb); + builder_.add_id(id); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MonsterT : public ::flatbuffers::NativeTable { + typedef Monster TableType; + std::unique_ptr pos{}; + int16_t mana = 150; + int16_t hp = 100; + std::string name{}; + std::vector inventory{}; + MyGame::Example::Color color = MyGame::Example::Color_Blue; + MyGame::Example::AnyUnion test{}; + std::vector test4{}; + std::vector testarrayofstring{}; + std::vector> testarrayoftables{}; + std::unique_ptr enemy{}; + std::vector testnestedflatbuffer{}; + std::unique_ptr testempty{}; + bool testbool = false; + int32_t testhashs32_fnv1 = 0; + uint32_t testhashu32_fnv1 = 0; + int64_t testhashs64_fnv1 = 0; + uint64_t testhashu64_fnv1 = 0; + int32_t testhashs32_fnv1a = 0; + Stat *testhashu32_fnv1a = nullptr; + int64_t testhashs64_fnv1a = 0; + uint64_t testhashu64_fnv1a = 0; + std::vector testarrayofbools{}; + float testf = 3.14159f; + float testf2 = 3.0f; + float testf3 = 0.0f; + std::vector testarrayofstring2{}; + std::vector testarrayofsortedstruct{}; + std::vector flex{}; + std::vector test5{}; + std::vector vector_of_longs{}; + std::vector vector_of_doubles{}; + std::unique_ptr parent_namespace_test{}; + std::vector> vector_of_referrables{}; + ReferrableT *single_weak_reference = nullptr; + std::vector vector_of_weak_references{}; + std::vector> vector_of_strong_referrables{}; + ReferrableT *co_owning_reference = nullptr; + std::vector> vector_of_co_owning_references{}; + ReferrableT *non_owning_reference = nullptr; + std::vector vector_of_non_owning_references{}; + MyGame::Example::AnyUniqueAliasesUnion any_unique{}; + MyGame::Example::AnyAmbiguousAliasesUnion any_ambiguous{}; + std::vector vector_of_enums{}; + MyGame::Example::Race signed_enum = MyGame::Example::Race_None; + std::vector testrequirednestedflatbuffer{}; + std::vector> scalar_key_sorted_tables{}; + MyGame::Example::Test native_inline{}; + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0); + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne; + float nan_default = std::numeric_limits::quiet_NaN(); + float inf_default = std::numeric_limits::infinity(); + float positive_inf_default = std::numeric_limits::infinity(); + float infinity_default = std::numeric_limits::infinity(); + float positive_infinity_default = std::numeric_limits::infinity(); + float negative_inf_default = -std::numeric_limits::infinity(); + float negative_infinity_default = -std::numeric_limits::infinity(); + double double_inf_default = std::numeric_limits::infinity(); + MonsterT() = default; + MonsterT(const MonsterT &o); + MonsterT(MonsterT&&) FLATBUFFERS_NOEXCEPT = default; + MonsterT &operator=(MonsterT o) FLATBUFFERS_NOEXCEPT; +}; + +/// an example documentation comment: "monster object" +struct Monster FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MonsterT NativeTableType; + typedef MonsterBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MonsterTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_POS = 4, + VT_MANA = 6, + VT_HP = 8, + VT_NAME = 10, + VT_INVENTORY = 14, + VT_COLOR = 16, + VT_TEST_TYPE = 18, + VT_TEST = 20, + VT_TEST4 = 22, + VT_TESTARRAYOFSTRING = 24, + VT_TESTARRAYOFTABLES = 26, + VT_ENEMY = 28, + VT_TESTNESTEDFLATBUFFER = 30, + VT_TESTEMPTY = 32, + VT_TESTBOOL = 34, + VT_TESTHASHS32_FNV1 = 36, + VT_TESTHASHU32_FNV1 = 38, + VT_TESTHASHS64_FNV1 = 40, + VT_TESTHASHU64_FNV1 = 42, + VT_TESTHASHS32_FNV1A = 44, + VT_TESTHASHU32_FNV1A = 46, + VT_TESTHASHS64_FNV1A = 48, + VT_TESTHASHU64_FNV1A = 50, + VT_TESTARRAYOFBOOLS = 52, + VT_TESTF = 54, + VT_TESTF2 = 56, + VT_TESTF3 = 58, + VT_TESTARRAYOFSTRING2 = 60, + VT_TESTARRAYOFSORTEDSTRUCT = 62, + VT_FLEX = 64, + VT_TEST5 = 66, + VT_VECTOR_OF_LONGS = 68, + VT_VECTOR_OF_DOUBLES = 70, + VT_PARENT_NAMESPACE_TEST = 72, + VT_VECTOR_OF_REFERRABLES = 74, + VT_SINGLE_WEAK_REFERENCE = 76, + VT_VECTOR_OF_WEAK_REFERENCES = 78, + VT_VECTOR_OF_STRONG_REFERRABLES = 80, + VT_CO_OWNING_REFERENCE = 82, + VT_VECTOR_OF_CO_OWNING_REFERENCES = 84, + VT_NON_OWNING_REFERENCE = 86, + VT_VECTOR_OF_NON_OWNING_REFERENCES = 88, + VT_ANY_UNIQUE_TYPE = 90, + VT_ANY_UNIQUE = 92, + VT_ANY_AMBIGUOUS_TYPE = 94, + VT_ANY_AMBIGUOUS = 96, + VT_VECTOR_OF_ENUMS = 98, + VT_SIGNED_ENUM = 100, + VT_TESTREQUIREDNESTEDFLATBUFFER = 102, + VT_SCALAR_KEY_SORTED_TABLES = 104, + VT_NATIVE_INLINE = 106, + VT_LONG_ENUM_NON_ENUM_DEFAULT = 108, + VT_LONG_ENUM_NORMAL_DEFAULT = 110, + VT_NAN_DEFAULT = 112, + VT_INF_DEFAULT = 114, + VT_POSITIVE_INF_DEFAULT = 116, + VT_INFINITY_DEFAULT = 118, + VT_POSITIVE_INFINITY_DEFAULT = 120, + VT_NEGATIVE_INF_DEFAULT = 122, + VT_NEGATIVE_INFINITY_DEFAULT = 124, + VT_DOUBLE_INF_DEFAULT = 126 + }; + const MyGame::Example::Vec3 *pos() const { + return GetStruct(VT_POS); + } + MyGame::Example::Vec3 *mutable_pos() { + return GetStruct(VT_POS); + } + int16_t mana() const { + return GetField(VT_MANA, 150); + } + bool mutate_mana(int16_t _mana = 150) { + return SetField(VT_MANA, _mana, 150); + } + int16_t hp() const { + return GetField(VT_HP, 100); + } + bool mutate_hp(int16_t _hp = 100) { + return SetField(VT_HP, _hp, 100); + } + const ::flatbuffers::String *name() const { + return GetPointer(VT_NAME); + } + ::flatbuffers::String *mutable_name() { + return GetPointer<::flatbuffers::String *>(VT_NAME); + } + bool KeyCompareLessThan(const Monster * const o) const { + return *name() < *o->name(); + } + int KeyCompareWithValue(const char *_name) const { + return strcmp(name()->c_str(), _name); + } + template + int KeyCompareWithValue(const StringType& _name) const { + if (name()->c_str() < _name) return -1; + if (_name < name()->c_str()) return 1; + return 0; + } + const ::flatbuffers::Vector *inventory() const { + return GetPointer *>(VT_INVENTORY); + } + ::flatbuffers::Vector *mutable_inventory() { + return GetPointer<::flatbuffers::Vector *>(VT_INVENTORY); + } + MyGame::Example::Color color() const { + return static_cast(GetField(VT_COLOR, 8)); + } + bool mutate_color(MyGame::Example::Color _color = static_cast(8)) { + return SetField(VT_COLOR, static_cast(_color), 8); + } + MyGame::Example::Any test_type() const { + return static_cast(GetField(VT_TEST_TYPE, 0)); + } + const void *test() const { + return GetPointer(VT_TEST); + } + template const T *test_as() const; + const MyGame::Example::Monster *test_as_Monster() const { + return test_type() == MyGame::Example::Any_Monster ? static_cast(test()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *test_as_TestSimpleTableWithEnum() const { + return test_type() == MyGame::Example::Any_TestSimpleTableWithEnum ? static_cast(test()) : nullptr; + } + const MyGame::Example2::Monster *test_as_MyGame_Example2_Monster() const { + return test_type() == MyGame::Example::Any_MyGame_Example2_Monster ? static_cast(test()) : nullptr; + } + void *mutable_test() { + return GetPointer(VT_TEST); + } + const ::flatbuffers::Vector *test4() const { + return GetPointer *>(VT_TEST4); + } + ::flatbuffers::Vector *mutable_test4() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST4); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING); + } + /// an example documentation comment: this will end up in the generated code + /// multiline too + const ::flatbuffers::Vector<::flatbuffers::Offset> *testarrayoftables() const { + return GetPointer> *>(VT_TESTARRAYOFTABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_testarrayoftables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_TESTARRAYOFTABLES); + } + const MyGame::Example::Monster *enemy() const { + return GetPointer(VT_ENEMY); + } + MyGame::Example::Monster *mutable_enemy() { + return GetPointer(VT_ENEMY); + } + const ::flatbuffers::Vector *testnestedflatbuffer() const { + return GetPointer *>(VT_TESTNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testnestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testnestedflatbuffer_nested_root() const { + const auto _f = testnestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const MyGame::Example::Stat *testempty() const { + return GetPointer(VT_TESTEMPTY); + } + MyGame::Example::Stat *mutable_testempty() { + return GetPointer(VT_TESTEMPTY); + } + bool testbool() const { + return GetField(VT_TESTBOOL, 0) != 0; + } + bool mutate_testbool(bool _testbool = 0) { + return SetField(VT_TESTBOOL, static_cast(_testbool), 0); + } + int32_t testhashs32_fnv1() const { + return GetField(VT_TESTHASHS32_FNV1, 0); + } + bool mutate_testhashs32_fnv1(int32_t _testhashs32_fnv1 = 0) { + return SetField(VT_TESTHASHS32_FNV1, _testhashs32_fnv1, 0); + } + uint32_t testhashu32_fnv1() const { + return GetField(VT_TESTHASHU32_FNV1, 0); + } + bool mutate_testhashu32_fnv1(uint32_t _testhashu32_fnv1 = 0) { + return SetField(VT_TESTHASHU32_FNV1, _testhashu32_fnv1, 0); + } + int64_t testhashs64_fnv1() const { + return GetField(VT_TESTHASHS64_FNV1, 0); + } + bool mutate_testhashs64_fnv1(int64_t _testhashs64_fnv1 = 0) { + return SetField(VT_TESTHASHS64_FNV1, _testhashs64_fnv1, 0); + } + uint64_t testhashu64_fnv1() const { + return GetField(VT_TESTHASHU64_FNV1, 0); + } + bool mutate_testhashu64_fnv1(uint64_t _testhashu64_fnv1 = 0) { + return SetField(VT_TESTHASHU64_FNV1, _testhashu64_fnv1, 0); + } + int32_t testhashs32_fnv1a() const { + return GetField(VT_TESTHASHS32_FNV1A, 0); + } + bool mutate_testhashs32_fnv1a(int32_t _testhashs32_fnv1a = 0) { + return SetField(VT_TESTHASHS32_FNV1A, _testhashs32_fnv1a, 0); + } + uint32_t testhashu32_fnv1a() const { + return GetField(VT_TESTHASHU32_FNV1A, 0); + } + bool mutate_testhashu32_fnv1a(uint32_t _testhashu32_fnv1a = 0) { + return SetField(VT_TESTHASHU32_FNV1A, _testhashu32_fnv1a, 0); + } + int64_t testhashs64_fnv1a() const { + return GetField(VT_TESTHASHS64_FNV1A, 0); + } + bool mutate_testhashs64_fnv1a(int64_t _testhashs64_fnv1a = 0) { + return SetField(VT_TESTHASHS64_FNV1A, _testhashs64_fnv1a, 0); + } + uint64_t testhashu64_fnv1a() const { + return GetField(VT_TESTHASHU64_FNV1A, 0); + } + bool mutate_testhashu64_fnv1a(uint64_t _testhashu64_fnv1a = 0) { + return SetField(VT_TESTHASHU64_FNV1A, _testhashu64_fnv1a, 0); + } + const ::flatbuffers::Vector *testarrayofbools() const { + return GetPointer *>(VT_TESTARRAYOFBOOLS); + } + ::flatbuffers::Vector *mutable_testarrayofbools() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFBOOLS); + } + float testf() const { + return GetField(VT_TESTF, 3.14159f); + } + bool mutate_testf(float _testf = 3.14159f) { + return SetField(VT_TESTF, _testf, 3.14159f); + } + float testf2() const { + return GetField(VT_TESTF2, 3.0f); + } + bool mutate_testf2(float _testf2 = 3.0f) { + return SetField(VT_TESTF2, _testf2, 3.0f); + } + float testf3() const { + return GetField(VT_TESTF3, 0.0f); + } + bool mutate_testf3(float _testf3 = 0.0f) { + return SetField(VT_TESTF3, _testf3, 0.0f); + } + const ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2() const { + return GetPointer> *>(VT_TESTARRAYOFSTRING2); + } + ::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *mutable_testarrayofstring2() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>> *>(VT_TESTARRAYOFSTRING2); + } + const ::flatbuffers::Vector *testarrayofsortedstruct() const { + return GetPointer *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + ::flatbuffers::Vector *mutable_testarrayofsortedstruct() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTARRAYOFSORTEDSTRUCT); + } + const ::flatbuffers::Vector *flex() const { + return GetPointer *>(VT_FLEX); + } + ::flatbuffers::Vector *mutable_flex() { + return GetPointer<::flatbuffers::Vector *>(VT_FLEX); + } + flexbuffers::Reference flex_flexbuffer_root() const { + const auto _f = flex(); + return _f ? flexbuffers::GetRoot(_f->Data(), _f->size()) + : flexbuffers::Reference(); + } + const ::flatbuffers::Vector *test5() const { + return GetPointer *>(VT_TEST5); + } + ::flatbuffers::Vector *mutable_test5() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST5); + } + const ::flatbuffers::Vector *vector_of_longs() const { + return GetPointer *>(VT_VECTOR_OF_LONGS); + } + ::flatbuffers::Vector *mutable_vector_of_longs() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_LONGS); + } + const ::flatbuffers::Vector *vector_of_doubles() const { + return GetPointer *>(VT_VECTOR_OF_DOUBLES); + } + ::flatbuffers::Vector *mutable_vector_of_doubles() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_DOUBLES); + } + const MyGame::InParentNamespace *parent_namespace_test() const { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + MyGame::InParentNamespace *mutable_parent_namespace_test() { + return GetPointer(VT_PARENT_NAMESPACE_TEST); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_REFERRABLES); + } + uint64_t single_weak_reference() const { + return GetField(VT_SINGLE_WEAK_REFERENCE, 0); + } + bool mutate_single_weak_reference(uint64_t _single_weak_reference = 0) { + return SetField(VT_SINGLE_WEAK_REFERENCE, _single_weak_reference, 0); + } + const ::flatbuffers::Vector *vector_of_weak_references() const { + return GetPointer *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_weak_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_WEAK_REFERENCES); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *vector_of_strong_referrables() const { + return GetPointer> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_vector_of_strong_referrables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_VECTOR_OF_STRONG_REFERRABLES); + } + uint64_t co_owning_reference() const { + return GetField(VT_CO_OWNING_REFERENCE, 0); + } + bool mutate_co_owning_reference(uint64_t _co_owning_reference = 0) { + return SetField(VT_CO_OWNING_REFERENCE, _co_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_co_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_co_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_CO_OWNING_REFERENCES); + } + uint64_t non_owning_reference() const { + return GetField(VT_NON_OWNING_REFERENCE, 0); + } + bool mutate_non_owning_reference(uint64_t _non_owning_reference = 0) { + return SetField(VT_NON_OWNING_REFERENCE, _non_owning_reference, 0); + } + const ::flatbuffers::Vector *vector_of_non_owning_references() const { + return GetPointer *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + ::flatbuffers::Vector *mutable_vector_of_non_owning_references() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_NON_OWNING_REFERENCES); + } + MyGame::Example::AnyUniqueAliases any_unique_type() const { + return static_cast(GetField(VT_ANY_UNIQUE_TYPE, 0)); + } + const void *any_unique() const { + return GetPointer(VT_ANY_UNIQUE); + } + template const T *any_unique_as() const; + const MyGame::Example::Monster *any_unique_as_M() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example::TestSimpleTableWithEnum *any_unique_as_TS() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_TS ? static_cast(any_unique()) : nullptr; + } + const MyGame::Example2::Monster *any_unique_as_M2() const { + return any_unique_type() == MyGame::Example::AnyUniqueAliases_M2 ? static_cast(any_unique()) : nullptr; + } + void *mutable_any_unique() { + return GetPointer(VT_ANY_UNIQUE); + } + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type() const { + return static_cast(GetField(VT_ANY_AMBIGUOUS_TYPE, 0)); + } + const void *any_ambiguous() const { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const MyGame::Example::Monster *any_ambiguous_as_M1() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M1 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M2() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M2 ? static_cast(any_ambiguous()) : nullptr; + } + const MyGame::Example::Monster *any_ambiguous_as_M3() const { + return any_ambiguous_type() == MyGame::Example::AnyAmbiguousAliases_M3 ? static_cast(any_ambiguous()) : nullptr; + } + void *mutable_any_ambiguous() { + return GetPointer(VT_ANY_AMBIGUOUS); + } + const ::flatbuffers::Vector *vector_of_enums() const { + return GetPointer *>(VT_VECTOR_OF_ENUMS); + } + ::flatbuffers::Vector *mutable_vector_of_enums() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTOR_OF_ENUMS); + } + MyGame::Example::Race signed_enum() const { + return static_cast(GetField(VT_SIGNED_ENUM, -1)); + } + bool mutate_signed_enum(MyGame::Example::Race _signed_enum = static_cast(-1)) { + return SetField(VT_SIGNED_ENUM, static_cast(_signed_enum), -1); + } + const ::flatbuffers::Vector *testrequirednestedflatbuffer() const { + return GetPointer *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + ::flatbuffers::Vector *mutable_testrequirednestedflatbuffer() { + return GetPointer<::flatbuffers::Vector *>(VT_TESTREQUIREDNESTEDFLATBUFFER); + } + const MyGame::Example::Monster *testrequirednestedflatbuffer_nested_root() const { + const auto _f = testrequirednestedflatbuffer(); + return _f ? ::flatbuffers::GetRoot(_f->Data()) + : nullptr; + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *scalar_key_sorted_tables() const { + return GetPointer> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_scalar_key_sorted_tables() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_SCALAR_KEY_SORTED_TABLES); + } + const MyGame::Example::Test *native_inline() const { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::Test *mutable_native_inline() { + return GetStruct(VT_NATIVE_INLINE); + } + MyGame::Example::LongEnum long_enum_non_enum_default() const { + return static_cast(GetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, 0)); + } + bool mutate_long_enum_non_enum_default(MyGame::Example::LongEnum _long_enum_non_enum_default = static_cast(0)) { + return SetField(VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(_long_enum_non_enum_default), 0); + } + MyGame::Example::LongEnum long_enum_normal_default() const { + return static_cast(GetField(VT_LONG_ENUM_NORMAL_DEFAULT, 2ULL)); + } + bool mutate_long_enum_normal_default(MyGame::Example::LongEnum _long_enum_normal_default = static_cast(2ULL)) { + return SetField(VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(_long_enum_normal_default), 2ULL); + } + float nan_default() const { + return GetField(VT_NAN_DEFAULT, std::numeric_limits::quiet_NaN()); + } + bool mutate_nan_default(float _nan_default = std::numeric_limits::quiet_NaN()) { + return SetField(VT_NAN_DEFAULT, _nan_default, std::numeric_limits::quiet_NaN()); + } + float inf_default() const { + return GetField(VT_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_inf_default(float _inf_default = std::numeric_limits::infinity()) { + return SetField(VT_INF_DEFAULT, _inf_default, std::numeric_limits::infinity()); + } + float positive_inf_default() const { + return GetField(VT_POSITIVE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_inf_default(float _positive_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INF_DEFAULT, _positive_inf_default, std::numeric_limits::infinity()); + } + float infinity_default() const { + return GetField(VT_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_infinity_default(float _infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_INFINITY_DEFAULT, _infinity_default, std::numeric_limits::infinity()); + } + float positive_infinity_default() const { + return GetField(VT_POSITIVE_INFINITY_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_positive_infinity_default(float _positive_infinity_default = std::numeric_limits::infinity()) { + return SetField(VT_POSITIVE_INFINITY_DEFAULT, _positive_infinity_default, std::numeric_limits::infinity()); + } + float negative_inf_default() const { + return GetField(VT_NEGATIVE_INF_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_inf_default(float _negative_inf_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INF_DEFAULT, _negative_inf_default, -std::numeric_limits::infinity()); + } + float negative_infinity_default() const { + return GetField(VT_NEGATIVE_INFINITY_DEFAULT, -std::numeric_limits::infinity()); + } + bool mutate_negative_infinity_default(float _negative_infinity_default = -std::numeric_limits::infinity()) { + return SetField(VT_NEGATIVE_INFINITY_DEFAULT, _negative_infinity_default, -std::numeric_limits::infinity()); + } + double double_inf_default() const { + return GetField(VT_DOUBLE_INF_DEFAULT, std::numeric_limits::infinity()); + } + bool mutate_double_inf_default(double _double_inf_default = std::numeric_limits::infinity()) { + return SetField(VT_DOUBLE_INF_DEFAULT, _double_inf_default, std::numeric_limits::infinity()); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_POS, 8) && + VerifyField(verifier, VT_MANA, 2) && + VerifyField(verifier, VT_HP, 2) && + VerifyOffsetRequired(verifier, VT_NAME) && + verifier.VerifyString(name()) && + VerifyOffset(verifier, VT_INVENTORY) && + verifier.VerifyVector(inventory()) && + VerifyField(verifier, VT_COLOR, 1) && + VerifyField(verifier, VT_TEST_TYPE, 1) && + VerifyOffset(verifier, VT_TEST) && + VerifyAny(verifier, test(), test_type()) && + VerifyOffset(verifier, VT_TEST4) && + verifier.VerifyVector(test4()) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING) && + verifier.VerifyVector(testarrayofstring()) && + verifier.VerifyVectorOfStrings(testarrayofstring()) && + VerifyOffset(verifier, VT_TESTARRAYOFTABLES) && + verifier.VerifyVector(testarrayoftables()) && + verifier.VerifyVectorOfTables(testarrayoftables()) && + VerifyOffset(verifier, VT_ENEMY) && + verifier.VerifyTable(enemy()) && + VerifyOffset(verifier, VT_TESTNESTEDFLATBUFFER) && + verifier.VerifyVector(testnestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testnestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_TESTEMPTY) && + verifier.VerifyTable(testempty()) && + VerifyField(verifier, VT_TESTBOOL, 1) && + VerifyField(verifier, VT_TESTHASHS32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1, 8) && + VerifyField(verifier, VT_TESTHASHS32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHU32_FNV1A, 4) && + VerifyField(verifier, VT_TESTHASHS64_FNV1A, 8) && + VerifyField(verifier, VT_TESTHASHU64_FNV1A, 8) && + VerifyOffset(verifier, VT_TESTARRAYOFBOOLS) && + verifier.VerifyVector(testarrayofbools()) && + VerifyField(verifier, VT_TESTF, 4) && + VerifyField(verifier, VT_TESTF2, 4) && + VerifyField(verifier, VT_TESTF3, 4) && + VerifyOffset(verifier, VT_TESTARRAYOFSTRING2) && + verifier.VerifyVector(testarrayofstring2()) && + verifier.VerifyVectorOfStrings(testarrayofstring2()) && + VerifyOffset(verifier, VT_TESTARRAYOFSORTEDSTRUCT) && + verifier.VerifyVector(testarrayofsortedstruct()) && + VerifyOffset(verifier, VT_FLEX) && + verifier.VerifyVector(flex()) && + flexbuffers::VerifyNestedFlexBuffer(flex(), verifier) && + VerifyOffset(verifier, VT_TEST5) && + verifier.VerifyVector(test5()) && + VerifyOffset(verifier, VT_VECTOR_OF_LONGS) && + verifier.VerifyVector(vector_of_longs()) && + VerifyOffset(verifier, VT_VECTOR_OF_DOUBLES) && + verifier.VerifyVector(vector_of_doubles()) && + VerifyOffset(verifier, VT_PARENT_NAMESPACE_TEST) && + verifier.VerifyTable(parent_namespace_test()) && + VerifyOffset(verifier, VT_VECTOR_OF_REFERRABLES) && + verifier.VerifyVector(vector_of_referrables()) && + verifier.VerifyVectorOfTables(vector_of_referrables()) && + VerifyField(verifier, VT_SINGLE_WEAK_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_WEAK_REFERENCES) && + verifier.VerifyVector(vector_of_weak_references()) && + VerifyOffset(verifier, VT_VECTOR_OF_STRONG_REFERRABLES) && + verifier.VerifyVector(vector_of_strong_referrables()) && + verifier.VerifyVectorOfTables(vector_of_strong_referrables()) && + VerifyField(verifier, VT_CO_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_CO_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_co_owning_references()) && + VerifyField(verifier, VT_NON_OWNING_REFERENCE, 8) && + VerifyOffset(verifier, VT_VECTOR_OF_NON_OWNING_REFERENCES) && + verifier.VerifyVector(vector_of_non_owning_references()) && + VerifyField(verifier, VT_ANY_UNIQUE_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_UNIQUE) && + VerifyAnyUniqueAliases(verifier, any_unique(), any_unique_type()) && + VerifyField(verifier, VT_ANY_AMBIGUOUS_TYPE, 1) && + VerifyOffset(verifier, VT_ANY_AMBIGUOUS) && + VerifyAnyAmbiguousAliases(verifier, any_ambiguous(), any_ambiguous_type()) && + VerifyOffset(verifier, VT_VECTOR_OF_ENUMS) && + verifier.VerifyVector(vector_of_enums()) && + VerifyField(verifier, VT_SIGNED_ENUM, 1) && + VerifyOffset(verifier, VT_TESTREQUIREDNESTEDFLATBUFFER) && + verifier.VerifyVector(testrequirednestedflatbuffer()) && + verifier.VerifyNestedFlatBuffer(testrequirednestedflatbuffer(), nullptr) && + VerifyOffset(verifier, VT_SCALAR_KEY_SORTED_TABLES) && + verifier.VerifyVector(scalar_key_sorted_tables()) && + verifier.VerifyVectorOfTables(scalar_key_sorted_tables()) && + VerifyField(verifier, VT_NATIVE_INLINE, 2) && + VerifyField(verifier, VT_LONG_ENUM_NON_ENUM_DEFAULT, 8) && + VerifyField(verifier, VT_LONG_ENUM_NORMAL_DEFAULT, 8) && + VerifyField(verifier, VT_NAN_DEFAULT, 4) && + VerifyField(verifier, VT_INF_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_POSITIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INF_DEFAULT, 4) && + VerifyField(verifier, VT_NEGATIVE_INFINITY_DEFAULT, 4) && + VerifyField(verifier, VT_DOUBLE_INF_DEFAULT, 8) && + verifier.EndTable(); + } + MonsterT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const MyGame::Example::Monster *Monster::test_as() const { + return test_as_Monster(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::test_as() const { + return test_as_TestSimpleTableWithEnum(); +} + +template<> inline const MyGame::Example2::Monster *Monster::test_as() const { + return test_as_MyGame_Example2_Monster(); +} + +template<> inline const MyGame::Example::Monster *Monster::any_unique_as() const { + return any_unique_as_M(); +} + +template<> inline const MyGame::Example::TestSimpleTableWithEnum *Monster::any_unique_as() const { + return any_unique_as_TS(); +} + +template<> inline const MyGame::Example2::Monster *Monster::any_unique_as() const { + return any_unique_as_M2(); +} + +struct MonsterBuilder { + typedef Monster Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_pos(const MyGame::Example::Vec3 *pos) { + fbb_.AddStruct(Monster::VT_POS, pos); + } + void add_mana(int16_t mana) { + fbb_.AddElement(Monster::VT_MANA, mana, 150); + } + void add_hp(int16_t hp) { + fbb_.AddElement(Monster::VT_HP, hp, 100); + } + void add_name(::flatbuffers::Offset<::flatbuffers::String> name) { + fbb_.AddOffset(Monster::VT_NAME, name); + } + void add_inventory(::flatbuffers::Offset<::flatbuffers::Vector> inventory) { + fbb_.AddOffset(Monster::VT_INVENTORY, inventory); + } + void add_color(MyGame::Example::Color color) { + fbb_.AddElement(Monster::VT_COLOR, static_cast(color), 8); + } + void add_test_type(MyGame::Example::Any test_type) { + fbb_.AddElement(Monster::VT_TEST_TYPE, static_cast(test_type), 0); + } + void add_test(::flatbuffers::Offset test) { + fbb_.AddOffset(Monster::VT_TEST, test); + } + void add_test4(::flatbuffers::Offset<::flatbuffers::Vector> test4) { + fbb_.AddOffset(Monster::VT_TEST4, test4); + } + void add_testarrayofstring(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + } + void add_testarrayoftables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFTABLES, testarrayoftables); + } + void add_enemy(::flatbuffers::Offset enemy) { + fbb_.AddOffset(Monster::VT_ENEMY, enemy); + } + void add_testnestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTNESTEDFLATBUFFER, testnestedflatbuffer); + } + void add_testempty(::flatbuffers::Offset testempty) { + fbb_.AddOffset(Monster::VT_TESTEMPTY, testempty); + } + void add_testbool(bool testbool) { + fbb_.AddElement(Monster::VT_TESTBOOL, static_cast(testbool), 0); + } + void add_testhashs32_fnv1(int32_t testhashs32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1, testhashs32_fnv1, 0); + } + void add_testhashu32_fnv1(uint32_t testhashu32_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1, testhashu32_fnv1, 0); + } + void add_testhashs64_fnv1(int64_t testhashs64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1, testhashs64_fnv1, 0); + } + void add_testhashu64_fnv1(uint64_t testhashu64_fnv1) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1, testhashu64_fnv1, 0); + } + void add_testhashs32_fnv1a(int32_t testhashs32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS32_FNV1A, testhashs32_fnv1a, 0); + } + void add_testhashu32_fnv1a(uint32_t testhashu32_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU32_FNV1A, testhashu32_fnv1a, 0); + } + void add_testhashs64_fnv1a(int64_t testhashs64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHS64_FNV1A, testhashs64_fnv1a, 0); + } + void add_testhashu64_fnv1a(uint64_t testhashu64_fnv1a) { + fbb_.AddElement(Monster::VT_TESTHASHU64_FNV1A, testhashu64_fnv1a, 0); + } + void add_testarrayofbools(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFBOOLS, testarrayofbools); + } + void add_testf(float testf) { + fbb_.AddElement(Monster::VT_TESTF, testf, 3.14159f); + } + void add_testf2(float testf2) { + fbb_.AddElement(Monster::VT_TESTF2, testf2, 3.0f); + } + void add_testf3(float testf3) { + fbb_.AddElement(Monster::VT_TESTF3, testf3, 0.0f); + } + void add_testarrayofstring2(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSTRING2, testarrayofstring2); + } + void add_testarrayofsortedstruct(::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct) { + fbb_.AddOffset(Monster::VT_TESTARRAYOFSORTEDSTRUCT, testarrayofsortedstruct); + } + void add_flex(::flatbuffers::Offset<::flatbuffers::Vector> flex) { + fbb_.AddOffset(Monster::VT_FLEX, flex); + } + void add_test5(::flatbuffers::Offset<::flatbuffers::Vector> test5) { + fbb_.AddOffset(Monster::VT_TEST5, test5); + } + void add_vector_of_longs(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_LONGS, vector_of_longs); + } + void add_vector_of_doubles(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_DOUBLES, vector_of_doubles); + } + void add_parent_namespace_test(::flatbuffers::Offset parent_namespace_test) { + fbb_.AddOffset(Monster::VT_PARENT_NAMESPACE_TEST, parent_namespace_test); + } + void add_vector_of_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_REFERRABLES, vector_of_referrables); + } + void add_single_weak_reference(uint64_t single_weak_reference) { + fbb_.AddElement(Monster::VT_SINGLE_WEAK_REFERENCE, single_weak_reference, 0); + } + void add_vector_of_weak_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_WEAK_REFERENCES, vector_of_weak_references); + } + void add_vector_of_strong_referrables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_STRONG_REFERRABLES, vector_of_strong_referrables); + } + void add_co_owning_reference(uint64_t co_owning_reference) { + fbb_.AddElement(Monster::VT_CO_OWNING_REFERENCE, co_owning_reference, 0); + } + void add_vector_of_co_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_CO_OWNING_REFERENCES, vector_of_co_owning_references); + } + void add_non_owning_reference(uint64_t non_owning_reference) { + fbb_.AddElement(Monster::VT_NON_OWNING_REFERENCE, non_owning_reference, 0); + } + void add_vector_of_non_owning_references(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_NON_OWNING_REFERENCES, vector_of_non_owning_references); + } + void add_any_unique_type(MyGame::Example::AnyUniqueAliases any_unique_type) { + fbb_.AddElement(Monster::VT_ANY_UNIQUE_TYPE, static_cast(any_unique_type), 0); + } + void add_any_unique(::flatbuffers::Offset any_unique) { + fbb_.AddOffset(Monster::VT_ANY_UNIQUE, any_unique); + } + void add_any_ambiguous_type(MyGame::Example::AnyAmbiguousAliases any_ambiguous_type) { + fbb_.AddElement(Monster::VT_ANY_AMBIGUOUS_TYPE, static_cast(any_ambiguous_type), 0); + } + void add_any_ambiguous(::flatbuffers::Offset any_ambiguous) { + fbb_.AddOffset(Monster::VT_ANY_AMBIGUOUS, any_ambiguous); + } + void add_vector_of_enums(::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums) { + fbb_.AddOffset(Monster::VT_VECTOR_OF_ENUMS, vector_of_enums); + } + void add_signed_enum(MyGame::Example::Race signed_enum) { + fbb_.AddElement(Monster::VT_SIGNED_ENUM, static_cast(signed_enum), -1); + } + void add_testrequirednestedflatbuffer(::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer) { + fbb_.AddOffset(Monster::VT_TESTREQUIREDNESTEDFLATBUFFER, testrequirednestedflatbuffer); + } + void add_scalar_key_sorted_tables(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables) { + fbb_.AddOffset(Monster::VT_SCALAR_KEY_SORTED_TABLES, scalar_key_sorted_tables); + } + void add_native_inline(const MyGame::Example::Test *native_inline) { + fbb_.AddStruct(Monster::VT_NATIVE_INLINE, native_inline); + } + void add_long_enum_non_enum_default(MyGame::Example::LongEnum long_enum_non_enum_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NON_ENUM_DEFAULT, static_cast(long_enum_non_enum_default), 0); + } + void add_long_enum_normal_default(MyGame::Example::LongEnum long_enum_normal_default) { + fbb_.AddElement(Monster::VT_LONG_ENUM_NORMAL_DEFAULT, static_cast(long_enum_normal_default), 2ULL); + } + void add_nan_default(float nan_default) { + fbb_.AddElement(Monster::VT_NAN_DEFAULT, nan_default, std::numeric_limits::quiet_NaN()); + } + void add_inf_default(float inf_default) { + fbb_.AddElement(Monster::VT_INF_DEFAULT, inf_default, std::numeric_limits::infinity()); + } + void add_positive_inf_default(float positive_inf_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INF_DEFAULT, positive_inf_default, std::numeric_limits::infinity()); + } + void add_infinity_default(float infinity_default) { + fbb_.AddElement(Monster::VT_INFINITY_DEFAULT, infinity_default, std::numeric_limits::infinity()); + } + void add_positive_infinity_default(float positive_infinity_default) { + fbb_.AddElement(Monster::VT_POSITIVE_INFINITY_DEFAULT, positive_infinity_default, std::numeric_limits::infinity()); + } + void add_negative_inf_default(float negative_inf_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INF_DEFAULT, negative_inf_default, -std::numeric_limits::infinity()); + } + void add_negative_infinity_default(float negative_infinity_default) { + fbb_.AddElement(Monster::VT_NEGATIVE_INFINITY_DEFAULT, negative_infinity_default, -std::numeric_limits::infinity()); + } + void add_double_inf_default(double double_inf_default) { + fbb_.AddElement(Monster::VT_DOUBLE_INF_DEFAULT, double_inf_default, std::numeric_limits::infinity()); + } + explicit MonsterBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + fbb_.Required(o, Monster::VT_NAME); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMonster( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + ::flatbuffers::Offset<::flatbuffers::String> name = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> inventory = 0, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test4 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> testarrayoftables = 0, + ::flatbuffers::Offset enemy = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testnestedflatbuffer = 0, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofbools = 0, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset<::flatbuffers::String>>> testarrayofstring2 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> testarrayofsortedstruct = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> flex = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test5 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_longs = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_doubles = 0, + ::flatbuffers::Offset parent_namespace_test = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_referrables = 0, + uint64_t single_weak_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_weak_references = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> vector_of_strong_referrables = 0, + uint64_t co_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_co_owning_references = 0, + uint64_t non_owning_reference = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_non_owning_references = 0, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vector_of_enums = 0, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + ::flatbuffers::Offset<::flatbuffers::Vector> testrequirednestedflatbuffer = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> scalar_key_sorted_tables = 0, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + MonsterBuilder builder_(_fbb); + builder_.add_double_inf_default(double_inf_default); + builder_.add_long_enum_normal_default(long_enum_normal_default); + builder_.add_long_enum_non_enum_default(long_enum_non_enum_default); + builder_.add_non_owning_reference(non_owning_reference); + builder_.add_co_owning_reference(co_owning_reference); + builder_.add_single_weak_reference(single_weak_reference); + builder_.add_testhashu64_fnv1a(testhashu64_fnv1a); + builder_.add_testhashs64_fnv1a(testhashs64_fnv1a); + builder_.add_testhashu64_fnv1(testhashu64_fnv1); + builder_.add_testhashs64_fnv1(testhashs64_fnv1); + builder_.add_negative_infinity_default(negative_infinity_default); + builder_.add_negative_inf_default(negative_inf_default); + builder_.add_positive_infinity_default(positive_infinity_default); + builder_.add_infinity_default(infinity_default); + builder_.add_positive_inf_default(positive_inf_default); + builder_.add_inf_default(inf_default); + builder_.add_nan_default(nan_default); + builder_.add_native_inline(native_inline); + builder_.add_scalar_key_sorted_tables(scalar_key_sorted_tables); + builder_.add_testrequirednestedflatbuffer(testrequirednestedflatbuffer); + builder_.add_vector_of_enums(vector_of_enums); + builder_.add_any_ambiguous(any_ambiguous); + builder_.add_any_unique(any_unique); + builder_.add_vector_of_non_owning_references(vector_of_non_owning_references); + builder_.add_vector_of_co_owning_references(vector_of_co_owning_references); + builder_.add_vector_of_strong_referrables(vector_of_strong_referrables); + builder_.add_vector_of_weak_references(vector_of_weak_references); + builder_.add_vector_of_referrables(vector_of_referrables); + builder_.add_parent_namespace_test(parent_namespace_test); + builder_.add_vector_of_doubles(vector_of_doubles); + builder_.add_vector_of_longs(vector_of_longs); + builder_.add_test5(test5); + builder_.add_flex(flex); + builder_.add_testarrayofsortedstruct(testarrayofsortedstruct); + builder_.add_testarrayofstring2(testarrayofstring2); + builder_.add_testf3(testf3); + builder_.add_testf2(testf2); + builder_.add_testf(testf); + builder_.add_testarrayofbools(testarrayofbools); + builder_.add_testhashu32_fnv1a(testhashu32_fnv1a); + builder_.add_testhashs32_fnv1a(testhashs32_fnv1a); + builder_.add_testhashu32_fnv1(testhashu32_fnv1); + builder_.add_testhashs32_fnv1(testhashs32_fnv1); + builder_.add_testempty(testempty); + builder_.add_testnestedflatbuffer(testnestedflatbuffer); + builder_.add_enemy(enemy); + builder_.add_testarrayoftables(testarrayoftables); + builder_.add_testarrayofstring(testarrayofstring); + builder_.add_test4(test4); + builder_.add_test(test); + builder_.add_inventory(inventory); + builder_.add_name(name); + builder_.add_pos(pos); + builder_.add_hp(hp); + builder_.add_mana(mana); + builder_.add_signed_enum(signed_enum); + builder_.add_any_ambiguous_type(any_ambiguous_type); + builder_.add_any_unique_type(any_unique_type); + builder_.add_testbool(testbool); + builder_.add_test_type(test_type); + builder_.add_color(color); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMonsterDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const MyGame::Example::Vec3 *pos = nullptr, + int16_t mana = 150, + int16_t hp = 100, + const char *name = nullptr, + const std::vector *inventory = nullptr, + MyGame::Example::Color color = MyGame::Example::Color_Blue, + MyGame::Example::Any test_type = MyGame::Example::Any_NONE, + ::flatbuffers::Offset test = 0, + const std::vector *test4 = nullptr, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring = nullptr, + std::vector<::flatbuffers::Offset> *testarrayoftables = nullptr, + ::flatbuffers::Offset enemy = 0, + const std::vector *testnestedflatbuffer = nullptr, + ::flatbuffers::Offset testempty = 0, + bool testbool = false, + int32_t testhashs32_fnv1 = 0, + uint32_t testhashu32_fnv1 = 0, + int64_t testhashs64_fnv1 = 0, + uint64_t testhashu64_fnv1 = 0, + int32_t testhashs32_fnv1a = 0, + uint32_t testhashu32_fnv1a = 0, + int64_t testhashs64_fnv1a = 0, + uint64_t testhashu64_fnv1a = 0, + const std::vector *testarrayofbools = nullptr, + float testf = 3.14159f, + float testf2 = 3.0f, + float testf3 = 0.0f, + const std::vector<::flatbuffers::Offset<::flatbuffers::String>> *testarrayofstring2 = nullptr, + std::vector *testarrayofsortedstruct = nullptr, + const std::vector *flex = nullptr, + const std::vector *test5 = nullptr, + const std::vector *vector_of_longs = nullptr, + const std::vector *vector_of_doubles = nullptr, + ::flatbuffers::Offset parent_namespace_test = 0, + std::vector<::flatbuffers::Offset> *vector_of_referrables = nullptr, + uint64_t single_weak_reference = 0, + const std::vector *vector_of_weak_references = nullptr, + std::vector<::flatbuffers::Offset> *vector_of_strong_referrables = nullptr, + uint64_t co_owning_reference = 0, + const std::vector *vector_of_co_owning_references = nullptr, + uint64_t non_owning_reference = 0, + const std::vector *vector_of_non_owning_references = nullptr, + MyGame::Example::AnyUniqueAliases any_unique_type = MyGame::Example::AnyUniqueAliases_NONE, + ::flatbuffers::Offset any_unique = 0, + MyGame::Example::AnyAmbiguousAliases any_ambiguous_type = MyGame::Example::AnyAmbiguousAliases_NONE, + ::flatbuffers::Offset any_ambiguous = 0, + const std::vector *vector_of_enums = nullptr, + MyGame::Example::Race signed_enum = MyGame::Example::Race_None, + const std::vector *testrequirednestedflatbuffer = nullptr, + std::vector<::flatbuffers::Offset> *scalar_key_sorted_tables = nullptr, + const MyGame::Example::Test *native_inline = nullptr, + MyGame::Example::LongEnum long_enum_non_enum_default = static_cast(0), + MyGame::Example::LongEnum long_enum_normal_default = MyGame::Example::LongEnum_LongOne, + float nan_default = std::numeric_limits::quiet_NaN(), + float inf_default = std::numeric_limits::infinity(), + float positive_inf_default = std::numeric_limits::infinity(), + float infinity_default = std::numeric_limits::infinity(), + float positive_infinity_default = std::numeric_limits::infinity(), + float negative_inf_default = -std::numeric_limits::infinity(), + float negative_infinity_default = -std::numeric_limits::infinity(), + double double_inf_default = std::numeric_limits::infinity()) { + auto name__ = name ? _fbb.CreateString(name) : 0; + auto inventory__ = inventory ? _fbb.CreateVector(*inventory) : 0; + auto test4__ = test4 ? _fbb.CreateVectorOfStructs(*test4) : 0; + auto testarrayofstring__ = testarrayofstring ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring) : 0; + auto testarrayoftables__ = testarrayoftables ? _fbb.CreateVectorOfSortedTables(testarrayoftables) : 0; + auto testnestedflatbuffer__ = testnestedflatbuffer ? _fbb.CreateVector(*testnestedflatbuffer) : 0; + auto testarrayofbools__ = testarrayofbools ? _fbb.CreateVector(*testarrayofbools) : 0; + auto testarrayofstring2__ = testarrayofstring2 ? _fbb.CreateVector<::flatbuffers::Offset<::flatbuffers::String>>(*testarrayofstring2) : 0; + auto testarrayofsortedstruct__ = testarrayofsortedstruct ? _fbb.CreateVectorOfSortedStructs(testarrayofsortedstruct) : 0; + auto flex__ = flex ? _fbb.CreateVector(*flex) : 0; + auto test5__ = test5 ? _fbb.CreateVectorOfStructs(*test5) : 0; + auto vector_of_longs__ = vector_of_longs ? _fbb.CreateVector(*vector_of_longs) : 0; + auto vector_of_doubles__ = vector_of_doubles ? _fbb.CreateVector(*vector_of_doubles) : 0; + auto vector_of_referrables__ = vector_of_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_referrables) : 0; + auto vector_of_weak_references__ = vector_of_weak_references ? _fbb.CreateVector(*vector_of_weak_references) : 0; + auto vector_of_strong_referrables__ = vector_of_strong_referrables ? _fbb.CreateVectorOfSortedTables(vector_of_strong_referrables) : 0; + auto vector_of_co_owning_references__ = vector_of_co_owning_references ? _fbb.CreateVector(*vector_of_co_owning_references) : 0; + auto vector_of_non_owning_references__ = vector_of_non_owning_references ? _fbb.CreateVector(*vector_of_non_owning_references) : 0; + auto vector_of_enums__ = vector_of_enums ? _fbb.CreateVector(*vector_of_enums) : 0; + auto testrequirednestedflatbuffer__ = testrequirednestedflatbuffer ? _fbb.CreateVector(*testrequirednestedflatbuffer) : 0; + auto scalar_key_sorted_tables__ = scalar_key_sorted_tables ? _fbb.CreateVectorOfSortedTables(scalar_key_sorted_tables) : 0; + return MyGame::Example::CreateMonster( + _fbb, + pos, + mana, + hp, + name__, + inventory__, + color, + test_type, + test, + test4__, + testarrayofstring__, + testarrayoftables__, + enemy, + testnestedflatbuffer__, + testempty, + testbool, + testhashs32_fnv1, + testhashu32_fnv1, + testhashs64_fnv1, + testhashu64_fnv1, + testhashs32_fnv1a, + testhashu32_fnv1a, + testhashs64_fnv1a, + testhashu64_fnv1a, + testarrayofbools__, + testf, + testf2, + testf3, + testarrayofstring2__, + testarrayofsortedstruct__, + flex__, + test5__, + vector_of_longs__, + vector_of_doubles__, + parent_namespace_test, + vector_of_referrables__, + single_weak_reference, + vector_of_weak_references__, + vector_of_strong_referrables__, + co_owning_reference, + vector_of_co_owning_references__, + non_owning_reference, + vector_of_non_owning_references__, + any_unique_type, + any_unique, + any_ambiguous_type, + any_ambiguous, + vector_of_enums__, + signed_enum, + testrequirednestedflatbuffer__, + scalar_key_sorted_tables__, + native_inline, + long_enum_non_enum_default, + long_enum_normal_default, + nan_default, + inf_default, + positive_inf_default, + infinity_default, + positive_infinity_default, + negative_inf_default, + negative_infinity_default, + double_inf_default); +} + +::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct TypeAliasesT : public ::flatbuffers::NativeTable { + typedef TypeAliases TableType; + int8_t i8 = 0; + uint8_t u8 = 0; + int16_t i16 = 0; + uint16_t u16 = 0; + int32_t i32 = 0; + uint32_t u32 = 0; + int64_t i64 = 0; + uint64_t u64 = 0; + float f32 = 0.0f; + double f64 = 0.0; + std::vector v8{}; + std::vector vf64{}; +}; + +struct TypeAliases FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TypeAliasesT NativeTableType; + typedef TypeAliasesBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TypeAliasesTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_I8 = 4, + VT_U8 = 6, + VT_I16 = 8, + VT_U16 = 10, + VT_I32 = 12, + VT_U32 = 14, + VT_I64 = 16, + VT_U64 = 18, + VT_F32 = 20, + VT_F64 = 22, + VT_V8 = 24, + VT_VF64 = 26 + }; + int8_t i8() const { + return GetField(VT_I8, 0); + } + bool mutate_i8(int8_t _i8 = 0) { + return SetField(VT_I8, _i8, 0); + } + uint8_t u8() const { + return GetField(VT_U8, 0); + } + bool mutate_u8(uint8_t _u8 = 0) { + return SetField(VT_U8, _u8, 0); + } + int16_t i16() const { + return GetField(VT_I16, 0); + } + bool mutate_i16(int16_t _i16 = 0) { + return SetField(VT_I16, _i16, 0); + } + uint16_t u16() const { + return GetField(VT_U16, 0); + } + bool mutate_u16(uint16_t _u16 = 0) { + return SetField(VT_U16, _u16, 0); + } + int32_t i32() const { + return GetField(VT_I32, 0); + } + bool mutate_i32(int32_t _i32 = 0) { + return SetField(VT_I32, _i32, 0); + } + uint32_t u32() const { + return GetField(VT_U32, 0); + } + bool mutate_u32(uint32_t _u32 = 0) { + return SetField(VT_U32, _u32, 0); + } + int64_t i64() const { + return GetField(VT_I64, 0); + } + bool mutate_i64(int64_t _i64 = 0) { + return SetField(VT_I64, _i64, 0); + } + uint64_t u64() const { + return GetField(VT_U64, 0); + } + bool mutate_u64(uint64_t _u64 = 0) { + return SetField(VT_U64, _u64, 0); + } + float f32() const { + return GetField(VT_F32, 0.0f); + } + bool mutate_f32(float _f32 = 0.0f) { + return SetField(VT_F32, _f32, 0.0f); + } + double f64() const { + return GetField(VT_F64, 0.0); + } + bool mutate_f64(double _f64 = 0.0) { + return SetField(VT_F64, _f64, 0.0); + } + const ::flatbuffers::Vector *v8() const { + return GetPointer *>(VT_V8); + } + ::flatbuffers::Vector *mutable_v8() { + return GetPointer<::flatbuffers::Vector *>(VT_V8); + } + const ::flatbuffers::Vector *vf64() const { + return GetPointer *>(VT_VF64); + } + ::flatbuffers::Vector *mutable_vf64() { + return GetPointer<::flatbuffers::Vector *>(VT_VF64); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_I8, 1) && + VerifyField(verifier, VT_U8, 1) && + VerifyField(verifier, VT_I16, 2) && + VerifyField(verifier, VT_U16, 2) && + VerifyField(verifier, VT_I32, 4) && + VerifyField(verifier, VT_U32, 4) && + VerifyField(verifier, VT_I64, 8) && + VerifyField(verifier, VT_U64, 8) && + VerifyField(verifier, VT_F32, 4) && + VerifyField(verifier, VT_F64, 8) && + VerifyOffset(verifier, VT_V8) && + verifier.VerifyVector(v8()) && + VerifyOffset(verifier, VT_VF64) && + verifier.VerifyVector(vf64()) && + verifier.EndTable(); + } + TypeAliasesT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TypeAliasesBuilder { + typedef TypeAliases Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_i8(int8_t i8) { + fbb_.AddElement(TypeAliases::VT_I8, i8, 0); + } + void add_u8(uint8_t u8) { + fbb_.AddElement(TypeAliases::VT_U8, u8, 0); + } + void add_i16(int16_t i16) { + fbb_.AddElement(TypeAliases::VT_I16, i16, 0); + } + void add_u16(uint16_t u16) { + fbb_.AddElement(TypeAliases::VT_U16, u16, 0); + } + void add_i32(int32_t i32) { + fbb_.AddElement(TypeAliases::VT_I32, i32, 0); + } + void add_u32(uint32_t u32) { + fbb_.AddElement(TypeAliases::VT_U32, u32, 0); + } + void add_i64(int64_t i64) { + fbb_.AddElement(TypeAliases::VT_I64, i64, 0); + } + void add_u64(uint64_t u64) { + fbb_.AddElement(TypeAliases::VT_U64, u64, 0); + } + void add_f32(float f32) { + fbb_.AddElement(TypeAliases::VT_F32, f32, 0.0f); + } + void add_f64(double f64) { + fbb_.AddElement(TypeAliases::VT_F64, f64, 0.0); + } + void add_v8(::flatbuffers::Offset<::flatbuffers::Vector> v8) { + fbb_.AddOffset(TypeAliases::VT_V8, v8); + } + void add_vf64(::flatbuffers::Offset<::flatbuffers::Vector> vf64) { + fbb_.AddOffset(TypeAliases::VT_VF64, vf64); + } + explicit TypeAliasesBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTypeAliases( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + ::flatbuffers::Offset<::flatbuffers::Vector> v8 = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vf64 = 0) { + TypeAliasesBuilder builder_(_fbb); + builder_.add_f64(f64); + builder_.add_u64(u64); + builder_.add_i64(i64); + builder_.add_vf64(vf64); + builder_.add_v8(v8); + builder_.add_f32(f32); + builder_.add_u32(u32); + builder_.add_i32(i32); + builder_.add_u16(u16); + builder_.add_i16(i16); + builder_.add_u8(u8); + builder_.add_i8(i8); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTypeAliasesDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t i8 = 0, + uint8_t u8 = 0, + int16_t i16 = 0, + uint16_t u16 = 0, + int32_t i32 = 0, + uint32_t u32 = 0, + int64_t i64 = 0, + uint64_t u64 = 0, + float f32 = 0.0f, + double f64 = 0.0, + const std::vector *v8 = nullptr, + const std::vector *vf64 = nullptr) { + auto v8__ = v8 ? _fbb.CreateVector(*v8) : 0; + auto vf64__ = vf64 ? _fbb.CreateVector(*vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + i8, + u8, + i16, + u16, + i32, + u32, + i64, + u64, + f32, + f64, + v8__, + vf64__); +} + +::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace Example + + +inline bool operator==(const InParentNamespaceT &, const InParentNamespaceT &) { + return true; +} + +inline bool operator!=(const InParentNamespaceT &lhs, const InParentNamespaceT &rhs) { + return !(lhs == rhs); +} + + +inline InParentNamespaceT *InParentNamespace::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new InParentNamespaceT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void InParentNamespace::UnPackTo(InParentNamespaceT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset InParentNamespace::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateInParentNamespace(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateInParentNamespace(::flatbuffers::FlatBufferBuilder &_fbb, const InParentNamespaceT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const InParentNamespaceT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::CreateInParentNamespace( + _fbb); +} + +namespace Example2 { + + +inline bool operator==(const MonsterT &, const MonsterT &) { + return true; +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + return MyGame::Example2::CreateMonster( + _fbb); +} + +} // namespace Example2 + +namespace Example { + + +inline bool operator==(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return + (lhs.color == rhs.color); +} + +inline bool operator!=(const TestSimpleTableWithEnumT &lhs, const TestSimpleTableWithEnumT &rhs) { + return !(lhs == rhs); +} + + +inline TestSimpleTableWithEnumT *TestSimpleTableWithEnum::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TestSimpleTableWithEnumT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TestSimpleTableWithEnum::UnPackTo(TestSimpleTableWithEnumT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = color(); _o->color = _e; } +} + +inline ::flatbuffers::Offset TestSimpleTableWithEnum::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTestSimpleTableWithEnum(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTestSimpleTableWithEnum(::flatbuffers::FlatBufferBuilder &_fbb, const TestSimpleTableWithEnumT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TestSimpleTableWithEnumT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _color = _o->color; + return MyGame::Example::CreateTestSimpleTableWithEnum( + _fbb, + _color); +} + + +inline bool operator==(const StatT &lhs, const StatT &rhs) { + return + (lhs.id == rhs.id) && + (lhs.val == rhs.val) && + (lhs.count == rhs.count); +} + +inline bool operator!=(const StatT &lhs, const StatT &rhs) { + return !(lhs == rhs); +} + + +inline StatT *Stat::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new StatT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Stat::UnPackTo(StatT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); if (_e) _o->id = _e->str(); } + { auto _e = val(); _o->val = _e; } + { auto _e = count(); _o->count = _e; } +} + +inline ::flatbuffers::Offset Stat::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const StatT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateStat(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateStat(::flatbuffers::FlatBufferBuilder &_fbb, const StatT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const StatT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id.empty() ? 0 : _fbb.CreateString(_o->id); + auto _val = _o->val; + auto _count = _o->count; + return MyGame::Example::CreateStat( + _fbb, + _id, + _val, + _count); +} + + +inline bool operator==(const ReferrableT &lhs, const ReferrableT &rhs) { + return + (lhs.id == rhs.id); +} + +inline bool operator!=(const ReferrableT &lhs, const ReferrableT &rhs) { + return !(lhs == rhs); +} + + +inline ReferrableT *Referrable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new ReferrableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Referrable::UnPackTo(ReferrableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = id(); _o->id = _e; } +} + +inline ::flatbuffers::Offset Referrable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateReferrable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateReferrable(::flatbuffers::FlatBufferBuilder &_fbb, const ReferrableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ReferrableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _id = _o->id; + return MyGame::Example::CreateReferrable( + _fbb, + _id); +} + + +inline bool operator==(const MonsterT &lhs, const MonsterT &rhs) { + return + ((lhs.pos == rhs.pos) || (lhs.pos && rhs.pos && *lhs.pos == *rhs.pos)) && + (lhs.mana == rhs.mana) && + (lhs.hp == rhs.hp) && + (lhs.name == rhs.name) && + (lhs.inventory == rhs.inventory) && + (lhs.color == rhs.color) && + (lhs.test == rhs.test) && + (lhs.test4 == rhs.test4) && + (lhs.testarrayofstring == rhs.testarrayofstring) && + (lhs.testarrayoftables.size() == rhs.testarrayoftables.size() && std::equal(lhs.testarrayoftables.cbegin(), lhs.testarrayoftables.cend(), rhs.testarrayoftables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + ((lhs.enemy == rhs.enemy) || (lhs.enemy && rhs.enemy && *lhs.enemy == *rhs.enemy)) && + (lhs.testnestedflatbuffer == rhs.testnestedflatbuffer) && + ((lhs.testempty == rhs.testempty) || (lhs.testempty && rhs.testempty && *lhs.testempty == *rhs.testempty)) && + (lhs.testbool == rhs.testbool) && + (lhs.testhashs32_fnv1 == rhs.testhashs32_fnv1) && + (lhs.testhashu32_fnv1 == rhs.testhashu32_fnv1) && + (lhs.testhashs64_fnv1 == rhs.testhashs64_fnv1) && + (lhs.testhashu64_fnv1 == rhs.testhashu64_fnv1) && + (lhs.testhashs32_fnv1a == rhs.testhashs32_fnv1a) && + (lhs.testhashu32_fnv1a == rhs.testhashu32_fnv1a) && + (lhs.testhashs64_fnv1a == rhs.testhashs64_fnv1a) && + (lhs.testhashu64_fnv1a == rhs.testhashu64_fnv1a) && + (lhs.testarrayofbools == rhs.testarrayofbools) && + (lhs.testf == rhs.testf) && + (lhs.testf2 == rhs.testf2) && + (lhs.testf3 == rhs.testf3) && + (lhs.testarrayofstring2 == rhs.testarrayofstring2) && + (lhs.testarrayofsortedstruct == rhs.testarrayofsortedstruct) && + (lhs.flex == rhs.flex) && + (lhs.test5 == rhs.test5) && + (lhs.vector_of_longs == rhs.vector_of_longs) && + (lhs.vector_of_doubles == rhs.vector_of_doubles) && + ((lhs.parent_namespace_test == rhs.parent_namespace_test) || (lhs.parent_namespace_test && rhs.parent_namespace_test && *lhs.parent_namespace_test == *rhs.parent_namespace_test)) && + (lhs.vector_of_referrables.size() == rhs.vector_of_referrables.size() && std::equal(lhs.vector_of_referrables.cbegin(), lhs.vector_of_referrables.cend(), rhs.vector_of_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.single_weak_reference == rhs.single_weak_reference) && + (lhs.vector_of_weak_references == rhs.vector_of_weak_references) && + (lhs.vector_of_strong_referrables.size() == rhs.vector_of_strong_referrables.size() && std::equal(lhs.vector_of_strong_referrables.cbegin(), lhs.vector_of_strong_referrables.cend(), rhs.vector_of_strong_referrables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.co_owning_reference == rhs.co_owning_reference) && + (lhs.vector_of_co_owning_references == rhs.vector_of_co_owning_references) && + (lhs.non_owning_reference == rhs.non_owning_reference) && + (lhs.vector_of_non_owning_references == rhs.vector_of_non_owning_references) && + (lhs.any_unique == rhs.any_unique) && + (lhs.any_ambiguous == rhs.any_ambiguous) && + (lhs.vector_of_enums == rhs.vector_of_enums) && + (lhs.signed_enum == rhs.signed_enum) && + (lhs.testrequirednestedflatbuffer == rhs.testrequirednestedflatbuffer) && + (lhs.scalar_key_sorted_tables.size() == rhs.scalar_key_sorted_tables.size() && std::equal(lhs.scalar_key_sorted_tables.cbegin(), lhs.scalar_key_sorted_tables.cend(), rhs.scalar_key_sorted_tables.cbegin(), [](std::unique_ptr const &a, std::unique_ptr const &b) { return (a == b) || (a && b && *a == *b); })) && + (lhs.native_inline == rhs.native_inline) && + (lhs.long_enum_non_enum_default == rhs.long_enum_non_enum_default) && + (lhs.long_enum_normal_default == rhs.long_enum_normal_default) && + (lhs.nan_default == rhs.nan_default) && + (lhs.inf_default == rhs.inf_default) && + (lhs.positive_inf_default == rhs.positive_inf_default) && + (lhs.infinity_default == rhs.infinity_default) && + (lhs.positive_infinity_default == rhs.positive_infinity_default) && + (lhs.negative_inf_default == rhs.negative_inf_default) && + (lhs.negative_infinity_default == rhs.negative_infinity_default) && + (lhs.double_inf_default == rhs.double_inf_default); +} + +inline bool operator!=(const MonsterT &lhs, const MonsterT &rhs) { + return !(lhs == rhs); +} + + +inline MonsterT::MonsterT(const MonsterT &o) + : pos((o.pos) ? new MyGame::Example::Vec3(*o.pos) : nullptr), + mana(o.mana), + hp(o.hp), + name(o.name), + inventory(o.inventory), + color(o.color), + test(o.test), + test4(o.test4), + testarrayofstring(o.testarrayofstring), + enemy((o.enemy) ? new MyGame::Example::MonsterT(*o.enemy) : nullptr), + testnestedflatbuffer(o.testnestedflatbuffer), + testempty((o.testempty) ? new MyGame::Example::StatT(*o.testempty) : nullptr), + testbool(o.testbool), + testhashs32_fnv1(o.testhashs32_fnv1), + testhashu32_fnv1(o.testhashu32_fnv1), + testhashs64_fnv1(o.testhashs64_fnv1), + testhashu64_fnv1(o.testhashu64_fnv1), + testhashs32_fnv1a(o.testhashs32_fnv1a), + testhashu32_fnv1a(o.testhashu32_fnv1a), + testhashs64_fnv1a(o.testhashs64_fnv1a), + testhashu64_fnv1a(o.testhashu64_fnv1a), + testarrayofbools(o.testarrayofbools), + testf(o.testf), + testf2(o.testf2), + testf3(o.testf3), + testarrayofstring2(o.testarrayofstring2), + testarrayofsortedstruct(o.testarrayofsortedstruct), + flex(o.flex), + test5(o.test5), + vector_of_longs(o.vector_of_longs), + vector_of_doubles(o.vector_of_doubles), + parent_namespace_test((o.parent_namespace_test) ? new MyGame::InParentNamespaceT(*o.parent_namespace_test) : nullptr), + single_weak_reference(o.single_weak_reference), + vector_of_weak_references(o.vector_of_weak_references), + co_owning_reference(o.co_owning_reference), + non_owning_reference(o.non_owning_reference), + vector_of_non_owning_references(o.vector_of_non_owning_references), + any_unique(o.any_unique), + any_ambiguous(o.any_ambiguous), + vector_of_enums(o.vector_of_enums), + signed_enum(o.signed_enum), + testrequirednestedflatbuffer(o.testrequirednestedflatbuffer), + native_inline(o.native_inline), + long_enum_non_enum_default(o.long_enum_non_enum_default), + long_enum_normal_default(o.long_enum_normal_default), + nan_default(o.nan_default), + inf_default(o.inf_default), + positive_inf_default(o.positive_inf_default), + infinity_default(o.infinity_default), + positive_infinity_default(o.positive_infinity_default), + negative_inf_default(o.negative_inf_default), + negative_infinity_default(o.negative_infinity_default), + double_inf_default(o.double_inf_default) { + testarrayoftables.reserve(o.testarrayoftables.size()); + for (const auto &testarrayoftables_ : o.testarrayoftables) { testarrayoftables.emplace_back((testarrayoftables_) ? new MyGame::Example::MonsterT(*testarrayoftables_) : nullptr); } + vector_of_referrables.reserve(o.vector_of_referrables.size()); + for (const auto &vector_of_referrables_ : o.vector_of_referrables) { vector_of_referrables.emplace_back((vector_of_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_referrables_) : nullptr); } + vector_of_strong_referrables.reserve(o.vector_of_strong_referrables.size()); + for (const auto &vector_of_strong_referrables_ : o.vector_of_strong_referrables) { vector_of_strong_referrables.emplace_back((vector_of_strong_referrables_) ? new MyGame::Example::ReferrableT(*vector_of_strong_referrables_) : nullptr); } + vector_of_co_owning_references.reserve(o.vector_of_co_owning_references.size()); + for (const auto &vector_of_co_owning_references_ : o.vector_of_co_owning_references) { vector_of_co_owning_references.emplace_back((vector_of_co_owning_references_) ? new ReferrableT(*vector_of_co_owning_references_) : nullptr); } + scalar_key_sorted_tables.reserve(o.scalar_key_sorted_tables.size()); + for (const auto &scalar_key_sorted_tables_ : o.scalar_key_sorted_tables) { scalar_key_sorted_tables.emplace_back((scalar_key_sorted_tables_) ? new MyGame::Example::StatT(*scalar_key_sorted_tables_) : nullptr); } +} + +inline MonsterT &MonsterT::operator=(MonsterT o) FLATBUFFERS_NOEXCEPT { + std::swap(pos, o.pos); + std::swap(mana, o.mana); + std::swap(hp, o.hp); + std::swap(name, o.name); + std::swap(inventory, o.inventory); + std::swap(color, o.color); + std::swap(test, o.test); + std::swap(test4, o.test4); + std::swap(testarrayofstring, o.testarrayofstring); + std::swap(testarrayoftables, o.testarrayoftables); + std::swap(enemy, o.enemy); + std::swap(testnestedflatbuffer, o.testnestedflatbuffer); + std::swap(testempty, o.testempty); + std::swap(testbool, o.testbool); + std::swap(testhashs32_fnv1, o.testhashs32_fnv1); + std::swap(testhashu32_fnv1, o.testhashu32_fnv1); + std::swap(testhashs64_fnv1, o.testhashs64_fnv1); + std::swap(testhashu64_fnv1, o.testhashu64_fnv1); + std::swap(testhashs32_fnv1a, o.testhashs32_fnv1a); + std::swap(testhashu32_fnv1a, o.testhashu32_fnv1a); + std::swap(testhashs64_fnv1a, o.testhashs64_fnv1a); + std::swap(testhashu64_fnv1a, o.testhashu64_fnv1a); + std::swap(testarrayofbools, o.testarrayofbools); + std::swap(testf, o.testf); + std::swap(testf2, o.testf2); + std::swap(testf3, o.testf3); + std::swap(testarrayofstring2, o.testarrayofstring2); + std::swap(testarrayofsortedstruct, o.testarrayofsortedstruct); + std::swap(flex, o.flex); + std::swap(test5, o.test5); + std::swap(vector_of_longs, o.vector_of_longs); + std::swap(vector_of_doubles, o.vector_of_doubles); + std::swap(parent_namespace_test, o.parent_namespace_test); + std::swap(vector_of_referrables, o.vector_of_referrables); + std::swap(single_weak_reference, o.single_weak_reference); + std::swap(vector_of_weak_references, o.vector_of_weak_references); + std::swap(vector_of_strong_referrables, o.vector_of_strong_referrables); + std::swap(co_owning_reference, o.co_owning_reference); + std::swap(vector_of_co_owning_references, o.vector_of_co_owning_references); + std::swap(non_owning_reference, o.non_owning_reference); + std::swap(vector_of_non_owning_references, o.vector_of_non_owning_references); + std::swap(any_unique, o.any_unique); + std::swap(any_ambiguous, o.any_ambiguous); + std::swap(vector_of_enums, o.vector_of_enums); + std::swap(signed_enum, o.signed_enum); + std::swap(testrequirednestedflatbuffer, o.testrequirednestedflatbuffer); + std::swap(scalar_key_sorted_tables, o.scalar_key_sorted_tables); + std::swap(native_inline, o.native_inline); + std::swap(long_enum_non_enum_default, o.long_enum_non_enum_default); + std::swap(long_enum_normal_default, o.long_enum_normal_default); + std::swap(nan_default, o.nan_default); + std::swap(inf_default, o.inf_default); + std::swap(positive_inf_default, o.positive_inf_default); + std::swap(infinity_default, o.infinity_default); + std::swap(positive_infinity_default, o.positive_infinity_default); + std::swap(negative_inf_default, o.negative_inf_default); + std::swap(negative_infinity_default, o.negative_infinity_default); + std::swap(double_inf_default, o.double_inf_default); + return *this; +} + +inline MonsterT *Monster::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MonsterT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Monster::UnPackTo(MonsterT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = pos(); if (_e) _o->pos = std::unique_ptr(new MyGame::Example::Vec3(*_e)); } + { auto _e = mana(); _o->mana = _e; } + { auto _e = hp(); _o->hp = _e; } + { auto _e = name(); if (_e) _o->name = _e->str(); } + { auto _e = inventory(); if (_e) { _o->inventory.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->inventory.begin()); } } + { auto _e = color(); _o->color = _e; } + { auto _e = test_type(); _o->test.type = _e; } + { auto _e = test(); if (_e) _o->test.value = MyGame::Example::AnyUnion::UnPack(_e, test_type(), _resolver); } + { auto _e = test4(); if (_e) { _o->test4.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test4[_i] = *_e->Get(_i); } } else { _o->test4.resize(0); } } + { auto _e = testarrayofstring(); if (_e) { _o->testarrayofstring.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring.resize(0); } } + { auto _e = testarrayoftables(); if (_e) { _o->testarrayoftables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->testarrayoftables[_i]) { _e->Get(_i)->UnPackTo(_o->testarrayoftables[_i].get(), _resolver); } else { _o->testarrayoftables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->testarrayoftables.resize(0); } } + { auto _e = enemy(); if (_e) { if(_o->enemy) { _e->UnPackTo(_o->enemy.get(), _resolver); } else { _o->enemy = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->enemy) { _o->enemy.reset(); } } + { auto _e = testnestedflatbuffer(); if (_e) { _o->testnestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testnestedflatbuffer.begin()); } } + { auto _e = testempty(); if (_e) { if(_o->testempty) { _e->UnPackTo(_o->testempty.get(), _resolver); } else { _o->testempty = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->testempty) { _o->testempty.reset(); } } + { auto _e = testbool(); _o->testbool = _e; } + { auto _e = testhashs32_fnv1(); _o->testhashs32_fnv1 = _e; } + { auto _e = testhashu32_fnv1(); _o->testhashu32_fnv1 = _e; } + { auto _e = testhashs64_fnv1(); _o->testhashs64_fnv1 = _e; } + { auto _e = testhashu64_fnv1(); _o->testhashu64_fnv1 = _e; } + { auto _e = testhashs32_fnv1a(); _o->testhashs32_fnv1a = _e; } + { auto _e = testhashu32_fnv1a(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->testhashu32_fnv1a), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->testhashu32_fnv1a = nullptr; } + { auto _e = testhashs64_fnv1a(); _o->testhashs64_fnv1a = _e; } + { auto _e = testhashu64_fnv1a(); _o->testhashu64_fnv1a = _e; } + { auto _e = testarrayofbools(); if (_e) { _o->testarrayofbools.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofbools[_i] = _e->Get(_i) != 0; } } else { _o->testarrayofbools.resize(0); } } + { auto _e = testf(); _o->testf = _e; } + { auto _e = testf2(); _o->testf2 = _e; } + { auto _e = testf3(); _o->testf3 = _e; } + { auto _e = testarrayofstring2(); if (_e) { _o->testarrayofstring2.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofstring2[_i] = _e->Get(_i)->str(); } } else { _o->testarrayofstring2.resize(0); } } + { auto _e = testarrayofsortedstruct(); if (_e) { _o->testarrayofsortedstruct.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->testarrayofsortedstruct[_i] = *_e->Get(_i); } } else { _o->testarrayofsortedstruct.resize(0); } } + { auto _e = flex(); if (_e) { _o->flex.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->flex.begin()); } } + { auto _e = test5(); if (_e) { _o->test5.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test5[_i] = *_e->Get(_i); } } else { _o->test5.resize(0); } } + { auto _e = vector_of_longs(); if (_e) { _o->vector_of_longs.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_longs[_i] = _e->Get(_i); } } else { _o->vector_of_longs.resize(0); } } + { auto _e = vector_of_doubles(); if (_e) { _o->vector_of_doubles.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_doubles[_i] = _e->Get(_i); } } else { _o->vector_of_doubles.resize(0); } } + { auto _e = parent_namespace_test(); if (_e) { if(_o->parent_namespace_test) { _e->UnPackTo(_o->parent_namespace_test.get(), _resolver); } else { _o->parent_namespace_test = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->parent_namespace_test) { _o->parent_namespace_test.reset(); } } + { auto _e = vector_of_referrables(); if (_e) { _o->vector_of_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_referrables[_i].get(), _resolver); } else { _o->vector_of_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_referrables.resize(0); } } + { auto _e = single_weak_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->single_weak_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->single_weak_reference = nullptr; } + { auto _e = vector_of_weak_references(); if (_e) { _o->vector_of_weak_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_weak_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_weak_references[_i] = nullptr; } } else { _o->vector_of_weak_references.resize(0); } } + { auto _e = vector_of_strong_referrables(); if (_e) { _o->vector_of_strong_referrables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->vector_of_strong_referrables[_i]) { _e->Get(_i)->UnPackTo(_o->vector_of_strong_referrables[_i].get(), _resolver); } else { _o->vector_of_strong_referrables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->vector_of_strong_referrables.resize(0); } } + { auto _e = co_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->co_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->co_owning_reference = nullptr; } + { auto _e = vector_of_co_owning_references(); if (_e) { _o->vector_of_co_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, default_ptr_type*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_co_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i)));/* else do nothing */} } else { _o->vector_of_co_owning_references.resize(0); } } + { auto _e = non_owning_reference(); /*scalar resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->non_owning_reference), static_cast<::flatbuffers::hash_value_t>(_e)); else _o->non_owning_reference = nullptr; } + { auto _e = vector_of_non_owning_references(); if (_e) { _o->vector_of_non_owning_references.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { /*vector resolver, naked*/ if (_resolver) (*_resolver)(reinterpret_cast(&_o->vector_of_non_owning_references[_i]), static_cast<::flatbuffers::hash_value_t>(_e->Get(_i))); else _o->vector_of_non_owning_references[_i] = nullptr; } } else { _o->vector_of_non_owning_references.resize(0); } } + { auto _e = any_unique_type(); _o->any_unique.type = _e; } + { auto _e = any_unique(); if (_e) _o->any_unique.value = MyGame::Example::AnyUniqueAliasesUnion::UnPack(_e, any_unique_type(), _resolver); } + { auto _e = any_ambiguous_type(); _o->any_ambiguous.type = _e; } + { auto _e = any_ambiguous(); if (_e) _o->any_ambiguous.value = MyGame::Example::AnyAmbiguousAliasesUnion::UnPack(_e, any_ambiguous_type(), _resolver); } + { auto _e = vector_of_enums(); if (_e) { _o->vector_of_enums.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vector_of_enums[_i] = static_cast(_e->Get(_i)); } } else { _o->vector_of_enums.resize(0); } } + { auto _e = signed_enum(); _o->signed_enum = _e; } + { auto _e = testrequirednestedflatbuffer(); if (_e) { _o->testrequirednestedflatbuffer.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->testrequirednestedflatbuffer.begin()); } } + { auto _e = scalar_key_sorted_tables(); if (_e) { _o->scalar_key_sorted_tables.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { if(_o->scalar_key_sorted_tables[_i]) { _e->Get(_i)->UnPackTo(_o->scalar_key_sorted_tables[_i].get(), _resolver); } else { _o->scalar_key_sorted_tables[_i] = std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } } else { _o->scalar_key_sorted_tables.resize(0); } } + { auto _e = native_inline(); if (_e) _o->native_inline = *_e; } + { auto _e = long_enum_non_enum_default(); _o->long_enum_non_enum_default = _e; } + { auto _e = long_enum_normal_default(); _o->long_enum_normal_default = _e; } + { auto _e = nan_default(); _o->nan_default = _e; } + { auto _e = inf_default(); _o->inf_default = _e; } + { auto _e = positive_inf_default(); _o->positive_inf_default = _e; } + { auto _e = infinity_default(); _o->infinity_default = _e; } + { auto _e = positive_infinity_default(); _o->positive_infinity_default = _e; } + { auto _e = negative_inf_default(); _o->negative_inf_default = _e; } + { auto _e = negative_infinity_default(); _o->negative_infinity_default = _e; } + { auto _e = double_inf_default(); _o->double_inf_default = _e; } +} + +inline ::flatbuffers::Offset Monster::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMonster(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMonster(::flatbuffers::FlatBufferBuilder &_fbb, const MonsterT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MonsterT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _pos = _o->pos ? _o->pos.get() : nullptr; + auto _mana = _o->mana; + auto _hp = _o->hp; + auto _name = _fbb.CreateString(_o->name); + auto _inventory = _o->inventory.size() ? _fbb.CreateVector(_o->inventory) : 0; + auto _color = _o->color; + auto _test_type = _o->test.type; + auto _test = _o->test.Pack(_fbb); + auto _test4 = _o->test4.size() ? _fbb.CreateVectorOfStructs(_o->test4) : 0; + auto _testarrayofstring = _o->testarrayofstring.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring) : 0; + auto _testarrayoftables = _o->testarrayoftables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->testarrayoftables.size(), [](size_t i, _VectorArgs *__va) { return CreateMonster(*__va->__fbb, __va->__o->testarrayoftables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _enemy = _o->enemy ? CreateMonster(_fbb, _o->enemy.get(), _rehasher) : 0; + auto _testnestedflatbuffer = _o->testnestedflatbuffer.size() ? _fbb.CreateVector(_o->testnestedflatbuffer) : 0; + auto _testempty = _o->testempty ? CreateStat(_fbb, _o->testempty.get(), _rehasher) : 0; + auto _testbool = _o->testbool; + auto _testhashs32_fnv1 = _o->testhashs32_fnv1; + auto _testhashu32_fnv1 = _o->testhashu32_fnv1; + auto _testhashs64_fnv1 = _o->testhashs64_fnv1; + auto _testhashu64_fnv1 = _o->testhashu64_fnv1; + auto _testhashs32_fnv1a = _o->testhashs32_fnv1a; + auto _testhashu32_fnv1a = _rehasher ? static_cast((*_rehasher)(_o->testhashu32_fnv1a)) : 0; + auto _testhashs64_fnv1a = _o->testhashs64_fnv1a; + auto _testhashu64_fnv1a = _o->testhashu64_fnv1a; + auto _testarrayofbools = _o->testarrayofbools.size() ? _fbb.CreateVector(_o->testarrayofbools) : 0; + auto _testf = _o->testf; + auto _testf2 = _o->testf2; + auto _testf3 = _o->testf3; + auto _testarrayofstring2 = _o->testarrayofstring2.size() ? _fbb.CreateVectorOfStrings(_o->testarrayofstring2) : 0; + auto _testarrayofsortedstruct = _o->testarrayofsortedstruct.size() ? _fbb.CreateVectorOfStructs(_o->testarrayofsortedstruct) : 0; + auto _flex = _o->flex.size() ? _fbb.CreateVector(_o->flex) : 0; + auto _test5 = _o->test5.size() ? _fbb.CreateVectorOfStructs(_o->test5) : 0; + auto _vector_of_longs = _o->vector_of_longs.size() ? _fbb.CreateVector(_o->vector_of_longs) : 0; + auto _vector_of_doubles = _o->vector_of_doubles.size() ? _fbb.CreateVector(_o->vector_of_doubles) : 0; + auto _parent_namespace_test = _o->parent_namespace_test ? CreateInParentNamespace(_fbb, _o->parent_namespace_test.get(), _rehasher) : 0; + auto _vector_of_referrables = _o->vector_of_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _single_weak_reference = _rehasher ? static_cast((*_rehasher)(_o->single_weak_reference)) : 0; + auto _vector_of_weak_references = _o->vector_of_weak_references.size() ? _fbb.CreateVector(_o->vector_of_weak_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_weak_references[i])) : 0; }, &_va ) : 0; + auto _vector_of_strong_referrables = _o->vector_of_strong_referrables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->vector_of_strong_referrables.size(), [](size_t i, _VectorArgs *__va) { return CreateReferrable(*__va->__fbb, __va->__o->vector_of_strong_referrables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _co_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->co_owning_reference)) : 0; + auto _vector_of_co_owning_references = _o->vector_of_co_owning_references.size() ? _fbb.CreateVector(_o->vector_of_co_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_co_owning_references[i].get())) : 0; }, &_va ) : 0; + auto _non_owning_reference = _rehasher ? static_cast((*_rehasher)(_o->non_owning_reference)) : 0; + auto _vector_of_non_owning_references = _o->vector_of_non_owning_references.size() ? _fbb.CreateVector(_o->vector_of_non_owning_references.size(), [](size_t i, _VectorArgs *__va) { return __va->__rehasher ? static_cast((*__va->__rehasher)(__va->__o->vector_of_non_owning_references[i])) : 0; }, &_va ) : 0; + auto _any_unique_type = _o->any_unique.type; + auto _any_unique = _o->any_unique.Pack(_fbb); + auto _any_ambiguous_type = _o->any_ambiguous.type; + auto _any_ambiguous = _o->any_ambiguous.Pack(_fbb); + auto _vector_of_enums = _o->vector_of_enums.size() ? _fbb.CreateVectorScalarCast(::flatbuffers::data(_o->vector_of_enums), _o->vector_of_enums.size()) : 0; + auto _signed_enum = _o->signed_enum; + auto _testrequirednestedflatbuffer = _o->testrequirednestedflatbuffer.size() ? _fbb.CreateVector(_o->testrequirednestedflatbuffer) : 0; + auto _scalar_key_sorted_tables = _o->scalar_key_sorted_tables.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->scalar_key_sorted_tables.size(), [](size_t i, _VectorArgs *__va) { return CreateStat(*__va->__fbb, __va->__o->scalar_key_sorted_tables[i].get(), __va->__rehasher); }, &_va ) : 0; + auto _native_inline = &_o->native_inline; + auto _long_enum_non_enum_default = _o->long_enum_non_enum_default; + auto _long_enum_normal_default = _o->long_enum_normal_default; + auto _nan_default = _o->nan_default; + auto _inf_default = _o->inf_default; + auto _positive_inf_default = _o->positive_inf_default; + auto _infinity_default = _o->infinity_default; + auto _positive_infinity_default = _o->positive_infinity_default; + auto _negative_inf_default = _o->negative_inf_default; + auto _negative_infinity_default = _o->negative_infinity_default; + auto _double_inf_default = _o->double_inf_default; + return MyGame::Example::CreateMonster( + _fbb, + _pos, + _mana, + _hp, + _name, + _inventory, + _color, + _test_type, + _test, + _test4, + _testarrayofstring, + _testarrayoftables, + _enemy, + _testnestedflatbuffer, + _testempty, + _testbool, + _testhashs32_fnv1, + _testhashu32_fnv1, + _testhashs64_fnv1, + _testhashu64_fnv1, + _testhashs32_fnv1a, + _testhashu32_fnv1a, + _testhashs64_fnv1a, + _testhashu64_fnv1a, + _testarrayofbools, + _testf, + _testf2, + _testf3, + _testarrayofstring2, + _testarrayofsortedstruct, + _flex, + _test5, + _vector_of_longs, + _vector_of_doubles, + _parent_namespace_test, + _vector_of_referrables, + _single_weak_reference, + _vector_of_weak_references, + _vector_of_strong_referrables, + _co_owning_reference, + _vector_of_co_owning_references, + _non_owning_reference, + _vector_of_non_owning_references, + _any_unique_type, + _any_unique, + _any_ambiguous_type, + _any_ambiguous, + _vector_of_enums, + _signed_enum, + _testrequirednestedflatbuffer, + _scalar_key_sorted_tables, + _native_inline, + _long_enum_non_enum_default, + _long_enum_normal_default, + _nan_default, + _inf_default, + _positive_inf_default, + _infinity_default, + _positive_infinity_default, + _negative_inf_default, + _negative_infinity_default, + _double_inf_default); +} + + +inline bool operator==(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return + (lhs.i8 == rhs.i8) && + (lhs.u8 == rhs.u8) && + (lhs.i16 == rhs.i16) && + (lhs.u16 == rhs.u16) && + (lhs.i32 == rhs.i32) && + (lhs.u32 == rhs.u32) && + (lhs.i64 == rhs.i64) && + (lhs.u64 == rhs.u64) && + (lhs.f32 == rhs.f32) && + (lhs.f64 == rhs.f64) && + (lhs.v8 == rhs.v8) && + (lhs.vf64 == rhs.vf64); +} + +inline bool operator!=(const TypeAliasesT &lhs, const TypeAliasesT &rhs) { + return !(lhs == rhs); +} + + +inline TypeAliasesT *TypeAliases::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TypeAliasesT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TypeAliases::UnPackTo(TypeAliasesT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = i8(); _o->i8 = _e; } + { auto _e = u8(); _o->u8 = _e; } + { auto _e = i16(); _o->i16 = _e; } + { auto _e = u16(); _o->u16 = _e; } + { auto _e = i32(); _o->i32 = _e; } + { auto _e = u32(); _o->u32 = _e; } + { auto _e = i64(); _o->i64 = _e; } + { auto _e = u64(); _o->u64 = _e; } + { auto _e = f32(); _o->f32 = _e; } + { auto _e = f64(); _o->f64 = _e; } + { auto _e = v8(); if (_e) { _o->v8.resize(_e->size()); std::copy(_e->begin(), _e->end(), _o->v8.begin()); } } + { auto _e = vf64(); if (_e) { _o->vf64.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vf64[_i] = _e->Get(_i); } } else { _o->vf64.resize(0); } } +} + +inline ::flatbuffers::Offset TypeAliases::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTypeAliases(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTypeAliases(::flatbuffers::FlatBufferBuilder &_fbb, const TypeAliasesT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TypeAliasesT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _i8 = _o->i8; + auto _u8 = _o->u8; + auto _i16 = _o->i16; + auto _u16 = _o->u16; + auto _i32 = _o->i32; + auto _u32 = _o->u32; + auto _i64 = _o->i64; + auto _u64 = _o->u64; + auto _f32 = _o->f32; + auto _f64 = _o->f64; + auto _v8 = _o->v8.size() ? _fbb.CreateVector(_o->v8) : 0; + auto _vf64 = _o->vf64.size() ? _fbb.CreateVector(_o->vf64) : 0; + return MyGame::Example::CreateTypeAliases( + _fbb, + _i8, + _u8, + _i16, + _u16, + _i32, + _u32, + _i64, + _u64, + _f32, + _f64, + _v8, + _vf64); +} + +inline bool VerifyAny(::flatbuffers::Verifier &verifier, const void *obj, Any type) { + switch (type) { + case Any_NONE: { + return true; + } + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAny( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUnion::UnPack(const void *obj, Any type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUnion::AnyUnion(const AnyUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Any_Monster: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case Any_TestSimpleTableWithEnum: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case Any_MyGame_Example2_Monster: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUnion::Reset() { + switch (type) { + case Any_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_TestSimpleTableWithEnum: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Any_MyGame_Example2_Monster: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Any_NONE; +} + +inline bool VerifyAnyUniqueAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyUniqueAliases type) { + switch (type) { + case AnyUniqueAliases_NONE: { + return true; + } + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyUniqueAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyUniqueAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyUniqueAliasesUnion::UnPack(const void *obj, AnyUniqueAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyUniqueAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + return CreateTestSimpleTableWithEnum(_fbb, ptr, _rehasher).Union(); + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyUniqueAliasesUnion::AnyUniqueAliasesUnion(const AnyUniqueAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyUniqueAliases_M: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_TS: { + value = new MyGame::Example::TestSimpleTableWithEnumT(*reinterpret_cast(u.value)); + break; + } + case AnyUniqueAliases_M2: { + value = new MyGame::Example2::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyUniqueAliasesUnion::Reset() { + switch (type) { + case AnyUniqueAliases_M: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_TS: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyUniqueAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyUniqueAliases_NONE; +} + +inline bool VerifyAnyAmbiguousAliases(::flatbuffers::Verifier &verifier, const void *obj, AnyAmbiguousAliases type) { + switch (type) { + case AnyAmbiguousAliases_NONE: { + return true; + } + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyAnyAmbiguousAliasesVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyAnyAmbiguousAliases( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *AnyAmbiguousAliasesUnion::UnPack(const void *obj, AnyAmbiguousAliases type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset AnyAmbiguousAliasesUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + return CreateMonster(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline AnyAmbiguousAliasesUnion::AnyAmbiguousAliasesUnion(const AnyAmbiguousAliasesUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case AnyAmbiguousAliases_M1: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M2: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + case AnyAmbiguousAliases_M3: { + value = new MyGame::Example::MonsterT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void AnyAmbiguousAliasesUnion::Reset() { + switch (type) { + case AnyAmbiguousAliases_M1: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M2: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case AnyAmbiguousAliases_M3: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = AnyAmbiguousAliases_NONE; +} + +inline const ::flatbuffers::TypeTable *ColorTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const int64_t values[] = { 1, 2, 8 }; + static const char * const names[] = { + "Red", + "Green", + "Blue" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RaceTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::RaceTypeTable + }; + static const int64_t values[] = { -1, 0, 1, 2 }; + static const char * const names[] = { + "None", + "Human", + "Dwarf", + "Elf" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 4, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *LongEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 }, + { ::flatbuffers::ET_ULONG, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::LongEnumTypeTable + }; + static const int64_t values[] = { 2ULL, 4ULL, 1099511627776ULL }; + static const char * const names[] = { + "LongOne", + "LongTwo", + "LongBig" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "Monster", + "TestSimpleTableWithEnum", + "MyGame_Example2_Monster" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyUniqueAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable, + MyGame::Example::TestSimpleTableWithEnumTypeTable, + MyGame::Example2::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M", + "TS", + "M2" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AnyAmbiguousAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::MonsterTypeTable + }; + static const char * const names[] = { + "NONE", + "M1", + "M2", + "M3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace Example + +inline const ::flatbuffers::TypeTable *InParentNamespaceTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +namespace Example2 { + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 0, nullptr, nullptr, nullptr, nullptr, nullptr + }; + return &tt; +} + +} // namespace Example2 + +namespace Example { + +inline const ::flatbuffers::TypeTable *TestTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 } + }; + static const int64_t values[] = { 0, 2, 4 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TestSimpleTableWithEnumTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UCHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable + }; + static const char * const names[] = { + "color" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *Vec3TypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::ColorTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 4, 8, 16, 24, 26, 32 }; + static const char * const names[] = { + "x", + "y", + "z", + "test1", + "test2", + "test3" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 6, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AbilityTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "id", + "distance" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::AbilityTypeTable, + MyGame::Example::TestTypeTable + }; + static const int64_t values[] = { 0, 8, 12, 20 }; + static const char * const names[] = { + "a", + "b", + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructOfStructsOfStructsTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::StructOfStructsTypeTable + }; + static const int64_t values[] = { 0, 20 }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StatTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 } + }; + static const char * const names[] = { + "id", + "val", + "count" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 3, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ReferrableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_ULONG, 0, -1 } + }; + static const char * const names[] = { + "id" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MonsterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_UCHAR, 0, 1 }, + { ::flatbuffers::ET_UTYPE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 4 }, + { ::flatbuffers::ET_SEQUENCE, 0, 4 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 5 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_BOOL, 1, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_STRING, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 6 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 3 }, + { ::flatbuffers::ET_LONG, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 7 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 8 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 1, -1 }, + { ::flatbuffers::ET_UTYPE, 0, 9 }, + { ::flatbuffers::ET_SEQUENCE, 0, 9 }, + { ::flatbuffers::ET_UTYPE, 0, 10 }, + { ::flatbuffers::ET_SEQUENCE, 0, 10 }, + { ::flatbuffers::ET_UCHAR, 1, 1 }, + { ::flatbuffers::ET_CHAR, 0, 11 }, + { ::flatbuffers::ET_UCHAR, 1, -1 }, + { ::flatbuffers::ET_SEQUENCE, 1, 5 }, + { ::flatbuffers::ET_SEQUENCE, 0, 3 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_ULONG, 0, 12 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + MyGame::Example::Vec3TypeTable, + MyGame::Example::ColorTypeTable, + MyGame::Example::AnyTypeTable, + MyGame::Example::TestTypeTable, + MyGame::Example::MonsterTypeTable, + MyGame::Example::StatTypeTable, + MyGame::Example::AbilityTypeTable, + MyGame::InParentNamespaceTypeTable, + MyGame::Example::ReferrableTypeTable, + MyGame::Example::AnyUniqueAliasesTypeTable, + MyGame::Example::AnyAmbiguousAliasesTypeTable, + MyGame::Example::RaceTypeTable, + MyGame::Example::LongEnumTypeTable + }; + static const char * const names[] = { + "pos", + "mana", + "hp", + "name", + "friendly", + "inventory", + "color", + "test_type", + "test", + "test4", + "testarrayofstring", + "testarrayoftables", + "enemy", + "testnestedflatbuffer", + "testempty", + "testbool", + "testhashs32_fnv1", + "testhashu32_fnv1", + "testhashs64_fnv1", + "testhashu64_fnv1", + "testhashs32_fnv1a", + "testhashu32_fnv1a", + "testhashs64_fnv1a", + "testhashu64_fnv1a", + "testarrayofbools", + "testf", + "testf2", + "testf3", + "testarrayofstring2", + "testarrayofsortedstruct", + "flex", + "test5", + "vector_of_longs", + "vector_of_doubles", + "parent_namespace_test", + "vector_of_referrables", + "single_weak_reference", + "vector_of_weak_references", + "vector_of_strong_referrables", + "co_owning_reference", + "vector_of_co_owning_references", + "non_owning_reference", + "vector_of_non_owning_references", + "any_unique_type", + "any_unique", + "any_ambiguous_type", + "any_ambiguous", + "vector_of_enums", + "signed_enum", + "testrequirednestedflatbuffer", + "scalar_key_sorted_tables", + "native_inline", + "long_enum_non_enum_default", + "long_enum_normal_default", + "nan_default", + "inf_default", + "positive_inf_default", + "infinity_default", + "positive_infinity_default", + "negative_inf_default", + "negative_infinity_default", + "double_inf_default" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 62, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TypeAliasesTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_CHAR, 1, -1 }, + { ::flatbuffers::ET_DOUBLE, 1, -1 } + }; + static const char * const names[] = { + "i8", + "u8", + "i16", + "u16", + "i32", + "u32", + "i64", + "u64", + "f32", + "f64", + "v8", + "vf64" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 12, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const MyGame::Example::Monster *GetMonster(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const MyGame::Example::Monster *GetSizePrefixedMonster(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Monster *GetMutableMonster(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline MyGame::Example::Monster *GetMutableSizePrefixedMonster(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MonsterIdentifier() { + return "MONS"; +} + +inline bool MonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier()); +} + +inline bool SizePrefixedMonsterBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MonsterIdentifier(), true); +} + +inline bool VerifyMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MonsterIdentifier()); +} + +inline bool VerifySizePrefixedMonsterBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MonsterIdentifier()); +} + +inline const char *MonsterExtension() { + return "mon"; +} + +inline void FinishMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MonsterIdentifier()); +} + +inline void FinishSizePrefixedMonsterBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MonsterIdentifier()); +} + +inline std::unique_ptr UnPackMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMonster(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMonster( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMonster(buf)->UnPack(res)); +} + +} // namespace Example +} // namespace MyGame + +#endif // FLATBUFFERS_GENERATED_MONSTERTEST_MYGAME_EXAMPLE_H_ diff --git a/third_party/flatbuffers/tests/monsterdata_extra.json b/third_party/flatbuffers/tests/monsterdata_extra.json new file mode 100644 index 00000000000..53045cdd59c --- /dev/null +++ b/third_party/flatbuffers/tests/monsterdata_extra.json @@ -0,0 +1,15 @@ +{ + // Initialize with non-default values. + d0 : -nan, // match with default + d1 : +inf, + d2 : -inf, + d3: nan, + f0 : +nan, // match with default + f1 : -nan, // match with default + f2 : +inf, // match with default + f3 : -inf, // match with default + // Values should have exact binary representation + // to avoid rounding effects in tests. + dvec : [2.0, +inf, -inf, nan,], + fvec : [1.0, -inf, +inf, nan], +} diff --git a/third_party/flatbuffers/tests/monsterdata_go_wire.mon.sp b/third_party/flatbuffers/tests/monsterdata_go_wire.mon.sp new file mode 100644 index 00000000000..daddcd0e68e Binary files /dev/null and b/third_party/flatbuffers/tests/monsterdata_go_wire.mon.sp differ diff --git a/third_party/flatbuffers/tests/monsterdata_python_wire.mon b/third_party/flatbuffers/tests/monsterdata_python_wire.mon new file mode 100644 index 00000000000..2fb956d58c9 Binary files /dev/null and b/third_party/flatbuffers/tests/monsterdata_python_wire.mon differ diff --git a/third_party/flatbuffers/tests/monsterdata_test.afb b/third_party/flatbuffers/tests/monsterdata_test.afb new file mode 100644 index 00000000000..225ff439213 --- /dev/null +++ b/third_party/flatbuffers/tests/monsterdata_test.afb @@ -0,0 +1,276 @@ +// Annotated Flatbuffer Binary +// +// Schema file: monster_test.fbs +// Binary file: monsterdata_test.mon + +header: + +0x0000 | 78 00 00 00 | UOffset32 | 0x00000078 (120) Loc: 0x0078 | offset to root table `MyGame.Example.Monster` + +0x0004 | 4D 4F 4E 53 | char[4] | MONS | File Identifier + +padding: + +0x0008 | 00 00 00 00 | uint8_t[4] | .... | padding + +vtable (MyGame.Example.Monster): + +0x000C | 6C 00 | uint16_t | 0x006C (108) | size of this vtable + +0x000E | 94 00 | uint16_t | 0x0094 (148) | size of referring table + +0x0010 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `pos` (id: 0) + +0x0012 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `mana` (id: 1) (Short) + +0x0014 | 06 00 | VOffset16 | 0x0006 (6) | offset to field `hp` (id: 2) + +0x0016 | 2C 00 | VOffset16 | 0x002C (44) | offset to field `name` (id: 3) + +0x0018 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `friendly` (id: 4) (Bool) + +0x001A | 30 00 | VOffset16 | 0x0030 (48) | offset to field `inventory` (id: 5) + +0x001C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `color` (id: 6) (UByte) + +0x001E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `test_type` (id: 7) + +0x0020 | 34 00 | VOffset16 | 0x0034 (52) | offset to field `test` (id: 8) + +0x0022 | 38 00 | VOffset16 | 0x0038 (56) | offset to field `test4` (id: 9) + +0x0024 | 3C 00 | VOffset16 | 0x003C (60) | offset to field `testarrayofstring` (id: 10) + +0x0026 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testarrayoftables` (id: 11) (Vector) + +0x0028 | 40 00 | VOffset16 | 0x0040 (64) | offset to field `enemy` (id: 12) + +0x002A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testnestedflatbuffer` (id: 13) (Vector) + +0x002C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testempty` (id: 14) (Obj) + +0x002E | 05 00 | VOffset16 | 0x0005 (5) | offset to field `testbool` (id: 15) + +0x0030 | 44 00 | VOffset16 | 0x0044 (68) | offset to field `testhashs32_fnv1` (id: 16) + +0x0032 | 48 00 | VOffset16 | 0x0048 (72) | offset to field `testhashu32_fnv1` (id: 17) + +0x0034 | 70 00 | VOffset16 | 0x0070 (112) | offset to field `testhashs64_fnv1` (id: 18) + +0x0036 | 78 00 | VOffset16 | 0x0078 (120) | offset to field `testhashu64_fnv1` (id: 19) + +0x0038 | 4C 00 | VOffset16 | 0x004C (76) | offset to field `testhashs32_fnv1a` (id: 20) + +0x003A | 50 00 | VOffset16 | 0x0050 (80) | offset to field `testhashu32_fnv1a` (id: 21) + +0x003C | 80 00 | VOffset16 | 0x0080 (128) | offset to field `testhashs64_fnv1a` (id: 22) + +0x003E | 88 00 | VOffset16 | 0x0088 (136) | offset to field `testhashu64_fnv1a` (id: 23) + +0x0040 | 54 00 | VOffset16 | 0x0054 (84) | offset to field `testarrayofbools` (id: 24) + +0x0042 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testf` (id: 25) (Float) + +0x0044 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testf2` (id: 26) (Float) + +0x0046 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testf3` (id: 27) (Float) + +0x0048 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testarrayofstring2` (id: 28) (Vector) + +0x004A | 58 00 | VOffset16 | 0x0058 (88) | offset to field `testarrayofsortedstruct` (id: 29) + +0x004C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `flex` (id: 30) (Vector) + +0x004E | 5C 00 | VOffset16 | 0x005C (92) | offset to field `test5` (id: 31) + +0x0050 | 60 00 | VOffset16 | 0x0060 (96) | offset to field `vector_of_longs` (id: 32) + +0x0052 | 64 00 | VOffset16 | 0x0064 (100) | offset to field `vector_of_doubles` (id: 33) + +0x0054 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `parent_namespace_test` (id: 34) (Obj) + +0x0056 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `vector_of_referrables` (id: 35) (Vector) + +0x0058 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `single_weak_reference` (id: 36) (ULong) + +0x005A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `vector_of_weak_references` (id: 37) (Vector) + +0x005C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `vector_of_strong_referrables` (id: 38) (Vector) + +0x005E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `co_owning_reference` (id: 39) (ULong) + +0x0060 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `vector_of_co_owning_references` (id: 40) (Vector) + +0x0062 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `non_owning_reference` (id: 41) (ULong) + +0x0064 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `vector_of_non_owning_references` (id: 42) (Vector) + +0x0066 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `any_unique_type` (id: 43) (UType) + +0x0068 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `any_unique` (id: 44) (Union) + +0x006A | 00 00 | VOffset16 | 0x0000 (0) | offset to field `any_ambiguous_type` (id: 45) (UType) + +0x006C | 00 00 | VOffset16 | 0x0000 (0) | offset to field `any_ambiguous` (id: 46) (Union) + +0x006E | 00 00 | VOffset16 | 0x0000 (0) | offset to field `vector_of_enums` (id: 47) (Vector) + +0x0070 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `signed_enum` (id: 48) (Byte) + +0x0072 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `testrequirednestedflatbuffer` (id: 49) (Vector) + +0x0074 | 68 00 | VOffset16 | 0x0068 (104) | offset to field `scalar_key_sorted_tables` (id: 50) + +0x0076 | 6C 00 | VOffset16 | 0x006C (108) | offset to field `native_inline` (id: 51) + +root_table (MyGame.Example.Monster): + +0x0078 | 6C 00 00 00 | SOffset32 | 0x0000006C (108) Loc: 0x000C | offset to vtable + +0x007C | 01 | UType8 | 0x01 (1) | table field `test_type` (UType) + +0x007D | 01 | uint8_t | 0x01 (1) | table field `testbool` (Bool) + +0x007E | 50 00 | int16_t | 0x0050 (80) | table field `hp` (Short) + +0x0080 | 00 00 80 3F | float | 0x3F800000 (1) | struct field `pos.x` of 'MyGame.Example.Vec3' (Float) + +0x0084 | 00 00 00 40 | float | 0x40000000 (2) | struct field `pos.y` of 'MyGame.Example.Vec3' (Float) + +0x0088 | 00 00 40 40 | float | 0x40400000 (3) | struct field `pos.z` of 'MyGame.Example.Vec3' (Float) + +0x008C | 00 00 00 00 | uint8_t[4] | .... | padding + +0x0090 | 00 00 00 00 00 00 08 40 | double | 0x4008000000000000 (3) | struct field `pos.test1` of 'MyGame.Example.Vec3' (Double) + +0x0098 | 02 | uint8_t | 0x02 (2) | struct field `pos.test2` of 'MyGame.Example.Vec3' (UByte) + +0x0099 | 00 | uint8_t[1] | . | padding + +0x009A | 05 00 | int16_t | 0x0005 (5) | struct field `pos.test3.a` of 'MyGame.Example.Test' (Short) + +0x009C | 06 | uint8_t | 0x06 (6) | struct field `pos.test3.b` of 'MyGame.Example.Test' (Byte) + +0x009D | 00 | uint8_t[1] | . | padding + +0x009E | 00 00 | uint8_t[2] | .. | padding + +0x00A0 | 00 00 00 00 | uint8_t[4] | .... | padding + +0x00A4 | A4 01 00 00 | UOffset32 | 0x000001A4 (420) Loc: 0x0248 | offset to field `name` (string) + +0x00A8 | 94 01 00 00 | UOffset32 | 0x00000194 (404) Loc: 0x023C | offset to field `inventory` (vector) + +0x00AC | 2C 01 00 00 | UOffset32 | 0x0000012C (300) Loc: 0x01D8 | offset to field `test` (union of type `Monster`) + +0x00B0 | 10 01 00 00 | UOffset32 | 0x00000110 (272) Loc: 0x01C0 | offset to field `test4` (vector) + +0x00B4 | DC 00 00 00 | UOffset32 | 0x000000DC (220) Loc: 0x0190 | offset to field `testarrayofstring` (vector) + +0x00B8 | C4 00 00 00 | UOffset32 | 0x000000C4 (196) Loc: 0x017C | offset to field `enemy` (table) + +0x00BC | 41 C9 79 DD | uint32_t | 0xDD79C941 (3715746113) | table field `testhashs32_fnv1` (Int) + +0x00C0 | 41 C9 79 DD | uint32_t | 0xDD79C941 (3715746113) | table field `testhashu32_fnv1` (UInt) + +0x00C4 | 71 A4 81 8E | uint32_t | 0x8E81A471 (2390860913) | table field `testhashs32_fnv1a` (Int) + +0x00C8 | 71 A4 81 8E | uint32_t | 0x8E81A471 (2390860913) | table field `testhashu32_fnv1a` (UInt) + +0x00CC | A8 00 00 00 | UOffset32 | 0x000000A8 (168) Loc: 0x0174 | offset to field `testarrayofbools` (vector) + +0x00D0 | 88 00 00 00 | UOffset32 | 0x00000088 (136) Loc: 0x0158 | offset to field `testarrayofsortedstruct` (vector) + +0x00D4 | E0 00 00 00 | UOffset32 | 0x000000E0 (224) Loc: 0x01B4 | offset to field `test5` (vector) + +0x00D8 | 34 01 00 00 | UOffset32 | 0x00000134 (308) Loc: 0x020C | offset to field `vector_of_longs` (vector) + +0x00DC | 10 01 00 00 | UOffset32 | 0x00000110 (272) Loc: 0x01EC | offset to field `vector_of_doubles` (vector) + +0x00E0 | 2C 00 00 00 | UOffset32 | 0x0000002C (44) Loc: 0x010C | offset to field `scalar_key_sorted_tables` (vector) + +0x00E4 | 01 00 | int16_t | 0x0001 (1) | struct field `native_inline.a` of 'MyGame.Example.Test' (Short) + +0x00E6 | 02 | uint8_t | 0x02 (2) | struct field `native_inline.b` of 'MyGame.Example.Test' (Byte) + +0x00E7 | 00 | uint8_t[1] | . | padding + +0x00E8 | 81 91 7B F2 CD 80 0F 6E | int64_t | 0x6E0F80CDF27B9181 (7930699090847568257) | table field `testhashs64_fnv1` (Long) + +0x00F0 | 81 91 7B F2 CD 80 0F 6E | uint64_t | 0x6E0F80CDF27B9181 (7930699090847568257) | table field `testhashu64_fnv1` (ULong) + +0x00F8 | F1 DD 67 C7 DC 48 F9 43 | int64_t | 0x43F948DCC767DDF1 (4898026182817603057) | table field `testhashs64_fnv1a` (Long) + +0x0100 | F1 DD 67 C7 DC 48 F9 43 | uint64_t | 0x43F948DCC767DDF1 (4898026182817603057) | table field `testhashu64_fnv1a` (ULong) + +0x0108 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (MyGame.Example.Monster.scalar_key_sorted_tables): + +0x010C | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x0110 | 10 00 00 00 | UOffset32 | 0x00000010 (16) Loc: 0x0120 | offset to table[0] + +0x0114 | 28 00 00 00 | UOffset32 | 0x00000028 (40) Loc: 0x013C | offset to table[1] + +padding: + +0x0118 | 00 00 | uint8_t[2] | .. | padding + +vtable (MyGame.Example.Stat): + +0x011A | 06 00 | uint16_t | 0x0006 (6) | size of this vtable + +0x011C | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x011E | 04 00 | VOffset16 | 0x0004 (4) | offset to field `id` (id: 0) + +table (MyGame.Example.Stat): + +0x0120 | 06 00 00 00 | SOffset32 | 0x00000006 (6) Loc: 0x011A | offset to vtable + +0x0124 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0128 | offset to field `id` (string) + +string (MyGame.Example.Stat.id): + +0x0128 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x012C | 6D 69 73 73 | char[4] | miss | string literal + +0x0130 | 00 | char | 0x00 (0) | string terminator + +vtable (MyGame.Example.Stat): + +0x0132 | 0A 00 | uint16_t | 0x000A (10) | size of this vtable + +0x0134 | 14 00 | uint16_t | 0x0014 (20) | size of referring table + +0x0136 | 08 00 | VOffset16 | 0x0008 (8) | offset to field `id` (id: 0) + +0x0138 | 0C 00 | VOffset16 | 0x000C (12) | offset to field `val` (id: 1) + +0x013A | 06 00 | VOffset16 | 0x0006 (6) | offset to field `count` (id: 2) + +table (MyGame.Example.Stat): + +0x013C | 0A 00 00 00 | SOffset32 | 0x0000000A (10) Loc: 0x0132 | offset to vtable + +0x0140 | 00 00 | uint8_t[2] | .. | padding + +0x0142 | 01 00 | uint16_t | 0x0001 (1) | table field `count` (UShort) + +0x0144 | 0C 00 00 00 | UOffset32 | 0x0000000C (12) Loc: 0x0150 | offset to field `id` (string) + +0x0148 | 0A 00 00 00 00 00 00 00 | int64_t | 0x000000000000000A (10) | table field `val` (Long) + +string (MyGame.Example.Stat.id): + +0x0150 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of string + +0x0154 | 68 69 74 | char[3] | hit | string literal + +0x0157 | 00 | char | 0x00 (0) | string terminator + +vector (MyGame.Example.Monster.testarrayofsortedstruct): + +0x0158 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x015C | 00 00 00 00 | uint32_t | 0x00000000 (0) | struct field `[0].id` of 'MyGame.Example.Ability' (UInt) + +0x0160 | 2D 00 00 00 | uint32_t | 0x0000002D (45) | struct field `[0].distance` of 'MyGame.Example.Ability' (UInt) + +0x0164 | 01 00 00 00 | uint32_t | 0x00000001 (1) | struct field `[1].id` of 'MyGame.Example.Ability' (UInt) + +0x0168 | 15 00 00 00 | uint32_t | 0x00000015 (21) | struct field `[1].distance` of 'MyGame.Example.Ability' (UInt) + +0x016C | 05 00 00 00 | uint32_t | 0x00000005 (5) | struct field `[2].id` of 'MyGame.Example.Ability' (UInt) + +0x0170 | 0C 00 00 00 | uint32_t | 0x0000000C (12) | struct field `[2].distance` of 'MyGame.Example.Ability' (UInt) + +vector (MyGame.Example.Monster.testarrayofbools): + +0x0174 | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x0178 | 01 | uint8_t | 0x01 (1) | value[0] + +0x0179 | 00 | uint8_t | 0x00 (0) | value[1] + +0x017A | 01 | uint8_t | 0x01 (1) | value[2] + +table (MyGame.Example.Monster): + +0x017C | B0 FF FF FF | SOffset32 | 0xFFFFFFB0 (-80) Loc: 0x01CC | offset to vtable + +0x0180 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x0184 | offset to field `name` (string) + +string (MyGame.Example.Monster.name): + +0x0184 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x0188 | 46 72 65 64 | char[4] | Fred | string literal + +0x018C | 00 | char | 0x00 (0) | string terminator + +padding: + +0x018D | 00 00 00 | uint8_t[3] | ... | padding + +vector (MyGame.Example.Monster.testarrayofstring): + +0x0190 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x0194 | 14 00 00 00 | UOffset32 | 0x00000014 (20) Loc: 0x01A8 | offset to string[0] + +0x0198 | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x019C | offset to string[1] + +string (MyGame.Example.Monster.testarrayofstring): + +0x019C | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x01A0 | 74 65 73 74 32 | char[5] | test2 | string literal + +0x01A5 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x01A6 | 00 00 | uint8_t[2] | .. | padding + +string (MyGame.Example.Monster.testarrayofstring): + +0x01A8 | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of string + +0x01AC | 74 65 73 74 31 | char[5] | test1 | string literal + +0x01B1 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x01B2 | 00 00 | uint8_t[2] | .. | padding + +vector (MyGame.Example.Monster.test5): + +0x01B4 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01B8 | 0A 00 | int16_t | 0x000A (10) | struct field `[0].a` of 'MyGame.Example.Test' (Short) + +0x01BA | 14 | uint8_t | 0x14 (20) | struct field `[0].b` of 'MyGame.Example.Test' (Byte) + +0x01BB | 00 | uint8_t[1] | . | padding + +0x01BC | 1E 00 | int16_t | 0x001E (30) | struct field `[1].a` of 'MyGame.Example.Test' (Short) + +0x01BE | 28 | uint8_t | 0x28 (40) | struct field `[1].b` of 'MyGame.Example.Test' (Byte) + +0x01BF | 00 | uint8_t[1] | . | padding + +vector (MyGame.Example.Monster.test4): + +0x01C0 | 02 00 00 00 | uint32_t | 0x00000002 (2) | length of vector (# items) + +0x01C4 | 0A 00 | int16_t | 0x000A (10) | struct field `[0].a` of 'MyGame.Example.Test' (Short) + +0x01C6 | 14 | uint8_t | 0x14 (20) | struct field `[0].b` of 'MyGame.Example.Test' (Byte) + +0x01C7 | 00 | uint8_t[1] | . | padding + +0x01C8 | 1E 00 | int16_t | 0x001E (30) | struct field `[1].a` of 'MyGame.Example.Test' (Short) + +0x01CA | 28 | uint8_t | 0x28 (40) | struct field `[1].b` of 'MyGame.Example.Test' (Byte) + +0x01CB | 00 | uint8_t[1] | . | padding + +vtable (MyGame.Example.Monster): + +0x01CC | 0C 00 | uint16_t | 0x000C (12) | size of this vtable + +0x01CE | 08 00 | uint16_t | 0x0008 (8) | size of referring table + +0x01D0 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `pos` (id: 0) (Obj) + +0x01D2 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `mana` (id: 1) (Short) + +0x01D4 | 00 00 | VOffset16 | 0x0000 (0) | offset to field `hp` (id: 2) (Short) + +0x01D6 | 04 00 | VOffset16 | 0x0004 (4) | offset to field `name` (id: 3) + +table (MyGame.Example.Monster): + +0x01D8 | 0C 00 00 00 | SOffset32 | 0x0000000C (12) Loc: 0x01CC | offset to vtable + +0x01DC | 04 00 00 00 | UOffset32 | 0x00000004 (4) Loc: 0x01E0 | offset to field `name` (string) + +string (MyGame.Example.Monster.name): + +0x01E0 | 04 00 00 00 | uint32_t | 0x00000004 (4) | length of string + +0x01E4 | 46 72 65 64 | char[4] | Fred | string literal + +0x01E8 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x01E9 | 00 00 00 | uint8_t[3] | ... | padding + +vector (MyGame.Example.Monster.vector_of_doubles): + +0x01EC | 03 00 00 00 | uint32_t | 0x00000003 (3) | length of vector (# items) + +0x01F0 | FF FF FF FF FF FF EF FF | double | 0xFFEFFFFFFFFFFFFF (-1.79769e+308) | value[0] + +0x01F8 | 00 00 00 00 00 00 00 00 | double | 0x0000000000000000 (0) | value[1] + +0x0200 | FF FF FF FF FF FF EF 7F | double | 0x7FEFFFFFFFFFFFFF (1.79769e+308) | value[2] + +padding: + +0x0208 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (MyGame.Example.Monster.vector_of_longs): + +0x020C | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of vector (# items) + +0x0210 | 01 00 00 00 00 00 00 00 | int64_t | 0x0000000000000001 (1) | value[0] + +0x0218 | 64 00 00 00 00 00 00 00 | int64_t | 0x0000000000000064 (100) | value[1] + +0x0220 | 10 27 00 00 00 00 00 00 | int64_t | 0x0000000000002710 (10000) | value[2] + +0x0228 | 40 42 0F 00 00 00 00 00 | int64_t | 0x00000000000F4240 (1000000) | value[3] + +0x0230 | 00 E1 F5 05 00 00 00 00 | int64_t | 0x0000000005F5E100 (100000000) | value[4] + +padding: + +0x0238 | 00 00 00 00 | uint8_t[4] | .... | padding + +vector (MyGame.Example.Monster.inventory): + +0x023C | 05 00 00 00 | uint32_t | 0x00000005 (5) | length of vector (# items) + +0x0240 | 00 | uint8_t | 0x00 (0) | value[0] + +0x0241 | 01 | uint8_t | 0x01 (1) | value[1] + +0x0242 | 02 | uint8_t | 0x02 (2) | value[2] + +0x0243 | 03 | uint8_t | 0x03 (3) | value[3] + +0x0244 | 04 | uint8_t | 0x04 (4) | value[4] + +padding: + +0x0245 | 00 00 00 | uint8_t[3] | ... | padding + +string (MyGame.Example.Monster.name): + +0x0248 | 09 00 00 00 | uint32_t | 0x00000009 (9) | length of string + +0x024C | 4D 79 4D 6F 6E 73 74 65 | char[9] | MyMonste | string literal + +0x0254 | 72 | | r + +0x0255 | 00 | char | 0x00 (0) | string terminator + +padding: + +0x0256 | 00 00 | uint8_t[2] | .. | padding diff --git a/third_party/flatbuffers/tests/monsterdata_test.golden b/third_party/flatbuffers/tests/monsterdata_test.golden new file mode 100644 index 00000000000..4bead9744b1 --- /dev/null +++ b/third_party/flatbuffers/tests/monsterdata_test.golden @@ -0,0 +1,82 @@ +{ + pos: { + x: 1.0, + y: 2.0, + z: 3.0, + test1: 3.14159265359, + test2: "Green", + test3: { + a: 10, + b: 20 + } + }, + hp: 80, + name: "MyMonster", + inventory: [ + 0, + 1, + 2, + 3, + 4, + 5, + 6, + 7, + 8, + 9 + ], + test_type: "Monster", + test: { + name: "Fred" + }, + test4: [ + { + a: 10, + b: 20 + }, + { + a: 30, + b: 40 + } + ], + testarrayofstring: [ + "bob", + "fred", + "bob", + "fred" + ], + testarrayoftables: [ + { + hp: 1000, + name: "Barney" + }, + { + name: "Fred" + }, + { + name: "Wilma" + } + ], + testnestedflatbuffer: { + name: "NestedMonster" + }, + testbool: true, + testhashs32_fnv1: -579221183, + testhashu32_fnv1: 3715746113, + testhashs64_fnv1: 7930699090847568257, + testhashu64_fnv1: 7930699090847568257, + testhashs32_fnv1a: -1904106383, + testhashu32_fnv1a: 2390860913, + testhashs64_fnv1a: 4898026182817603057, + testhashu64_fnv1a: 4898026182817603057, + flex: 1234, + test5: [ + { + a: 10, + b: 20 + }, + { + a: 30, + b: 40 + } + ] +} diff --git a/third_party/flatbuffers/tests/monsterdata_test.json b/third_party/flatbuffers/tests/monsterdata_test.json new file mode 100644 index 00000000000..411c0554b05 --- /dev/null +++ b/third_party/flatbuffers/tests/monsterdata_test.json @@ -0,0 +1,98 @@ +{ + pos: { + x: 1, + y: "2", + z: 3, + test1: 3, + test2: "Green", + test3: { + a: 5, + b: 6 + } + }, + hp: 80, + name: "MyMonster", + inventory: [ + 0, + 1, + 2, + 3, + 4 + ], + vector_of_longs: [ + 1, + 100, + 10000, + 1000000, + 100000000 + ], + vector_of_doubles: [ + -1.7976931348623157e+308, + 0, + 1.7976931348623157e+308 + ], + test_type: "Monster", + test: { + name: "Fred", + pos: null + }, + test4: [ + { + a: 10, + b: 20 + }, + { + b: "40", + a: 30 + } + ], + test5: [ + { + a: 10, + b: 20 + }, + { + b: "40", + a: 30 + } + ], + testarrayofstring: [ + "test1", + "test2" + ], + enemy: { + name: "Fred" + }, + testarrayofbools: [ + true, + false, + true + ], + testbool: true, + testhashs32_fnv1: "This string is being hashed!", + testhashu32_fnv1: "This string is being hashed!", + testhashs64_fnv1: "This string is being hashed!", + testhashu64_fnv1: "This string is being hashed!", + testhashs32_fnv1a: "This string is being hashed!", + testhashu32_fnv1a: "This string is being hashed!", + testhashs64_fnv1a: "This string is being hashed!", + testhashu64_fnv1a: "This string is being hashed!", + testarrayofsortedstruct: [ + {id: 5,distance: 12 + }, + {id: 1,distance: 21 + }, + {id: 0,distance: 45 + } + ], + scalar_key_sorted_tables: [ + {id: "hit",val: 10,count: 1 + }, + {id: "miss",val: 0,count: 0 + } + ], + native_inline: { + a: 1, + b: 2 + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/monsterdata_test.mon b/third_party/flatbuffers/tests/monsterdata_test.mon new file mode 100644 index 00000000000..da0ed8698fc Binary files /dev/null and b/third_party/flatbuffers/tests/monsterdata_test.mon differ diff --git a/third_party/flatbuffers/tests/more_defaults.fbs b/third_party/flatbuffers/tests/more_defaults.fbs new file mode 100644 index 00000000000..da4976a4f75 --- /dev/null +++ b/third_party/flatbuffers/tests/more_defaults.fbs @@ -0,0 +1,12 @@ + +enum ABC: int { A, B, C } + + +table MoreDefaults { + ints: [int] = []; + floats: [float] = [ ]; + empty_string: string = ""; + some_string: string = "some"; + abcs: [ABC] = []; + bools: [bool] = []; +} diff --git a/third_party/flatbuffers/tests/more_defaults/abc_generated.rs b/third_party/flatbuffers/tests/more_defaults/abc_generated.rs new file mode 100644 index 00000000000..cff89ca72c6 --- /dev/null +++ b/third_party/flatbuffers/tests/more_defaults/abc_generated.rs @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ABC: i32 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ABC: i32 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ABC: [ABC; 3] = [ + ABC::A, + ABC::B, + ABC::C, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct ABC(pub i32); +#[allow(non_upper_case_globals)] +impl ABC { + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); + + pub const ENUM_MIN: i32 = 0; + pub const ENUM_MAX: i32 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, + } + } +} +impl core::fmt::Debug for ABC { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for ABC { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for ABC { + type Output = ABC; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for ABC { + type Scalar = i32; + #[inline] + fn to_little_endian(self) -> i32 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i32) -> Self { + let b = i32::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for ABC { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i32::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for ABC {} diff --git a/third_party/flatbuffers/tests/more_defaults/mod.rs b/third_party/flatbuffers/tests/more_defaults/mod.rs new file mode 100644 index 00000000000..940204d589b --- /dev/null +++ b/third_party/flatbuffers/tests/more_defaults/mod.rs @@ -0,0 +1,6 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +mod abc_generated; +pub use self::abc_generated::*; +mod more_defaults_generated; +pub use self::more_defaults_generated::*; diff --git a/third_party/flatbuffers/tests/more_defaults/more_defaults_generated.rs b/third_party/flatbuffers/tests/more_defaults/more_defaults_generated.rs new file mode 100644 index 00000000000..bf6d3e799f7 --- /dev/null +++ b/third_party/flatbuffers/tests/more_defaults/more_defaults_generated.rs @@ -0,0 +1,292 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum MoreDefaultsOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct MoreDefaults<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for MoreDefaults<'a> { + type Inner = MoreDefaults<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> MoreDefaults<'a> { + pub const VT_INTS: flatbuffers::VOffsetT = 4; + pub const VT_FLOATS: flatbuffers::VOffsetT = 6; + pub const VT_EMPTY_STRING: flatbuffers::VOffsetT = 8; + pub const VT_SOME_STRING: flatbuffers::VOffsetT = 10; + pub const VT_ABCS: flatbuffers::VOffsetT = 12; + pub const VT_BOOLS: flatbuffers::VOffsetT = 14; + + pub const fn get_fully_qualified_name() -> &'static str { + "MoreDefaults" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + MoreDefaults { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args MoreDefaultsArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = MoreDefaultsBuilder::new(_fbb); + if let Some(x) = args.bools { builder.add_bools(x); } + if let Some(x) = args.abcs { builder.add_abcs(x); } + if let Some(x) = args.some_string { builder.add_some_string(x); } + if let Some(x) = args.empty_string { builder.add_empty_string(x); } + if let Some(x) = args.floats { builder.add_floats(x); } + if let Some(x) = args.ints { builder.add_ints(x); } + builder.finish() + } + + pub fn unpack(&self) -> MoreDefaultsT { + let ints = { + let x = self.ints(); + x.into_iter().collect() + }; + let floats = { + let x = self.floats(); + x.into_iter().collect() + }; + let empty_string = { + let x = self.empty_string(); + x.to_string() + }; + let some_string = { + let x = self.some_string(); + x.to_string() + }; + let abcs = { + let x = self.abcs(); + x.into_iter().collect() + }; + let bools = { + let x = self.bools(); + x.into_iter().collect() + }; + MoreDefaultsT { + ints, + floats, + empty_string, + some_string, + abcs, + bools, + } + } + + #[inline] + pub fn ints(&self) -> flatbuffers::Vector<'a, i32> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(MoreDefaults::VT_INTS, Some(Default::default())).unwrap()} + } + #[inline] + pub fn floats(&self) -> flatbuffers::Vector<'a, f32> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(MoreDefaults::VT_FLOATS, Some(Default::default())).unwrap()} + } + #[inline] + pub fn empty_string(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(MoreDefaults::VT_EMPTY_STRING, Some(&"")).unwrap()} + } + #[inline] + pub fn some_string(&self) -> &'a str { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(MoreDefaults::VT_SOME_STRING, Some(&"some")).unwrap()} + } + #[inline] + pub fn abcs(&self) -> flatbuffers::Vector<'a, ABC> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(MoreDefaults::VT_ABCS, Some(Default::default())).unwrap()} + } + #[inline] + pub fn bools(&self) -> flatbuffers::Vector<'a, bool> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(MoreDefaults::VT_BOOLS, Some(Default::default())).unwrap()} + } +} + +impl flatbuffers::Verifiable for MoreDefaults<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>>("ints", Self::VT_INTS, false)? + .visit_field::>>("floats", Self::VT_FLOATS, false)? + .visit_field::>("empty_string", Self::VT_EMPTY_STRING, false)? + .visit_field::>("some_string", Self::VT_SOME_STRING, false)? + .visit_field::>>("abcs", Self::VT_ABCS, false)? + .visit_field::>>("bools", Self::VT_BOOLS, false)? + .finish(); + Ok(()) + } +} +pub struct MoreDefaultsArgs<'a> { + pub ints: Option>>, + pub floats: Option>>, + pub empty_string: Option>, + pub some_string: Option>, + pub abcs: Option>>, + pub bools: Option>>, +} +impl<'a> Default for MoreDefaultsArgs<'a> { + #[inline] + fn default() -> Self { + MoreDefaultsArgs { + ints: None, + floats: None, + empty_string: None, + some_string: None, + abcs: None, + bools: None, + } + } +} + +pub struct MoreDefaultsBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> MoreDefaultsBuilder<'a, 'b, A> { + #[inline] + pub fn add_ints(&mut self, ints: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(MoreDefaults::VT_INTS, ints); + } + #[inline] + pub fn add_floats(&mut self, floats: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(MoreDefaults::VT_FLOATS, floats); + } + #[inline] + pub fn add_empty_string(&mut self, empty_string: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(MoreDefaults::VT_EMPTY_STRING, empty_string); + } + #[inline] + pub fn add_some_string(&mut self, some_string: flatbuffers::WIPOffset<&'b str>) { + self.fbb_.push_slot_always::>(MoreDefaults::VT_SOME_STRING, some_string); + } + #[inline] + pub fn add_abcs(&mut self, abcs: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(MoreDefaults::VT_ABCS, abcs); + } + #[inline] + pub fn add_bools(&mut self, bools: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(MoreDefaults::VT_BOOLS, bools); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> MoreDefaultsBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + MoreDefaultsBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for MoreDefaults<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("MoreDefaults"); + ds.field("ints", &self.ints()); + ds.field("floats", &self.floats()); + ds.field("empty_string", &self.empty_string()); + ds.field("some_string", &self.some_string()); + ds.field("abcs", &self.abcs()); + ds.field("bools", &self.bools()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct MoreDefaultsT { + pub ints: Vec, + pub floats: Vec, + pub empty_string: String, + pub some_string: String, + pub abcs: Vec, + pub bools: Vec, +} +impl Default for MoreDefaultsT { + fn default() -> Self { + Self { + ints: Default::default(), + floats: Default::default(), + empty_string: "".to_string(), + some_string: "some".to_string(), + abcs: Default::default(), + bools: Default::default(), + } + } +} +impl MoreDefaultsT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let ints = Some({ + let x = &self.ints; + _fbb.create_vector(x) + }); + let floats = Some({ + let x = &self.floats; + _fbb.create_vector(x) + }); + let empty_string = Some({ + let x = &self.empty_string; + _fbb.create_string(x) + }); + let some_string = Some({ + let x = &self.some_string; + _fbb.create_string(x) + }); + let abcs = Some({ + let x = &self.abcs; + _fbb.create_vector(x) + }); + let bools = Some({ + let x = &self.bools; + _fbb.create_vector(x) + }); + MoreDefaults::create(_fbb, &MoreDefaultsArgs{ + ints, + floats, + empty_string, + some_string, + abcs, + bools, + }) + } +} diff --git a/third_party/flatbuffers/tests/name_clash_test/invalid_test1.fbs b/third_party/flatbuffers/tests/name_clash_test/invalid_test1.fbs new file mode 100644 index 00000000000..aa7213fab7c --- /dev/null +++ b/third_party/flatbuffers/tests/name_clash_test/invalid_test1.fbs @@ -0,0 +1,5 @@ +include "invalid_test2.fbs"; + +namespace A; + +table X {} diff --git a/third_party/flatbuffers/tests/name_clash_test/invalid_test2.fbs b/third_party/flatbuffers/tests/name_clash_test/invalid_test2.fbs new file mode 100644 index 00000000000..6d70e9c64e8 --- /dev/null +++ b/third_party/flatbuffers/tests/name_clash_test/invalid_test2.fbs @@ -0,0 +1,3 @@ +namespace A; + +union X {} diff --git a/third_party/flatbuffers/tests/name_clash_test/valid_test1.fbs b/third_party/flatbuffers/tests/name_clash_test/valid_test1.fbs new file mode 100644 index 00000000000..d61dea60426 --- /dev/null +++ b/third_party/flatbuffers/tests/name_clash_test/valid_test1.fbs @@ -0,0 +1,5 @@ +include "valid_test2.fbs"; + +namespace A; + +table X {} diff --git a/third_party/flatbuffers/tests/name_clash_test/valid_test2.fbs b/third_party/flatbuffers/tests/name_clash_test/valid_test2.fbs new file mode 100644 index 00000000000..78edad6fea2 --- /dev/null +++ b/third_party/flatbuffers/tests/name_clash_test/valid_test2.fbs @@ -0,0 +1,3 @@ +namespace B; + +union X {} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.cs new file mode 100644 index 00000000000..bb17d7b35e2 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.cs @@ -0,0 +1,17 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA.NamespaceB +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum EnumInNestedNS : sbyte +{ + A = 0, + B = 1, + C = 2, +}; + + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.go new file mode 100644 index 00000000000..6cec5ffc37b --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.go @@ -0,0 +1,32 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceB + +import "strconv" + +type EnumInNestedNS int8 + +const ( + EnumInNestedNSA EnumInNestedNS = 0 + EnumInNestedNSB EnumInNestedNS = 1 + EnumInNestedNSC EnumInNestedNS = 2 +) + +var EnumNamesEnumInNestedNS = map[EnumInNestedNS]string{ + EnumInNestedNSA: "A", + EnumInNestedNSB: "B", + EnumInNestedNSC: "C", +} + +var EnumValuesEnumInNestedNS = map[string]EnumInNestedNS{ + "A": EnumInNestedNSA, + "B": EnumInNestedNSB, + "C": EnumInNestedNSC, +} + +func (v EnumInNestedNS) String() string { + if s, ok := EnumNamesEnumInNestedNS[v]; ok { + return s + } + return "EnumInNestedNS(" + strconv.FormatInt(int64(v), 10) + ")" +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java new file mode 100644 index 00000000000..949c2043daa --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.java @@ -0,0 +1,16 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +@SuppressWarnings("unused") +public final class EnumInNestedNS { + private EnumInNestedNS() { } + public static final byte A = 0; + public static final byte B = 1; + public static final byte C = 2; + + public static final String[] names = { "A", "B", "C", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.kt new file mode 100644 index 00000000000..0ede58cabf9 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.kt @@ -0,0 +1,15 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB + +@Suppress("unused") +@ExperimentalUnsignedTypes +class EnumInNestedNS private constructor() { + companion object { + const val A: Byte = 0 + const val B: Byte = 1 + const val C: Byte = 2 + val names : Array = arrayOf("A", "B", "C") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.lua new file mode 100644 index 00000000000..60b1fb16fdd --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.lua @@ -0,0 +1,11 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceB + +local EnumInNestedNS = { + A = 0, + B = 1, + C = 2, +} + +return EnumInNestedNS -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.php new file mode 100644 index 00000000000..bcb22b75942 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.php @@ -0,0 +1,25 @@ +"A", + EnumInNestedNS::B=>"B", + EnumInNestedNS::C=>"C", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py new file mode 100644 index 00000000000..ae74c5477f4 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/EnumInNestedNS.py @@ -0,0 +1,8 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceB + +class EnumInNestedNS(object): + A = 0 + B = 1 + C = 2 diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs new file mode 100644 index 00000000000..2874a273832 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.cs @@ -0,0 +1,62 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA.NamespaceB +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct StructInNestedNS : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public StructInNestedNS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int A { get { return __p.bb.GetInt(__p.bb_pos + 0); } } + public void MutateA(int a) { __p.bb.PutInt(__p.bb_pos + 0, a); } + public int B { get { return __p.bb.GetInt(__p.bb_pos + 4); } } + public void MutateB(int b) { __p.bb.PutInt(__p.bb_pos + 4, b); } + + public static Offset CreateStructInNestedNS(FlatBufferBuilder builder, int A, int B) { + builder.Prep(4, 8); + builder.PutInt(B); + builder.PutInt(A); + return new Offset(builder.Offset); + } + public StructInNestedNST UnPack() { + var _o = new StructInNestedNST(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(StructInNestedNST _o) { + _o.A = this.A; + _o.B = this.B; + } + public static Offset Pack(FlatBufferBuilder builder, StructInNestedNST _o) { + if (_o == null) return default(Offset); + return CreateStructInNestedNS( + builder, + _o.A, + _o.B); + } +} + +public class StructInNestedNST +{ + [Newtonsoft.Json.JsonProperty("a")] + public int A { get; set; } + [Newtonsoft.Json.JsonProperty("b")] + public int B { get; set; } + + public StructInNestedNST() { + this.A = 0; + this.B = 0; + } +} + + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.go new file mode 100644 index 00000000000..854403fca4e --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.go @@ -0,0 +1,62 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceB + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type StructInNestedNST struct { + A int32 + B int32 +} + +func (t *StructInNestedNST) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + return CreateStructInNestedNS(builder, t.A, t.B) +} +func (rcv *StructInNestedNS) UnPackTo(t *StructInNestedNST) { + t.A = rcv.A() + t.B = rcv.B() +} + +func (rcv *StructInNestedNS) UnPack() *StructInNestedNST { + if rcv == nil { return nil } + t := &StructInNestedNST{} + rcv.UnPackTo(t) + return t +} + +type StructInNestedNS struct { + _tab flatbuffers.Struct +} + +func (rcv *StructInNestedNS) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *StructInNestedNS) Table() flatbuffers.Table { + return rcv._tab.Table +} + +func (rcv *StructInNestedNS) A() int32 { + return rcv._tab.GetInt32(rcv._tab.Pos + flatbuffers.UOffsetT(0)) +} +func (rcv *StructInNestedNS) MutateA(n int32) bool { + return rcv._tab.MutateInt32(rcv._tab.Pos+flatbuffers.UOffsetT(0), n) +} + +func (rcv *StructInNestedNS) B() int32 { + return rcv._tab.GetInt32(rcv._tab.Pos + flatbuffers.UOffsetT(4)) +} +func (rcv *StructInNestedNS) MutateB(n int32) bool { + return rcv._tab.MutateInt32(rcv._tab.Pos+flatbuffers.UOffsetT(4), n) +} + +func CreateStructInNestedNS(builder *flatbuffers.Builder, a int32, b int32) flatbuffers.UOffsetT { + builder.Prep(4, 8) + builder.PrependInt32(b) + builder.PrependInt32(a) + return builder.Offset() +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java new file mode 100644 index 00000000000..7184f0332ff --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.java @@ -0,0 +1,52 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +@SuppressWarnings("unused") +public final class StructInNestedNS extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public StructInNestedNS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int a() { return bb.getInt(bb_pos + 0); } + public void mutateA(int a) { bb.putInt(bb_pos + 0, a); } + public int b() { return bb.getInt(bb_pos + 4); } + public void mutateB(int b) { bb.putInt(bb_pos + 4, b); } + + public static int createStructInNestedNS(FlatBufferBuilder builder, int a, int b) { + builder.prep(4, 8); + builder.putInt(b); + builder.putInt(a); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public StructInNestedNS get(int j) { return get(new StructInNestedNS(), j); } + public StructInNestedNS get(StructInNestedNS obj, int j) { return obj.__assign(__element(j), bb); } + } + public StructInNestedNST unpack() { + StructInNestedNST _o = new StructInNestedNST(); + unpackTo(_o); + return _o; + } + public void unpackTo(StructInNestedNST _o) { + int _oA = a(); + _o.setA(_oA); + int _oB = b(); + _o.setB(_oB); + } + public static int pack(FlatBufferBuilder builder, StructInNestedNST _o) { + if (_o == null) return 0; + return createStructInNestedNS( + builder, + _o.getA(), + _o.getB()); + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.kt new file mode 100644 index 00000000000..7aad3c4599c --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.kt @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +@ExperimentalUnsignedTypes +class StructInNestedNS : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : StructInNestedNS { + __init(_i, _bb) + return this + } + val a : Int get() = bb.getInt(bb_pos + 0) + fun mutateA(a: Int) : ByteBuffer = bb.putInt(bb_pos + 0, a) + val b : Int get() = bb.getInt(bb_pos + 4) + fun mutateB(b: Int) : ByteBuffer = bb.putInt(bb_pos + 4, b) + companion object { + fun createStructInNestedNS(builder: FlatBufferBuilder, a: Int, b: Int) : Int { + builder.prep(4, 8) + builder.putInt(b) + builder.putInt(a) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.lua new file mode 100644 index 00000000000..9ca75418822 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.lua @@ -0,0 +1,31 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceB + +local flatbuffers = require('flatbuffers') + +local StructInNestedNS = {} -- the module +local StructInNestedNS_mt = {} -- the class metatable + +function StructInNestedNS.New() + local o = {} + setmetatable(o, {__index = StructInNestedNS_mt}) + return o +end +function StructInNestedNS_mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end +function StructInNestedNS_mt:A() + return self.view:Get(flatbuffers.N.Int32, self.view.pos + 0) +end +function StructInNestedNS_mt:B() + return self.view:Get(flatbuffers.N.Int32, self.view.pos + 4) +end +function StructInNestedNS.CreateStructInNestedNS(builder, a, b) + builder:Prep(4, 8) + builder:PrependInt32(b) + builder:PrependInt32(a) + return builder:Offset() +end + +return StructInNestedNS -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.php new file mode 100644 index 00000000000..d3054841a2d --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.php @@ -0,0 +1,52 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function GetA() + { + return $this->bb->getInt($this->bb_pos + 0); + } + + /** + * @return int + */ + public function GetB() + { + return $this->bb->getInt($this->bb_pos + 4); + } + + + /** + * @return int offset + */ + public static function createStructInNestedNS(FlatBufferBuilder $builder, $a, $b) + { + $builder->prep(4, 8); + $builder->putInt($b); + $builder->putInt($a); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.py new file mode 100644 index 00000000000..f49495b6244 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNS.py @@ -0,0 +1,60 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceB + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class StructInNestedNS(object): + __slots__ = ['_tab'] + + @classmethod + def SizeOf(cls): + return 8 + + # StructInNestedNS + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # StructInNestedNS + def A(self): return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(0)) + # StructInNestedNS + def B(self): return self._tab.Get(flatbuffers.number_types.Int32Flags, self._tab.Pos + flatbuffers.number_types.UOffsetTFlags.py_type(4)) + +def CreateStructInNestedNS(builder, a, b): + builder.Prep(4, 8) + builder.PrependInt32(b) + builder.PrependInt32(a) + return builder.Offset() + + +class StructInNestedNST(object): + + # StructInNestedNST + def __init__(self): + self.a = 0 # type: int + self.b = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + structInNestedNS = StructInNestedNS() + structInNestedNS.Init(buf, pos) + return cls.InitFromObj(structInNestedNS) + + @classmethod + def InitFromObj(cls, structInNestedNS): + x = StructInNestedNST() + x._UnPack(structInNestedNS) + return x + + # StructInNestedNST + def _UnPack(self, structInNestedNS): + if structInNestedNS is None: + return + self.a = structInNestedNS.A() + self.b = structInNestedNS.B() + + # StructInNestedNST + def Pack(self, builder): + return CreateStructInNestedNS(builder, self.a, self.b) diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNST.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNST.java new file mode 100644 index 00000000000..0e6963c4214 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/StructInNestedNST.java @@ -0,0 +1,28 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class StructInNestedNST { + private int a; + private int b; + + public int getA() { return a; } + + public void setA(int a) { this.a = a; } + + public int getB() { return b; } + + public void setB(int b) { this.b = b; } + + + public StructInNestedNST() { + this.a = 0; + this.b = 0; + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs new file mode 100644 index 00000000000..179974c1776 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.cs @@ -0,0 +1,75 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA.NamespaceB +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct TableInNestedNS : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static TableInNestedNS GetRootAsTableInNestedNS(ByteBuffer _bb) { return GetRootAsTableInNestedNS(_bb, new TableInNestedNS()); } + public static TableInNestedNS GetRootAsTableInNestedNS(ByteBuffer _bb, TableInNestedNS obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public TableInNestedNS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int Foo { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateFoo(int foo) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, foo); return true; } else { return false; } } + + public static Offset CreateTableInNestedNS(FlatBufferBuilder builder, + int foo = 0) { + builder.StartTable(1); + TableInNestedNS.AddFoo(builder, foo); + return TableInNestedNS.EndTableInNestedNS(builder); + } + + public static void StartTableInNestedNS(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddFoo(FlatBufferBuilder builder, int foo) { builder.AddInt(0, foo, 0); } + public static Offset EndTableInNestedNS(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public TableInNestedNST UnPack() { + var _o = new TableInNestedNST(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(TableInNestedNST _o) { + _o.Foo = this.Foo; + } + public static Offset Pack(FlatBufferBuilder builder, TableInNestedNST _o) { + if (_o == null) return default(Offset); + return CreateTableInNestedNS( + builder, + _o.Foo); + } +} + +public class TableInNestedNST +{ + [Newtonsoft.Json.JsonProperty("foo")] + public int Foo { get; set; } + + public TableInNestedNST() { + this.Foo = 0; + } +} + + +static public class TableInNestedNSVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Foo*/, 4 /*int*/, 4, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.go new file mode 100644 index 00000000000..37826456726 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.go @@ -0,0 +1,78 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceB + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type TableInNestedNST struct { + Foo int32 +} + +func (t *TableInNestedNST) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + TableInNestedNSStart(builder) + TableInNestedNSAddFoo(builder, t.Foo) + return TableInNestedNSEnd(builder) +} + +func (rcv *TableInNestedNS) UnPackTo(t *TableInNestedNST) { + t.Foo = rcv.Foo() +} + +func (rcv *TableInNestedNS) UnPack() *TableInNestedNST { + if rcv == nil { return nil } + t := &TableInNestedNST{} + rcv.UnPackTo(t) + return t +} + +type TableInNestedNS struct { + _tab flatbuffers.Table +} + +func GetRootAsTableInNestedNS(buf []byte, offset flatbuffers.UOffsetT) *TableInNestedNS { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &TableInNestedNS{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsTableInNestedNS(buf []byte, offset flatbuffers.UOffsetT) *TableInNestedNS { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &TableInNestedNS{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *TableInNestedNS) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *TableInNestedNS) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *TableInNestedNS) Foo() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *TableInNestedNS) MutateFoo(n int32) bool { + return rcv._tab.MutateInt32Slot(4, n) +} + +func TableInNestedNSStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func TableInNestedNSAddFoo(builder *flatbuffers.Builder, foo int32) { + builder.PrependInt32Slot(0, foo, 0) +} +func TableInNestedNSEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java new file mode 100644 index 00000000000..de274122d5b --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.java @@ -0,0 +1,57 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +@SuppressWarnings("unused") +public final class TableInNestedNS extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static TableInNestedNS getRootAsTableInNestedNS(ByteBuffer _bb) { return getRootAsTableInNestedNS(_bb, new TableInNestedNS()); } + public static TableInNestedNS getRootAsTableInNestedNS(ByteBuffer _bb, TableInNestedNS obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public TableInNestedNS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int foo() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean mutateFoo(int foo) { int o = __offset(4); if (o != 0) { bb.putInt(o + bb_pos, foo); return true; } else { return false; } } + + public static int createTableInNestedNS(FlatBufferBuilder builder, + int foo) { + builder.startTable(1); + TableInNestedNS.addFoo(builder, foo); + return TableInNestedNS.endTableInNestedNS(builder); + } + + public static void startTableInNestedNS(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addFoo(FlatBufferBuilder builder, int foo) { builder.addInt(0, foo, 0); } + public static int endTableInNestedNS(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public TableInNestedNS get(int j) { return get(new TableInNestedNS(), j); } + public TableInNestedNS get(TableInNestedNS obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public TableInNestedNST unpack() { + TableInNestedNST _o = new TableInNestedNST(); + unpackTo(_o); + return _o; + } + public void unpackTo(TableInNestedNST _o) { + int _oFoo = foo(); + _o.setFoo(_oFoo); + } + public static int pack(FlatBufferBuilder builder, TableInNestedNST _o) { + if (_o == null) return 0; + return createTableInNestedNS( + builder, + _o.getFoo()); + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt new file mode 100644 index 00000000000..419013179b5 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.kt @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +@ExperimentalUnsignedTypes +class TableInNestedNS : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : TableInNestedNS { + __init(_i, _bb) + return this + } + val foo : Int + get() { + val o = __offset(4) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + fun mutateFoo(foo: Int) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.putInt(o + bb_pos, foo) + true + } else { + false + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsTableInNestedNS(_bb: ByteBuffer): TableInNestedNS = getRootAsTableInNestedNS(_bb, TableInNestedNS()) + fun getRootAsTableInNestedNS(_bb: ByteBuffer, obj: TableInNestedNS): TableInNestedNS { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createTableInNestedNS(builder: FlatBufferBuilder, foo: Int) : Int { + builder.startTable(1) + addFoo(builder, foo) + return endTableInNestedNS(builder) + } + fun startTableInNestedNS(builder: FlatBufferBuilder) = builder.startTable(1) + fun addFoo(builder: FlatBufferBuilder, foo: Int) = builder.addInt(0, foo, 0) + fun endTableInNestedNS(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua new file mode 100644 index 00000000000..af86203eeb8 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.lua @@ -0,0 +1,38 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceB + +local flatbuffers = require('flatbuffers') + +local TableInNestedNS = {} -- the module +local TableInNestedNS_mt = {} -- the class metatable + +function TableInNestedNS.New() + local o = {} + setmetatable(o, {__index = TableInNestedNS_mt}) + return o +end +function TableInNestedNS.GetRootAsTableInNestedNS(buf, offset) + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) + local o = TableInNestedNS.New() + o:Init(buf, n + offset) + return o +end +function TableInNestedNS_mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end +function TableInNestedNS_mt:Foo() + local o = self.view:Offset(4) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int32, o + self.view.pos) + end + return 0 +end +function TableInNestedNS.Start(builder) builder:StartObject(1) end +function TableInNestedNS.AddFoo(builder, foo) builder:PrependInt32Slot(0, foo, 0) end +function TableInNestedNS.End(builder) return builder:EndObject() end + +return TableInNestedNS -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.php new file mode 100644 index 00000000000..d16379d8781 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.php @@ -0,0 +1,84 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return TableInNestedNS + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function getFoo() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startTableInNestedNS(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return TableInNestedNS + */ + public static function createTableInNestedNS(FlatBufferBuilder $builder, $foo) + { + $builder->startObject(1); + self::addFoo($builder, $foo); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addFoo(FlatBufferBuilder $builder, $foo) + { + $builder->addIntX(0, $foo, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endTableInNestedNS(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py new file mode 100644 index 00000000000..a9848d801be --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNS.py @@ -0,0 +1,73 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceB + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TableInNestedNS(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TableInNestedNS() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTableInNestedNS(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # TableInNestedNS + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TableInNestedNS + def Foo(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + +def TableInNestedNSStart(builder): builder.StartObject(1) +def Start(builder): + return TableInNestedNSStart(builder) +def TableInNestedNSAddFoo(builder, foo): builder.PrependInt32Slot(0, foo, 0) +def AddFoo(builder, foo): + return TableInNestedNSAddFoo(builder, foo) +def TableInNestedNSEnd(builder): return builder.EndObject() +def End(builder): + return TableInNestedNSEnd(builder) + +class TableInNestedNST(object): + + # TableInNestedNST + def __init__(self): + self.foo = 0 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + tableInNestedNS = TableInNestedNS() + tableInNestedNS.Init(buf, pos) + return cls.InitFromObj(tableInNestedNS) + + @classmethod + def InitFromObj(cls, tableInNestedNS): + x = TableInNestedNST() + x._UnPack(tableInNestedNS) + return x + + # TableInNestedNST + def _UnPack(self, tableInNestedNS): + if tableInNestedNS is None: + return + self.foo = tableInNestedNS.Foo() + + # TableInNestedNST + def Pack(self, builder): + TableInNestedNSStart(builder) + TableInNestedNSAddFoo(builder, self.foo) + tableInNestedNS = TableInNestedNSEnd(builder) + return tableInNestedNS diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNST.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNST.java new file mode 100644 index 00000000000..1968a9680c4 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/TableInNestedNST.java @@ -0,0 +1,22 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class TableInNestedNST { + private int foo; + + public int getFoo() { return foo; } + + public void setFoo(int foo) { this.foo = foo; } + + + public TableInNestedNST() { + this.foo = 0; + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.cs new file mode 100644 index 00000000000..f44cd9076d3 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.cs @@ -0,0 +1,97 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA.NamespaceB +{ + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum UnionInNestedNS : byte +{ + NONE = 0, + TableInNestedNS = 1, +}; + +public class UnionInNestedNSUnion { + public UnionInNestedNS Type { get; set; } + public object Value { get; set; } + + public UnionInNestedNSUnion() { + this.Type = UnionInNestedNS.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public NamespaceA.NamespaceB.TableInNestedNST AsTableInNestedNS() { return this.As(); } + public static UnionInNestedNSUnion FromTableInNestedNS(NamespaceA.NamespaceB.TableInNestedNST _tableinnestedns) { return new UnionInNestedNSUnion{ Type = UnionInNestedNS.TableInNestedNS, Value = _tableinnestedns }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, UnionInNestedNSUnion _o) { + switch (_o.Type) { + default: return 0; + case UnionInNestedNS.TableInNestedNS: return NamespaceA.NamespaceB.TableInNestedNS.Pack(builder, _o.AsTableInNestedNS()).Value; + } + } +} + +public class UnionInNestedNSUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(UnionInNestedNSUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as UnionInNestedNSUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, UnionInNestedNSUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as UnionInNestedNSUnion, serializer); + } + } + public UnionInNestedNSUnion ReadJson(Newtonsoft.Json.JsonReader reader, UnionInNestedNSUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case UnionInNestedNS.TableInNestedNS: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class UnionInNestedNSVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((UnionInNestedNS)typeId) + { + case UnionInNestedNS.TableInNestedNS: + result = NamespaceA.NamespaceB.TableInNestedNSVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.go new file mode 100644 index 00000000000..f7b1d1c2d99 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.go @@ -0,0 +1,36 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceB + +import ( + "strconv" + + flatbuffers "github.com/google/flatbuffers/go" + + NamespaceA__NamespaceB "NamespaceA/NamespaceB" +) + +type UnionInNestedNST struct { + Type UnionInNestedNS + Value interface{} +} + +func (t *UnionInNestedNST) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { + return 0 + } + switch t.Type { + case UnionInNestedNSTableInNestedNS: + return t.Value.(*NamespaceA__NamespaceB.TableInNestedNST).Pack(builder) + } + return 0 +} + +func (rcv UnionInNestedNS) UnPack(table flatbuffers.Table) *UnionInNestedNST { + switch rcv { + case UnionInNestedNSTableInNestedNS: + x := TableInNestedNS{_tab: table} + return &NamespaceA__NamespaceB.UnionInNestedNST{ Type: UnionInNestedNSTableInNestedNS, Value: x.UnPack() } + } + return nil +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.java new file mode 100644 index 00000000000..27f24e3cc13 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.java @@ -0,0 +1,15 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +@SuppressWarnings("unused") +public final class UnionInNestedNS { + private UnionInNestedNS() { } + public static final byte NONE = 0; + public static final byte TableInNestedNS = 1; + + public static final String[] names = { "NONE", "TableInNestedNS", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.kt new file mode 100644 index 00000000000..1c52f95c23b --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.kt @@ -0,0 +1,14 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB + +@Suppress("unused") +@ExperimentalUnsignedTypes +class UnionInNestedNS private constructor() { + companion object { + const val NONE: UByte = 0u + const val TableInNestedNS: UByte = 1u + val names : Array = arrayOf("NONE", "TableInNestedNS") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.lua new file mode 100644 index 00000000000..30bc93e5161 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.lua @@ -0,0 +1,10 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceB + +local UnionInNestedNS = { + NONE = 0, + TableInNestedNS = 1, +} + +return UnionInNestedNS -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.php new file mode 100644 index 00000000000..ff948d739b7 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.php @@ -0,0 +1,23 @@ +"NONE", + UnionInNestedNS::TableInNestedNS=>"TableInNestedNS", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.py new file mode 100644 index 00000000000..af601c7c47f --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNS.py @@ -0,0 +1,15 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceB + +class UnionInNestedNS(object): + NONE = 0 + TableInNestedNS = 1 + +def UnionInNestedNSCreator(unionType, table): + from flatbuffers.table import Table + if not isinstance(table, Table): + return None + if unionType == UnionInNestedNS().TableInNestedNS: + return TableInNestedNST.InitFromBuf(table.Bytes, table.Pos) + return None diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNSUnion.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNSUnion.java new file mode 100644 index 00000000000..5b8993825e2 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/UnionInNestedNSUnion.java @@ -0,0 +1,33 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA.NamespaceB; + +import com.google.flatbuffers.FlatBufferBuilder; + +public class UnionInNestedNSUnion { + private byte type; + private Object value; + + public byte getType() { return type; } + + public void setType(byte type) { this.type = type; } + + public Object getValue() { return value; } + + public void setValue(Object value) { this.value = value; } + + public UnionInNestedNSUnion() { + this.type = UnionInNestedNS.NONE; + this.value = null; + } + + public NamespaceA.NamespaceB.TableInNestedNST asTableInNestedNS() { return (NamespaceA.NamespaceB.TableInNestedNST) value; } + + public static int pack(FlatBufferBuilder builder, UnionInNestedNSUnion _o) { + switch (_o.type) { + case UnionInNestedNS.TableInNestedNS: return NamespaceA.NamespaceB.TableInNestedNS.pack(builder, _o.asTableInNestedNS()); + default: return 0; + } + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/__init__.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/NamespaceB/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.cs new file mode 100644 index 00000000000..04ef8a4bc4e --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.cs @@ -0,0 +1,75 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct SecondTableInA : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static SecondTableInA GetRootAsSecondTableInA(ByteBuffer _bb) { return GetRootAsSecondTableInA(_bb, new SecondTableInA()); } + public static SecondTableInA GetRootAsSecondTableInA(ByteBuffer _bb, SecondTableInA obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public SecondTableInA __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public NamespaceC.TableInC? ReferToC { get { int o = __p.__offset(4); return o != 0 ? (NamespaceC.TableInC?)(new NamespaceC.TableInC()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + + public static Offset CreateSecondTableInA(FlatBufferBuilder builder, + Offset refer_to_cOffset = default(Offset)) { + builder.StartTable(1); + SecondTableInA.AddReferToC(builder, refer_to_cOffset); + return SecondTableInA.EndSecondTableInA(builder); + } + + public static void StartSecondTableInA(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddReferToC(FlatBufferBuilder builder, Offset referToCOffset) { builder.AddOffset(0, referToCOffset.Value, 0); } + public static Offset EndSecondTableInA(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public SecondTableInAT UnPack() { + var _o = new SecondTableInAT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(SecondTableInAT _o) { + _o.ReferToC = this.ReferToC.HasValue ? this.ReferToC.Value.UnPack() : null; + } + public static Offset Pack(FlatBufferBuilder builder, SecondTableInAT _o) { + if (_o == null) return default(Offset); + var _refer_to_c = _o.ReferToC == null ? default(Offset) : NamespaceC.TableInC.Pack(builder, _o.ReferToC); + return CreateSecondTableInA( + builder, + _refer_to_c); + } +} + +public class SecondTableInAT +{ + [Newtonsoft.Json.JsonProperty("refer_to_c")] + public NamespaceC.TableInCT ReferToC { get; set; } + + public SecondTableInAT() { + this.ReferToC = null; + } +} + + +static public class SecondTableInAVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyTable(tablePos, 4 /*ReferToC*/, NamespaceC.TableInCVerify.Verify, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.go new file mode 100644 index 00000000000..f88a682c548 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.go @@ -0,0 +1,82 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceA + +import ( + flatbuffers "github.com/google/flatbuffers/go" + + NamespaceC "NamespaceC" +) + +type SecondTableInAT struct { + ReferToC *NamespaceC.TableInCT +} + +func (t *SecondTableInAT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + referToCOffset := t.ReferToC.Pack(builder) + SecondTableInAStart(builder) + SecondTableInAAddReferToC(builder, referToCOffset) + return SecondTableInAEnd(builder) +} + +func (rcv *SecondTableInA) UnPackTo(t *SecondTableInAT) { + t.ReferToC = rcv.ReferToC(nil).UnPack() +} + +func (rcv *SecondTableInA) UnPack() *SecondTableInAT { + if rcv == nil { return nil } + t := &SecondTableInAT{} + rcv.UnPackTo(t) + return t +} + +type SecondTableInA struct { + _tab flatbuffers.Table +} + +func GetRootAsSecondTableInA(buf []byte, offset flatbuffers.UOffsetT) *SecondTableInA { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &SecondTableInA{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsSecondTableInA(buf []byte, offset flatbuffers.UOffsetT) *SecondTableInA { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &SecondTableInA{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *SecondTableInA) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *SecondTableInA) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *SecondTableInA) ReferToC(obj *NamespaceC.TableInC) *NamespaceC.TableInC { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(NamespaceC.TableInC) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func SecondTableInAStart(builder *flatbuffers.Builder) { + builder.StartObject(1) +} +func SecondTableInAAddReferToC(builder *flatbuffers.Builder, referToC flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(referToC), 0) +} +func SecondTableInAEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.java new file mode 100644 index 00000000000..72348d84f23 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.java @@ -0,0 +1,58 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +@SuppressWarnings("unused") +public final class SecondTableInA extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static SecondTableInA getRootAsSecondTableInA(ByteBuffer _bb) { return getRootAsSecondTableInA(_bb, new SecondTableInA()); } + public static SecondTableInA getRootAsSecondTableInA(ByteBuffer _bb, SecondTableInA obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public SecondTableInA __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public NamespaceC.TableInC referToC() { return referToC(new NamespaceC.TableInC()); } + public NamespaceC.TableInC referToC(NamespaceC.TableInC obj) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + + public static int createSecondTableInA(FlatBufferBuilder builder, + int referToCOffset) { + builder.startTable(1); + SecondTableInA.addReferToC(builder, referToCOffset); + return SecondTableInA.endSecondTableInA(builder); + } + + public static void startSecondTableInA(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addReferToC(FlatBufferBuilder builder, int referToCOffset) { builder.addOffset(0, referToCOffset, 0); } + public static int endSecondTableInA(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public SecondTableInA get(int j) { return get(new SecondTableInA(), j); } + public SecondTableInA get(SecondTableInA obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public SecondTableInAT unpack() { + SecondTableInAT _o = new SecondTableInAT(); + unpackTo(_o); + return _o; + } + public void unpackTo(SecondTableInAT _o) { + if (referToC() != null) _o.setReferToC(referToC().unpack()); + else _o.setReferToC(null); + } + public static int pack(FlatBufferBuilder builder, SecondTableInAT _o) { + if (_o == null) return 0; + int _refer_to_c = _o.getReferToC() == null ? 0 : NamespaceC.TableInC.pack(builder, _o.getReferToC()); + return createSecondTableInA( + builder, + _refer_to_c); + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.kt new file mode 100644 index 00000000000..1bef8989f6a --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.kt @@ -0,0 +1,60 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +@ExperimentalUnsignedTypes +class SecondTableInA : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : SecondTableInA { + __init(_i, _bb) + return this + } + val referToC : NamespaceC.TableInC? get() = referToC(NamespaceC.TableInC()) + fun referToC(obj: NamespaceC.TableInC) : NamespaceC.TableInC? { + val o = __offset(4) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsSecondTableInA(_bb: ByteBuffer): SecondTableInA = getRootAsSecondTableInA(_bb, SecondTableInA()) + fun getRootAsSecondTableInA(_bb: ByteBuffer, obj: SecondTableInA): SecondTableInA { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createSecondTableInA(builder: FlatBufferBuilder, referToCOffset: Int) : Int { + builder.startTable(1) + addReferToC(builder, referToCOffset) + return endSecondTableInA(builder) + } + fun startSecondTableInA(builder: FlatBufferBuilder) = builder.startTable(1) + fun addReferToC(builder: FlatBufferBuilder, referToC: Int) = builder.addOffset(0, referToC, 0) + fun endSecondTableInA(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.lua new file mode 100644 index 00000000000..b953c124c4b --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.lua @@ -0,0 +1,40 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceA + +local flatbuffers = require('flatbuffers') + +local SecondTableInA = {} -- the module +local SecondTableInA_mt = {} -- the class metatable + +function SecondTableInA.New() + local o = {} + setmetatable(o, {__index = SecondTableInA_mt}) + return o +end +function SecondTableInA.GetRootAsSecondTableInA(buf, offset) + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) + local o = SecondTableInA.New() + o:Init(buf, n + offset) + return o +end +function SecondTableInA_mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end +function SecondTableInA_mt:ReferToC() + local o = self.view:Offset(4) + if o ~= 0 then + local x = self.view:Indirect(o + self.view.pos) + local obj = require('NamespaceC.TableInC').New() + obj:Init(self.view.bytes, x) + return obj + end +end +function SecondTableInA.Start(builder) builder:StartObject(1) end +function SecondTableInA.AddReferToC(builder, referToC) builder:PrependUOffsetTRelativeSlot(0, referToC, 0) end +function SecondTableInA.End(builder) return builder:EndObject() end + +return SecondTableInA -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.php new file mode 100644 index 00000000000..c9bc65c1500 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.php @@ -0,0 +1,82 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return SecondTableInA + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + public function getReferToC() + { + $obj = new TableInC(); + $o = $this->__offset(4); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startSecondTableInA(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return SecondTableInA + */ + public static function createSecondTableInA(FlatBufferBuilder $builder, $refer_to_c) + { + $builder->startObject(1); + self::addReferToC($builder, $refer_to_c); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addReferToC(FlatBufferBuilder $builder, $referToC) + { + $builder->addOffsetX(0, $referToC, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endSecondTableInA(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.py new file mode 100644 index 00000000000..474f44d4dd1 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInA.py @@ -0,0 +1,84 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceA + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class SecondTableInA(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = SecondTableInA() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsSecondTableInA(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # SecondTableInA + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # SecondTableInA + def ReferToC(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = TableInC() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def SecondTableInAStart(builder): builder.StartObject(1) +def Start(builder): + return SecondTableInAStart(builder) +def SecondTableInAAddReferToC(builder, referToC): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToC), 0) +def AddReferToC(builder, referToC): + return SecondTableInAAddReferToC(builder, referToC) +def SecondTableInAEnd(builder): return builder.EndObject() +def End(builder): + return SecondTableInAEnd(builder) +try: + from typing import Optional +except: + pass + +class SecondTableInAT(object): + + # SecondTableInAT + def __init__(self): + self.referToC = None # type: Optional[TableInCT] + + @classmethod + def InitFromBuf(cls, buf, pos): + secondTableInA = SecondTableInA() + secondTableInA.Init(buf, pos) + return cls.InitFromObj(secondTableInA) + + @classmethod + def InitFromObj(cls, secondTableInA): + x = SecondTableInAT() + x._UnPack(secondTableInA) + return x + + # SecondTableInAT + def _UnPack(self, secondTableInA): + if secondTableInA is None: + return + if secondTableInA.ReferToC() is not None: + self.referToC = TableInCT.InitFromObj(secondTableInA.ReferToC()) + + # SecondTableInAT + def Pack(self, builder): + if self.referToC is not None: + referToC = self.referToC.Pack(builder) + SecondTableInAStart(builder) + if self.referToC is not None: + SecondTableInAAddReferToC(builder, referToC) + secondTableInA = SecondTableInAEnd(builder) + return secondTableInA diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInAT.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInAT.java new file mode 100644 index 00000000000..98fe21ccf08 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/SecondTableInAT.java @@ -0,0 +1,22 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class SecondTableInAT { + private NamespaceC.TableInCT referToC; + + public NamespaceC.TableInCT getReferToC() { return referToC; } + + public void setReferToC(NamespaceC.TableInCT referToC) { this.referToC = referToC; } + + + public SecondTableInAT() { + this.referToC = null; + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.cs new file mode 100644 index 00000000000..638fb4b7c67 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.cs @@ -0,0 +1,38 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +namespace NamespaceA +{ + +using System; +using Google.FlatBuffers; + +public sealed class TableInC : Table { + public static TableInC GetRootAsTableInC(ByteBuffer _bb) { return GetRootAsTableInC(_bb, new TableInC()); } + public static TableInC GetRootAsTableInC(ByteBuffer _bb, TableInC obj) { return (obj.__init(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public TableInC __init(int _i, ByteBuffer _bb) { bb_pos = _i; bb = _bb; return this; } + + public NamespaceA.TableInFirstNS ReferToA1 { get { return GetReferToA1(new NamespaceA.TableInFirstNS()); } } + public NamespaceA.TableInFirstNS GetReferToA1(NamespaceA.TableInFirstNS obj) { int o = __offset(4); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; } + public SecondTableInA ReferToA2 { get { return GetReferToA2(new SecondTableInA()); } } + public SecondTableInA GetReferToA2(SecondTableInA obj) { int o = __offset(6); return o != 0 ? obj.__init(__indirect(o + bb_pos), bb) : null; } + + public static Offset CreateTableInC(FlatBufferBuilder builder, + Offset refer_to_a1Offset = default(Offset), + Offset refer_to_a2Offset = default(Offset)) { + builder.StartObject(2); + TableInC.AddReferToA2(builder, refer_to_a2Offset); + TableInC.AddReferToA1(builder, refer_to_a1Offset); + return TableInC.EndTableInC(builder); + } + + public static void StartTableInC(FlatBufferBuilder builder) { builder.StartObject(2); } + public static void AddReferToA1(FlatBufferBuilder builder, Offset referToA1Offset) { builder.AddOffset(0, referToA1Offset.Value, 0); } + public static void AddReferToA2(FlatBufferBuilder builder, Offset referToA2Offset) { builder.AddOffset(1, referToA2Offset.Value, 0); } + public static Offset EndTableInC(FlatBufferBuilder builder) { + int o = builder.EndObject(); + return new Offset(o); + } +}; + + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.go new file mode 100644 index 00000000000..6f3d3f2124f --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.go @@ -0,0 +1,46 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) +type TableInC struct { + _tab flatbuffers.Table +} + +func (rcv *TableInC) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *TableInC) ReferToA1(obj *TableInFirstNS) *TableInFirstNS { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(TableInFirstNS) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *TableInC) ReferToA2(obj *SecondTableInA) *SecondTableInA { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(SecondTableInA) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func TableInCStart(builder *flatbuffers.Builder) { builder.StartObject(2) } +func TableInCAddReferToA1(builder *flatbuffers.Builder, referToA1 flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(referToA1), 0) } +func TableInCAddReferToA2(builder *flatbuffers.Builder, referToA2 flatbuffers.UOffsetT) { builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(referToA2), 0) } +func TableInCEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { return builder.EndObject() } diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.php new file mode 100644 index 00000000000..49705f82002 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.php @@ -0,0 +1,100 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return TableInC + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + public function getReferToA1() + { + $obj = new TableInFirstNS(); + $o = $this->__offset(4); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + public function getReferToA2() + { + $obj = new SecondTableInA(); + $o = $this->__offset(6); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startTableInC(FlatBufferBuilder $builder) + { + $builder->StartObject(2); + } + + /** + * @param FlatBufferBuilder $builder + * @return TableInC + */ + public static function createTableInC(FlatBufferBuilder $builder, $refer_to_a1, $refer_to_a2) + { + $builder->startObject(2); + self::addReferToA1($builder, $refer_to_a1); + self::addReferToA2($builder, $refer_to_a2); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addReferToA1(FlatBufferBuilder $builder, $referToA1) + { + $builder->addOffsetX(0, $referToA1, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addReferToA2(FlatBufferBuilder $builder, $referToA2) + { + $builder->addOffsetX(1, $referToA2, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endTableInC(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.py new file mode 100644 index 00000000000..4afea1af98e --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInC.py @@ -0,0 +1,39 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceA + +import flatbuffers + +class TableInC(object): + __slots__ = ['_tab'] + + # TableInC + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TableInC + def ReferToA1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from .TableInFirstNS import TableInFirstNS + obj = TableInFirstNS() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # TableInC + def ReferToA2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + from .SecondTableInA import SecondTableInA + obj = SecondTableInA() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def TableInCStart(builder): builder.StartObject(2) +def TableInCAddReferToA1(builder, referToA1): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToA1), 0) +def TableInCAddReferToA2(builder, referToA2): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(referToA2), 0) +def TableInCEnd(builder): return builder.EndObject() diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.cs new file mode 100644 index 00000000000..084ab0f8169 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.cs @@ -0,0 +1,133 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct TableInFirstNS : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static TableInFirstNS GetRootAsTableInFirstNS(ByteBuffer _bb) { return GetRootAsTableInFirstNS(_bb, new TableInFirstNS()); } + public static TableInFirstNS GetRootAsTableInFirstNS(ByteBuffer _bb, TableInFirstNS obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public TableInFirstNS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public NamespaceA.NamespaceB.TableInNestedNS? FooTable { get { int o = __p.__offset(4); return o != 0 ? (NamespaceA.NamespaceB.TableInNestedNS?)(new NamespaceA.NamespaceB.TableInNestedNS()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + public NamespaceA.NamespaceB.EnumInNestedNS FooEnum { get { int o = __p.__offset(6); return o != 0 ? (NamespaceA.NamespaceB.EnumInNestedNS)__p.bb.GetSbyte(o + __p.bb_pos) : NamespaceA.NamespaceB.EnumInNestedNS.A; } } + public bool MutateFooEnum(NamespaceA.NamespaceB.EnumInNestedNS foo_enum) { int o = __p.__offset(6); if (o != 0) { __p.bb.PutSbyte(o + __p.bb_pos, (sbyte)foo_enum); return true; } else { return false; } } + public NamespaceA.NamespaceB.UnionInNestedNS FooUnionType { get { int o = __p.__offset(8); return o != 0 ? (NamespaceA.NamespaceB.UnionInNestedNS)__p.bb.Get(o + __p.bb_pos) : NamespaceA.NamespaceB.UnionInNestedNS.NONE; } } + public TTable? FooUnion() where TTable : struct, IFlatbufferObject { int o = __p.__offset(10); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public NamespaceA.NamespaceB.TableInNestedNS FooUnionAsTableInNestedNS() { return FooUnion().Value; } + public NamespaceA.NamespaceB.StructInNestedNS? FooStruct { get { int o = __p.__offset(12); return o != 0 ? (NamespaceA.NamespaceB.StructInNestedNS?)(new NamespaceA.NamespaceB.StructInNestedNS()).__assign(o + __p.bb_pos, __p.bb) : null; } } + + public static Offset CreateTableInFirstNS(FlatBufferBuilder builder, + Offset foo_tableOffset = default(Offset), + NamespaceA.NamespaceB.EnumInNestedNS foo_enum = NamespaceA.NamespaceB.EnumInNestedNS.A, + NamespaceA.NamespaceB.UnionInNestedNS foo_union_type = NamespaceA.NamespaceB.UnionInNestedNS.NONE, + int foo_unionOffset = 0, + NamespaceA.NamespaceB.StructInNestedNST foo_struct = null) { + builder.StartTable(5); + TableInFirstNS.AddFooStruct(builder, NamespaceA.NamespaceB.StructInNestedNS.Pack(builder, foo_struct)); + TableInFirstNS.AddFooUnion(builder, foo_unionOffset); + TableInFirstNS.AddFooTable(builder, foo_tableOffset); + TableInFirstNS.AddFooUnionType(builder, foo_union_type); + TableInFirstNS.AddFooEnum(builder, foo_enum); + return TableInFirstNS.EndTableInFirstNS(builder); + } + + public static void StartTableInFirstNS(FlatBufferBuilder builder) { builder.StartTable(5); } + public static void AddFooTable(FlatBufferBuilder builder, Offset fooTableOffset) { builder.AddOffset(0, fooTableOffset.Value, 0); } + public static void AddFooEnum(FlatBufferBuilder builder, NamespaceA.NamespaceB.EnumInNestedNS fooEnum) { builder.AddSbyte(1, (sbyte)fooEnum, 0); } + public static void AddFooUnionType(FlatBufferBuilder builder, NamespaceA.NamespaceB.UnionInNestedNS fooUnionType) { builder.AddByte(2, (byte)fooUnionType, 0); } + public static void AddFooUnion(FlatBufferBuilder builder, int fooUnionOffset) { builder.AddOffset(3, fooUnionOffset, 0); } + public static void AddFooStruct(FlatBufferBuilder builder, Offset fooStructOffset) { builder.AddStruct(4, fooStructOffset.Value, 0); } + public static Offset EndTableInFirstNS(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public TableInFirstNST UnPack() { + var _o = new TableInFirstNST(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(TableInFirstNST _o) { + _o.FooTable = this.FooTable.HasValue ? this.FooTable.Value.UnPack() : null; + _o.FooEnum = this.FooEnum; + _o.FooUnion = new NamespaceA.NamespaceB.UnionInNestedNSUnion(); + _o.FooUnion.Type = this.FooUnionType; + switch (this.FooUnionType) { + default: break; + case NamespaceA.NamespaceB.UnionInNestedNS.TableInNestedNS: + _o.FooUnion.Value = this.FooUnion().HasValue ? this.FooUnion().Value.UnPack() : null; + break; + } + _o.FooStruct = this.FooStruct.HasValue ? this.FooStruct.Value.UnPack() : null; + } + public static Offset Pack(FlatBufferBuilder builder, TableInFirstNST _o) { + if (_o == null) return default(Offset); + var _foo_table = _o.FooTable == null ? default(Offset) : NamespaceA.NamespaceB.TableInNestedNS.Pack(builder, _o.FooTable); + var _foo_union_type = _o.FooUnion == null ? NamespaceA.NamespaceB.UnionInNestedNS.NONE : _o.FooUnion.Type; + var _foo_union = _o.FooUnion == null ? 0 : NamespaceA.NamespaceB.UnionInNestedNSUnion.Pack(builder, _o.FooUnion); + return CreateTableInFirstNS( + builder, + _foo_table, + _o.FooEnum, + _foo_union_type, + _foo_union, + _o.FooStruct); + } +} + +public class TableInFirstNST +{ + [Newtonsoft.Json.JsonProperty("foo_table")] + public NamespaceA.NamespaceB.TableInNestedNST FooTable { get; set; } + [Newtonsoft.Json.JsonProperty("foo_enum")] + public NamespaceA.NamespaceB.EnumInNestedNS FooEnum { get; set; } + [Newtonsoft.Json.JsonProperty("foo_union_type")] + private NamespaceA.NamespaceB.UnionInNestedNS FooUnionType { + get { + return this.FooUnion != null ? this.FooUnion.Type : NamespaceA.NamespaceB.UnionInNestedNS.NONE; + } + set { + this.FooUnion = new NamespaceA.NamespaceB.UnionInNestedNSUnion(); + this.FooUnion.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("foo_union")] + [Newtonsoft.Json.JsonConverter(typeof(NamespaceA.NamespaceB.UnionInNestedNSUnion_JsonConverter))] + public NamespaceA.NamespaceB.UnionInNestedNSUnion FooUnion { get; set; } + [Newtonsoft.Json.JsonProperty("foo_struct")] + public NamespaceA.NamespaceB.StructInNestedNST FooStruct { get; set; } + + public TableInFirstNST() { + this.FooTable = null; + this.FooEnum = NamespaceA.NamespaceB.EnumInNestedNS.A; + this.FooUnion = null; + this.FooStruct = new NamespaceA.NamespaceB.StructInNestedNST(); + } +} + + +static public class TableInFirstNSVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyTable(tablePos, 4 /*FooTable*/, NamespaceA.NamespaceB.TableInNestedNSVerify.Verify, false) + && verifier.VerifyField(tablePos, 6 /*FooEnum*/, 1 /*NamespaceA.NamespaceB.EnumInNestedNS*/, 1, false) + && verifier.VerifyField(tablePos, 8 /*FooUnionType*/, 1 /*NamespaceA.NamespaceB.UnionInNestedNS*/, 1, false) + && verifier.VerifyUnion(tablePos, 8, 10 /*FooUnion*/, NamespaceA.NamespaceB.UnionInNestedNSVerify.Verify, false) + && verifier.VerifyField(tablePos, 12 /*FooStruct*/, 8 /*NamespaceA.NamespaceB.StructInNestedNS*/, 4, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.go b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.go new file mode 100644 index 00000000000..3feaaaa1e46 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.go @@ -0,0 +1,158 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceA + +import ( + flatbuffers "github.com/google/flatbuffers/go" + + NamespaceA__NamespaceB "NamespaceA/NamespaceB" +) + +type TableInFirstNST struct { + FooTable *NamespaceA__NamespaceB.TableInNestedNST + FooEnum NamespaceA__NamespaceB.EnumInNestedNS + FooUnion *NamespaceA__NamespaceB.UnionInNestedNST + FooStruct *NamespaceA__NamespaceB.StructInNestedNST +} + +func (t *TableInFirstNST) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + fooTableOffset := t.FooTable.Pack(builder) + fooUnionOffset := t.FooUnion.Pack(builder) + + TableInFirstNSStart(builder) + TableInFirstNSAddFooTable(builder, fooTableOffset) + TableInFirstNSAddFooEnum(builder, t.FooEnum) + if t.FooUnion != nil { + TableInFirstNSAddFooUnionType(builder, t.FooUnion.Type) + } + TableInFirstNSAddFooUnion(builder, fooUnionOffset) + fooStructOffset := t.FooStruct.Pack(builder) + TableInFirstNSAddFooStruct(builder, fooStructOffset) + return TableInFirstNSEnd(builder) +} + +func (rcv *TableInFirstNS) UnPackTo(t *TableInFirstNST) { + t.FooTable = rcv.FooTable(nil).UnPack() + t.FooEnum = rcv.FooEnum() + fooUnionTable := flatbuffers.Table{} + if rcv.FooUnion(&fooUnionTable) { + t.FooUnion = rcv.FooUnionType().UnPack(fooUnionTable) + } + t.FooStruct = rcv.FooStruct(nil).UnPack() +} + +func (rcv *TableInFirstNS) UnPack() *TableInFirstNST { + if rcv == nil { return nil } + t := &TableInFirstNST{} + rcv.UnPackTo(t) + return t +} + +type TableInFirstNS struct { + _tab flatbuffers.Table +} + +func GetRootAsTableInFirstNS(buf []byte, offset flatbuffers.UOffsetT) *TableInFirstNS { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &TableInFirstNS{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsTableInFirstNS(buf []byte, offset flatbuffers.UOffsetT) *TableInFirstNS { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &TableInFirstNS{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *TableInFirstNS) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *TableInFirstNS) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *TableInFirstNS) FooTable(obj *NamespaceA__NamespaceB.TableInNestedNS) *NamespaceA__NamespaceB.TableInNestedNS { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(NamespaceA__NamespaceB.TableInNestedNS) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *TableInFirstNS) FooEnum() NamespaceA__NamespaceB.EnumInNestedNS { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + return NamespaceA__NamespaceB.EnumInNestedNS(rcv._tab.GetInt8(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *TableInFirstNS) MutateFooEnum(n NamespaceA__NamespaceB.EnumInNestedNS) bool { + return rcv._tab.MutateInt8Slot(6, int8(n)) +} + +func (rcv *TableInFirstNS) FooUnionType() NamespaceA__NamespaceB.UnionInNestedNS { + o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) + if o != 0 { + return NamespaceA__NamespaceB.UnionInNestedNS(rcv._tab.GetByte(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *TableInFirstNS) MutateFooUnionType(n NamespaceA__NamespaceB.UnionInNestedNS) bool { + return rcv._tab.MutateByteSlot(8, byte(n)) +} + +func (rcv *TableInFirstNS) FooUnion(obj *flatbuffers.Table) bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(10)) + if o != 0 { + rcv._tab.Union(obj, o) + return true + } + return false +} + +func (rcv *TableInFirstNS) FooStruct(obj *NamespaceA__NamespaceB.StructInNestedNS) *NamespaceA__NamespaceB.StructInNestedNS { + o := flatbuffers.UOffsetT(rcv._tab.Offset(12)) + if o != 0 { + x := o + rcv._tab.Pos + if obj == nil { + obj = new(NamespaceA__NamespaceB.StructInNestedNS) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func TableInFirstNSStart(builder *flatbuffers.Builder) { + builder.StartObject(5) +} +func TableInFirstNSAddFooTable(builder *flatbuffers.Builder, fooTable flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(fooTable), 0) +} +func TableInFirstNSAddFooEnum(builder *flatbuffers.Builder, fooEnum NamespaceA__NamespaceB.EnumInNestedNS) { + builder.PrependInt8Slot(1, int8(fooEnum), 0) +} +func TableInFirstNSAddFooUnionType(builder *flatbuffers.Builder, fooUnionType NamespaceA__NamespaceB.UnionInNestedNS) { + builder.PrependByteSlot(2, byte(fooUnionType), 0) +} +func TableInFirstNSAddFooUnion(builder *flatbuffers.Builder, fooUnion flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(3, flatbuffers.UOffsetT(fooUnion), 0) +} +func TableInFirstNSAddFooStruct(builder *flatbuffers.Builder, fooStruct flatbuffers.UOffsetT) { + builder.PrependStructSlot(4, flatbuffers.UOffsetT(fooStruct), 0) +} +func TableInFirstNSEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.java new file mode 100644 index 00000000000..71c32148fa3 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.java @@ -0,0 +1,83 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +@SuppressWarnings("unused") +public final class TableInFirstNS extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static TableInFirstNS getRootAsTableInFirstNS(ByteBuffer _bb) { return getRootAsTableInFirstNS(_bb, new TableInFirstNS()); } + public static TableInFirstNS getRootAsTableInFirstNS(ByteBuffer _bb, TableInFirstNS obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public TableInFirstNS __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public NamespaceA.NamespaceB.TableInNestedNS fooTable() { return fooTable(new NamespaceA.NamespaceB.TableInNestedNS()); } + public NamespaceA.NamespaceB.TableInNestedNS fooTable(NamespaceA.NamespaceB.TableInNestedNS obj) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public byte fooEnum() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) : 0; } + public boolean mutateFooEnum(byte foo_enum) { int o = __offset(6); if (o != 0) { bb.put(o + bb_pos, foo_enum); return true; } else { return false; } } + public byte fooUnionType() { int o = __offset(8); return o != 0 ? bb.get(o + bb_pos) : 0; } + public Table fooUnion(Table obj) { int o = __offset(10); return o != 0 ? __union(obj, o + bb_pos) : null; } + public NamespaceA.NamespaceB.StructInNestedNS fooStruct() { return fooStruct(new NamespaceA.NamespaceB.StructInNestedNS()); } + public NamespaceA.NamespaceB.StructInNestedNS fooStruct(NamespaceA.NamespaceB.StructInNestedNS obj) { int o = __offset(12); return o != 0 ? obj.__assign(o + bb_pos, bb) : null; } + + public static void startTableInFirstNS(FlatBufferBuilder builder) { builder.startTable(5); } + public static void addFooTable(FlatBufferBuilder builder, int fooTableOffset) { builder.addOffset(0, fooTableOffset, 0); } + public static void addFooEnum(FlatBufferBuilder builder, byte fooEnum) { builder.addByte(1, fooEnum, 0); } + public static void addFooUnionType(FlatBufferBuilder builder, byte fooUnionType) { builder.addByte(2, fooUnionType, 0); } + public static void addFooUnion(FlatBufferBuilder builder, int fooUnionOffset) { builder.addOffset(3, fooUnionOffset, 0); } + public static void addFooStruct(FlatBufferBuilder builder, int fooStructOffset) { builder.addStruct(4, fooStructOffset, 0); } + public static int endTableInFirstNS(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public TableInFirstNS get(int j) { return get(new TableInFirstNS(), j); } + public TableInFirstNS get(TableInFirstNS obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public TableInFirstNST unpack() { + TableInFirstNST _o = new TableInFirstNST(); + unpackTo(_o); + return _o; + } + public void unpackTo(TableInFirstNST _o) { + if (fooTable() != null) _o.setFooTable(fooTable().unpack()); + else _o.setFooTable(null); + byte _oFooEnum = fooEnum(); + _o.setFooEnum(_oFooEnum); + NamespaceA.NamespaceB.UnionInNestedNSUnion _oFooUnion = new NamespaceA.NamespaceB.UnionInNestedNSUnion(); + byte _oFooUnionType = fooUnionType(); + _oFooUnion.setType(_oFooUnionType); + Table _oFooUnionValue; + switch (_oFooUnionType) { + case NamespaceA.NamespaceB.UnionInNestedNS.TableInNestedNS: + _oFooUnionValue = fooUnion(new NamespaceA.NamespaceB.TableInNestedNS()); + _oFooUnion.setValue(_oFooUnionValue != null ? ((NamespaceA.NamespaceB.TableInNestedNS) _oFooUnionValue).unpack() : null); + break; + default: break; + } + _o.setFooUnion(_oFooUnion); + if (fooStruct() != null) fooStruct().unpackTo(_o.getFooStruct()); + else _o.setFooStruct(null); + } + public static int pack(FlatBufferBuilder builder, TableInFirstNST _o) { + if (_o == null) return 0; + int _foo_table = _o.getFooTable() == null ? 0 : NamespaceA.NamespaceB.TableInNestedNS.pack(builder, _o.getFooTable()); + byte _fooUnionType = _o.getFooUnion() == null ? NamespaceA.NamespaceB.UnionInNestedNS.NONE : _o.getFooUnion().getType(); + int _fooUnion = _o.getFooUnion() == null ? 0 : NamespaceA.NamespaceB.UnionInNestedNSUnion.pack(builder, _o.getFooUnion()); + startTableInFirstNS(builder); + addFooTable(builder, _foo_table); + addFooEnum(builder, _o.getFooEnum()); + addFooUnionType(builder, _fooUnionType); + addFooUnion(builder, _fooUnion); + addFooStruct(builder, NamespaceA.NamespaceB.StructInNestedNS.pack(builder, _o.getFooStruct())); + return endTableInFirstNS(builder); + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.kt new file mode 100644 index 00000000000..17d0c1616d7 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.kt @@ -0,0 +1,99 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +@ExperimentalUnsignedTypes +class TableInFirstNS : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : TableInFirstNS { + __init(_i, _bb) + return this + } + val fooTable : NamespaceA.NamespaceB.TableInNestedNS? get() = fooTable(NamespaceA.NamespaceB.TableInNestedNS()) + fun fooTable(obj: NamespaceA.NamespaceB.TableInNestedNS) : NamespaceA.NamespaceB.TableInNestedNS? { + val o = __offset(4) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + val fooEnum : Byte + get() { + val o = __offset(6) + return if(o != 0) bb.get(o + bb_pos) else 0 + } + fun mutateFooEnum(fooEnum: Byte) : Boolean { + val o = __offset(6) + return if (o != 0) { + bb.put(o + bb_pos, fooEnum) + true + } else { + false + } + } + val fooUnionType : UByte + get() { + val o = __offset(8) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + fun mutateFooUnionType(fooUnionType: UByte) : Boolean { + val o = __offset(8) + return if (o != 0) { + bb.put(o + bb_pos, fooUnionType.toByte()) + true + } else { + false + } + } + fun fooUnion(obj: Table) : Table? { + val o = __offset(10); return if (o != 0) __union(obj, o + bb_pos) else null + } + val fooStruct : NamespaceA.NamespaceB.StructInNestedNS? get() = fooStruct(NamespaceA.NamespaceB.StructInNestedNS()) + fun fooStruct(obj: NamespaceA.NamespaceB.StructInNestedNS) : NamespaceA.NamespaceB.StructInNestedNS? { + val o = __offset(12) + return if (o != 0) { + obj.__assign(o + bb_pos, bb) + } else { + null + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsTableInFirstNS(_bb: ByteBuffer): TableInFirstNS = getRootAsTableInFirstNS(_bb, TableInFirstNS()) + fun getRootAsTableInFirstNS(_bb: ByteBuffer, obj: TableInFirstNS): TableInFirstNS { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun startTableInFirstNS(builder: FlatBufferBuilder) = builder.startTable(5) + fun addFooTable(builder: FlatBufferBuilder, fooTable: Int) = builder.addOffset(0, fooTable, 0) + fun addFooEnum(builder: FlatBufferBuilder, fooEnum: Byte) = builder.addByte(1, fooEnum, 0) + fun addFooUnionType(builder: FlatBufferBuilder, fooUnionType: UByte) = builder.addByte(2, fooUnionType.toByte(), 0) + fun addFooUnion(builder: FlatBufferBuilder, fooUnion: Int) = builder.addOffset(3, fooUnion, 0) + fun addFooStruct(builder: FlatBufferBuilder, fooStruct: Int) = builder.addStruct(4, fooStruct, 0) + fun endTableInFirstNS(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.lua new file mode 100644 index 00000000000..1b62cc5fae5 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.lua @@ -0,0 +1,75 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceA + +local flatbuffers = require('flatbuffers') + +local TableInFirstNS = {} -- the module +local TableInFirstNS_mt = {} -- the class metatable + +function TableInFirstNS.New() + local o = {} + setmetatable(o, {__index = TableInFirstNS_mt}) + return o +end +function TableInFirstNS.GetRootAsTableInFirstNS(buf, offset) + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) + local o = TableInFirstNS.New() + o:Init(buf, n + offset) + return o +end +function TableInFirstNS_mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end +function TableInFirstNS_mt:FooTable() + local o = self.view:Offset(4) + if o ~= 0 then + local x = self.view:Indirect(o + self.view.pos) + local obj = require('NamespaceA.NamespaceB.TableInNestedNS').New() + obj:Init(self.view.bytes, x) + return obj + end +end +function TableInFirstNS_mt:FooEnum() + local o = self.view:Offset(6) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Int8, o + self.view.pos) + end + return 0 +end +function TableInFirstNS_mt:FooUnionType() + local o = self.view:Offset(8) + if o ~= 0 then + return self.view:Get(flatbuffers.N.Uint8, o + self.view.pos) + end + return 0 +end +function TableInFirstNS_mt:FooUnion() + local o = self.view:Offset(10) + if o ~= 0 then + local obj = flatbuffers.view.New(require('flatbuffers.binaryarray').New(0), 0) + self.view:Union(obj, o) + return obj + end +end +function TableInFirstNS_mt:FooStruct() + local o = self.view:Offset(12) + if o ~= 0 then + local x = o + self.view.pos + local obj = require('NamespaceA.NamespaceB.StructInNestedNS').New() + obj:Init(self.view.bytes, x) + return obj + end +end +function TableInFirstNS.Start(builder) builder:StartObject(5) end +function TableInFirstNS.AddFooTable(builder, fooTable) builder:PrependUOffsetTRelativeSlot(0, fooTable, 0) end +function TableInFirstNS.AddFooEnum(builder, fooEnum) builder:PrependInt8Slot(1, fooEnum, 0) end +function TableInFirstNS.AddFooUnionType(builder, fooUnionType) builder:PrependUint8Slot(2, fooUnionType, 0) end +function TableInFirstNS.AddFooUnion(builder, fooUnion) builder:PrependUOffsetTRelativeSlot(3, fooUnion, 0) end +function TableInFirstNS.AddFooStruct(builder, fooStruct) builder:PrependStructSlot(4, fooStruct, 0) end +function TableInFirstNS.End(builder) return builder:EndObject() end + +return TableInFirstNS -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.php b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.php new file mode 100644 index 00000000000..637ead54338 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.php @@ -0,0 +1,155 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return TableInFirstNS + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + public function getFooTable() + { + $obj = new TableInNestedNS(); + $o = $this->__offset(4); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @return sbyte + */ + public function getFooEnum() + { + $o = $this->__offset(6); + return $o != 0 ? $this->bb->getSbyte($o + $this->bb_pos) : \NamespaceA\NamespaceB\EnumInNestedNS::A; + } + + /** + * @return byte + */ + public function getFooUnionType() + { + $o = $this->__offset(8); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \NamespaceA\NamespaceB\UnionInNestedNS::NONE; + } + + /** + * @returnint + */ + public function getFooUnion($obj) + { + $o = $this->__offset(10); + return $o != 0 ? $this->__union($obj, $o) : null; + } + + public function getFooStruct() + { + $obj = new StructInNestedNS(); + $o = $this->__offset(12); + return $o != 0 ? $obj->init($o + $this->bb_pos, $this->bb) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startTableInFirstNS(FlatBufferBuilder $builder) + { + $builder->StartObject(5); + } + + /** + * @param FlatBufferBuilder $builder + * @return TableInFirstNS + */ + public static function createTableInFirstNS(FlatBufferBuilder $builder, $foo_table, $foo_enum, $foo_union_type, $foo_union, $foo_struct) + { + $builder->startObject(5); + self::addFooTable($builder, $foo_table); + self::addFooEnum($builder, $foo_enum); + self::addFooUnionType($builder, $foo_union_type); + self::addFooUnion($builder, $foo_union); + self::addFooStruct($builder, $foo_struct); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addFooTable(FlatBufferBuilder $builder, $fooTable) + { + $builder->addOffsetX(0, $fooTable, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param sbyte + * @return void + */ + public static function addFooEnum(FlatBufferBuilder $builder, $fooEnum) + { + $builder->addSbyteX(1, $fooEnum, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addFooUnionType(FlatBufferBuilder $builder, $fooUnionType) + { + $builder->addByteX(2, $fooUnionType, 0); + } + + public static function addFooUnion(FlatBufferBuilder $builder, $offset) + { + $builder->addOffsetX(3, $offset, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addFooStruct(FlatBufferBuilder $builder, $fooStruct) + { + $builder->addStructX(4, $fooStruct, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endTableInFirstNS(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.py new file mode 100644 index 00000000000..8f191f8ad78 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNS.py @@ -0,0 +1,148 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceA + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TableInFirstNS(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TableInFirstNS() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTableInFirstNS(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # TableInFirstNS + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TableInFirstNS + def FooTable(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = TableInNestedNS() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # TableInFirstNS + def FooEnum(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # TableInFirstNS + def FooUnionType(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # TableInFirstNS + def FooUnion(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + from flatbuffers.table import Table + obj = Table(bytearray(), 0) + self._tab.Union(obj, o) + return obj + return None + + # TableInFirstNS + def FooStruct(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + x = o + self._tab.Pos + obj = StructInNestedNS() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def TableInFirstNSStart(builder): builder.StartObject(5) +def Start(builder): + return TableInFirstNSStart(builder) +def TableInFirstNSAddFooTable(builder, fooTable): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(fooTable), 0) +def AddFooTable(builder, fooTable): + return TableInFirstNSAddFooTable(builder, fooTable) +def TableInFirstNSAddFooEnum(builder, fooEnum): builder.PrependInt8Slot(1, fooEnum, 0) +def AddFooEnum(builder, fooEnum): + return TableInFirstNSAddFooEnum(builder, fooEnum) +def TableInFirstNSAddFooUnionType(builder, fooUnionType): builder.PrependUint8Slot(2, fooUnionType, 0) +def AddFooUnionType(builder, fooUnionType): + return TableInFirstNSAddFooUnionType(builder, fooUnionType) +def TableInFirstNSAddFooUnion(builder, fooUnion): builder.PrependUOffsetTRelativeSlot(3, flatbuffers.number_types.UOffsetTFlags.py_type(fooUnion), 0) +def AddFooUnion(builder, fooUnion): + return TableInFirstNSAddFooUnion(builder, fooUnion) +def TableInFirstNSAddFooStruct(builder, fooStruct): builder.PrependStructSlot(4, flatbuffers.number_types.UOffsetTFlags.py_type(fooStruct), 0) +def AddFooStruct(builder, fooStruct): + return TableInFirstNSAddFooStruct(builder, fooStruct) +def TableInFirstNSEnd(builder): return builder.EndObject() +def End(builder): + return TableInFirstNSEnd(builder) +try: + from typing import Optional, Union +except: + pass + +class TableInFirstNST(object): + + # TableInFirstNST + def __init__(self): + self.fooTable = None # type: Optional[TableInNestedNST] + self.fooEnum = 0 # type: int + self.fooUnionType = 0 # type: int + self.fooUnion = None # type: Union[None, TableInNestedNST] + self.fooStruct = None # type: Optional[StructInNestedNST] + + @classmethod + def InitFromBuf(cls, buf, pos): + tableInFirstNS = TableInFirstNS() + tableInFirstNS.Init(buf, pos) + return cls.InitFromObj(tableInFirstNS) + + @classmethod + def InitFromObj(cls, tableInFirstNS): + x = TableInFirstNST() + x._UnPack(tableInFirstNS) + return x + + # TableInFirstNST + def _UnPack(self, tableInFirstNS): + if tableInFirstNS is None: + return + if tableInFirstNS.FooTable() is not None: + self.fooTable = TableInNestedNST.InitFromObj(tableInFirstNS.FooTable()) + self.fooEnum = tableInFirstNS.FooEnum() + self.fooUnionType = tableInFirstNS.FooUnionType() + self.fooUnion = UnionInNestedNSCreator(self.fooUnionType, tableInFirstNS.FooUnion()) + if tableInFirstNS.FooStruct() is not None: + self.fooStruct = StructInNestedNST.InitFromObj(tableInFirstNS.FooStruct()) + + # TableInFirstNST + def Pack(self, builder): + if self.fooTable is not None: + fooTable = self.fooTable.Pack(builder) + if self.fooUnion is not None: + fooUnion = self.fooUnion.Pack(builder) + TableInFirstNSStart(builder) + if self.fooTable is not None: + TableInFirstNSAddFooTable(builder, fooTable) + TableInFirstNSAddFooEnum(builder, self.fooEnum) + TableInFirstNSAddFooUnionType(builder, self.fooUnionType) + if self.fooUnion is not None: + TableInFirstNSAddFooUnion(builder, fooUnion) + if self.fooStruct is not None: + fooStruct = self.fooStruct.Pack(builder) + TableInFirstNSAddFooStruct(builder, fooStruct) + tableInFirstNS = TableInFirstNSEnd(builder) + return tableInFirstNS diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNST.java b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNST.java new file mode 100644 index 00000000000..ee439d42df5 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceA/TableInFirstNST.java @@ -0,0 +1,40 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceA; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class TableInFirstNST { + private NamespaceA.NamespaceB.TableInNestedNST fooTable; + private byte fooEnum; + private NamespaceA.NamespaceB.UnionInNestedNSUnion fooUnion; + private NamespaceA.NamespaceB.StructInNestedNST fooStruct; + + public NamespaceA.NamespaceB.TableInNestedNST getFooTable() { return fooTable; } + + public void setFooTable(NamespaceA.NamespaceB.TableInNestedNST fooTable) { this.fooTable = fooTable; } + + public byte getFooEnum() { return fooEnum; } + + public void setFooEnum(byte fooEnum) { this.fooEnum = fooEnum; } + + public NamespaceA.NamespaceB.UnionInNestedNSUnion getFooUnion() { return fooUnion; } + + public void setFooUnion(NamespaceA.NamespaceB.UnionInNestedNSUnion fooUnion) { this.fooUnion = fooUnion; } + + public NamespaceA.NamespaceB.StructInNestedNST getFooStruct() { return fooStruct; } + + public void setFooStruct(NamespaceA.NamespaceB.StructInNestedNST fooStruct) { this.fooStruct = fooStruct; } + + + public TableInFirstNST() { + this.fooTable = null; + this.fooEnum = 0; + this.fooUnion = null; + this.fooStruct = new NamespaceA.NamespaceB.StructInNestedNST(); + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceA/__init__.py b/third_party/flatbuffers/tests/namespace_test/NamespaceA/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.cs b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.cs new file mode 100644 index 00000000000..ed9eebb4ea8 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.cs @@ -0,0 +1,86 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceC +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct TableInC : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static TableInC GetRootAsTableInC(ByteBuffer _bb) { return GetRootAsTableInC(_bb, new TableInC()); } + public static TableInC GetRootAsTableInC(ByteBuffer _bb, TableInC obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public TableInC __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public NamespaceA.TableInFirstNS? ReferToA1 { get { int o = __p.__offset(4); return o != 0 ? (NamespaceA.TableInFirstNS?)(new NamespaceA.TableInFirstNS()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + public NamespaceA.SecondTableInA? ReferToA2 { get { int o = __p.__offset(6); return o != 0 ? (NamespaceA.SecondTableInA?)(new NamespaceA.SecondTableInA()).__assign(__p.__indirect(o + __p.bb_pos), __p.bb) : null; } } + + public static Offset CreateTableInC(FlatBufferBuilder builder, + Offset refer_to_a1Offset = default(Offset), + Offset refer_to_a2Offset = default(Offset)) { + builder.StartTable(2); + TableInC.AddReferToA2(builder, refer_to_a2Offset); + TableInC.AddReferToA1(builder, refer_to_a1Offset); + return TableInC.EndTableInC(builder); + } + + public static void StartTableInC(FlatBufferBuilder builder) { builder.StartTable(2); } + public static void AddReferToA1(FlatBufferBuilder builder, Offset referToA1Offset) { builder.AddOffset(0, referToA1Offset.Value, 0); } + public static void AddReferToA2(FlatBufferBuilder builder, Offset referToA2Offset) { builder.AddOffset(1, referToA2Offset.Value, 0); } + public static Offset EndTableInC(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public TableInCT UnPack() { + var _o = new TableInCT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(TableInCT _o) { + _o.ReferToA1 = this.ReferToA1.HasValue ? this.ReferToA1.Value.UnPack() : null; + _o.ReferToA2 = this.ReferToA2.HasValue ? this.ReferToA2.Value.UnPack() : null; + } + public static Offset Pack(FlatBufferBuilder builder, TableInCT _o) { + if (_o == null) return default(Offset); + var _refer_to_a1 = _o.ReferToA1 == null ? default(Offset) : NamespaceA.TableInFirstNS.Pack(builder, _o.ReferToA1); + var _refer_to_a2 = _o.ReferToA2 == null ? default(Offset) : NamespaceA.SecondTableInA.Pack(builder, _o.ReferToA2); + return CreateTableInC( + builder, + _refer_to_a1, + _refer_to_a2); + } +} + +public class TableInCT +{ + [Newtonsoft.Json.JsonProperty("refer_to_a1")] + public NamespaceA.TableInFirstNST ReferToA1 { get; set; } + [Newtonsoft.Json.JsonProperty("refer_to_a2")] + public NamespaceA.SecondTableInAT ReferToA2 { get; set; } + + public TableInCT() { + this.ReferToA1 = null; + this.ReferToA2 = null; + } +} + + +static public class TableInCVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyTable(tablePos, 4 /*ReferToA1*/, NamespaceA.TableInFirstNSVerify.Verify, false) + && verifier.VerifyTable(tablePos, 6 /*ReferToA2*/, NamespaceA.SecondTableInAVerify.Verify, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.go b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.go new file mode 100644 index 00000000000..f17163427f5 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.go @@ -0,0 +1,102 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package NamespaceC + +import ( + flatbuffers "github.com/google/flatbuffers/go" + + NamespaceA "NamespaceA" +) + +type TableInCT struct { + ReferToA1 *NamespaceA.TableInFirstNST + ReferToA2 *NamespaceA.SecondTableInAT +} + +func (t *TableInCT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + referToA1Offset := t.ReferToA1.Pack(builder) + referToA2Offset := t.ReferToA2.Pack(builder) + TableInCStart(builder) + TableInCAddReferToA1(builder, referToA1Offset) + TableInCAddReferToA2(builder, referToA2Offset) + return TableInCEnd(builder) +} + +func (rcv *TableInC) UnPackTo(t *TableInCT) { + t.ReferToA1 = rcv.ReferToA1(nil).UnPack() + t.ReferToA2 = rcv.ReferToA2(nil).UnPack() +} + +func (rcv *TableInC) UnPack() *TableInCT { + if rcv == nil { return nil } + t := &TableInCT{} + rcv.UnPackTo(t) + return t +} + +type TableInC struct { + _tab flatbuffers.Table +} + +func GetRootAsTableInC(buf []byte, offset flatbuffers.UOffsetT) *TableInC { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &TableInC{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsTableInC(buf []byte, offset flatbuffers.UOffsetT) *TableInC { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &TableInC{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *TableInC) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *TableInC) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *TableInC) ReferToA1(obj *NamespaceA.TableInFirstNS) *NamespaceA.TableInFirstNS { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(NamespaceA.TableInFirstNS) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *TableInC) ReferToA2(obj *NamespaceA.SecondTableInA) *NamespaceA.SecondTableInA { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(NamespaceA.SecondTableInA) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func TableInCStart(builder *flatbuffers.Builder) { + builder.StartObject(2) +} +func TableInCAddReferToA1(builder *flatbuffers.Builder, referToA1 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(referToA1), 0) +} +func TableInCAddReferToA2(builder *flatbuffers.Builder, referToA2 flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(referToA2), 0) +} +func TableInCEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.java b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.java new file mode 100644 index 00000000000..cb442ac4301 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.java @@ -0,0 +1,67 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceC; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +@SuppressWarnings("unused") +public final class TableInC extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static TableInC getRootAsTableInC(ByteBuffer _bb) { return getRootAsTableInC(_bb, new TableInC()); } + public static TableInC getRootAsTableInC(ByteBuffer _bb, TableInC obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public TableInC __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public NamespaceA.TableInFirstNS referToA1() { return referToA1(new NamespaceA.TableInFirstNS()); } + public NamespaceA.TableInFirstNS referToA1(NamespaceA.TableInFirstNS obj) { int o = __offset(4); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + public NamespaceA.SecondTableInA referToA2() { return referToA2(new NamespaceA.SecondTableInA()); } + public NamespaceA.SecondTableInA referToA2(NamespaceA.SecondTableInA obj) { int o = __offset(6); return o != 0 ? obj.__assign(__indirect(o + bb_pos), bb) : null; } + + public static int createTableInC(FlatBufferBuilder builder, + int referToA1Offset, + int referToA2Offset) { + builder.startTable(2); + TableInC.addReferToA2(builder, referToA2Offset); + TableInC.addReferToA1(builder, referToA1Offset); + return TableInC.endTableInC(builder); + } + + public static void startTableInC(FlatBufferBuilder builder) { builder.startTable(2); } + public static void addReferToA1(FlatBufferBuilder builder, int referToA1Offset) { builder.addOffset(0, referToA1Offset, 0); } + public static void addReferToA2(FlatBufferBuilder builder, int referToA2Offset) { builder.addOffset(1, referToA2Offset, 0); } + public static int endTableInC(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public TableInC get(int j) { return get(new TableInC(), j); } + public TableInC get(TableInC obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public TableInCT unpack() { + TableInCT _o = new TableInCT(); + unpackTo(_o); + return _o; + } + public void unpackTo(TableInCT _o) { + if (referToA1() != null) _o.setReferToA1(referToA1().unpack()); + else _o.setReferToA1(null); + if (referToA2() != null) _o.setReferToA2(referToA2().unpack()); + else _o.setReferToA2(null); + } + public static int pack(FlatBufferBuilder builder, TableInCT _o) { + if (_o == null) return 0; + int _refer_to_a1 = _o.getReferToA1() == null ? 0 : NamespaceA.TableInFirstNS.pack(builder, _o.getReferToA1()); + int _refer_to_a2 = _o.getReferToA2() == null ? 0 : NamespaceA.SecondTableInA.pack(builder, _o.getReferToA2()); + return createTableInC( + builder, + _refer_to_a1, + _refer_to_a2); + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.kt b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.kt new file mode 100644 index 00000000000..27b57f0fd73 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.kt @@ -0,0 +1,71 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceC + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +@ExperimentalUnsignedTypes +class TableInC : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : TableInC { + __init(_i, _bb) + return this + } + val referToA1 : NamespaceA.TableInFirstNS? get() = referToA1(NamespaceA.TableInFirstNS()) + fun referToA1(obj: NamespaceA.TableInFirstNS) : NamespaceA.TableInFirstNS? { + val o = __offset(4) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + val referToA2 : NamespaceA.SecondTableInA? get() = referToA2(NamespaceA.SecondTableInA()) + fun referToA2(obj: NamespaceA.SecondTableInA) : NamespaceA.SecondTableInA? { + val o = __offset(6) + return if (o != 0) { + obj.__assign(__indirect(o + bb_pos), bb) + } else { + null + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsTableInC(_bb: ByteBuffer): TableInC = getRootAsTableInC(_bb, TableInC()) + fun getRootAsTableInC(_bb: ByteBuffer, obj: TableInC): TableInC { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createTableInC(builder: FlatBufferBuilder, referToA1Offset: Int, referToA2Offset: Int) : Int { + builder.startTable(2) + addReferToA2(builder, referToA2Offset) + addReferToA1(builder, referToA1Offset) + return endTableInC(builder) + } + fun startTableInC(builder: FlatBufferBuilder) = builder.startTable(2) + fun addReferToA1(builder: FlatBufferBuilder, referToA1: Int) = builder.addOffset(0, referToA1, 0) + fun addReferToA2(builder: FlatBufferBuilder, referToA2: Int) = builder.addOffset(1, referToA2, 0) + fun endTableInC(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.lua b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.lua new file mode 100644 index 00000000000..71e48427f69 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.lua @@ -0,0 +1,50 @@ +-- automatically generated by the FlatBuffers compiler, do not modify + +-- namespace: NamespaceC + +local flatbuffers = require('flatbuffers') + +local TableInC = {} -- the module +local TableInC_mt = {} -- the class metatable + +function TableInC.New() + local o = {} + setmetatable(o, {__index = TableInC_mt}) + return o +end +function TableInC.GetRootAsTableInC(buf, offset) + if type(buf) == "string" then + buf = flatbuffers.binaryArray.New(buf) + end + local n = flatbuffers.N.UOffsetT:Unpack(buf, offset) + local o = TableInC.New() + o:Init(buf, n + offset) + return o +end +function TableInC_mt:Init(buf, pos) + self.view = flatbuffers.view.New(buf, pos) +end +function TableInC_mt:ReferToA1() + local o = self.view:Offset(4) + if o ~= 0 then + local x = self.view:Indirect(o + self.view.pos) + local obj = require('NamespaceA.TableInFirstNS').New() + obj:Init(self.view.bytes, x) + return obj + end +end +function TableInC_mt:ReferToA2() + local o = self.view:Offset(6) + if o ~= 0 then + local x = self.view:Indirect(o + self.view.pos) + local obj = require('NamespaceA.SecondTableInA').New() + obj:Init(self.view.bytes, x) + return obj + end +end +function TableInC.Start(builder) builder:StartObject(2) end +function TableInC.AddReferToA1(builder, referToA1) builder:PrependUOffsetTRelativeSlot(0, referToA1, 0) end +function TableInC.AddReferToA2(builder, referToA2) builder:PrependUOffsetTRelativeSlot(1, referToA2, 0) end +function TableInC.End(builder) return builder:EndObject() end + +return TableInC -- return the module \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.php b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.php new file mode 100644 index 00000000000..116aea1f940 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.php @@ -0,0 +1,100 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return TableInC + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + public function getReferToA1() + { + $obj = new TableInFirstNS(); + $o = $this->__offset(4); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + public function getReferToA2() + { + $obj = new SecondTableInA(); + $o = $this->__offset(6); + return $o != 0 ? $obj->init($this->__indirect($o + $this->bb_pos), $this->bb) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startTableInC(FlatBufferBuilder $builder) + { + $builder->StartObject(2); + } + + /** + * @param FlatBufferBuilder $builder + * @return TableInC + */ + public static function createTableInC(FlatBufferBuilder $builder, $refer_to_a1, $refer_to_a2) + { + $builder->startObject(2); + self::addReferToA1($builder, $refer_to_a1); + self::addReferToA2($builder, $refer_to_a2); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addReferToA1(FlatBufferBuilder $builder, $referToA1) + { + $builder->addOffsetX(0, $referToA1, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addReferToA2(FlatBufferBuilder $builder, $referToA2) + { + $builder->addOffsetX(1, $referToA2, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endTableInC(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.py b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.py new file mode 100644 index 00000000000..762e1a1ae04 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInC.py @@ -0,0 +1,104 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: NamespaceC + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class TableInC(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = TableInC() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsTableInC(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # TableInC + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # TableInC + def ReferToA1(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = TableInFirstNS() + obj.Init(self._tab.Bytes, x) + return obj + return None + + # TableInC + def ReferToA2(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + x = self._tab.Indirect(o + self._tab.Pos) + obj = SecondTableInA() + obj.Init(self._tab.Bytes, x) + return obj + return None + +def TableInCStart(builder): builder.StartObject(2) +def Start(builder): + return TableInCStart(builder) +def TableInCAddReferToA1(builder, referToA1): builder.PrependUOffsetTRelativeSlot(0, flatbuffers.number_types.UOffsetTFlags.py_type(referToA1), 0) +def AddReferToA1(builder, referToA1): + return TableInCAddReferToA1(builder, referToA1) +def TableInCAddReferToA2(builder, referToA2): builder.PrependUOffsetTRelativeSlot(1, flatbuffers.number_types.UOffsetTFlags.py_type(referToA2), 0) +def AddReferToA2(builder, referToA2): + return TableInCAddReferToA2(builder, referToA2) +def TableInCEnd(builder): return builder.EndObject() +def End(builder): + return TableInCEnd(builder) +try: + from typing import Optional +except: + pass + +class TableInCT(object): + + # TableInCT + def __init__(self): + self.referToA1 = None # type: Optional[TableInFirstNST] + self.referToA2 = None # type: Optional[SecondTableInAT] + + @classmethod + def InitFromBuf(cls, buf, pos): + tableInC = TableInC() + tableInC.Init(buf, pos) + return cls.InitFromObj(tableInC) + + @classmethod + def InitFromObj(cls, tableInC): + x = TableInCT() + x._UnPack(tableInC) + return x + + # TableInCT + def _UnPack(self, tableInC): + if tableInC is None: + return + if tableInC.ReferToA1() is not None: + self.referToA1 = TableInFirstNST.InitFromObj(tableInC.ReferToA1()) + if tableInC.ReferToA2() is not None: + self.referToA2 = SecondTableInAT.InitFromObj(tableInC.ReferToA2()) + + # TableInCT + def Pack(self, builder): + if self.referToA1 is not None: + referToA1 = self.referToA1.Pack(builder) + if self.referToA2 is not None: + referToA2 = self.referToA2.Pack(builder) + TableInCStart(builder) + if self.referToA1 is not None: + TableInCAddReferToA1(builder, referToA1) + if self.referToA2 is not None: + TableInCAddReferToA2(builder, referToA2) + tableInC = TableInCEnd(builder) + return tableInC diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInCT.java b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInCT.java new file mode 100644 index 00000000000..d2650911010 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/NamespaceC/TableInCT.java @@ -0,0 +1,28 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package NamespaceC; + +import java.nio.*; +import java.lang.*; +import java.util.*; +import com.google.flatbuffers.*; + +public class TableInCT { + private NamespaceA.TableInFirstNST referToA1; + private NamespaceA.SecondTableInAT referToA2; + + public NamespaceA.TableInFirstNST getReferToA1() { return referToA1; } + + public void setReferToA1(NamespaceA.TableInFirstNST referToA1) { this.referToA1 = referToA1; } + + public NamespaceA.SecondTableInAT getReferToA2() { return referToA2; } + + public void setReferToA2(NamespaceA.SecondTableInAT referToA2) { this.referToA2 = referToA2; } + + + public TableInCT() { + this.referToA1 = null; + this.referToA2 = null; + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/NamespaceC/__init__.py b/third_party/flatbuffers/tests/namespace_test/NamespaceC/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/namespace_test/mod.rs b/third_party/flatbuffers/tests/namespace_test/mod.rs new file mode 100644 index 00000000000..22c667e8b5c --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/mod.rs @@ -0,0 +1,25 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod namespace_a { + use super::*; + pub mod namespace_b { + use super::*; + mod union_in_nested_ns_generated; + pub use self::union_in_nested_ns_generated::*; + mod enum_in_nested_ns_generated; + pub use self::enum_in_nested_ns_generated::*; + mod table_in_nested_ns_generated; + pub use self::table_in_nested_ns_generated::*; + mod struct_in_nested_ns_generated; + pub use self::struct_in_nested_ns_generated::*; + } // namespace_b + mod table_in_first_ns_generated; + pub use self::table_in_first_ns_generated::*; + mod second_table_in_a_generated; + pub use self::second_table_in_a_generated::*; +} // namespace_a +pub mod namespace_c { + use super::*; + mod table_in_c_generated; + pub use self::table_in_c_generated::*; +} // namespace_c diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs new file mode 100644 index 00000000000..59277bd4081 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/enum_in_nested_ns_generated.rs @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ENUM_IN_NESTED_NS: i8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ENUM_IN_NESTED_NS: i8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ENUM_IN_NESTED_NS: [EnumInNestedNS; 3] = [ + EnumInNestedNS::A, + EnumInNestedNS::B, + EnumInNestedNS::C, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct EnumInNestedNS(pub i8); +#[allow(non_upper_case_globals)] +impl EnumInNestedNS { + pub const A: Self = Self(0); + pub const B: Self = Self(1); + pub const C: Self = Self(2); + + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + Self::C, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + Self::C => Some("C"), + _ => None, + } + } +} +impl core::fmt::Debug for EnumInNestedNS { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for EnumInNestedNS { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for EnumInNestedNS { + type Output = EnumInNestedNS; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for EnumInNestedNS { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for EnumInNestedNS { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for EnumInNestedNS {} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs new file mode 100644 index 00000000000..db22105b8e7 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/struct_in_nested_ns_generated.rs @@ -0,0 +1,163 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct StructInNestedNS, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct StructInNestedNS(pub [u8; 8]); +impl Default for StructInNestedNS { + fn default() -> Self { + Self([0; 8]) + } +} +impl core::fmt::Debug for StructInNestedNS { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("StructInNestedNS") + .field("a", &self.a()) + .field("b", &self.b()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for StructInNestedNS {} +impl<'a> flatbuffers::Follow<'a> for StructInNestedNS { + type Inner = &'a StructInNestedNS; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a StructInNestedNS>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a StructInNestedNS { + type Inner = &'a StructInNestedNS; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for StructInNestedNS { + type Output = StructInNestedNS; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const StructInNestedNS as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for StructInNestedNS { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> StructInNestedNS { + #[allow(clippy::too_many_arguments)] + pub fn new( + a: i32, + b: i32, + ) -> Self { + let mut s = Self([0; 8]); + s.set_a(a); + s.set_b(b); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.NamespaceB.StructInNestedNS" + } + + pub fn a(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_a(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn b(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_b(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> StructInNestedNST { + StructInNestedNST { + a: self.a(), + b: self.b(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct StructInNestedNST { + pub a: i32, + pub b: i32, +} +impl StructInNestedNST { + pub fn pack(&self) -> StructInNestedNS { + StructInNestedNS::new( + self.a, + self.b, + ) + } +} + diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs new file mode 100644 index 00000000000..34c3794a594 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/table_in_nested_ns_generated.rs @@ -0,0 +1,141 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableInNestedNSOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableInNestedNS<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableInNestedNS<'a> { + type Inner = TableInNestedNS<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableInNestedNS<'a> { + pub const VT_FOO: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.NamespaceB.TableInNestedNS" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableInNestedNS { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableInNestedNSArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = TableInNestedNSBuilder::new(_fbb); + builder.add_foo(args.foo); + builder.finish() + } + + pub fn unpack(&self) -> TableInNestedNST { + let foo = self.foo(); + TableInNestedNST { + foo, + } + } + + #[inline] + pub fn foo(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInNestedNS::VT_FOO, Some(0)).unwrap()} + } +} + +impl flatbuffers::Verifiable for TableInNestedNS<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("foo", Self::VT_FOO, false)? + .finish(); + Ok(()) + } +} +pub struct TableInNestedNSArgs { + pub foo: i32, +} +impl<'a> Default for TableInNestedNSArgs { + #[inline] + fn default() -> Self { + TableInNestedNSArgs { + foo: 0, + } + } +} + +pub struct TableInNestedNSBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableInNestedNSBuilder<'a, 'b, A> { + #[inline] + pub fn add_foo(&mut self, foo: i32) { + self.fbb_.push_slot::(TableInNestedNS::VT_FOO, foo, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableInNestedNSBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableInNestedNSBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableInNestedNS<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableInNestedNS"); + ds.field("foo", &self.foo()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableInNestedNST { + pub foo: i32, +} +impl Default for TableInNestedNST { + fn default() -> Self { + Self { + foo: 0, + } + } +} +impl TableInNestedNST { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let foo = self.foo; + TableInNestedNS::create(_fbb, &TableInNestedNSArgs{ + foo, + }) + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs new file mode 100644 index 00000000000..c31674983f6 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_a/namespace_b/union_in_nested_ns_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_UNION_IN_NESTED_NS: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_UNION_IN_NESTED_NS: u8 = 1; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_UNION_IN_NESTED_NS: [UnionInNestedNS; 2] = [ + UnionInNestedNS::NONE, + UnionInNestedNS::TableInNestedNS, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct UnionInNestedNS(pub u8); +#[allow(non_upper_case_globals)] +impl UnionInNestedNS { + pub const NONE: Self = Self(0); + pub const TableInNestedNS: Self = Self(1); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 1; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::TableInNestedNS, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::TableInNestedNS => Some("TableInNestedNS"), + _ => None, + } + } +} +impl core::fmt::Debug for UnionInNestedNS { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for UnionInNestedNS { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for UnionInNestedNS { + type Output = UnionInNestedNS; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for UnionInNestedNS { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for UnionInNestedNS { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for UnionInNestedNS {} +pub struct UnionInNestedNSUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum UnionInNestedNST { + NONE, + TableInNestedNS(Box), +} +impl Default for UnionInNestedNST { + fn default() -> Self { + Self::NONE + } +} +impl UnionInNestedNST { + pub fn union_in_nested_ns_type(&self) -> UnionInNestedNS { + match self { + Self::NONE => UnionInNestedNS::NONE, + Self::TableInNestedNS(_) => UnionInNestedNS::TableInNestedNS, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::TableInNestedNS(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned TableInNestedNST, setting the union to NONE. + pub fn take_table_in_nested_ns(&mut self) -> Option> { + if let Self::TableInNestedNS(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::TableInNestedNS(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the TableInNestedNST. + pub fn as_table_in_nested_ns(&self) -> Option<&TableInNestedNST> { + if let Self::TableInNestedNS(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the TableInNestedNST. + pub fn as_table_in_nested_ns_mut(&mut self) -> Option<&mut TableInNestedNST> { + if let Self::TableInNestedNS(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_a/second_table_in_a_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_a/second_table_in_a_generated.rs new file mode 100644 index 00000000000..495b866cbf4 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_a/second_table_in_a_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum SecondTableInAOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct SecondTableInA<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for SecondTableInA<'a> { + type Inner = SecondTableInA<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> SecondTableInA<'a> { + pub const VT_REFER_TO_C: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.SecondTableInA" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + SecondTableInA { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args SecondTableInAArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = SecondTableInABuilder::new(_fbb); + if let Some(x) = args.refer_to_c { builder.add_refer_to_c(x); } + builder.finish() + } + + pub fn unpack(&self) -> SecondTableInAT { + let refer_to_c = self.refer_to_c().map(|x| { + Box::new(x.unpack()) + }); + SecondTableInAT { + refer_to_c, + } + } + + #[inline] + pub fn refer_to_c(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(SecondTableInA::VT_REFER_TO_C, None)} + } +} + +impl flatbuffers::Verifiable for SecondTableInA<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("refer_to_c", Self::VT_REFER_TO_C, false)? + .finish(); + Ok(()) + } +} +pub struct SecondTableInAArgs<'a> { + pub refer_to_c: Option>>, +} +impl<'a> Default for SecondTableInAArgs<'a> { + #[inline] + fn default() -> Self { + SecondTableInAArgs { + refer_to_c: None, + } + } +} + +pub struct SecondTableInABuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> SecondTableInABuilder<'a, 'b, A> { + #[inline] + pub fn add_refer_to_c(&mut self, refer_to_c: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(SecondTableInA::VT_REFER_TO_C, refer_to_c); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> SecondTableInABuilder<'a, 'b, A> { + let start = _fbb.start_table(); + SecondTableInABuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for SecondTableInA<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("SecondTableInA"); + ds.field("refer_to_c", &self.refer_to_c()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct SecondTableInAT { + pub refer_to_c: Option>, +} +impl Default for SecondTableInAT { + fn default() -> Self { + Self { + refer_to_c: None, + } + } +} +impl SecondTableInAT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let refer_to_c = self.refer_to_c.as_ref().map(|x|{ + x.pack(_fbb) + }); + SecondTableInA::create(_fbb, &SecondTableInAArgs{ + refer_to_c, + }) + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs new file mode 100644 index 00000000000..351009ac6a7 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_a/table_in_first_ns_generated.rs @@ -0,0 +1,275 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableInFirstNSOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableInFirstNS<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableInFirstNS<'a> { + type Inner = TableInFirstNS<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableInFirstNS<'a> { + pub const VT_FOO_TABLE: flatbuffers::VOffsetT = 4; + pub const VT_FOO_ENUM: flatbuffers::VOffsetT = 6; + pub const VT_FOO_UNION_TYPE: flatbuffers::VOffsetT = 8; + pub const VT_FOO_UNION: flatbuffers::VOffsetT = 10; + pub const VT_FOO_STRUCT: flatbuffers::VOffsetT = 12; + + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceA.TableInFirstNS" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableInFirstNS { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableInFirstNSArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableInFirstNSBuilder::new(_fbb); + if let Some(x) = args.foo_struct { builder.add_foo_struct(x); } + if let Some(x) = args.foo_union { builder.add_foo_union(x); } + if let Some(x) = args.foo_table { builder.add_foo_table(x); } + builder.add_foo_union_type(args.foo_union_type); + builder.add_foo_enum(args.foo_enum); + builder.finish() + } + + pub fn unpack(&self) -> TableInFirstNST { + let foo_table = self.foo_table().map(|x| { + Box::new(x.unpack()) + }); + let foo_enum = self.foo_enum(); + let foo_union = match self.foo_union_type() { + namespace_b::UnionInNestedNS::NONE => namespace_b::UnionInNestedNST::NONE, + namespace_b::UnionInNestedNS::TableInNestedNS => namespace_b::UnionInNestedNST::TableInNestedNS(Box::new( + self.foo_union_as_table_in_nested_ns() + .expect("Invalid union table, expected `namespace_b::UnionInNestedNS::TableInNestedNS`.") + .unpack() + )), + _ => namespace_b::UnionInNestedNST::NONE, + }; + let foo_struct = self.foo_struct().map(|x| { + x.unpack() + }); + TableInFirstNST { + foo_table, + foo_enum, + foo_union, + foo_struct, + } + } + + #[inline] + pub fn foo_table(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableInFirstNS::VT_FOO_TABLE, None)} + } + #[inline] + pub fn foo_enum(&self) -> namespace_b::EnumInNestedNS { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInFirstNS::VT_FOO_ENUM, Some(namespace_b::EnumInNestedNS::A)).unwrap()} + } + #[inline] + pub fn foo_union_type(&self) -> namespace_b::UnionInNestedNS { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInFirstNS::VT_FOO_UNION_TYPE, Some(namespace_b::UnionInNestedNS::NONE)).unwrap()} + } + #[inline] + pub fn foo_union(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(TableInFirstNS::VT_FOO_UNION, None)} + } + #[inline] + pub fn foo_struct(&self) -> Option<&'a namespace_b::StructInNestedNS> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(TableInFirstNS::VT_FOO_STRUCT, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn foo_union_as_table_in_nested_ns(&self) -> Option> { + if self.foo_union_type() == namespace_b::UnionInNestedNS::TableInNestedNS { + self.foo_union().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { namespace_b::TableInNestedNS::init_from_table(t) } + }) + } else { + None + } + } + +} + +impl flatbuffers::Verifiable for TableInFirstNS<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("foo_table", Self::VT_FOO_TABLE, false)? + .visit_field::("foo_enum", Self::VT_FOO_ENUM, false)? + .visit_union::("foo_union_type", Self::VT_FOO_UNION_TYPE, "foo_union", Self::VT_FOO_UNION, false, |key, v, pos| { + match key { + namespace_b::UnionInNestedNS::TableInNestedNS => v.verify_union_variant::>("namespace_b::UnionInNestedNS::TableInNestedNS", pos), + _ => Ok(()), + } + })? + .visit_field::("foo_struct", Self::VT_FOO_STRUCT, false)? + .finish(); + Ok(()) + } +} +pub struct TableInFirstNSArgs<'a> { + pub foo_table: Option>>, + pub foo_enum: namespace_b::EnumInNestedNS, + pub foo_union_type: namespace_b::UnionInNestedNS, + pub foo_union: Option>, + pub foo_struct: Option<&'a namespace_b::StructInNestedNS>, +} +impl<'a> Default for TableInFirstNSArgs<'a> { + #[inline] + fn default() -> Self { + TableInFirstNSArgs { + foo_table: None, + foo_enum: namespace_b::EnumInNestedNS::A, + foo_union_type: namespace_b::UnionInNestedNS::NONE, + foo_union: None, + foo_struct: None, + } + } +} + +pub struct TableInFirstNSBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableInFirstNSBuilder<'a, 'b, A> { + #[inline] + pub fn add_foo_table(&mut self, foo_table: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableInFirstNS::VT_FOO_TABLE, foo_table); + } + #[inline] + pub fn add_foo_enum(&mut self, foo_enum: namespace_b::EnumInNestedNS) { + self.fbb_.push_slot::(TableInFirstNS::VT_FOO_ENUM, foo_enum, namespace_b::EnumInNestedNS::A); + } + #[inline] + pub fn add_foo_union_type(&mut self, foo_union_type: namespace_b::UnionInNestedNS) { + self.fbb_.push_slot::(TableInFirstNS::VT_FOO_UNION_TYPE, foo_union_type, namespace_b::UnionInNestedNS::NONE); + } + #[inline] + pub fn add_foo_union(&mut self, foo_union: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(TableInFirstNS::VT_FOO_UNION, foo_union); + } + #[inline] + pub fn add_foo_struct(&mut self, foo_struct: &namespace_b::StructInNestedNS) { + self.fbb_.push_slot_always::<&namespace_b::StructInNestedNS>(TableInFirstNS::VT_FOO_STRUCT, foo_struct); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableInFirstNSBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableInFirstNSBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableInFirstNS<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableInFirstNS"); + ds.field("foo_table", &self.foo_table()); + ds.field("foo_enum", &self.foo_enum()); + ds.field("foo_union_type", &self.foo_union_type()); + match self.foo_union_type() { + namespace_b::UnionInNestedNS::TableInNestedNS => { + if let Some(x) = self.foo_union_as_table_in_nested_ns() { + ds.field("foo_union", &x) + } else { + ds.field("foo_union", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("foo_union", &x) + }, + }; + ds.field("foo_struct", &self.foo_struct()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableInFirstNST { + pub foo_table: Option>, + pub foo_enum: namespace_b::EnumInNestedNS, + pub foo_union: namespace_b::UnionInNestedNST, + pub foo_struct: Option, +} +impl Default for TableInFirstNST { + fn default() -> Self { + Self { + foo_table: None, + foo_enum: namespace_b::EnumInNestedNS::A, + foo_union: namespace_b::UnionInNestedNST::NONE, + foo_struct: None, + } + } +} +impl TableInFirstNST { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let foo_table = self.foo_table.as_ref().map(|x|{ + x.pack(_fbb) + }); + let foo_enum = self.foo_enum; + let foo_union_type = self.foo_union.union_in_nested_ns_type(); + let foo_union = self.foo_union.pack(_fbb); + let foo_struct_tmp = self.foo_struct.as_ref().map(|x| x.pack()); + let foo_struct = foo_struct_tmp.as_ref(); + TableInFirstNS::create(_fbb, &TableInFirstNSArgs{ + foo_table, + foo_enum, + foo_union_type, + foo_union, + foo_struct, + }) + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_c/table_in_c_generated.rs b/third_party/flatbuffers/tests/namespace_test/namespace_c/table_in_c_generated.rs new file mode 100644 index 00000000000..e8062415322 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_c/table_in_c_generated.rs @@ -0,0 +1,172 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum TableInCOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct TableInC<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for TableInC<'a> { + type Inner = TableInC<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> TableInC<'a> { + pub const VT_REFER_TO_A1: flatbuffers::VOffsetT = 4; + pub const VT_REFER_TO_A2: flatbuffers::VOffsetT = 6; + + pub const fn get_fully_qualified_name() -> &'static str { + "NamespaceC.TableInC" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + TableInC { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args TableInCArgs<'args> + ) -> flatbuffers::WIPOffset> { + let mut builder = TableInCBuilder::new(_fbb); + if let Some(x) = args.refer_to_a2 { builder.add_refer_to_a2(x); } + if let Some(x) = args.refer_to_a1 { builder.add_refer_to_a1(x); } + builder.finish() + } + + pub fn unpack(&self) -> TableInCT { + let refer_to_a1 = self.refer_to_a1().map(|x| { + Box::new(x.unpack()) + }); + let refer_to_a2 = self.refer_to_a2().map(|x| { + Box::new(x.unpack()) + }); + TableInCT { + refer_to_a1, + refer_to_a2, + } + } + + #[inline] + pub fn refer_to_a1(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableInC::VT_REFER_TO_A1, None)} + } + #[inline] + pub fn refer_to_a2(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>(TableInC::VT_REFER_TO_A2, None)} + } +} + +impl flatbuffers::Verifiable for TableInC<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::>("refer_to_a1", Self::VT_REFER_TO_A1, false)? + .visit_field::>("refer_to_a2", Self::VT_REFER_TO_A2, false)? + .finish(); + Ok(()) + } +} +pub struct TableInCArgs<'a> { + pub refer_to_a1: Option>>, + pub refer_to_a2: Option>>, +} +impl<'a> Default for TableInCArgs<'a> { + #[inline] + fn default() -> Self { + TableInCArgs { + refer_to_a1: None, + refer_to_a2: None, + } + } +} + +pub struct TableInCBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> TableInCBuilder<'a, 'b, A> { + #[inline] + pub fn add_refer_to_a1(&mut self, refer_to_a1: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableInC::VT_REFER_TO_A1, refer_to_a1); + } + #[inline] + pub fn add_refer_to_a2(&mut self, refer_to_a2: flatbuffers::WIPOffset>) { + self.fbb_.push_slot_always::>(TableInC::VT_REFER_TO_A2, refer_to_a2); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> TableInCBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + TableInCBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for TableInC<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("TableInC"); + ds.field("refer_to_a1", &self.refer_to_a1()); + ds.field("refer_to_a2", &self.refer_to_a2()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct TableInCT { + pub refer_to_a1: Option>, + pub refer_to_a2: Option>, +} +impl Default for TableInCT { + fn default() -> Self { + Self { + refer_to_a1: None, + refer_to_a2: None, + } + } +} +impl TableInCT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let refer_to_a1 = self.refer_to_a1.as_ref().map(|x|{ + x.pack(_fbb) + }); + let refer_to_a2 = self.refer_to_a2.as_ref().map(|x|{ + x.pack(_fbb) + }); + TableInC::create(_fbb, &TableInCArgs{ + refer_to_a1, + refer_to_a2, + }) + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test1.fbs b/third_party/flatbuffers/tests/namespace_test/namespace_test1.fbs new file mode 100644 index 00000000000..f0b9c1669cf --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test1.fbs @@ -0,0 +1,21 @@ +namespace NamespaceA.NamespaceB; + +table TableInNestedNS +{ + foo:int; +} + +union UnionInNestedNS { + TableInNestedNS, +} + +enum EnumInNestedNS:byte +{ + A, B, C +} + +struct StructInNestedNS +{ + a:int; + b:int; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test1_generated.h b/third_party/flatbuffers/tests/namespace_test/namespace_test1_generated.h new file mode 100644 index 00000000000..7bc8e1d451a --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test1_generated.h @@ -0,0 +1,465 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_NAMESPACETEST1_NAMESPACEA_NAMESPACEB_H_ +#define FLATBUFFERS_GENERATED_NAMESPACETEST1_NAMESPACEA_NAMESPACEB_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace NamespaceA { +namespace NamespaceB { + +struct TableInNestedNS; +struct TableInNestedNSBuilder; +struct TableInNestedNST; + +struct StructInNestedNS; + +bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs); +bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs); +bool operator==(const StructInNestedNS &lhs, const StructInNestedNS &rhs); +bool operator!=(const StructInNestedNS &lhs, const StructInNestedNS &rhs); + +inline const ::flatbuffers::TypeTable *TableInNestedNSTypeTable(); + +inline const ::flatbuffers::TypeTable *StructInNestedNSTypeTable(); + +enum UnionInNestedNS : uint8_t { + UnionInNestedNS_NONE = 0, + UnionInNestedNS_TableInNestedNS = 1, + UnionInNestedNS_MIN = UnionInNestedNS_NONE, + UnionInNestedNS_MAX = UnionInNestedNS_TableInNestedNS +}; + +inline const UnionInNestedNS (&EnumValuesUnionInNestedNS())[2] { + static const UnionInNestedNS values[] = { + UnionInNestedNS_NONE, + UnionInNestedNS_TableInNestedNS + }; + return values; +} + +inline const char * const *EnumNamesUnionInNestedNS() { + static const char * const names[3] = { + "NONE", + "TableInNestedNS", + nullptr + }; + return names; +} + +inline const char *EnumNameUnionInNestedNS(UnionInNestedNS e) { + if (::flatbuffers::IsOutRange(e, UnionInNestedNS_NONE, UnionInNestedNS_TableInNestedNS)) return ""; + const size_t index = static_cast(e); + return EnumNamesUnionInNestedNS()[index]; +} + +template struct UnionInNestedNSTraits { + static const UnionInNestedNS enum_value = UnionInNestedNS_NONE; +}; + +template<> struct UnionInNestedNSTraits { + static const UnionInNestedNS enum_value = UnionInNestedNS_TableInNestedNS; +}; + +template struct UnionInNestedNSUnionTraits { + static const UnionInNestedNS enum_value = UnionInNestedNS_NONE; +}; + +template<> struct UnionInNestedNSUnionTraits { + static const UnionInNestedNS enum_value = UnionInNestedNS_TableInNestedNS; +}; + +struct UnionInNestedNSUnion { + UnionInNestedNS type; + void *value; + + UnionInNestedNSUnion() : type(UnionInNestedNS_NONE), value(nullptr) {} + UnionInNestedNSUnion(UnionInNestedNSUnion&& u) FLATBUFFERS_NOEXCEPT : + type(UnionInNestedNS_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + UnionInNestedNSUnion(const UnionInNestedNSUnion &); + UnionInNestedNSUnion &operator=(const UnionInNestedNSUnion &u) + { UnionInNestedNSUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + UnionInNestedNSUnion &operator=(UnionInNestedNSUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~UnionInNestedNSUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = UnionInNestedNSUnionTraits::enum_value; + if (type != UnionInNestedNS_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, UnionInNestedNS type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + NamespaceA::NamespaceB::TableInNestedNST *AsTableInNestedNS() { + return type == UnionInNestedNS_TableInNestedNS ? + reinterpret_cast(value) : nullptr; + } + const NamespaceA::NamespaceB::TableInNestedNST *AsTableInNestedNS() const { + return type == UnionInNestedNS_TableInNestedNS ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const UnionInNestedNSUnion &lhs, const UnionInNestedNSUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case UnionInNestedNS_NONE: { + return true; + } + case UnionInNestedNS_TableInNestedNS: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const UnionInNestedNSUnion &lhs, const UnionInNestedNSUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyUnionInNestedNS(::flatbuffers::Verifier &verifier, const void *obj, UnionInNestedNS type); +bool VerifyUnionInNestedNSVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum EnumInNestedNS : int8_t { + EnumInNestedNS_A = 0, + EnumInNestedNS_B = 1, + EnumInNestedNS_C = 2, + EnumInNestedNS_MIN = EnumInNestedNS_A, + EnumInNestedNS_MAX = EnumInNestedNS_C +}; + +inline const EnumInNestedNS (&EnumValuesEnumInNestedNS())[3] { + static const EnumInNestedNS values[] = { + EnumInNestedNS_A, + EnumInNestedNS_B, + EnumInNestedNS_C + }; + return values; +} + +inline const char * const *EnumNamesEnumInNestedNS() { + static const char * const names[4] = { + "A", + "B", + "C", + nullptr + }; + return names; +} + +inline const char *EnumNameEnumInNestedNS(EnumInNestedNS e) { + if (::flatbuffers::IsOutRange(e, EnumInNestedNS_A, EnumInNestedNS_C)) return ""; + const size_t index = static_cast(e); + return EnumNamesEnumInNestedNS()[index]; +} + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) StructInNestedNS FLATBUFFERS_FINAL_CLASS { + private: + int32_t a_; + int32_t b_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return StructInNestedNSTypeTable(); + } + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.NamespaceB.StructInNestedNS"; + } + StructInNestedNS() + : a_(0), + b_(0) { + } + StructInNestedNS(int32_t _a, int32_t _b) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)) { + } + int32_t a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(int32_t _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + int32_t b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(int32_t _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } +}; +FLATBUFFERS_STRUCT_END(StructInNestedNS, 8); + +inline bool operator==(const StructInNestedNS &lhs, const StructInNestedNS &rhs) { + return + (lhs.a() == rhs.a()) && + (lhs.b() == rhs.b()); +} + +inline bool operator!=(const StructInNestedNS &lhs, const StructInNestedNS &rhs) { + return !(lhs == rhs); +} + + +struct TableInNestedNST : public ::flatbuffers::NativeTable { + typedef TableInNestedNS TableType; + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.NamespaceB.TableInNestedNST"; + } + int32_t foo = 0; +}; + +struct TableInNestedNS FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableInNestedNST NativeTableType; + typedef TableInNestedNSBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TableInNestedNSTypeTable(); + } + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.NamespaceB.TableInNestedNS"; + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_FOO = 4 + }; + int32_t foo() const { + return GetField(VT_FOO, 0); + } + bool mutate_foo(int32_t _foo = 0) { + return SetField(VT_FOO, _foo, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_FOO, 4) && + verifier.EndTable(); + } + TableInNestedNST *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TableInNestedNST *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TableInNestedNSBuilder { + typedef TableInNestedNS Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_foo(int32_t foo) { + fbb_.AddElement(TableInNestedNS::VT_FOO, foo, 0); + } + explicit TableInNestedNSBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableInNestedNS( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t foo = 0) { + TableInNestedNSBuilder builder_(_fbb); + builder_.add_foo(foo); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTableInNestedNS(::flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const TableInNestedNST &lhs, const TableInNestedNST &rhs) { + return + (lhs.foo == rhs.foo); +} + +inline bool operator!=(const TableInNestedNST &lhs, const TableInNestedNST &rhs) { + return !(lhs == rhs); +} + + +inline TableInNestedNST *TableInNestedNS::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TableInNestedNST()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TableInNestedNS::UnPackTo(TableInNestedNST *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = foo(); _o->foo = _e; } +} + +inline ::flatbuffers::Offset TableInNestedNS::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTableInNestedNS(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTableInNestedNS(::flatbuffers::FlatBufferBuilder &_fbb, const TableInNestedNST *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TableInNestedNST* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _foo = _o->foo; + return NamespaceA::NamespaceB::CreateTableInNestedNS( + _fbb, + _foo); +} + +inline bool VerifyUnionInNestedNS(::flatbuffers::Verifier &verifier, const void *obj, UnionInNestedNS type) { + switch (type) { + case UnionInNestedNS_NONE: { + return true; + } + case UnionInNestedNS_TableInNestedNS: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyUnionInNestedNSVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyUnionInNestedNS( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *UnionInNestedNSUnion::UnPack(const void *obj, UnionInNestedNS type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case UnionInNestedNS_TableInNestedNS: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset UnionInNestedNSUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case UnionInNestedNS_TableInNestedNS: { + auto ptr = reinterpret_cast(value); + return CreateTableInNestedNS(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline UnionInNestedNSUnion::UnionInNestedNSUnion(const UnionInNestedNSUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case UnionInNestedNS_TableInNestedNS: { + value = new NamespaceA::NamespaceB::TableInNestedNST(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void UnionInNestedNSUnion::Reset() { + switch (type) { + case UnionInNestedNS_TableInNestedNS: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = UnionInNestedNS_NONE; +} + +inline const ::flatbuffers::TypeTable *UnionInNestedNSTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + NamespaceA::NamespaceB::TableInNestedNSTypeTable + }; + static const char * const names[] = { + "NONE", + "TableInNestedNS" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 2, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *EnumInNestedNSTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + NamespaceA::NamespaceB::EnumInNestedNSTypeTable + }; + static const char * const names[] = { + "A", + "B", + "C" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TableInNestedNSTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "foo" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *StructInNestedNSTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8 }; + static const char * const names[] = { + "a", + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 2, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +} // namespace NamespaceB +} // namespace NamespaceA + +#endif // FLATBUFFERS_GENERATED_NAMESPACETEST1_NAMESPACEA_NAMESPACEB_H_ diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test1_generated.lobster b/third_party/flatbuffers/tests/namespace_test/namespace_test1_generated.lobster new file mode 100644 index 00000000000..5721b8f42f1 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test1_generated.lobster @@ -0,0 +1,47 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import flatbuffers + +namespace NamespaceA_NamespaceB + +enum UnionInNestedNS: + UnionInNestedNS_NONE = 0 + UnionInNestedNS_TableInNestedNS = 1 + +enum EnumInNestedNS: + EnumInNestedNS_A = 0 + EnumInNestedNS_B = 1 + EnumInNestedNS_C = 2 + +class TableInNestedNS + +class StructInNestedNS + +class TableInNestedNS : flatbuffers_handle + def foo(): + return buf_.flatbuffers_field_int32(pos_, 4, 0) + +def GetRootAsTableInNestedNS(buf:string): return TableInNestedNS { buf, buf.flatbuffers_indirect(0) } + +struct TableInNestedNSBuilder: + b_:flatbuffers_builder + def start(): + b_.StartObject(1) + return this + def add_foo(foo:int): + b_.PrependInt32Slot(0, foo, 0) + return this + def end(): + return b_.EndObject() + +class StructInNestedNS : flatbuffers_handle + def a(): + return buf_.read_int32_le(pos_ + 0) + def b(): + return buf_.read_int32_le(pos_ + 4) + +def CreateStructInNestedNS(b_:flatbuffers_builder, a:int, b:int): + b_.Prep(4, 8) + b_.PrependInt32(b) + b_.PrependInt32(a) + return b_.Offset() + diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart b/third_party/flatbuffers/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart new file mode 100644 index 00000000000..5e0fb1dc453 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test1_namespace_a.namespace_b_generated.dart @@ -0,0 +1,295 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable + +library namespace_a.namespace_b; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + + +class UnionInNestedNSTypeId { + final int value; + const UnionInNestedNSTypeId._(this.value); + + factory UnionInNestedNSTypeId.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum UnionInNestedNSTypeId'); + } + return result; + } + + static UnionInNestedNSTypeId? _createOrNull(int? value) => + value == null ? null : UnionInNestedNSTypeId.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 1; + static bool containsValue(int value) => values.containsKey(value); + + static const UnionInNestedNSTypeId NONE = UnionInNestedNSTypeId._(0); + static const UnionInNestedNSTypeId TableInNestedNS = UnionInNestedNSTypeId._(1); + static const Map values = { + 0: NONE, + 1: TableInNestedNS}; + + static const fb.Reader reader = _UnionInNestedNSTypeIdReader(); + + @override + String toString() { + return 'UnionInNestedNSTypeId{value: $value}'; + } +} + +class _UnionInNestedNSTypeIdReader extends fb.Reader { + const _UnionInNestedNSTypeIdReader(); + + @override + int get size => 1; + + @override + UnionInNestedNSTypeId read(fb.BufferContext bc, int offset) => + UnionInNestedNSTypeId.fromValue(const fb.Uint8Reader().read(bc, offset)); +} + +class EnumInNestedNS { + final int value; + const EnumInNestedNS._(this.value); + + factory EnumInNestedNS.fromValue(int value) { + final result = values[value]; + if (result == null) { + throw StateError('Invalid value $value for bit flag enum EnumInNestedNS'); + } + return result; + } + + static EnumInNestedNS? _createOrNull(int? value) => + value == null ? null : EnumInNestedNS.fromValue(value); + + static const int minValue = 0; + static const int maxValue = 2; + static bool containsValue(int value) => values.containsKey(value); + + static const EnumInNestedNS A = EnumInNestedNS._(0); + static const EnumInNestedNS B = EnumInNestedNS._(1); + static const EnumInNestedNS C = EnumInNestedNS._(2); + static const Map values = { + 0: A, + 1: B, + 2: C}; + + static const fb.Reader reader = _EnumInNestedNSReader(); + + @override + String toString() { + return 'EnumInNestedNS{value: $value}'; + } +} + +class _EnumInNestedNSReader extends fb.Reader { + const _EnumInNestedNSReader(); + + @override + int get size => 1; + + @override + EnumInNestedNS read(fb.BufferContext bc, int offset) => + EnumInNestedNS.fromValue(const fb.Int8Reader().read(bc, offset)); +} + +class TableInNestedNS { + TableInNestedNS._(this._bc, this._bcOffset); + factory TableInNestedNS(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableInNestedNSReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get foo => const fb.Int32Reader().vTableGet(_bc, _bcOffset, 4, 0); + + @override + String toString() { + return 'TableInNestedNS{foo: $foo}'; + } + + TableInNestedNST unpack() => TableInNestedNST( + foo: foo); + + static int pack(fb.Builder fbBuilder, TableInNestedNST? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableInNestedNST implements fb.Packable { + int foo; + + TableInNestedNST({ + this.foo = 0}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addInt32(0, foo); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableInNestedNST{foo: $foo}'; + } +} + +class _TableInNestedNSReader extends fb.TableReader { + const _TableInNestedNSReader(); + + @override + TableInNestedNS createObject(fb.BufferContext bc, int offset) => + TableInNestedNS._(bc, offset); +} + +class TableInNestedNSBuilder { + TableInNestedNSBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addFoo(int? foo) { + fbBuilder.addInt32(0, foo); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableInNestedNSObjectBuilder extends fb.ObjectBuilder { + final int? _foo; + + TableInNestedNSObjectBuilder({ + int? foo, + }) + : _foo = foo; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.startTable(1); + fbBuilder.addInt32(0, _foo); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class StructInNestedNS { + StructInNestedNS._(this._bc, this._bcOffset); + + static const fb.Reader reader = _StructInNestedNSReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + int get a => const fb.Int32Reader().read(_bc, _bcOffset + 0); + int get b => const fb.Int32Reader().read(_bc, _bcOffset + 4); + + @override + String toString() { + return 'StructInNestedNS{a: $a, b: $b}'; + } + + StructInNestedNST unpack() => StructInNestedNST( + a: a, + b: b); + + static int pack(fb.Builder fbBuilder, StructInNestedNST? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class StructInNestedNST implements fb.Packable { + int a; + int b; + + StructInNestedNST({ + required this.a, + required this.b}); + + @override + int pack(fb.Builder fbBuilder) { + fbBuilder.putInt32(b); + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + + @override + String toString() { + return 'StructInNestedNST{a: $a, b: $b}'; + } +} + +class _StructInNestedNSReader extends fb.StructReader { + const _StructInNestedNSReader(); + + @override + int get size => 8; + + @override + StructInNestedNS createObject(fb.BufferContext bc, int offset) => + StructInNestedNS._(bc, offset); +} + +class StructInNestedNSBuilder { + StructInNestedNSBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + int finish(int a, int b) { + fbBuilder.putInt32(b); + fbBuilder.putInt32(a); + return fbBuilder.offset; + } + +} + +class StructInNestedNSObjectBuilder extends fb.ObjectBuilder { + final int _a; + final int _b; + + StructInNestedNSObjectBuilder({ + required int a, + required int b, + }) + : _a = a, + _b = b; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + fbBuilder.putInt32(_b); + fbBuilder.putInt32(_a); + return fbBuilder.offset; + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test2.fbs b/third_party/flatbuffers/tests/namespace_test/namespace_test2.fbs new file mode 100644 index 00000000000..e1440e7c1c4 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test2.fbs @@ -0,0 +1,25 @@ +include "namespace_test1.fbs"; + +namespace NamespaceA; + +table TableInFirstNS +{ + foo_table:NamespaceB.TableInNestedNS; + foo_enum:NamespaceB.EnumInNestedNS; + foo_union:NamespaceB.UnionInNestedNS; + foo_struct:NamespaceB.StructInNestedNS; +} + +// Test switching namespaces inside a file. +namespace NamespaceC; + +table TableInC { + refer_to_a1:NamespaceA.TableInFirstNS; + refer_to_a2:NamespaceA.SecondTableInA; +} + +namespace NamespaceA; + +table SecondTableInA { + refer_to_c:NamespaceC.TableInC; +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test2_generated.h b/third_party/flatbuffers/tests/namespace_test/namespace_test2_generated.h new file mode 100644 index 00000000000..cf3a528d794 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test2_generated.h @@ -0,0 +1,603 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_NAMESPACETEST2_NAMESPACEA_H_ +#define FLATBUFFERS_GENERATED_NAMESPACETEST2_NAMESPACEA_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace NamespaceA { + +struct TableInFirstNS; +struct TableInFirstNSBuilder; +struct TableInFirstNST; + +} // namespace NamespaceA + +namespace NamespaceC { + +struct TableInC; +struct TableInCBuilder; +struct TableInCT; + +} // namespace NamespaceC + +namespace NamespaceA { + +struct SecondTableInA; +struct SecondTableInABuilder; +struct SecondTableInAT; + +bool operator==(const TableInFirstNST &lhs, const TableInFirstNST &rhs); +bool operator!=(const TableInFirstNST &lhs, const TableInFirstNST &rhs); +} // namespace NamespaceA + +namespace NamespaceC { + +bool operator==(const TableInCT &lhs, const TableInCT &rhs); +bool operator!=(const TableInCT &lhs, const TableInCT &rhs); +} // namespace NamespaceC + +namespace NamespaceA { + +bool operator==(const SecondTableInAT &lhs, const SecondTableInAT &rhs); +bool operator!=(const SecondTableInAT &lhs, const SecondTableInAT &rhs); + +inline const ::flatbuffers::TypeTable *TableInFirstNSTypeTable(); + +} // namespace NamespaceA + +namespace NamespaceC { + +inline const ::flatbuffers::TypeTable *TableInCTypeTable(); + +} // namespace NamespaceC + +namespace NamespaceA { + +inline const ::flatbuffers::TypeTable *SecondTableInATypeTable(); + +struct TableInFirstNST : public ::flatbuffers::NativeTable { + typedef TableInFirstNS TableType; + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.TableInFirstNST"; + } + std::unique_ptr foo_table{}; + NamespaceA::NamespaceB::EnumInNestedNS foo_enum = NamespaceA::NamespaceB::EnumInNestedNS_A; + NamespaceA::NamespaceB::UnionInNestedNSUnion foo_union{}; + std::unique_ptr foo_struct{}; + TableInFirstNST() = default; + TableInFirstNST(const TableInFirstNST &o); + TableInFirstNST(TableInFirstNST&&) FLATBUFFERS_NOEXCEPT = default; + TableInFirstNST &operator=(TableInFirstNST o) FLATBUFFERS_NOEXCEPT; +}; + +struct TableInFirstNS FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableInFirstNST NativeTableType; + typedef TableInFirstNSBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TableInFirstNSTypeTable(); + } + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.TableInFirstNS"; + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_FOO_TABLE = 4, + VT_FOO_ENUM = 6, + VT_FOO_UNION_TYPE = 8, + VT_FOO_UNION = 10, + VT_FOO_STRUCT = 12 + }; + const NamespaceA::NamespaceB::TableInNestedNS *foo_table() const { + return GetPointer(VT_FOO_TABLE); + } + NamespaceA::NamespaceB::TableInNestedNS *mutable_foo_table() { + return GetPointer(VT_FOO_TABLE); + } + NamespaceA::NamespaceB::EnumInNestedNS foo_enum() const { + return static_cast(GetField(VT_FOO_ENUM, 0)); + } + bool mutate_foo_enum(NamespaceA::NamespaceB::EnumInNestedNS _foo_enum = static_cast(0)) { + return SetField(VT_FOO_ENUM, static_cast(_foo_enum), 0); + } + NamespaceA::NamespaceB::UnionInNestedNS foo_union_type() const { + return static_cast(GetField(VT_FOO_UNION_TYPE, 0)); + } + const void *foo_union() const { + return GetPointer(VT_FOO_UNION); + } + template const T *foo_union_as() const; + const NamespaceA::NamespaceB::TableInNestedNS *foo_union_as_TableInNestedNS() const { + return foo_union_type() == NamespaceA::NamespaceB::UnionInNestedNS_TableInNestedNS ? static_cast(foo_union()) : nullptr; + } + void *mutable_foo_union() { + return GetPointer(VT_FOO_UNION); + } + const NamespaceA::NamespaceB::StructInNestedNS *foo_struct() const { + return GetStruct(VT_FOO_STRUCT); + } + NamespaceA::NamespaceB::StructInNestedNS *mutable_foo_struct() { + return GetStruct(VT_FOO_STRUCT); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_FOO_TABLE) && + verifier.VerifyTable(foo_table()) && + VerifyField(verifier, VT_FOO_ENUM, 1) && + VerifyField(verifier, VT_FOO_UNION_TYPE, 1) && + VerifyOffset(verifier, VT_FOO_UNION) && + VerifyUnionInNestedNS(verifier, foo_union(), foo_union_type()) && + VerifyField(verifier, VT_FOO_STRUCT, 4) && + verifier.EndTable(); + } + TableInFirstNST *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TableInFirstNST *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const NamespaceA::NamespaceB::TableInNestedNS *TableInFirstNS::foo_union_as() const { + return foo_union_as_TableInNestedNS(); +} + +struct TableInFirstNSBuilder { + typedef TableInFirstNS Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_foo_table(::flatbuffers::Offset foo_table) { + fbb_.AddOffset(TableInFirstNS::VT_FOO_TABLE, foo_table); + } + void add_foo_enum(NamespaceA::NamespaceB::EnumInNestedNS foo_enum) { + fbb_.AddElement(TableInFirstNS::VT_FOO_ENUM, static_cast(foo_enum), 0); + } + void add_foo_union_type(NamespaceA::NamespaceB::UnionInNestedNS foo_union_type) { + fbb_.AddElement(TableInFirstNS::VT_FOO_UNION_TYPE, static_cast(foo_union_type), 0); + } + void add_foo_union(::flatbuffers::Offset foo_union) { + fbb_.AddOffset(TableInFirstNS::VT_FOO_UNION, foo_union); + } + void add_foo_struct(const NamespaceA::NamespaceB::StructInNestedNS *foo_struct) { + fbb_.AddStruct(TableInFirstNS::VT_FOO_STRUCT, foo_struct); + } + explicit TableInFirstNSBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableInFirstNS( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset foo_table = 0, + NamespaceA::NamespaceB::EnumInNestedNS foo_enum = NamespaceA::NamespaceB::EnumInNestedNS_A, + NamespaceA::NamespaceB::UnionInNestedNS foo_union_type = NamespaceA::NamespaceB::UnionInNestedNS_NONE, + ::flatbuffers::Offset foo_union = 0, + const NamespaceA::NamespaceB::StructInNestedNS *foo_struct = nullptr) { + TableInFirstNSBuilder builder_(_fbb); + builder_.add_foo_struct(foo_struct); + builder_.add_foo_union(foo_union); + builder_.add_foo_table(foo_table); + builder_.add_foo_union_type(foo_union_type); + builder_.add_foo_enum(foo_enum); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTableInFirstNS(::flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace NamespaceA + +namespace NamespaceC { + +struct TableInCT : public ::flatbuffers::NativeTable { + typedef TableInC TableType; + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceC.TableInCT"; + } + std::unique_ptr refer_to_a1{}; + std::unique_ptr refer_to_a2{}; + TableInCT() = default; + TableInCT(const TableInCT &o); + TableInCT(TableInCT&&) FLATBUFFERS_NOEXCEPT = default; + TableInCT &operator=(TableInCT o) FLATBUFFERS_NOEXCEPT; +}; + +struct TableInC FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TableInCT NativeTableType; + typedef TableInCBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TableInCTypeTable(); + } + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceC.TableInC"; + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_REFER_TO_A1 = 4, + VT_REFER_TO_A2 = 6 + }; + const NamespaceA::TableInFirstNS *refer_to_a1() const { + return GetPointer(VT_REFER_TO_A1); + } + NamespaceA::TableInFirstNS *mutable_refer_to_a1() { + return GetPointer(VT_REFER_TO_A1); + } + const NamespaceA::SecondTableInA *refer_to_a2() const { + return GetPointer(VT_REFER_TO_A2); + } + NamespaceA::SecondTableInA *mutable_refer_to_a2() { + return GetPointer(VT_REFER_TO_A2); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_REFER_TO_A1) && + verifier.VerifyTable(refer_to_a1()) && + VerifyOffset(verifier, VT_REFER_TO_A2) && + verifier.VerifyTable(refer_to_a2()) && + verifier.EndTable(); + } + TableInCT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TableInCT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TableInCT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TableInCBuilder { + typedef TableInC Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_refer_to_a1(::flatbuffers::Offset refer_to_a1) { + fbb_.AddOffset(TableInC::VT_REFER_TO_A1, refer_to_a1); + } + void add_refer_to_a2(::flatbuffers::Offset refer_to_a2) { + fbb_.AddOffset(TableInC::VT_REFER_TO_A2, refer_to_a2); + } + explicit TableInCBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTableInC( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset refer_to_a1 = 0, + ::flatbuffers::Offset refer_to_a2 = 0) { + TableInCBuilder builder_(_fbb); + builder_.add_refer_to_a2(refer_to_a2); + builder_.add_refer_to_a1(refer_to_a1); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateTableInC(::flatbuffers::FlatBufferBuilder &_fbb, const TableInCT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +} // namespace NamespaceC + +namespace NamespaceA { + +struct SecondTableInAT : public ::flatbuffers::NativeTable { + typedef SecondTableInA TableType; + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.SecondTableInAT"; + } + std::unique_ptr refer_to_c{}; + SecondTableInAT() = default; + SecondTableInAT(const SecondTableInAT &o); + SecondTableInAT(SecondTableInAT&&) FLATBUFFERS_NOEXCEPT = default; + SecondTableInAT &operator=(SecondTableInAT o) FLATBUFFERS_NOEXCEPT; +}; + +struct SecondTableInA FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef SecondTableInAT NativeTableType; + typedef SecondTableInABuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return SecondTableInATypeTable(); + } + static FLATBUFFERS_CONSTEXPR_CPP11 const char *GetFullyQualifiedName() { + return "NamespaceA.SecondTableInA"; + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_REFER_TO_C = 4 + }; + const NamespaceC::TableInC *refer_to_c() const { + return GetPointer(VT_REFER_TO_C); + } + NamespaceC::TableInC *mutable_refer_to_c() { + return GetPointer(VT_REFER_TO_C); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_REFER_TO_C) && + verifier.VerifyTable(refer_to_c()) && + verifier.EndTable(); + } + SecondTableInAT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(SecondTableInAT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct SecondTableInABuilder { + typedef SecondTableInA Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_refer_to_c(::flatbuffers::Offset refer_to_c) { + fbb_.AddOffset(SecondTableInA::VT_REFER_TO_C, refer_to_c); + } + explicit SecondTableInABuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateSecondTableInA( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset refer_to_c = 0) { + SecondTableInABuilder builder_(_fbb); + builder_.add_refer_to_c(refer_to_c); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateSecondTableInA(::flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const TableInFirstNST &lhs, const TableInFirstNST &rhs) { + return + ((lhs.foo_table == rhs.foo_table) || (lhs.foo_table && rhs.foo_table && *lhs.foo_table == *rhs.foo_table)) && + (lhs.foo_enum == rhs.foo_enum) && + (lhs.foo_union == rhs.foo_union) && + ((lhs.foo_struct == rhs.foo_struct) || (lhs.foo_struct && rhs.foo_struct && *lhs.foo_struct == *rhs.foo_struct)); +} + +inline bool operator!=(const TableInFirstNST &lhs, const TableInFirstNST &rhs) { + return !(lhs == rhs); +} + + +inline TableInFirstNST::TableInFirstNST(const TableInFirstNST &o) + : foo_table((o.foo_table) ? new NamespaceA::NamespaceB::TableInNestedNST(*o.foo_table) : nullptr), + foo_enum(o.foo_enum), + foo_union(o.foo_union), + foo_struct((o.foo_struct) ? new NamespaceA::NamespaceB::StructInNestedNS(*o.foo_struct) : nullptr) { +} + +inline TableInFirstNST &TableInFirstNST::operator=(TableInFirstNST o) FLATBUFFERS_NOEXCEPT { + std::swap(foo_table, o.foo_table); + std::swap(foo_enum, o.foo_enum); + std::swap(foo_union, o.foo_union); + std::swap(foo_struct, o.foo_struct); + return *this; +} + +inline TableInFirstNST *TableInFirstNS::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TableInFirstNST()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TableInFirstNS::UnPackTo(TableInFirstNST *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = foo_table(); if (_e) { if(_o->foo_table) { _e->UnPackTo(_o->foo_table.get(), _resolver); } else { _o->foo_table = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->foo_table) { _o->foo_table.reset(); } } + { auto _e = foo_enum(); _o->foo_enum = _e; } + { auto _e = foo_union_type(); _o->foo_union.type = _e; } + { auto _e = foo_union(); if (_e) _o->foo_union.value = NamespaceA::NamespaceB::UnionInNestedNSUnion::UnPack(_e, foo_union_type(), _resolver); } + { auto _e = foo_struct(); if (_e) _o->foo_struct = std::unique_ptr(new NamespaceA::NamespaceB::StructInNestedNS(*_e)); } +} + +inline ::flatbuffers::Offset TableInFirstNS::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTableInFirstNS(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTableInFirstNS(::flatbuffers::FlatBufferBuilder &_fbb, const TableInFirstNST *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TableInFirstNST* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _foo_table = _o->foo_table ? CreateTableInNestedNS(_fbb, _o->foo_table.get(), _rehasher) : 0; + auto _foo_enum = _o->foo_enum; + auto _foo_union_type = _o->foo_union.type; + auto _foo_union = _o->foo_union.Pack(_fbb); + auto _foo_struct = _o->foo_struct ? _o->foo_struct.get() : nullptr; + return NamespaceA::CreateTableInFirstNS( + _fbb, + _foo_table, + _foo_enum, + _foo_union_type, + _foo_union, + _foo_struct); +} + +} // namespace NamespaceA + +namespace NamespaceC { + + +inline bool operator==(const TableInCT &lhs, const TableInCT &rhs) { + return + ((lhs.refer_to_a1 == rhs.refer_to_a1) || (lhs.refer_to_a1 && rhs.refer_to_a1 && *lhs.refer_to_a1 == *rhs.refer_to_a1)) && + ((lhs.refer_to_a2 == rhs.refer_to_a2) || (lhs.refer_to_a2 && rhs.refer_to_a2 && *lhs.refer_to_a2 == *rhs.refer_to_a2)); +} + +inline bool operator!=(const TableInCT &lhs, const TableInCT &rhs) { + return !(lhs == rhs); +} + + +inline TableInCT::TableInCT(const TableInCT &o) + : refer_to_a1((o.refer_to_a1) ? new NamespaceA::TableInFirstNST(*o.refer_to_a1) : nullptr), + refer_to_a2((o.refer_to_a2) ? new NamespaceA::SecondTableInAT(*o.refer_to_a2) : nullptr) { +} + +inline TableInCT &TableInCT::operator=(TableInCT o) FLATBUFFERS_NOEXCEPT { + std::swap(refer_to_a1, o.refer_to_a1); + std::swap(refer_to_a2, o.refer_to_a2); + return *this; +} + +inline TableInCT *TableInC::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TableInCT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TableInC::UnPackTo(TableInCT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = refer_to_a1(); if (_e) { if(_o->refer_to_a1) { _e->UnPackTo(_o->refer_to_a1.get(), _resolver); } else { _o->refer_to_a1 = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->refer_to_a1) { _o->refer_to_a1.reset(); } } + { auto _e = refer_to_a2(); if (_e) { if(_o->refer_to_a2) { _e->UnPackTo(_o->refer_to_a2.get(), _resolver); } else { _o->refer_to_a2 = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->refer_to_a2) { _o->refer_to_a2.reset(); } } +} + +inline ::flatbuffers::Offset TableInC::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TableInCT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTableInC(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTableInC(::flatbuffers::FlatBufferBuilder &_fbb, const TableInCT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TableInCT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _refer_to_a1 = _o->refer_to_a1 ? CreateTableInFirstNS(_fbb, _o->refer_to_a1.get(), _rehasher) : 0; + auto _refer_to_a2 = _o->refer_to_a2 ? CreateSecondTableInA(_fbb, _o->refer_to_a2.get(), _rehasher) : 0; + return NamespaceC::CreateTableInC( + _fbb, + _refer_to_a1, + _refer_to_a2); +} + +} // namespace NamespaceC + +namespace NamespaceA { + + +inline bool operator==(const SecondTableInAT &lhs, const SecondTableInAT &rhs) { + return + ((lhs.refer_to_c == rhs.refer_to_c) || (lhs.refer_to_c && rhs.refer_to_c && *lhs.refer_to_c == *rhs.refer_to_c)); +} + +inline bool operator!=(const SecondTableInAT &lhs, const SecondTableInAT &rhs) { + return !(lhs == rhs); +} + + +inline SecondTableInAT::SecondTableInAT(const SecondTableInAT &o) + : refer_to_c((o.refer_to_c) ? new NamespaceC::TableInCT(*o.refer_to_c) : nullptr) { +} + +inline SecondTableInAT &SecondTableInAT::operator=(SecondTableInAT o) FLATBUFFERS_NOEXCEPT { + std::swap(refer_to_c, o.refer_to_c); + return *this; +} + +inline SecondTableInAT *SecondTableInA::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new SecondTableInAT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void SecondTableInA::UnPackTo(SecondTableInAT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = refer_to_c(); if (_e) { if(_o->refer_to_c) { _e->UnPackTo(_o->refer_to_c.get(), _resolver); } else { _o->refer_to_c = std::unique_ptr(_e->UnPack(_resolver)); } } else if (_o->refer_to_c) { _o->refer_to_c.reset(); } } +} + +inline ::flatbuffers::Offset SecondTableInA::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateSecondTableInA(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateSecondTableInA(::flatbuffers::FlatBufferBuilder &_fbb, const SecondTableInAT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const SecondTableInAT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _refer_to_c = _o->refer_to_c ? CreateTableInC(_fbb, _o->refer_to_c.get(), _rehasher) : 0; + return NamespaceA::CreateSecondTableInA( + _fbb, + _refer_to_c); +} + +inline const ::flatbuffers::TypeTable *TableInFirstNSTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 1 }, + { ::flatbuffers::ET_UTYPE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 3 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + NamespaceA::NamespaceB::TableInNestedNSTypeTable, + NamespaceA::NamespaceB::EnumInNestedNSTypeTable, + NamespaceA::NamespaceB::UnionInNestedNSTypeTable, + NamespaceA::NamespaceB::StructInNestedNSTypeTable + }; + static const char * const names[] = { + "foo_table", + "foo_enum", + "foo_union_type", + "foo_union", + "foo_struct" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 5, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace NamespaceA + +namespace NamespaceC { + +inline const ::flatbuffers::TypeTable *TableInCTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + NamespaceA::TableInFirstNSTypeTable, + NamespaceA::SecondTableInATypeTable + }; + static const char * const names[] = { + "refer_to_a1", + "refer_to_a2" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 2, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace NamespaceC + +namespace NamespaceA { + +inline const ::flatbuffers::TypeTable *SecondTableInATypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + NamespaceC::TableInCTypeTable + }; + static const char * const names[] = { + "refer_to_c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace NamespaceA + +#endif // FLATBUFFERS_GENERATED_NAMESPACETEST2_NAMESPACEA_H_ diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test2_generated.lobster b/third_party/flatbuffers/tests/namespace_test/namespace_test2_generated.lobster new file mode 100644 index 00000000000..3820928d571 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test2_generated.lobster @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import flatbuffers + +namespace NamespaceA + +class TableInFirstNS + +namespace NamespaceC + +class TableInC + +namespace NamespaceA + +class SecondTableInA + +class TableInFirstNS : flatbuffers_handle + def foo_table(): + let o = buf_.flatbuffers_field_table(pos_, 4) + return if o: NamespaceA_NamespaceB_TableInNestedNS { buf_, o } else: nil + def foo_enum(): + return EnumInNestedNS(buf_.flatbuffers_field_int8(pos_, 6, 0)) + def foo_union_type(): + return UnionInNestedNS(buf_.flatbuffers_field_int8(pos_, 8, 0)) + def foo_union_as_TableInNestedNS(): + return NamespaceA_NamespaceB_TableInNestedNS { buf_, buf_.flatbuffers_field_table(pos_, 10) } + def foo_struct(): + let o = buf_.flatbuffers_field_struct(pos_, 12) + return if o: NamespaceA_NamespaceB_StructInNestedNS { buf_, o } else: nil + +def GetRootAsTableInFirstNS(buf:string): return TableInFirstNS { buf, buf.flatbuffers_indirect(0) } + +struct TableInFirstNSBuilder: + b_:flatbuffers_builder + def start(): + b_.StartObject(5) + return this + def add_foo_table(foo_table:flatbuffers_offset): + b_.PrependUOffsetTRelativeSlot(0, foo_table) + return this + def add_foo_enum(foo_enum:EnumInNestedNS): + b_.PrependInt8Slot(1, foo_enum, 0) + return this + def add_foo_union_type(foo_union_type:UnionInNestedNS): + b_.PrependUint8Slot(2, foo_union_type, 0) + return this + def add_foo_union(foo_union:flatbuffers_offset): + b_.PrependUOffsetTRelativeSlot(3, foo_union) + return this + def add_foo_struct(foo_struct:flatbuffers_offset): + b_.PrependStructSlot(4, foo_struct) + return this + def end(): + return b_.EndObject() + +namespace NamespaceC + +class TableInC : flatbuffers_handle + def refer_to_a1(): + let o = buf_.flatbuffers_field_table(pos_, 4) + return if o: NamespaceA_TableInFirstNS { buf_, o } else: nil + def refer_to_a2(): + let o = buf_.flatbuffers_field_table(pos_, 6) + return if o: NamespaceA_SecondTableInA { buf_, o } else: nil + +def GetRootAsTableInC(buf:string): return TableInC { buf, buf.flatbuffers_indirect(0) } + +struct TableInCBuilder: + b_:flatbuffers_builder + def start(): + b_.StartObject(2) + return this + def add_refer_to_a1(refer_to_a1:flatbuffers_offset): + b_.PrependUOffsetTRelativeSlot(0, refer_to_a1) + return this + def add_refer_to_a2(refer_to_a2:flatbuffers_offset): + b_.PrependUOffsetTRelativeSlot(1, refer_to_a2) + return this + def end(): + return b_.EndObject() + +namespace NamespaceA + +class SecondTableInA : flatbuffers_handle + def refer_to_c(): + let o = buf_.flatbuffers_field_table(pos_, 4) + return if o: NamespaceC_TableInC { buf_, o } else: nil + +def GetRootAsSecondTableInA(buf:string): return SecondTableInA { buf, buf.flatbuffers_indirect(0) } + +struct SecondTableInABuilder: + b_:flatbuffers_builder + def start(): + b_.StartObject(1) + return this + def add_refer_to_c(refer_to_c:flatbuffers_offset): + b_.PrependUOffsetTRelativeSlot(0, refer_to_c) + return this + def end(): + return b_.EndObject() + diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test2_namespace_a_generated.dart b/third_party/flatbuffers/tests/namespace_test/namespace_test2_namespace_a_generated.dart new file mode 100644 index 00000000000..070cb5f9a21 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test2_namespace_a_generated.dart @@ -0,0 +1,273 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable + +library namespace_a; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './namespace_test2_namespace_c_generated.dart' as namespace_c; + +class TableInFirstNS { + TableInFirstNS._(this._bc, this._bcOffset); + factory TableInFirstNS(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableInFirstNSReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + namespace_a_namespace_b.TableInNestedNS? get fooTable => namespace_a_namespace_b.TableInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 4); + EnumInNestedNS get fooEnum => EnumInNestedNS.fromValue(const fb.Int8Reader().vTableGet(_bc, _bcOffset, 6, 0)); + UnionInNestedNSTypeId? get fooUnionType => UnionInNestedNSTypeId._createOrNull(const fb.Uint8Reader().vTableGetNullable(_bc, _bcOffset, 8)); + dynamic get fooUnion { + switch (fooUnionType?.value) { + case 1: return TableInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 10); + default: return null; + } + } + namespace_a_namespace_b.StructInNestedNS? get fooStruct => namespace_a_namespace_b.StructInNestedNS.reader.vTableGetNullable(_bc, _bcOffset, 12); + + @override + String toString() { + return 'TableInFirstNS{fooTable: $fooTable, fooEnum: $fooEnum, fooUnionType: $fooUnionType, fooUnion: $fooUnion, fooStruct: $fooStruct}'; + } + + TableInFirstNST unpack() => TableInFirstNST( + fooTable: fooTable?.unpack(), + fooEnum: fooEnum, + fooUnionType: fooUnionType, + fooUnion: fooUnion, + fooStruct: fooStruct?.unpack()); + + static int pack(fb.Builder fbBuilder, TableInFirstNST? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableInFirstNST implements fb.Packable { + namespace_a_namespace_b.TableInNestedNST? fooTable; + EnumInNestedNS fooEnum; + UnionInNestedNSTypeId? fooUnionType; + dynamic fooUnion; + namespace_a_namespace_b.StructInNestedNST? fooStruct; + + TableInFirstNST({ + this.fooTable, + this.fooEnum = EnumInNestedNS.A, + this.fooUnionType, + this.fooUnion, + this.fooStruct}); + + @override + int pack(fb.Builder fbBuilder) { + final int? fooTableOffset = fooTable?.pack(fbBuilder); + final int? fooUnionOffset = fooUnion?.pack(fbBuilder); + fbBuilder.startTable(5); + fbBuilder.addOffset(0, fooTableOffset); + fbBuilder.addInt8(1, fooEnum.value); + fbBuilder.addUint8(2, fooUnionType?.value); + fbBuilder.addOffset(3, fooUnionOffset); + if (fooStruct != null) { + fbBuilder.addStruct(4, fooStruct!.pack(fbBuilder)); + } + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableInFirstNST{fooTable: $fooTable, fooEnum: $fooEnum, fooUnionType: $fooUnionType, fooUnion: $fooUnion, fooStruct: $fooStruct}'; + } +} + +class _TableInFirstNSReader extends fb.TableReader { + const _TableInFirstNSReader(); + + @override + TableInFirstNS createObject(fb.BufferContext bc, int offset) => + TableInFirstNS._(bc, offset); +} + +class TableInFirstNSBuilder { + TableInFirstNSBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(5); + } + + int addFooTableOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + int addFooEnum(EnumInNestedNS? fooEnum) { + fbBuilder.addInt8(1, fooEnum?.value); + return fbBuilder.offset; + } + int addFooUnionType(UnionInNestedNSTypeId? fooUnionType) { + fbBuilder.addUint8(2, fooUnionType?.value); + return fbBuilder.offset; + } + int addFooUnionOffset(int? offset) { + fbBuilder.addOffset(3, offset); + return fbBuilder.offset; + } + int addFooStruct(int offset) { + fbBuilder.addStruct(4, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableInFirstNSObjectBuilder extends fb.ObjectBuilder { + final namespace_a_namespace_b.TableInNestedNSObjectBuilder? _fooTable; + final EnumInNestedNS? _fooEnum; + final UnionInNestedNSTypeId? _fooUnionType; + final dynamic _fooUnion; + final namespace_a_namespace_b.StructInNestedNSObjectBuilder? _fooStruct; + + TableInFirstNSObjectBuilder({ + namespace_a_namespace_b.TableInNestedNSObjectBuilder? fooTable, + EnumInNestedNS? fooEnum, + UnionInNestedNSTypeId? fooUnionType, + dynamic fooUnion, + namespace_a_namespace_b.StructInNestedNSObjectBuilder? fooStruct, + }) + : _fooTable = fooTable, + _fooEnum = fooEnum, + _fooUnionType = fooUnionType, + _fooUnion = fooUnion, + _fooStruct = fooStruct; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? fooTableOffset = _fooTable?.getOrCreateOffset(fbBuilder); + final int? fooUnionOffset = _fooUnion?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(5); + fbBuilder.addOffset(0, fooTableOffset); + fbBuilder.addInt8(1, _fooEnum?.value); + fbBuilder.addUint8(2, _fooUnionType?.value); + fbBuilder.addOffset(3, fooUnionOffset); + if (_fooStruct != null) { + fbBuilder.addStruct(4, _fooStruct!.finish(fbBuilder)); + } + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} +class SecondTableInA { + SecondTableInA._(this._bc, this._bcOffset); + factory SecondTableInA(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _SecondTableInAReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + namespace_c.TableInC? get referToC => namespace_c.TableInC.reader.vTableGetNullable(_bc, _bcOffset, 4); + + @override + String toString() { + return 'SecondTableInA{referToC: $referToC}'; + } + + SecondTableInAT unpack() => SecondTableInAT( + referToC: referToC?.unpack()); + + static int pack(fb.Builder fbBuilder, SecondTableInAT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class SecondTableInAT implements fb.Packable { + namespace_c.TableInCT? referToC; + + SecondTableInAT({ + this.referToC}); + + @override + int pack(fb.Builder fbBuilder) { + final int? referToCOffset = referToC?.pack(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, referToCOffset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'SecondTableInAT{referToC: $referToC}'; + } +} + +class _SecondTableInAReader extends fb.TableReader { + const _SecondTableInAReader(); + + @override + SecondTableInA createObject(fb.BufferContext bc, int offset) => + SecondTableInA._(bc, offset); +} + +class SecondTableInABuilder { + SecondTableInABuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(1); + } + + int addReferToCOffset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class SecondTableInAObjectBuilder extends fb.ObjectBuilder { + final namespace_c.TableInCObjectBuilder? _referToC; + + SecondTableInAObjectBuilder({ + namespace_c.TableInCObjectBuilder? referToC, + }) + : _referToC = referToC; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? referToCOffset = _referToC?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(1); + fbBuilder.addOffset(0, referToCOffset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/namespace_test/namespace_test2_namespace_c_generated.dart b/third_party/flatbuffers/tests/namespace_test/namespace_test2_namespace_c_generated.dart new file mode 100644 index 00000000000..1c30bb4a554 --- /dev/null +++ b/third_party/flatbuffers/tests/namespace_test/namespace_test2_namespace_c_generated.dart @@ -0,0 +1,125 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// ignore_for_file: unused_import, unused_field, unused_element, unused_local_variable + +library namespace_c; + +import 'dart:typed_data' show Uint8List; +import 'package:flat_buffers/flat_buffers.dart' as fb; + +import './namespace_test2_namespace_a_generated.dart' as namespace_a; + +class TableInC { + TableInC._(this._bc, this._bcOffset); + factory TableInC(List bytes) { + final rootRef = fb.BufferContext.fromBytes(bytes); + return reader.read(rootRef, 0); + } + + static const fb.Reader reader = _TableInCReader(); + + final fb.BufferContext _bc; + final int _bcOffset; + + namespace_a.TableInFirstNS? get referToA1 => namespace_a.TableInFirstNS.reader.vTableGetNullable(_bc, _bcOffset, 4); + namespace_a.SecondTableInA? get referToA2 => namespace_a.SecondTableInA.reader.vTableGetNullable(_bc, _bcOffset, 6); + + @override + String toString() { + return 'TableInC{referToA1: $referToA1, referToA2: $referToA2}'; + } + + TableInCT unpack() => TableInCT( + referToA1: referToA1?.unpack(), + referToA2: referToA2?.unpack()); + + static int pack(fb.Builder fbBuilder, TableInCT? object) { + if (object == null) return 0; + return object.pack(fbBuilder); + } +} + +class TableInCT implements fb.Packable { + namespace_a.TableInFirstNST? referToA1; + namespace_a.SecondTableInAT? referToA2; + + TableInCT({ + this.referToA1, + this.referToA2}); + + @override + int pack(fb.Builder fbBuilder) { + final int? referToA1Offset = referToA1?.pack(fbBuilder); + final int? referToA2Offset = referToA2?.pack(fbBuilder); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, referToA1Offset); + fbBuilder.addOffset(1, referToA2Offset); + return fbBuilder.endTable(); + } + + @override + String toString() { + return 'TableInCT{referToA1: $referToA1, referToA2: $referToA2}'; + } +} + +class _TableInCReader extends fb.TableReader { + const _TableInCReader(); + + @override + TableInC createObject(fb.BufferContext bc, int offset) => + TableInC._(bc, offset); +} + +class TableInCBuilder { + TableInCBuilder(this.fbBuilder); + + final fb.Builder fbBuilder; + + void begin() { + fbBuilder.startTable(2); + } + + int addReferToA1Offset(int? offset) { + fbBuilder.addOffset(0, offset); + return fbBuilder.offset; + } + int addReferToA2Offset(int? offset) { + fbBuilder.addOffset(1, offset); + return fbBuilder.offset; + } + + int finish() { + return fbBuilder.endTable(); + } +} + +class TableInCObjectBuilder extends fb.ObjectBuilder { + final namespace_a.TableInFirstNSObjectBuilder? _referToA1; + final namespace_a.SecondTableInAObjectBuilder? _referToA2; + + TableInCObjectBuilder({ + namespace_a.TableInFirstNSObjectBuilder? referToA1, + namespace_a.SecondTableInAObjectBuilder? referToA2, + }) + : _referToA1 = referToA1, + _referToA2 = referToA2; + + /// Finish building, and store into the [fbBuilder]. + @override + int finish(fb.Builder fbBuilder) { + final int? referToA1Offset = _referToA1?.getOrCreateOffset(fbBuilder); + final int? referToA2Offset = _referToA2?.getOrCreateOffset(fbBuilder); + fbBuilder.startTable(2); + fbBuilder.addOffset(0, referToA1Offset); + fbBuilder.addOffset(1, referToA2Offset); + return fbBuilder.endTable(); + } + + /// Convenience method to serialize to byte list. + @override + Uint8List toBytes([String? fileIdentifier]) { + final fbBuilder = fb.Builder(deduplicateTables: false); + fbBuilder.finish(finish(fbBuilder), fileIdentifier); + return fbBuilder.buffer; + } +} diff --git a/third_party/flatbuffers/tests/nan_inf_test.fbs b/third_party/flatbuffers/tests/nan_inf_test.fbs new file mode 100644 index 00000000000..e9dc281d7b4 --- /dev/null +++ b/third_party/flatbuffers/tests/nan_inf_test.fbs @@ -0,0 +1,14 @@ +namespace Swift.Tests; + +table NanInfTable +{ + default_nan:double = nan; + default_inf:double = inf; + default_ninf:double = -inf; + value_nan:double; + value_inf:double; + value_ninf:double; + value:double; +} + +root_type NanInfTable; diff --git a/third_party/flatbuffers/tests/native_inline_table_test.fbs b/third_party/flatbuffers/tests/native_inline_table_test.fbs new file mode 100644 index 00000000000..cbe8940b508 --- /dev/null +++ b/third_party/flatbuffers/tests/native_inline_table_test.fbs @@ -0,0 +1,7 @@ +table NativeInlineTable { + a: int; +} + +table TestNativeInlineTable { + t: [NativeInlineTable] (native_inline); +} diff --git a/third_party/flatbuffers/tests/native_inline_table_test_generated.h b/third_party/flatbuffers/tests/native_inline_table_test_generated.h new file mode 100644 index 00000000000..c676ce1ddcb --- /dev/null +++ b/third_party/flatbuffers/tests/native_inline_table_test_generated.h @@ -0,0 +1,263 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_NATIVEINLINETABLETEST_H_ +#define FLATBUFFERS_GENERATED_NATIVEINLINETABLETEST_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +struct NativeInlineTable; +struct NativeInlineTableBuilder; +struct NativeInlineTableT; + +struct TestNativeInlineTable; +struct TestNativeInlineTableBuilder; +struct TestNativeInlineTableT; + +bool operator==(const NativeInlineTableT &lhs, const NativeInlineTableT &rhs); +bool operator!=(const NativeInlineTableT &lhs, const NativeInlineTableT &rhs); +bool operator==(const TestNativeInlineTableT &lhs, const TestNativeInlineTableT &rhs); +bool operator!=(const TestNativeInlineTableT &lhs, const TestNativeInlineTableT &rhs); + +inline const ::flatbuffers::TypeTable *NativeInlineTableTypeTable(); + +inline const ::flatbuffers::TypeTable *TestNativeInlineTableTypeTable(); + +struct NativeInlineTableT : public ::flatbuffers::NativeTable { + typedef NativeInlineTable TableType; + int32_t a = 0; +}; + +struct NativeInlineTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef NativeInlineTableT NativeTableType; + typedef NativeInlineTableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return NativeInlineTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4 + }; + int32_t a() const { + return GetField(VT_A, 0); + } + bool mutate_a(int32_t _a = 0) { + return SetField(VT_A, _a, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + verifier.EndTable(); + } + NativeInlineTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(NativeInlineTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const NativeInlineTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct NativeInlineTableBuilder { + typedef NativeInlineTable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(int32_t a) { + fbb_.AddElement(NativeInlineTable::VT_A, a, 0); + } + explicit NativeInlineTableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateNativeInlineTable( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0) { + NativeInlineTableBuilder builder_(_fbb); + builder_.add_a(a); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateNativeInlineTable(::flatbuffers::FlatBufferBuilder &_fbb, const NativeInlineTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct TestNativeInlineTableT : public ::flatbuffers::NativeTable { + typedef TestNativeInlineTable TableType; + std::vector t{}; +}; + +struct TestNativeInlineTable FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef TestNativeInlineTableT NativeTableType; + typedef TestNativeInlineTableBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return TestNativeInlineTableTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_T = 4 + }; + const ::flatbuffers::Vector<::flatbuffers::Offset> *t() const { + return GetPointer> *>(VT_T); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_t() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_T); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_T) && + verifier.VerifyVector(t()) && + verifier.VerifyVectorOfTables(t()) && + verifier.EndTable(); + } + TestNativeInlineTableT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(TestNativeInlineTableT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestNativeInlineTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct TestNativeInlineTableBuilder { + typedef TestNativeInlineTable Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_t(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> t) { + fbb_.AddOffset(TestNativeInlineTable::VT_T, t); + } + explicit TestNativeInlineTableBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateTestNativeInlineTable( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> t = 0) { + TestNativeInlineTableBuilder builder_(_fbb); + builder_.add_t(t); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateTestNativeInlineTableDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector<::flatbuffers::Offset> *t = nullptr) { + auto t__ = t ? _fbb.CreateVector<::flatbuffers::Offset>(*t) : 0; + return CreateTestNativeInlineTable( + _fbb, + t__); +} + +::flatbuffers::Offset CreateTestNativeInlineTable(::flatbuffers::FlatBufferBuilder &_fbb, const TestNativeInlineTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const NativeInlineTableT &lhs, const NativeInlineTableT &rhs) { + return + (lhs.a == rhs.a); +} + +inline bool operator!=(const NativeInlineTableT &lhs, const NativeInlineTableT &rhs) { + return !(lhs == rhs); +} + + +inline NativeInlineTableT *NativeInlineTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new NativeInlineTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void NativeInlineTable::UnPackTo(NativeInlineTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = a(); _o->a = _e; } +} + +inline ::flatbuffers::Offset NativeInlineTable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const NativeInlineTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateNativeInlineTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateNativeInlineTable(::flatbuffers::FlatBufferBuilder &_fbb, const NativeInlineTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const NativeInlineTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _a = _o->a; + return CreateNativeInlineTable( + _fbb, + _a); +} + + +inline bool operator==(const TestNativeInlineTableT &lhs, const TestNativeInlineTableT &rhs) { + return + (lhs.t == rhs.t); +} + +inline bool operator!=(const TestNativeInlineTableT &lhs, const TestNativeInlineTableT &rhs) { + return !(lhs == rhs); +} + + +inline TestNativeInlineTableT *TestNativeInlineTable::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new TestNativeInlineTableT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void TestNativeInlineTable::UnPackTo(TestNativeInlineTableT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = t(); if (_e) { _o->t.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->t[_i] = *std::unique_ptr(_e->Get(_i)->UnPack(_resolver)); } } else { _o->t.resize(0); } } +} + +inline ::flatbuffers::Offset TestNativeInlineTable::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const TestNativeInlineTableT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateTestNativeInlineTable(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateTestNativeInlineTable(::flatbuffers::FlatBufferBuilder &_fbb, const TestNativeInlineTableT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const TestNativeInlineTableT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _t = _o->t.size() ? _fbb.CreateVector<::flatbuffers::Offset> (_o->t.size(), [](size_t i, _VectorArgs *__va) { return CreateNativeInlineTable(*__va->__fbb, &(__va->__o->t[i]), __va->__rehasher); }, &_va ) : 0; + return CreateTestNativeInlineTable( + _fbb, + _t); +} + +inline const ::flatbuffers::TypeTable *NativeInlineTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *TestNativeInlineTableTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 1, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + NativeInlineTableTypeTable + }; + static const char * const names[] = { + "t" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +#endif // FLATBUFFERS_GENERATED_NATIVEINLINETABLETEST_H_ diff --git a/third_party/flatbuffers/tests/native_type_test.fbs b/third_party/flatbuffers/tests/native_type_test.fbs new file mode 100644 index 00000000000..e22150f5bd9 --- /dev/null +++ b/third_party/flatbuffers/tests/native_type_test.fbs @@ -0,0 +1,22 @@ +native_include "native_type_test_impl.h"; + +namespace Geometry; + +struct Vector3D (native_type:"Native::Vector3D") { + x:float; + y:float; + z:float; +} + +struct Vector3DAlt (native_type:"Native::Vector3D", native_type_pack_name:"Vector3DAlt") { + a:float; + b:float; + c:float; +} + +table ApplicationData { + vectors:[Vector3D]; + vectors_alt:[Vector3DAlt]; +} + +root_type ApplicationData; diff --git a/third_party/flatbuffers/tests/native_type_test_generated.h b/third_party/flatbuffers/tests/native_type_test_generated.h new file mode 100644 index 00000000000..afea063418b --- /dev/null +++ b/third_party/flatbuffers/tests/native_type_test_generated.h @@ -0,0 +1,338 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_NATIVETYPETEST_GEOMETRY_H_ +#define FLATBUFFERS_GENERATED_NATIVETYPETEST_GEOMETRY_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +#include "native_type_test_impl.h" + +namespace Geometry { + +struct Vector3D; + +struct Vector3DAlt; + +struct ApplicationData; +struct ApplicationDataBuilder; +struct ApplicationDataT; + +inline const ::flatbuffers::TypeTable *Vector3DTypeTable(); + +inline const ::flatbuffers::TypeTable *Vector3DAltTypeTable(); + +inline const ::flatbuffers::TypeTable *ApplicationDataTypeTable(); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3D FLATBUFFERS_FINAL_CLASS { + private: + float x_; + float y_; + float z_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vector3DTypeTable(); + } + Vector3D() + : x_(0), + y_(0), + z_(0) { + } + Vector3D(float _x, float _y, float _z) + : x_(::flatbuffers::EndianScalar(_x)), + y_(::flatbuffers::EndianScalar(_y)), + z_(::flatbuffers::EndianScalar(_z)) { + } + float x() const { + return ::flatbuffers::EndianScalar(x_); + } + void mutate_x(float _x) { + ::flatbuffers::WriteScalar(&x_, _x); + } + float y() const { + return ::flatbuffers::EndianScalar(y_); + } + void mutate_y(float _y) { + ::flatbuffers::WriteScalar(&y_, _y); + } + float z() const { + return ::flatbuffers::EndianScalar(z_); + } + void mutate_z(float _z) { + ::flatbuffers::WriteScalar(&z_, _z); + } +}; +FLATBUFFERS_STRUCT_END(Vector3D, 12); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Vector3DAlt FLATBUFFERS_FINAL_CLASS { + private: + float a_; + float b_; + float c_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return Vector3DAltTypeTable(); + } + Vector3DAlt() + : a_(0), + b_(0), + c_(0) { + } + Vector3DAlt(float _a, float _b, float _c) + : a_(::flatbuffers::EndianScalar(_a)), + b_(::flatbuffers::EndianScalar(_b)), + c_(::flatbuffers::EndianScalar(_c)) { + } + float a() const { + return ::flatbuffers::EndianScalar(a_); + } + void mutate_a(float _a) { + ::flatbuffers::WriteScalar(&a_, _a); + } + float b() const { + return ::flatbuffers::EndianScalar(b_); + } + void mutate_b(float _b) { + ::flatbuffers::WriteScalar(&b_, _b); + } + float c() const { + return ::flatbuffers::EndianScalar(c_); + } + void mutate_c(float _c) { + ::flatbuffers::WriteScalar(&c_, _c); + } +}; +FLATBUFFERS_STRUCT_END(Vector3DAlt, 12); + +struct ApplicationDataT : public ::flatbuffers::NativeTable { + typedef ApplicationData TableType; + std::vector vectors{}; + std::vector vectors_alt{}; +}; + +struct ApplicationData FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ApplicationDataT NativeTableType; + typedef ApplicationDataBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ApplicationDataTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_VECTORS = 4, + VT_VECTORS_ALT = 6 + }; + const ::flatbuffers::Vector *vectors() const { + return GetPointer *>(VT_VECTORS); + } + ::flatbuffers::Vector *mutable_vectors() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTORS); + } + const ::flatbuffers::Vector *vectors_alt() const { + return GetPointer *>(VT_VECTORS_ALT); + } + ::flatbuffers::Vector *mutable_vectors_alt() { + return GetPointer<::flatbuffers::Vector *>(VT_VECTORS_ALT); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_VECTORS) && + verifier.VerifyVector(vectors()) && + VerifyOffset(verifier, VT_VECTORS_ALT) && + verifier.VerifyVector(vectors_alt()) && + verifier.EndTable(); + } + ApplicationDataT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ApplicationDataT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ApplicationDataBuilder { + typedef ApplicationData Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_vectors(::flatbuffers::Offset<::flatbuffers::Vector> vectors) { + fbb_.AddOffset(ApplicationData::VT_VECTORS, vectors); + } + void add_vectors_alt(::flatbuffers::Offset<::flatbuffers::Vector> vectors_alt) { + fbb_.AddOffset(ApplicationData::VT_VECTORS_ALT, vectors_alt); + } + explicit ApplicationDataBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateApplicationData( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::Vector> vectors = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> vectors_alt = 0) { + ApplicationDataBuilder builder_(_fbb); + builder_.add_vectors_alt(vectors_alt); + builder_.add_vectors(vectors); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateApplicationDataDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const std::vector *vectors = nullptr, + const std::vector *vectors_alt = nullptr) { + auto vectors__ = vectors ? _fbb.CreateVectorOfStructs(*vectors) : 0; + auto vectors_alt__ = vectors_alt ? _fbb.CreateVectorOfStructs(*vectors_alt) : 0; + return Geometry::CreateApplicationData( + _fbb, + vectors__, + vectors_alt__); +} + +::flatbuffers::Offset CreateApplicationData(::flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +inline ApplicationDataT *ApplicationData::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new ApplicationDataT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void ApplicationData::UnPackTo(ApplicationDataT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = vectors(); if (_e) { _o->vectors.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vectors[_i] = ::flatbuffers::UnPack(*_e->Get(_i)); } } else { _o->vectors.resize(0); } } + { auto _e = vectors_alt(); if (_e) { _o->vectors_alt.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->vectors_alt[_i] = ::flatbuffers::UnPackVector3DAlt(*_e->Get(_i)); } } else { _o->vectors_alt.resize(0); } } +} + +inline ::flatbuffers::Offset ApplicationData::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateApplicationData(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateApplicationData(::flatbuffers::FlatBufferBuilder &_fbb, const ApplicationDataT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ApplicationDataT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _vectors = _o->vectors.size() ? _fbb.CreateVectorOfNativeStructs(_o->vectors) : 0; + auto _vectors_alt = _o->vectors_alt.size() ? _fbb.CreateVectorOfNativeStructs(_o->vectors_alt, ::flatbuffers::PackVector3DAlt) : 0; + return Geometry::CreateApplicationData( + _fbb, + _vectors, + _vectors_alt); +} + +inline const ::flatbuffers::TypeTable *Vector3DTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8, 12 }; + static const char * const names[] = { + "x", + "y", + "z" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *Vector3DAltTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 } + }; + static const int64_t values[] = { 0, 4, 8, 12 }; + static const char * const names[] = { + "a", + "b", + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 3, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ApplicationDataTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + Geometry::Vector3DTypeTable, + Geometry::Vector3DAltTypeTable + }; + static const char * const names[] = { + "vectors", + "vectors_alt" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 2, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const Geometry::ApplicationData *GetApplicationData(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const Geometry::ApplicationData *GetSizePrefixedApplicationData(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline ApplicationData *GetMutableApplicationData(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline Geometry::ApplicationData *GetMutableSizePrefixedApplicationData(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline bool VerifyApplicationDataBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(nullptr); +} + +inline bool VerifySizePrefixedApplicationDataBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(nullptr); +} + +inline void FinishApplicationDataBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root); +} + +inline void FinishSizePrefixedApplicationDataBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root); +} + +inline std::unique_ptr UnPackApplicationData( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetApplicationData(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedApplicationData( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedApplicationData(buf)->UnPack(res)); +} + +} // namespace Geometry + +#endif // FLATBUFFERS_GENERATED_NATIVETYPETEST_GEOMETRY_H_ diff --git a/third_party/flatbuffers/tests/native_type_test_impl.cpp b/third_party/flatbuffers/tests/native_type_test_impl.cpp new file mode 100644 index 00000000000..b5b595b8488 --- /dev/null +++ b/third_party/flatbuffers/tests/native_type_test_impl.cpp @@ -0,0 +1,21 @@ +#include "native_type_test_impl.h" + +#include "native_type_test_generated.h" + +namespace flatbuffers { +Geometry::Vector3D Pack(const Native::Vector3D &obj) { + return Geometry::Vector3D(obj.x, obj.y, obj.z); +} + +const Native::Vector3D UnPack(const Geometry::Vector3D &obj) { + return Native::Vector3D(obj.x(), obj.y(), obj.z()); +} + +Geometry::Vector3DAlt PackVector3DAlt(const Native::Vector3D &obj) { + return Geometry::Vector3DAlt(obj.x, obj.y, obj.z); +} + +const Native::Vector3D UnPackVector3DAlt(const Geometry::Vector3DAlt &obj) { + return Native::Vector3D(obj.a(), obj.b(), obj.c()); +} +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/native_type_test_impl.h b/third_party/flatbuffers/tests/native_type_test_impl.h new file mode 100644 index 00000000000..bc8f385ec66 --- /dev/null +++ b/third_party/flatbuffers/tests/native_type_test_impl.h @@ -0,0 +1,35 @@ +#ifndef NATIVE_TYPE_TEST_IMPL_H +#define NATIVE_TYPE_TEST_IMPL_H + +namespace Native { +struct Vector3D { + float x; + float y; + float z; + + Vector3D() { + x = 0; + y = 0; + z = 0; + } + Vector3D(float _x, float _y, float _z) { + this->x = _x; + this->y = _y; + this->z = _z; + } +}; +} // namespace Native + +namespace Geometry { +struct Vector3D; +struct Vector3DAlt; +} // namespace Geometry + +namespace flatbuffers { +Geometry::Vector3D Pack(const Native::Vector3D &obj); +const Native::Vector3D UnPack(const Geometry::Vector3D &obj); +Geometry::Vector3DAlt PackVector3DAlt(const Native::Vector3D &obj); +const Native::Vector3D UnPackVector3DAlt(const Geometry::Vector3DAlt &obj); +} // namespace flatbuffers + +#endif // VECTOR3D_PACK_H diff --git a/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test1.fbs b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test1.fbs new file mode 100644 index 00000000000..1b438473453 --- /dev/null +++ b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test1.fbs @@ -0,0 +1,3 @@ +namespace NamespaceB; + +enum Color:byte { Red, Green, Blue } diff --git a/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test1_generated.cs b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test1_generated.cs new file mode 100644 index 00000000000..f1e646c4214 --- /dev/null +++ b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test1_generated.cs @@ -0,0 +1,21 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceB +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Color : sbyte +{ + Red = 0, + Green = 1, + Blue = 2, +}; + + +} diff --git a/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test2.fbs b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test2.fbs new file mode 100644 index 00000000000..f2e04c3fb95 --- /dev/null +++ b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test2.fbs @@ -0,0 +1,3 @@ +namespace NamespaceA.NamespaceB; + +enum Color:byte { Purple } diff --git a/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test2_generated.cs b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test2_generated.cs new file mode 100644 index 00000000000..efd2584dd9e --- /dev/null +++ b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test2_generated.cs @@ -0,0 +1,19 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA.NamespaceB +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Color : sbyte +{ + Purple = 0, +}; + + +} diff --git a/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test3.fbs b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test3.fbs new file mode 100644 index 00000000000..2672ace7e79 --- /dev/null +++ b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test3.fbs @@ -0,0 +1,7 @@ +include "nested_namespace_test1.fbs"; + +namespace NamespaceA.NamespaceB; + +table ColorTestTable { + color:NamespaceB.Color = Blue; +} diff --git a/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test3_generated.cs b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test3_generated.cs new file mode 100644 index 00000000000..a4a64671f7e --- /dev/null +++ b/third_party/flatbuffers/tests/nested_namespace_test/nested_namespace_test3_generated.cs @@ -0,0 +1,75 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace NamespaceA.NamespaceB +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct ColorTestTable : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static ColorTestTable GetRootAsColorTestTable(ByteBuffer _bb) { return GetRootAsColorTestTable(_bb, new ColorTestTable()); } + public static ColorTestTable GetRootAsColorTestTable(ByteBuffer _bb, ColorTestTable obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public ColorTestTable __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public global::NamespaceB.Color Color { get { int o = __p.__offset(4); return o != 0 ? (global::NamespaceB.Color)__p.bb.GetSbyte(o + __p.bb_pos) : global::NamespaceB.Color.Blue; } } + public bool MutateColor(global::NamespaceB.Color color) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutSbyte(o + __p.bb_pos, (sbyte)color); return true; } else { return false; } } + + public static Offset CreateColorTestTable(FlatBufferBuilder builder, + global::NamespaceB.Color color = global::NamespaceB.Color.Blue) { + builder.StartTable(1); + ColorTestTable.AddColor(builder, color); + return ColorTestTable.EndColorTestTable(builder); + } + + public static void StartColorTestTable(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddColor(FlatBufferBuilder builder, global::NamespaceB.Color color) { builder.AddSbyte(0, (sbyte)color, 2); } + public static Offset EndColorTestTable(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public ColorTestTableT UnPack() { + var _o = new ColorTestTableT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(ColorTestTableT _o) { + _o.Color = this.Color; + } + public static Offset Pack(FlatBufferBuilder builder, ColorTestTableT _o) { + if (_o == null) return default(Offset); + return CreateColorTestTable( + builder, + _o.Color); + } +} + +public class ColorTestTableT +{ + [Newtonsoft.Json.JsonProperty("color")] + public global::NamespaceB.Color Color { get; set; } + + public ColorTestTableT() { + this.Color = global::NamespaceB.Color.Blue; + } +} + + +static public class ColorTestTableVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Color*/, 1 /*global::NamespaceB.Color*/, 1, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/nested_union_test.fbs b/third_party/flatbuffers/tests/nested_union_test.fbs new file mode 100644 index 00000000000..daa6048b566 --- /dev/null +++ b/third_party/flatbuffers/tests/nested_union_test.fbs @@ -0,0 +1,36 @@ +namespace MyGame.Example.NestedUnion; + +/// Composite components of Monster color. +enum Color:ubyte (bit_flags) { + Red = 0, // color Red = (1u << 0) + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Green, + /// \brief color Blue (1u << 3) + Blue = 3, +} + +table TestSimpleTableWithEnum (csharp_partial, private) { + color: Color = Green; +} + +struct Test { a:short; b:byte; } + +table Vec3 { + x:double; + y:double; + z:double; + test1:double; + test2:Color; + test3:Test; +} + +union Any { Vec3, TestSimpleTableWithEnum } + +table NestedUnionTest { + name:string; + data:Any; + id:short; +} + +root_type NestedUnionTest; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/nim/testnim.py b/third_party/flatbuffers/tests/nim/testnim.py new file mode 100644 index 00000000000..2a54cf3d34c --- /dev/null +++ b/third_party/flatbuffers/tests/nim/testnim.py @@ -0,0 +1,22 @@ +import glob +import os +import shutil +import subprocess +from pathlib import Path + +test_nim_dir = Path(__file__).absolute().parent +test_dir = test_nim_dir.parent + + +def main(): + try: + subprocess.check_call("testament --megatest:off all".split()) + finally: + shutil.rmtree(test_nim_dir / "nimcache") + shutil.rmtree(test_nim_dir / "testresults") + for f in glob.glob(str(test_nim_dir / "tests" / "*" / "test")): + os.remove(f) + + +if __name__ == "__main__": + main() diff --git a/third_party/flatbuffers/tests/nim/tests/moredefaults/test.nim b/third_party/flatbuffers/tests/nim/tests/moredefaults/test.nim new file mode 100644 index 00000000000..b49dc169dc0 --- /dev/null +++ b/third_party/flatbuffers/tests/nim/tests/moredefaults/test.nim @@ -0,0 +1,27 @@ +discard """ + action: "run" + exitcode: 0 + timeout: 60.0 +""" +import std/unittest +import flatbuffers +import ../../../MoreDefaults + +suite "TestMoreDefaults": + + test "testFlatbuffersObject": + var fbb = newBuilder(0) + fbb.MoreDefaultsStart() + let root = fbb.MoreDefaultsEnd() + fbb.Finish(root) + + var defaults: MoreDefaults + defaults.GetRootAs(fbb.FinishedBytes(), 0) + check(defaults.emptyString == "") + check(defaults.ints == []) + check(defaults.floats == []) + check(defaults.bools == []) + check(defaults.intsLength == 0) + check(defaults.floatsLength == 0) + check(defaults.abcsLength == 0) + check(defaults.boolsLength == 0) diff --git a/third_party/flatbuffers/tests/nim/tests/mutatingbool/test.nim b/third_party/flatbuffers/tests/nim/tests/mutatingbool/test.nim new file mode 100644 index 00000000000..b079cbf484b --- /dev/null +++ b/third_party/flatbuffers/tests/nim/tests/mutatingbool/test.nim @@ -0,0 +1,39 @@ +discard """ + action: "run" + exitcode: 0 + timeout: 60.0 +""" +import std/unittest +import std/options +import flatbuffers +import ../../../TestMutatingBool +import ../../../Property + +suite "TestMutatingBool": + + test "MutatingBool": + var builder = newBuilder(1024) + builder.TestMutatingBoolStart() + builder.TestMutatingBoolAddB(builder.PropertyCreate(false)) + let root = builder.TestMutatingBoolEnd() + builder.Finish(root) + + var test_mutating_bool: TestMutatingBool + GetRootAs(test_mutating_bool, builder.FinishedBytes(), 0) + check(test_mutating_bool.b.isSome) + var prop2 = test_mutating_bool.b.get() + check(prop2.property == false) + discard (prop2.property = false) + check(prop2.property == false) + discard (prop2.property = true) + check(prop2.property == true) + + test "EmptyBool": + var builder = newBuilder(1024) + builder.TestMutatingBoolStart() + let root = builder.TestMutatingBoolEnd() + builder.Finish(root) + + var test_mutating_bool: TestMutatingBool + GetRootAs(test_mutating_bool, builder.FinishedBytes(), 0) + check(test_mutating_bool.b.isNone) diff --git a/third_party/flatbuffers/tests/nim/tests/mygame/test.nim b/third_party/flatbuffers/tests/nim/tests/mygame/test.nim new file mode 100644 index 00000000000..c971d6079d3 --- /dev/null +++ b/third_party/flatbuffers/tests/nim/tests/mygame/test.nim @@ -0,0 +1,207 @@ +discard """ + action: "run" + exitcode: 0 + timeout: 60.0 +""" +import std/unittest +import std/options +import flatbuffers +import ../../../MyGame/Example/Test +import ../../../MyGame/Example/Monster +import ../../../MyGame/Example/Vec3 +import ../../../MyGame/Example/Color as ColorMod +import ../../../MyGame/Example/Any as AnyMod + +proc verifyMonster(monster: var Monster) = + check(monster.hp == 80) + check(monster.mana == 150) + check(monster.name == "MyMonster") + check(monster.pos.isSome) + let pos = monster.pos.get() + check(pos.x == 1) + check(pos.y == 2) + check(pos.z == 3) + check(pos.test1 == 3) + check(pos.test2 == Color.Green) + check(pos.test3.a == 5) + check(pos.test3.b == 6) + check(monster.testType == Any.Monster) + check(monster.test.isSome) + let monster2 = Monster(tab: monster.test.get()) + check(monster2.name == "Fred") + check((monster.mana = 10) == false) + check(monster.mana == 150) + check(monster.inventoryLength == 5) + var sum: uint8 = 0 + for item in monster.inventory: + sum += item + check(sum == 10) + check(monster.test4Length == 2) + + let test0 = monster.test4(0) + let test1 = monster.test4(1) + var sum0 = test0.a + test0.b + var sum1 = test1.a + test1.b + check(sum0 + sum1 == 100) + + check(monster.testarrayofstringLength == 2) + check(monster.testarrayofstring(0) == "test1") + check(monster.testarrayofstring(1) == "test2") + check(monster.testbool == true) + + +suite "TestMyGame": + + test "testData": + let data: seq[byte] = @[byte(48), 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, + 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, + 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, + 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, + 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, + 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, + 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, + 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, + 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, + 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, + 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, + 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, + 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, + 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0] + var monster: Monster + GetRootAs(monster, data, 0) + verifyMonster(monster) + + test "testCreateString": + var fbb = newBuilder(0) + let name = fbb.Create("Frodo") + fbb.Finish(name) + check(fbb.FinishedBytes() == @[byte(4), 0, 0, 0, 5, 0, 0, 0, 70, 114, 111, + 100, 111, 0, 0, 0]) + + test "testCreateVector": + var fbb = newBuilder(0) + let vec = fbb.Create(@[byte(0), 1, 2, 3, 4]) + fbb.Finish(vec) + check(fbb.FinishedBytes() == @[byte(4), 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, + 0, 0, 0]) + + test "createSimpleMonster": + var fbb = newBuilder(0) + let names = [ + fbb.Create("Frodo"), + fbb.Create("Barney"), + fbb.Create("Wilma"), + ] + fbb.MonsterStart() + fbb.MonsterAddName(names[0]) + let monster = fbb.MonsterEnd() + fbb.Finish(monster) + check(fbb.FinishedBytes() == @[byte(16), 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, + 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, + 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, + 114, 111, 100, 111, 0, 0, 0]) + + test "testCreateTestVector": + var fbb = newBuilder(0) + fbb.MonsterStartTest4Vector(2) + discard fbb.TestCreate(a = 30, b = 40) + discard fbb.TestCreate(a = 10, b = 20) + let test4 = fbb.EndVector() + fbb.Finish(test4) + check(fbb.FinishedBytes() == @[byte(4), 0, 0, 0, 2, 0, 0, 0, 10, 0, 20, 0, + 30, 0, 40, 0]) + + test "testTableWithStruct": + var fbb = newBuilder(0) + fbb.MonsterStart() + fbb.MonsterAddPos(fbb.Vec3Create(x = 1, + y = 2, + z = 3, + test1 = 3, + test2 = Color.Green, + test3_a = 5, test3_b = 6)) + + let monster_end = fbb.MonsterEnd() + fbb.Finish(monster_end) + check(fbb.FinishedBytes() == @[byte(12), 0, 0, 0, 0, 0, 6, 0, 36, 0, 4, 0, + 6, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0]) + + test "testCreateMonster": + var fbb = newBuilder(0) + let names = [ + fbb.Create("Frodo"), + fbb.Create("Barney"), + fbb.Create("Wilma"), + ] + + var offsets: seq[uoffset] = @[] + fbb.MonsterStart() + fbb.MonsterAddName(names[0]) + offsets.add(fbb.MonsterEnd()) + fbb.MonsterStart() + fbb.MonsterAddName(names[1]) + offsets.add(fbb.MonsterEnd()) + fbb.MonsterStart() + fbb.MonsterAddName(names[2]) + offsets.add(fbb.MonsterEnd()) + + let str = fbb.Create("MyMonster") + let test1 = fbb.Create("test1") + let test2 = fbb.Create("test2") + let inv = fbb.Create(@[byte(0), 1, 2, 3, 4]) + let fred = fbb.Create("Fred") + fbb.MonsterStart() + fbb.MonsterAddName(fred) + let mon2 = fbb.MonsterEnd() + + fbb.MonsterStartTest4Vector(2) + discard fbb.TestCreate(a = 30, b = 40) + discard fbb.TestCreate(a = 10, b = 20) + let test4 = fbb.EndVector() + + fbb.MonsterStartTestarrayofstringVector(2) + fbb.PrependOffsetRelative(test1) + fbb.PrependOffsetRelative(test2) + let stringTestVector = fbb.EndVector() + + fbb.MonsterStartTestarrayoftablesVector(3) + fbb.PrependOffsetRelative(offsets[0]) + fbb.PrependOffsetRelative(offsets[1]) + fbb.PrependOffsetRelative(offsets[2]) + let tableTestVector = fbb.EndVector() + + fbb.MonsterStart() + fbb.MonsterAddPos(fbb.Vec3Create(x = 1, + y = 2, + z = 3, + test1 = 3, + test2 = Color.Green, + test3_a = 5, test3_b = 6)) + fbb.MonsterAddHp(80) + fbb.MonsterAddName(str) + fbb.MonsterAddInventory(inv) + fbb.MonsterAddTestType(Any.Monster.uint8) + fbb.MonsterAddTest(mon2) + fbb.MonsterAddTest4(test4) + fbb.MonsterAddTestarrayofstring(stringTestVector) + fbb.MonsterAddTestbool(true) + fbb.MonsterAddTestarrayoftables(tableTestVector) + let monster_end = fbb.MonsterEnd() + fbb.Finish(monster_end) + check(fbb.FinishedBytes() == @[byte(40), 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, + 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, + 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 68, 0, 0, 0, 0, 0, 0, 1, 76, 0, 0, 0, + 84, 0, 0, 0, 92, 0, 0, 0, 0, 0, 0, 1, 104, 0, 0, 0, 136, 0, 0, 0, 0, 0, + 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 3, 0, 0, 0, 108, 0, 0, 0, 112, 0, + 0, 0, 128, 0, 0, 0, 2, 0, 0, 0, 52, 0, 0, 0, 60, 0, 0, 0, 2, 0, 0, 0, + 10, 0, 20, 0, 30, 0, 40, 0, 168, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, + 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, + 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, + 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, + 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, + 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, + 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, + 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) diff --git a/third_party/flatbuffers/tests/nim/tests/optional_scalars/test.nim b/third_party/flatbuffers/tests/nim/tests/optional_scalars/test.nim new file mode 100644 index 00000000000..1e02c59e05c --- /dev/null +++ b/third_party/flatbuffers/tests/nim/tests/optional_scalars/test.nim @@ -0,0 +1,29 @@ +discard """ + action: "run" + exitcode: 0 + timeout: 60.0 +""" +import std/unittest +import std/options +import flatbuffers +import ../../../optional_scalars/ScalarStuff + + +suite "TestOptionalScalars": + + test "OptionalScalars": + var builder = newBuilder(1024) + builder.ScalarStuffStart() + let root = builder.ScalarStuffEnd() + builder.Finish(root) + + var optionals: ScalarStuff + optionals.GetRootAs(builder.FinishedBytes(), 0) + + # Creates a flatbuffer with optional values. + check(optionals.justI8 == 0) + check(optionals.maybeF32.isNone) + check(optionals.defaultBool == true) + check(optionals.justU16 == 0) + check(optionals.maybeEnum.isNone) + check(optionals.defaultU64 == 42) diff --git a/third_party/flatbuffers/tests/optional_scalars.fbs b/third_party/flatbuffers/tests/optional_scalars.fbs new file mode 100644 index 00000000000..260d4432be9 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars.fbs @@ -0,0 +1,59 @@ +namespace optional_scalars; + +enum OptionalByte: byte { + None = 0, + One = 1, + Two = 2, +} + +// This table tests optional scalars in tables. It should be integrated with +// the main monster test once most languages support optional scalars. +table ScalarStuff { + just_i8: int8; + maybe_i8: int8 = null; + default_i8: int8 = 42; + just_u8: uint8; + maybe_u8: uint8 = null; + default_u8: uint8 = 42; + + just_i16: int16; + maybe_i16: int16 = null; + default_i16: int16 = 42; + just_u16: uint16; + maybe_u16: uint16 = null; + default_u16: uint16 = 42; + + just_i32: int32; + maybe_i32: int32 = null; + default_i32: int32 = 42; + just_u32: uint32; + maybe_u32: uint32 = null; + default_u32: uint32 = 42; + + just_i64: int64; + maybe_i64: int64 = null; + default_i64: int64 = 42; + just_u64: uint64; + maybe_u64: uint64 = null; + default_u64: uint64 = 42; + + just_f32: float32; + maybe_f32: float32 = null; + default_f32: float32 = 42; + just_f64: float64; + maybe_f64: float64 = null; + default_f64: float64 = 42; + + just_bool: bool; + maybe_bool: bool = null; + default_bool: bool = true; + + just_enum: OptionalByte; + maybe_enum: OptionalByte = null; + default_enum: OptionalByte = One; +} + +root_type ScalarStuff; + +file_identifier "NULL"; +file_extension "mon"; diff --git a/third_party/flatbuffers/tests/optional_scalars.json b/third_party/flatbuffers/tests/optional_scalars.json new file mode 100644 index 00000000000..87bd22efb95 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars.json @@ -0,0 +1,21 @@ +{ + just_i8: 4, + maybe_u8: 0, + default_u8: 0, + just_i16: 4, + maybe_u16: 0, + default_u16: 0, + just_i32: 4, + maybe_u32: 0, + default_u32: 0, + just_i64: 4, + maybe_u64: 0, + default_u64: 0, + just_f32: 4.0, + maybe_f64: 0.0, + default_f64: 0.0, + just_bool: true, + default_bool: false, + maybe_enum: "One", + default_enum: "Two" +} diff --git a/third_party/flatbuffers/tests/optional_scalars/OptionalByte.cs b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.cs new file mode 100644 index 00000000000..79a20045bbf --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.cs @@ -0,0 +1,16 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace optional_scalars +{ + +public enum OptionalByte : sbyte +{ + None = 0, + One = 1, + Two = 2, +}; + + +} diff --git a/third_party/flatbuffers/tests/optional_scalars/OptionalByte.go b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.go new file mode 100644 index 00000000000..e1f5ac00d2a --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.go @@ -0,0 +1,32 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package optional_scalars + +import "strconv" + +type OptionalByte int8 + +const ( + OptionalByteNone OptionalByte = 0 + OptionalByteOne OptionalByte = 1 + OptionalByteTwo OptionalByte = 2 +) + +var EnumNamesOptionalByte = map[OptionalByte]string{ + OptionalByteNone: "None", + OptionalByteOne: "One", + OptionalByteTwo: "Two", +} + +var EnumValuesOptionalByte = map[string]OptionalByte{ + "None": OptionalByteNone, + "One": OptionalByteOne, + "Two": OptionalByteTwo, +} + +func (v OptionalByte) String() string { + if s, ok := EnumNamesOptionalByte[v]; ok { + return s + } + return "OptionalByte(" + strconv.FormatInt(int64(v), 10) + ")" +} diff --git a/third_party/flatbuffers/tests/optional_scalars/OptionalByte.java b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.java new file mode 100644 index 00000000000..90a37fdfd8c --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.java @@ -0,0 +1,16 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package optional_scalars; + +@SuppressWarnings("unused") +public final class OptionalByte { + private OptionalByte() { } + public static final byte None = 0; + public static final byte One = 1; + public static final byte Two = 2; + + public static final String[] names = { "None", "One", "Two", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/optional_scalars/OptionalByte.kt b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.kt new file mode 100644 index 00000000000..7a8788631df --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.kt @@ -0,0 +1,12 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package optional_scalars + +@Suppress("unused") +class OptionalByte private constructor() { + companion object { + const val None: Byte = 0 + const val One: Byte = 1 + const val Two: Byte = 2 + } +} diff --git a/third_party/flatbuffers/tests/optional_scalars/OptionalByte.nim b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.nim new file mode 100644 index 00000000000..f95bc52346d --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.nim @@ -0,0 +1,14 @@ +#[ optional_scalars.OptionalByte + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : optional_scalars.ScalarStuff () +]# + +type OptionalByte*{.pure.} = enum + None = 0.int8, + One = 1.int8, + Two = 2.int8, diff --git a/third_party/flatbuffers/tests/optional_scalars/OptionalByte.py b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.py new file mode 100644 index 00000000000..5e7df8b6b9d --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/OptionalByte.py @@ -0,0 +1,8 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: optional_scalars + +class OptionalByte(object): + None_ = 0 + One = 1 + Two = 2 diff --git a/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.cs b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.cs new file mode 100644 index 00000000000..5d916beb7ec --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.cs @@ -0,0 +1,400 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace optional_scalars +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct ScalarStuff : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static ScalarStuff GetRootAsScalarStuff(ByteBuffer _bb) { return GetRootAsScalarStuff(_bb, new ScalarStuff()); } + public static ScalarStuff GetRootAsScalarStuff(ByteBuffer _bb, ScalarStuff obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool ScalarStuffBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "NULL"); } + public static bool VerifyScalarStuff(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("NULL", false, ScalarStuffVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public ScalarStuff __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public sbyte JustI8 { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetSbyte(o + __p.bb_pos) : (sbyte)0; } } + public sbyte? MaybeI8 { get { int o = __p.__offset(6); return o != 0 ? __p.bb.GetSbyte(o + __p.bb_pos) : (sbyte?)null; } } + public sbyte DefaultI8 { get { int o = __p.__offset(8); return o != 0 ? __p.bb.GetSbyte(o + __p.bb_pos) : (sbyte)42; } } + public byte JustU8 { get { int o = __p.__offset(10); return o != 0 ? __p.bb.Get(o + __p.bb_pos) : (byte)0; } } + public byte? MaybeU8 { get { int o = __p.__offset(12); return o != 0 ? __p.bb.Get(o + __p.bb_pos) : (byte?)null; } } + public byte DefaultU8 { get { int o = __p.__offset(14); return o != 0 ? __p.bb.Get(o + __p.bb_pos) : (byte)42; } } + public short JustI16 { get { int o = __p.__offset(16); return o != 0 ? __p.bb.GetShort(o + __p.bb_pos) : (short)0; } } + public short? MaybeI16 { get { int o = __p.__offset(18); return o != 0 ? __p.bb.GetShort(o + __p.bb_pos) : (short?)null; } } + public short DefaultI16 { get { int o = __p.__offset(20); return o != 0 ? __p.bb.GetShort(o + __p.bb_pos) : (short)42; } } + public ushort JustU16 { get { int o = __p.__offset(22); return o != 0 ? __p.bb.GetUshort(o + __p.bb_pos) : (ushort)0; } } + public ushort? MaybeU16 { get { int o = __p.__offset(24); return o != 0 ? __p.bb.GetUshort(o + __p.bb_pos) : (ushort?)null; } } + public ushort DefaultU16 { get { int o = __p.__offset(26); return o != 0 ? __p.bb.GetUshort(o + __p.bb_pos) : (ushort)42; } } + public int JustI32 { get { int o = __p.__offset(28); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public int? MaybeI32 { get { int o = __p.__offset(30); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int?)null; } } + public int DefaultI32 { get { int o = __p.__offset(32); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)42; } } + public uint JustU32 { get { int o = __p.__offset(34); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)0; } } + public uint? MaybeU32 { get { int o = __p.__offset(36); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint?)null; } } + public uint DefaultU32 { get { int o = __p.__offset(38); return o != 0 ? __p.bb.GetUint(o + __p.bb_pos) : (uint)42; } } + public long JustI64 { get { int o = __p.__offset(40); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)0; } } + public long? MaybeI64 { get { int o = __p.__offset(42); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long?)null; } } + public long DefaultI64 { get { int o = __p.__offset(44); return o != 0 ? __p.bb.GetLong(o + __p.bb_pos) : (long)42; } } + public ulong JustU64 { get { int o = __p.__offset(46); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)0; } } + public ulong? MaybeU64 { get { int o = __p.__offset(48); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong?)null; } } + public ulong DefaultU64 { get { int o = __p.__offset(50); return o != 0 ? __p.bb.GetUlong(o + __p.bb_pos) : (ulong)42; } } + public float JustF32 { get { int o = __p.__offset(52); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)0.0f; } } + public float? MaybeF32 { get { int o = __p.__offset(54); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float?)null; } } + public float DefaultF32 { get { int o = __p.__offset(56); return o != 0 ? __p.bb.GetFloat(o + __p.bb_pos) : (float)42.0f; } } + public double JustF64 { get { int o = __p.__offset(58); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)0.0; } } + public double? MaybeF64 { get { int o = __p.__offset(60); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double?)null; } } + public double DefaultF64 { get { int o = __p.__offset(62); return o != 0 ? __p.bb.GetDouble(o + __p.bb_pos) : (double)42.0; } } + public bool JustBool { get { int o = __p.__offset(64); return o != 0 ? 0!=__p.bb.Get(o + __p.bb_pos) : (bool)false; } } + public bool? MaybeBool { get { int o = __p.__offset(66); return o != 0 ? 0!=__p.bb.Get(o + __p.bb_pos) : (bool?)null; } } + public bool DefaultBool { get { int o = __p.__offset(68); return o != 0 ? 0!=__p.bb.Get(o + __p.bb_pos) : (bool)true; } } + public optional_scalars.OptionalByte JustEnum { get { int o = __p.__offset(70); return o != 0 ? (optional_scalars.OptionalByte)__p.bb.GetSbyte(o + __p.bb_pos) : optional_scalars.OptionalByte.None; } } + public optional_scalars.OptionalByte? MaybeEnum { get { int o = __p.__offset(72); return o != 0 ? (optional_scalars.OptionalByte)__p.bb.GetSbyte(o + __p.bb_pos) : (optional_scalars.OptionalByte?)null; } } + public optional_scalars.OptionalByte DefaultEnum { get { int o = __p.__offset(74); return o != 0 ? (optional_scalars.OptionalByte)__p.bb.GetSbyte(o + __p.bb_pos) : optional_scalars.OptionalByte.One; } } + + public static Offset CreateScalarStuff(FlatBufferBuilder builder, + sbyte just_i8 = 0, + sbyte? maybe_i8 = null, + sbyte default_i8 = 42, + byte just_u8 = 0, + byte? maybe_u8 = null, + byte default_u8 = 42, + short just_i16 = 0, + short? maybe_i16 = null, + short default_i16 = 42, + ushort just_u16 = 0, + ushort? maybe_u16 = null, + ushort default_u16 = 42, + int just_i32 = 0, + int? maybe_i32 = null, + int default_i32 = 42, + uint just_u32 = 0, + uint? maybe_u32 = null, + uint default_u32 = 42, + long just_i64 = 0, + long? maybe_i64 = null, + long default_i64 = 42, + ulong just_u64 = 0, + ulong? maybe_u64 = null, + ulong default_u64 = 42, + float just_f32 = 0.0f, + float? maybe_f32 = null, + float default_f32 = 42.0f, + double just_f64 = 0.0, + double? maybe_f64 = null, + double default_f64 = 42.0, + bool just_bool = false, + bool? maybe_bool = null, + bool default_bool = true, + optional_scalars.OptionalByte just_enum = optional_scalars.OptionalByte.None, + optional_scalars.OptionalByte? maybe_enum = null, + optional_scalars.OptionalByte default_enum = optional_scalars.OptionalByte.One) { + builder.StartTable(36); + ScalarStuff.AddDefaultF64(builder, default_f64); + ScalarStuff.AddMaybeF64(builder, maybe_f64); + ScalarStuff.AddJustF64(builder, just_f64); + ScalarStuff.AddDefaultU64(builder, default_u64); + ScalarStuff.AddMaybeU64(builder, maybe_u64); + ScalarStuff.AddJustU64(builder, just_u64); + ScalarStuff.AddDefaultI64(builder, default_i64); + ScalarStuff.AddMaybeI64(builder, maybe_i64); + ScalarStuff.AddJustI64(builder, just_i64); + ScalarStuff.AddDefaultF32(builder, default_f32); + ScalarStuff.AddMaybeF32(builder, maybe_f32); + ScalarStuff.AddJustF32(builder, just_f32); + ScalarStuff.AddDefaultU32(builder, default_u32); + ScalarStuff.AddMaybeU32(builder, maybe_u32); + ScalarStuff.AddJustU32(builder, just_u32); + ScalarStuff.AddDefaultI32(builder, default_i32); + ScalarStuff.AddMaybeI32(builder, maybe_i32); + ScalarStuff.AddJustI32(builder, just_i32); + ScalarStuff.AddDefaultU16(builder, default_u16); + ScalarStuff.AddMaybeU16(builder, maybe_u16); + ScalarStuff.AddJustU16(builder, just_u16); + ScalarStuff.AddDefaultI16(builder, default_i16); + ScalarStuff.AddMaybeI16(builder, maybe_i16); + ScalarStuff.AddJustI16(builder, just_i16); + ScalarStuff.AddDefaultEnum(builder, default_enum); + ScalarStuff.AddMaybeEnum(builder, maybe_enum); + ScalarStuff.AddJustEnum(builder, just_enum); + ScalarStuff.AddDefaultBool(builder, default_bool); + ScalarStuff.AddMaybeBool(builder, maybe_bool); + ScalarStuff.AddJustBool(builder, just_bool); + ScalarStuff.AddDefaultU8(builder, default_u8); + ScalarStuff.AddMaybeU8(builder, maybe_u8); + ScalarStuff.AddJustU8(builder, just_u8); + ScalarStuff.AddDefaultI8(builder, default_i8); + ScalarStuff.AddMaybeI8(builder, maybe_i8); + ScalarStuff.AddJustI8(builder, just_i8); + return ScalarStuff.EndScalarStuff(builder); + } + + public static void StartScalarStuff(FlatBufferBuilder builder) { builder.StartTable(36); } + public static void AddJustI8(FlatBufferBuilder builder, sbyte justI8) { builder.AddSbyte(0, justI8, 0); } + public static void AddMaybeI8(FlatBufferBuilder builder, sbyte? maybeI8) { builder.AddSbyte(1, maybeI8); } + public static void AddDefaultI8(FlatBufferBuilder builder, sbyte defaultI8) { builder.AddSbyte(2, defaultI8, 42); } + public static void AddJustU8(FlatBufferBuilder builder, byte justU8) { builder.AddByte(3, justU8, 0); } + public static void AddMaybeU8(FlatBufferBuilder builder, byte? maybeU8) { builder.AddByte(4, maybeU8); } + public static void AddDefaultU8(FlatBufferBuilder builder, byte defaultU8) { builder.AddByte(5, defaultU8, 42); } + public static void AddJustI16(FlatBufferBuilder builder, short justI16) { builder.AddShort(6, justI16, 0); } + public static void AddMaybeI16(FlatBufferBuilder builder, short? maybeI16) { builder.AddShort(7, maybeI16); } + public static void AddDefaultI16(FlatBufferBuilder builder, short defaultI16) { builder.AddShort(8, defaultI16, 42); } + public static void AddJustU16(FlatBufferBuilder builder, ushort justU16) { builder.AddUshort(9, justU16, 0); } + public static void AddMaybeU16(FlatBufferBuilder builder, ushort? maybeU16) { builder.AddUshort(10, maybeU16); } + public static void AddDefaultU16(FlatBufferBuilder builder, ushort defaultU16) { builder.AddUshort(11, defaultU16, 42); } + public static void AddJustI32(FlatBufferBuilder builder, int justI32) { builder.AddInt(12, justI32, 0); } + public static void AddMaybeI32(FlatBufferBuilder builder, int? maybeI32) { builder.AddInt(13, maybeI32); } + public static void AddDefaultI32(FlatBufferBuilder builder, int defaultI32) { builder.AddInt(14, defaultI32, 42); } + public static void AddJustU32(FlatBufferBuilder builder, uint justU32) { builder.AddUint(15, justU32, 0); } + public static void AddMaybeU32(FlatBufferBuilder builder, uint? maybeU32) { builder.AddUint(16, maybeU32); } + public static void AddDefaultU32(FlatBufferBuilder builder, uint defaultU32) { builder.AddUint(17, defaultU32, 42); } + public static void AddJustI64(FlatBufferBuilder builder, long justI64) { builder.AddLong(18, justI64, 0); } + public static void AddMaybeI64(FlatBufferBuilder builder, long? maybeI64) { builder.AddLong(19, maybeI64); } + public static void AddDefaultI64(FlatBufferBuilder builder, long defaultI64) { builder.AddLong(20, defaultI64, 42); } + public static void AddJustU64(FlatBufferBuilder builder, ulong justU64) { builder.AddUlong(21, justU64, 0); } + public static void AddMaybeU64(FlatBufferBuilder builder, ulong? maybeU64) { builder.AddUlong(22, maybeU64); } + public static void AddDefaultU64(FlatBufferBuilder builder, ulong defaultU64) { builder.AddUlong(23, defaultU64, 42); } + public static void AddJustF32(FlatBufferBuilder builder, float justF32) { builder.AddFloat(24, justF32, 0.0f); } + public static void AddMaybeF32(FlatBufferBuilder builder, float? maybeF32) { builder.AddFloat(25, maybeF32); } + public static void AddDefaultF32(FlatBufferBuilder builder, float defaultF32) { builder.AddFloat(26, defaultF32, 42.0f); } + public static void AddJustF64(FlatBufferBuilder builder, double justF64) { builder.AddDouble(27, justF64, 0.0); } + public static void AddMaybeF64(FlatBufferBuilder builder, double? maybeF64) { builder.AddDouble(28, maybeF64); } + public static void AddDefaultF64(FlatBufferBuilder builder, double defaultF64) { builder.AddDouble(29, defaultF64, 42.0); } + public static void AddJustBool(FlatBufferBuilder builder, bool justBool) { builder.AddBool(30, justBool, false); } + public static void AddMaybeBool(FlatBufferBuilder builder, bool? maybeBool) { builder.AddBool(31, maybeBool); } + public static void AddDefaultBool(FlatBufferBuilder builder, bool defaultBool) { builder.AddBool(32, defaultBool, true); } + public static void AddJustEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte justEnum) { builder.AddSbyte(33, (sbyte)justEnum, 0); } + public static void AddMaybeEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte? maybeEnum) { builder.AddSbyte(34, (sbyte?)maybeEnum); } + public static void AddDefaultEnum(FlatBufferBuilder builder, optional_scalars.OptionalByte defaultEnum) { builder.AddSbyte(35, (sbyte)defaultEnum, 1); } + public static Offset EndScalarStuff(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishScalarStuffBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value, "NULL"); } + public static void FinishSizePrefixedScalarStuffBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value, "NULL"); } + public ScalarStuffT UnPack() { + var _o = new ScalarStuffT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(ScalarStuffT _o) { + _o.JustI8 = this.JustI8; + _o.MaybeI8 = this.MaybeI8; + _o.DefaultI8 = this.DefaultI8; + _o.JustU8 = this.JustU8; + _o.MaybeU8 = this.MaybeU8; + _o.DefaultU8 = this.DefaultU8; + _o.JustI16 = this.JustI16; + _o.MaybeI16 = this.MaybeI16; + _o.DefaultI16 = this.DefaultI16; + _o.JustU16 = this.JustU16; + _o.MaybeU16 = this.MaybeU16; + _o.DefaultU16 = this.DefaultU16; + _o.JustI32 = this.JustI32; + _o.MaybeI32 = this.MaybeI32; + _o.DefaultI32 = this.DefaultI32; + _o.JustU32 = this.JustU32; + _o.MaybeU32 = this.MaybeU32; + _o.DefaultU32 = this.DefaultU32; + _o.JustI64 = this.JustI64; + _o.MaybeI64 = this.MaybeI64; + _o.DefaultI64 = this.DefaultI64; + _o.JustU64 = this.JustU64; + _o.MaybeU64 = this.MaybeU64; + _o.DefaultU64 = this.DefaultU64; + _o.JustF32 = this.JustF32; + _o.MaybeF32 = this.MaybeF32; + _o.DefaultF32 = this.DefaultF32; + _o.JustF64 = this.JustF64; + _o.MaybeF64 = this.MaybeF64; + _o.DefaultF64 = this.DefaultF64; + _o.JustBool = this.JustBool; + _o.MaybeBool = this.MaybeBool; + _o.DefaultBool = this.DefaultBool; + _o.JustEnum = this.JustEnum; + _o.MaybeEnum = this.MaybeEnum; + _o.DefaultEnum = this.DefaultEnum; + } + public static Offset Pack(FlatBufferBuilder builder, ScalarStuffT _o) { + if (_o == null) return default(Offset); + return CreateScalarStuff( + builder, + _o.JustI8, + _o.MaybeI8, + _o.DefaultI8, + _o.JustU8, + _o.MaybeU8, + _o.DefaultU8, + _o.JustI16, + _o.MaybeI16, + _o.DefaultI16, + _o.JustU16, + _o.MaybeU16, + _o.DefaultU16, + _o.JustI32, + _o.MaybeI32, + _o.DefaultI32, + _o.JustU32, + _o.MaybeU32, + _o.DefaultU32, + _o.JustI64, + _o.MaybeI64, + _o.DefaultI64, + _o.JustU64, + _o.MaybeU64, + _o.DefaultU64, + _o.JustF32, + _o.MaybeF32, + _o.DefaultF32, + _o.JustF64, + _o.MaybeF64, + _o.DefaultF64, + _o.JustBool, + _o.MaybeBool, + _o.DefaultBool, + _o.JustEnum, + _o.MaybeEnum, + _o.DefaultEnum); + } +} + +public class ScalarStuffT +{ + public sbyte JustI8 { get; set; } + public sbyte? MaybeI8 { get; set; } + public sbyte DefaultI8 { get; set; } + public byte JustU8 { get; set; } + public byte? MaybeU8 { get; set; } + public byte DefaultU8 { get; set; } + public short JustI16 { get; set; } + public short? MaybeI16 { get; set; } + public short DefaultI16 { get; set; } + public ushort JustU16 { get; set; } + public ushort? MaybeU16 { get; set; } + public ushort DefaultU16 { get; set; } + public int JustI32 { get; set; } + public int? MaybeI32 { get; set; } + public int DefaultI32 { get; set; } + public uint JustU32 { get; set; } + public uint? MaybeU32 { get; set; } + public uint DefaultU32 { get; set; } + public long JustI64 { get; set; } + public long? MaybeI64 { get; set; } + public long DefaultI64 { get; set; } + public ulong JustU64 { get; set; } + public ulong? MaybeU64 { get; set; } + public ulong DefaultU64 { get; set; } + public float JustF32 { get; set; } + public float? MaybeF32 { get; set; } + public float DefaultF32 { get; set; } + public double JustF64 { get; set; } + public double? MaybeF64 { get; set; } + public double DefaultF64 { get; set; } + public bool JustBool { get; set; } + public bool? MaybeBool { get; set; } + public bool DefaultBool { get; set; } + public optional_scalars.OptionalByte JustEnum { get; set; } + public optional_scalars.OptionalByte? MaybeEnum { get; set; } + public optional_scalars.OptionalByte DefaultEnum { get; set; } + + public ScalarStuffT() { + this.JustI8 = 0; + this.MaybeI8 = null; + this.DefaultI8 = 42; + this.JustU8 = 0; + this.MaybeU8 = null; + this.DefaultU8 = 42; + this.JustI16 = 0; + this.MaybeI16 = null; + this.DefaultI16 = 42; + this.JustU16 = 0; + this.MaybeU16 = null; + this.DefaultU16 = 42; + this.JustI32 = 0; + this.MaybeI32 = null; + this.DefaultI32 = 42; + this.JustU32 = 0; + this.MaybeU32 = null; + this.DefaultU32 = 42; + this.JustI64 = 0; + this.MaybeI64 = null; + this.DefaultI64 = 42; + this.JustU64 = 0; + this.MaybeU64 = null; + this.DefaultU64 = 42; + this.JustF32 = 0.0f; + this.MaybeF32 = null; + this.DefaultF32 = 42.0f; + this.JustF64 = 0.0; + this.MaybeF64 = null; + this.DefaultF64 = 42.0; + this.JustBool = false; + this.MaybeBool = null; + this.DefaultBool = true; + this.JustEnum = optional_scalars.OptionalByte.None; + this.MaybeEnum = null; + this.DefaultEnum = optional_scalars.OptionalByte.One; + } + public static ScalarStuffT DeserializeFromBinary(byte[] fbBuffer) { + return ScalarStuff.GetRootAsScalarStuff(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + ScalarStuff.FinishScalarStuffBuffer(fbb, ScalarStuff.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class ScalarStuffVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*JustI8*/, 1 /*sbyte*/, 1, false) + && verifier.VerifyField(tablePos, 6 /*MaybeI8*/, 1 /*sbyte*/, 1, false) + && verifier.VerifyField(tablePos, 8 /*DefaultI8*/, 1 /*sbyte*/, 1, false) + && verifier.VerifyField(tablePos, 10 /*JustU8*/, 1 /*byte*/, 1, false) + && verifier.VerifyField(tablePos, 12 /*MaybeU8*/, 1 /*byte*/, 1, false) + && verifier.VerifyField(tablePos, 14 /*DefaultU8*/, 1 /*byte*/, 1, false) + && verifier.VerifyField(tablePos, 16 /*JustI16*/, 2 /*short*/, 2, false) + && verifier.VerifyField(tablePos, 18 /*MaybeI16*/, 2 /*short*/, 2, false) + && verifier.VerifyField(tablePos, 20 /*DefaultI16*/, 2 /*short*/, 2, false) + && verifier.VerifyField(tablePos, 22 /*JustU16*/, 2 /*ushort*/, 2, false) + && verifier.VerifyField(tablePos, 24 /*MaybeU16*/, 2 /*ushort*/, 2, false) + && verifier.VerifyField(tablePos, 26 /*DefaultU16*/, 2 /*ushort*/, 2, false) + && verifier.VerifyField(tablePos, 28 /*JustI32*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 30 /*MaybeI32*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 32 /*DefaultI32*/, 4 /*int*/, 4, false) + && verifier.VerifyField(tablePos, 34 /*JustU32*/, 4 /*uint*/, 4, false) + && verifier.VerifyField(tablePos, 36 /*MaybeU32*/, 4 /*uint*/, 4, false) + && verifier.VerifyField(tablePos, 38 /*DefaultU32*/, 4 /*uint*/, 4, false) + && verifier.VerifyField(tablePos, 40 /*JustI64*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 42 /*MaybeI64*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 44 /*DefaultI64*/, 8 /*long*/, 8, false) + && verifier.VerifyField(tablePos, 46 /*JustU64*/, 8 /*ulong*/, 8, false) + && verifier.VerifyField(tablePos, 48 /*MaybeU64*/, 8 /*ulong*/, 8, false) + && verifier.VerifyField(tablePos, 50 /*DefaultU64*/, 8 /*ulong*/, 8, false) + && verifier.VerifyField(tablePos, 52 /*JustF32*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 54 /*MaybeF32*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 56 /*DefaultF32*/, 4 /*float*/, 4, false) + && verifier.VerifyField(tablePos, 58 /*JustF64*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 60 /*MaybeF64*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 62 /*DefaultF64*/, 8 /*double*/, 8, false) + && verifier.VerifyField(tablePos, 64 /*JustBool*/, 1 /*bool*/, 1, false) + && verifier.VerifyField(tablePos, 66 /*MaybeBool*/, 1 /*bool*/, 1, false) + && verifier.VerifyField(tablePos, 68 /*DefaultBool*/, 1 /*bool*/, 1, false) + && verifier.VerifyField(tablePos, 70 /*JustEnum*/, 1 /*optional_scalars.OptionalByte*/, 1, false) + && verifier.VerifyField(tablePos, 72 /*MaybeEnum*/, 1 /*optional_scalars.OptionalByte*/, 1, false) + && verifier.VerifyField(tablePos, 74 /*DefaultEnum*/, 1 /*optional_scalars.OptionalByte*/, 1, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.go b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.go new file mode 100644 index 00000000000..8b56567cab8 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.go @@ -0,0 +1,756 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package optional_scalars + +import ( + flatbuffers "github.com/google/flatbuffers/go" +) + +type ScalarStuffT struct { + JustI8 int8 `json:"just_i8"` + MaybeI8 *int8 `json:"maybe_i8"` + DefaultI8 int8 `json:"default_i8"` + JustU8 byte `json:"just_u8"` + MaybeU8 *byte `json:"maybe_u8"` + DefaultU8 byte `json:"default_u8"` + JustI16 int16 `json:"just_i16"` + MaybeI16 *int16 `json:"maybe_i16"` + DefaultI16 int16 `json:"default_i16"` + JustU16 uint16 `json:"just_u16"` + MaybeU16 *uint16 `json:"maybe_u16"` + DefaultU16 uint16 `json:"default_u16"` + JustI32 int32 `json:"just_i32"` + MaybeI32 *int32 `json:"maybe_i32"` + DefaultI32 int32 `json:"default_i32"` + JustU32 uint32 `json:"just_u32"` + MaybeU32 *uint32 `json:"maybe_u32"` + DefaultU32 uint32 `json:"default_u32"` + JustI64 int64 `json:"just_i64"` + MaybeI64 *int64 `json:"maybe_i64"` + DefaultI64 int64 `json:"default_i64"` + JustU64 uint64 `json:"just_u64"` + MaybeU64 *uint64 `json:"maybe_u64"` + DefaultU64 uint64 `json:"default_u64"` + JustF32 float32 `json:"just_f32"` + MaybeF32 *float32 `json:"maybe_f32"` + DefaultF32 float32 `json:"default_f32"` + JustF64 float64 `json:"just_f64"` + MaybeF64 *float64 `json:"maybe_f64"` + DefaultF64 float64 `json:"default_f64"` + JustBool bool `json:"just_bool"` + MaybeBool *bool `json:"maybe_bool"` + DefaultBool bool `json:"default_bool"` + JustEnum OptionalByte `json:"just_enum"` + MaybeEnum *OptionalByte `json:"maybe_enum"` + DefaultEnum OptionalByte `json:"default_enum"` +} + +func (t *ScalarStuffT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + ScalarStuffStart(builder) + ScalarStuffAddJustI8(builder, t.JustI8) + if t.MaybeI8 != nil { + ScalarStuffAddMaybeI8(builder, *t.MaybeI8) + } + ScalarStuffAddDefaultI8(builder, t.DefaultI8) + ScalarStuffAddJustU8(builder, t.JustU8) + if t.MaybeU8 != nil { + ScalarStuffAddMaybeU8(builder, *t.MaybeU8) + } + ScalarStuffAddDefaultU8(builder, t.DefaultU8) + ScalarStuffAddJustI16(builder, t.JustI16) + if t.MaybeI16 != nil { + ScalarStuffAddMaybeI16(builder, *t.MaybeI16) + } + ScalarStuffAddDefaultI16(builder, t.DefaultI16) + ScalarStuffAddJustU16(builder, t.JustU16) + if t.MaybeU16 != nil { + ScalarStuffAddMaybeU16(builder, *t.MaybeU16) + } + ScalarStuffAddDefaultU16(builder, t.DefaultU16) + ScalarStuffAddJustI32(builder, t.JustI32) + if t.MaybeI32 != nil { + ScalarStuffAddMaybeI32(builder, *t.MaybeI32) + } + ScalarStuffAddDefaultI32(builder, t.DefaultI32) + ScalarStuffAddJustU32(builder, t.JustU32) + if t.MaybeU32 != nil { + ScalarStuffAddMaybeU32(builder, *t.MaybeU32) + } + ScalarStuffAddDefaultU32(builder, t.DefaultU32) + ScalarStuffAddJustI64(builder, t.JustI64) + if t.MaybeI64 != nil { + ScalarStuffAddMaybeI64(builder, *t.MaybeI64) + } + ScalarStuffAddDefaultI64(builder, t.DefaultI64) + ScalarStuffAddJustU64(builder, t.JustU64) + if t.MaybeU64 != nil { + ScalarStuffAddMaybeU64(builder, *t.MaybeU64) + } + ScalarStuffAddDefaultU64(builder, t.DefaultU64) + ScalarStuffAddJustF32(builder, t.JustF32) + if t.MaybeF32 != nil { + ScalarStuffAddMaybeF32(builder, *t.MaybeF32) + } + ScalarStuffAddDefaultF32(builder, t.DefaultF32) + ScalarStuffAddJustF64(builder, t.JustF64) + if t.MaybeF64 != nil { + ScalarStuffAddMaybeF64(builder, *t.MaybeF64) + } + ScalarStuffAddDefaultF64(builder, t.DefaultF64) + ScalarStuffAddJustBool(builder, t.JustBool) + if t.MaybeBool != nil { + ScalarStuffAddMaybeBool(builder, *t.MaybeBool) + } + ScalarStuffAddDefaultBool(builder, t.DefaultBool) + ScalarStuffAddJustEnum(builder, t.JustEnum) + if t.MaybeEnum != nil { + ScalarStuffAddMaybeEnum(builder, *t.MaybeEnum) + } + ScalarStuffAddDefaultEnum(builder, t.DefaultEnum) + return ScalarStuffEnd(builder) +} + +func (rcv *ScalarStuff) UnPackTo(t *ScalarStuffT) { + t.JustI8 = rcv.JustI8() + t.MaybeI8 = rcv.MaybeI8() + t.DefaultI8 = rcv.DefaultI8() + t.JustU8 = rcv.JustU8() + t.MaybeU8 = rcv.MaybeU8() + t.DefaultU8 = rcv.DefaultU8() + t.JustI16 = rcv.JustI16() + t.MaybeI16 = rcv.MaybeI16() + t.DefaultI16 = rcv.DefaultI16() + t.JustU16 = rcv.JustU16() + t.MaybeU16 = rcv.MaybeU16() + t.DefaultU16 = rcv.DefaultU16() + t.JustI32 = rcv.JustI32() + t.MaybeI32 = rcv.MaybeI32() + t.DefaultI32 = rcv.DefaultI32() + t.JustU32 = rcv.JustU32() + t.MaybeU32 = rcv.MaybeU32() + t.DefaultU32 = rcv.DefaultU32() + t.JustI64 = rcv.JustI64() + t.MaybeI64 = rcv.MaybeI64() + t.DefaultI64 = rcv.DefaultI64() + t.JustU64 = rcv.JustU64() + t.MaybeU64 = rcv.MaybeU64() + t.DefaultU64 = rcv.DefaultU64() + t.JustF32 = rcv.JustF32() + t.MaybeF32 = rcv.MaybeF32() + t.DefaultF32 = rcv.DefaultF32() + t.JustF64 = rcv.JustF64() + t.MaybeF64 = rcv.MaybeF64() + t.DefaultF64 = rcv.DefaultF64() + t.JustBool = rcv.JustBool() + t.MaybeBool = rcv.MaybeBool() + t.DefaultBool = rcv.DefaultBool() + t.JustEnum = rcv.JustEnum() + t.MaybeEnum = rcv.MaybeEnum() + t.DefaultEnum = rcv.DefaultEnum() +} + +func (rcv *ScalarStuff) UnPack() *ScalarStuffT { + if rcv == nil { return nil } + t := &ScalarStuffT{} + rcv.UnPackTo(t) + return t +} + +type ScalarStuff struct { + _tab flatbuffers.Table +} + +func GetRootAsScalarStuff(buf []byte, offset flatbuffers.UOffsetT) *ScalarStuff { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &ScalarStuff{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsScalarStuff(buf []byte, offset flatbuffers.UOffsetT) *ScalarStuff { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &ScalarStuff{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *ScalarStuff) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *ScalarStuff) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *ScalarStuff) JustI8() int8 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + return rcv._tab.GetInt8(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustI8(n int8) bool { + return rcv._tab.MutateInt8Slot(4, n) +} + +func (rcv *ScalarStuff) MaybeI8() *int8 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + v := rcv._tab.GetInt8(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeI8(n int8) bool { + return rcv._tab.MutateInt8Slot(6, n) +} + +func (rcv *ScalarStuff) DefaultI8() int8 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(8)) + if o != 0 { + return rcv._tab.GetInt8(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultI8(n int8) bool { + return rcv._tab.MutateInt8Slot(8, n) +} + +func (rcv *ScalarStuff) JustU8() byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(10)) + if o != 0 { + return rcv._tab.GetByte(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustU8(n byte) bool { + return rcv._tab.MutateByteSlot(10, n) +} + +func (rcv *ScalarStuff) MaybeU8() *byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(12)) + if o != 0 { + v := rcv._tab.GetByte(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeU8(n byte) bool { + return rcv._tab.MutateByteSlot(12, n) +} + +func (rcv *ScalarStuff) DefaultU8() byte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(14)) + if o != 0 { + return rcv._tab.GetByte(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultU8(n byte) bool { + return rcv._tab.MutateByteSlot(14, n) +} + +func (rcv *ScalarStuff) JustI16() int16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(16)) + if o != 0 { + return rcv._tab.GetInt16(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustI16(n int16) bool { + return rcv._tab.MutateInt16Slot(16, n) +} + +func (rcv *ScalarStuff) MaybeI16() *int16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(18)) + if o != 0 { + v := rcv._tab.GetInt16(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeI16(n int16) bool { + return rcv._tab.MutateInt16Slot(18, n) +} + +func (rcv *ScalarStuff) DefaultI16() int16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(20)) + if o != 0 { + return rcv._tab.GetInt16(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultI16(n int16) bool { + return rcv._tab.MutateInt16Slot(20, n) +} + +func (rcv *ScalarStuff) JustU16() uint16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(22)) + if o != 0 { + return rcv._tab.GetUint16(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustU16(n uint16) bool { + return rcv._tab.MutateUint16Slot(22, n) +} + +func (rcv *ScalarStuff) MaybeU16() *uint16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(24)) + if o != 0 { + v := rcv._tab.GetUint16(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeU16(n uint16) bool { + return rcv._tab.MutateUint16Slot(24, n) +} + +func (rcv *ScalarStuff) DefaultU16() uint16 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(26)) + if o != 0 { + return rcv._tab.GetUint16(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultU16(n uint16) bool { + return rcv._tab.MutateUint16Slot(26, n) +} + +func (rcv *ScalarStuff) JustI32() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(28)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustI32(n int32) bool { + return rcv._tab.MutateInt32Slot(28, n) +} + +func (rcv *ScalarStuff) MaybeI32() *int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(30)) + if o != 0 { + v := rcv._tab.GetInt32(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeI32(n int32) bool { + return rcv._tab.MutateInt32Slot(30, n) +} + +func (rcv *ScalarStuff) DefaultI32() int32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(32)) + if o != 0 { + return rcv._tab.GetInt32(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultI32(n int32) bool { + return rcv._tab.MutateInt32Slot(32, n) +} + +func (rcv *ScalarStuff) JustU32() uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(34)) + if o != 0 { + return rcv._tab.GetUint32(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustU32(n uint32) bool { + return rcv._tab.MutateUint32Slot(34, n) +} + +func (rcv *ScalarStuff) MaybeU32() *uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(36)) + if o != 0 { + v := rcv._tab.GetUint32(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeU32(n uint32) bool { + return rcv._tab.MutateUint32Slot(36, n) +} + +func (rcv *ScalarStuff) DefaultU32() uint32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(38)) + if o != 0 { + return rcv._tab.GetUint32(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultU32(n uint32) bool { + return rcv._tab.MutateUint32Slot(38, n) +} + +func (rcv *ScalarStuff) JustI64() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(40)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustI64(n int64) bool { + return rcv._tab.MutateInt64Slot(40, n) +} + +func (rcv *ScalarStuff) MaybeI64() *int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(42)) + if o != 0 { + v := rcv._tab.GetInt64(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeI64(n int64) bool { + return rcv._tab.MutateInt64Slot(42, n) +} + +func (rcv *ScalarStuff) DefaultI64() int64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(44)) + if o != 0 { + return rcv._tab.GetInt64(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultI64(n int64) bool { + return rcv._tab.MutateInt64Slot(44, n) +} + +func (rcv *ScalarStuff) JustU64() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(46)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustU64(n uint64) bool { + return rcv._tab.MutateUint64Slot(46, n) +} + +func (rcv *ScalarStuff) MaybeU64() *uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(48)) + if o != 0 { + v := rcv._tab.GetUint64(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeU64(n uint64) bool { + return rcv._tab.MutateUint64Slot(48, n) +} + +func (rcv *ScalarStuff) DefaultU64() uint64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(50)) + if o != 0 { + return rcv._tab.GetUint64(o + rcv._tab.Pos) + } + return 42 +} + +func (rcv *ScalarStuff) MutateDefaultU64(n uint64) bool { + return rcv._tab.MutateUint64Slot(50, n) +} + +func (rcv *ScalarStuff) JustF32() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(52)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return 0.0 +} + +func (rcv *ScalarStuff) MutateJustF32(n float32) bool { + return rcv._tab.MutateFloat32Slot(52, n) +} + +func (rcv *ScalarStuff) MaybeF32() *float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(54)) + if o != 0 { + v := rcv._tab.GetFloat32(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeF32(n float32) bool { + return rcv._tab.MutateFloat32Slot(54, n) +} + +func (rcv *ScalarStuff) DefaultF32() float32 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(56)) + if o != 0 { + return rcv._tab.GetFloat32(o + rcv._tab.Pos) + } + return 42.0 +} + +func (rcv *ScalarStuff) MutateDefaultF32(n float32) bool { + return rcv._tab.MutateFloat32Slot(56, n) +} + +func (rcv *ScalarStuff) JustF64() float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(58)) + if o != 0 { + return rcv._tab.GetFloat64(o + rcv._tab.Pos) + } + return 0.0 +} + +func (rcv *ScalarStuff) MutateJustF64(n float64) bool { + return rcv._tab.MutateFloat64Slot(58, n) +} + +func (rcv *ScalarStuff) MaybeF64() *float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(60)) + if o != 0 { + v := rcv._tab.GetFloat64(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeF64(n float64) bool { + return rcv._tab.MutateFloat64Slot(60, n) +} + +func (rcv *ScalarStuff) DefaultF64() float64 { + o := flatbuffers.UOffsetT(rcv._tab.Offset(62)) + if o != 0 { + return rcv._tab.GetFloat64(o + rcv._tab.Pos) + } + return 42.0 +} + +func (rcv *ScalarStuff) MutateDefaultF64(n float64) bool { + return rcv._tab.MutateFloat64Slot(62, n) +} + +func (rcv *ScalarStuff) JustBool() bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(64)) + if o != 0 { + return rcv._tab.GetBool(o + rcv._tab.Pos) + } + return false +} + +func (rcv *ScalarStuff) MutateJustBool(n bool) bool { + return rcv._tab.MutateBoolSlot(64, n) +} + +func (rcv *ScalarStuff) MaybeBool() *bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(66)) + if o != 0 { + v := rcv._tab.GetBool(o + rcv._tab.Pos) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeBool(n bool) bool { + return rcv._tab.MutateBoolSlot(66, n) +} + +func (rcv *ScalarStuff) DefaultBool() bool { + o := flatbuffers.UOffsetT(rcv._tab.Offset(68)) + if o != 0 { + return rcv._tab.GetBool(o + rcv._tab.Pos) + } + return true +} + +func (rcv *ScalarStuff) MutateDefaultBool(n bool) bool { + return rcv._tab.MutateBoolSlot(68, n) +} + +func (rcv *ScalarStuff) JustEnum() OptionalByte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(70)) + if o != 0 { + return OptionalByte(rcv._tab.GetInt8(o + rcv._tab.Pos)) + } + return 0 +} + +func (rcv *ScalarStuff) MutateJustEnum(n OptionalByte) bool { + return rcv._tab.MutateInt8Slot(70, int8(n)) +} + +func (rcv *ScalarStuff) MaybeEnum() *OptionalByte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(72)) + if o != 0 { + v := OptionalByte(rcv._tab.GetInt8(o + rcv._tab.Pos)) + return &v + } + return nil +} + +func (rcv *ScalarStuff) MutateMaybeEnum(n OptionalByte) bool { + return rcv._tab.MutateInt8Slot(72, int8(n)) +} + +func (rcv *ScalarStuff) DefaultEnum() OptionalByte { + o := flatbuffers.UOffsetT(rcv._tab.Offset(74)) + if o != 0 { + return OptionalByte(rcv._tab.GetInt8(o + rcv._tab.Pos)) + } + return 1 +} + +func (rcv *ScalarStuff) MutateDefaultEnum(n OptionalByte) bool { + return rcv._tab.MutateInt8Slot(74, int8(n)) +} + +func ScalarStuffStart(builder *flatbuffers.Builder) { + builder.StartObject(36) +} +func ScalarStuffAddJustI8(builder *flatbuffers.Builder, justI8 int8) { + builder.PrependInt8Slot(0, justI8, 0) +} +func ScalarStuffAddMaybeI8(builder *flatbuffers.Builder, maybeI8 int8) { + builder.PrependInt8(maybeI8) + builder.Slot(1) +} +func ScalarStuffAddDefaultI8(builder *flatbuffers.Builder, defaultI8 int8) { + builder.PrependInt8Slot(2, defaultI8, 42) +} +func ScalarStuffAddJustU8(builder *flatbuffers.Builder, justU8 byte) { + builder.PrependByteSlot(3, justU8, 0) +} +func ScalarStuffAddMaybeU8(builder *flatbuffers.Builder, maybeU8 byte) { + builder.PrependByte(maybeU8) + builder.Slot(4) +} +func ScalarStuffAddDefaultU8(builder *flatbuffers.Builder, defaultU8 byte) { + builder.PrependByteSlot(5, defaultU8, 42) +} +func ScalarStuffAddJustI16(builder *flatbuffers.Builder, justI16 int16) { + builder.PrependInt16Slot(6, justI16, 0) +} +func ScalarStuffAddMaybeI16(builder *flatbuffers.Builder, maybeI16 int16) { + builder.PrependInt16(maybeI16) + builder.Slot(7) +} +func ScalarStuffAddDefaultI16(builder *flatbuffers.Builder, defaultI16 int16) { + builder.PrependInt16Slot(8, defaultI16, 42) +} +func ScalarStuffAddJustU16(builder *flatbuffers.Builder, justU16 uint16) { + builder.PrependUint16Slot(9, justU16, 0) +} +func ScalarStuffAddMaybeU16(builder *flatbuffers.Builder, maybeU16 uint16) { + builder.PrependUint16(maybeU16) + builder.Slot(10) +} +func ScalarStuffAddDefaultU16(builder *flatbuffers.Builder, defaultU16 uint16) { + builder.PrependUint16Slot(11, defaultU16, 42) +} +func ScalarStuffAddJustI32(builder *flatbuffers.Builder, justI32 int32) { + builder.PrependInt32Slot(12, justI32, 0) +} +func ScalarStuffAddMaybeI32(builder *flatbuffers.Builder, maybeI32 int32) { + builder.PrependInt32(maybeI32) + builder.Slot(13) +} +func ScalarStuffAddDefaultI32(builder *flatbuffers.Builder, defaultI32 int32) { + builder.PrependInt32Slot(14, defaultI32, 42) +} +func ScalarStuffAddJustU32(builder *flatbuffers.Builder, justU32 uint32) { + builder.PrependUint32Slot(15, justU32, 0) +} +func ScalarStuffAddMaybeU32(builder *flatbuffers.Builder, maybeU32 uint32) { + builder.PrependUint32(maybeU32) + builder.Slot(16) +} +func ScalarStuffAddDefaultU32(builder *flatbuffers.Builder, defaultU32 uint32) { + builder.PrependUint32Slot(17, defaultU32, 42) +} +func ScalarStuffAddJustI64(builder *flatbuffers.Builder, justI64 int64) { + builder.PrependInt64Slot(18, justI64, 0) +} +func ScalarStuffAddMaybeI64(builder *flatbuffers.Builder, maybeI64 int64) { + builder.PrependInt64(maybeI64) + builder.Slot(19) +} +func ScalarStuffAddDefaultI64(builder *flatbuffers.Builder, defaultI64 int64) { + builder.PrependInt64Slot(20, defaultI64, 42) +} +func ScalarStuffAddJustU64(builder *flatbuffers.Builder, justU64 uint64) { + builder.PrependUint64Slot(21, justU64, 0) +} +func ScalarStuffAddMaybeU64(builder *flatbuffers.Builder, maybeU64 uint64) { + builder.PrependUint64(maybeU64) + builder.Slot(22) +} +func ScalarStuffAddDefaultU64(builder *flatbuffers.Builder, defaultU64 uint64) { + builder.PrependUint64Slot(23, defaultU64, 42) +} +func ScalarStuffAddJustF32(builder *flatbuffers.Builder, justF32 float32) { + builder.PrependFloat32Slot(24, justF32, 0.0) +} +func ScalarStuffAddMaybeF32(builder *flatbuffers.Builder, maybeF32 float32) { + builder.PrependFloat32(maybeF32) + builder.Slot(25) +} +func ScalarStuffAddDefaultF32(builder *flatbuffers.Builder, defaultF32 float32) { + builder.PrependFloat32Slot(26, defaultF32, 42.0) +} +func ScalarStuffAddJustF64(builder *flatbuffers.Builder, justF64 float64) { + builder.PrependFloat64Slot(27, justF64, 0.0) +} +func ScalarStuffAddMaybeF64(builder *flatbuffers.Builder, maybeF64 float64) { + builder.PrependFloat64(maybeF64) + builder.Slot(28) +} +func ScalarStuffAddDefaultF64(builder *flatbuffers.Builder, defaultF64 float64) { + builder.PrependFloat64Slot(29, defaultF64, 42.0) +} +func ScalarStuffAddJustBool(builder *flatbuffers.Builder, justBool bool) { + builder.PrependBoolSlot(30, justBool, false) +} +func ScalarStuffAddMaybeBool(builder *flatbuffers.Builder, maybeBool bool) { + builder.PrependBool(maybeBool) + builder.Slot(31) +} +func ScalarStuffAddDefaultBool(builder *flatbuffers.Builder, defaultBool bool) { + builder.PrependBoolSlot(32, defaultBool, true) +} +func ScalarStuffAddJustEnum(builder *flatbuffers.Builder, justEnum OptionalByte) { + builder.PrependInt8Slot(33, int8(justEnum), 0) +} +func ScalarStuffAddMaybeEnum(builder *flatbuffers.Builder, maybeEnum OptionalByte) { + builder.PrependInt8(int8(maybeEnum)) + builder.Slot(34) +} +func ScalarStuffAddDefaultEnum(builder *flatbuffers.Builder, defaultEnum OptionalByte) { + builder.PrependInt8Slot(35, int8(defaultEnum), 1) +} +func ScalarStuffEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.java b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.java new file mode 100644 index 00000000000..d288bd7241f --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.java @@ -0,0 +1,208 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package optional_scalars; + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class ScalarStuff extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static ScalarStuff getRootAsScalarStuff(ByteBuffer _bb) { return getRootAsScalarStuff(_bb, new ScalarStuff()); } + public static ScalarStuff getRootAsScalarStuff(ByteBuffer _bb, ScalarStuff obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public static boolean ScalarStuffBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "NULL"); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public ScalarStuff __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public byte justI8() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; } + public boolean hasMaybeI8() { return 0 != __offset(6); } + public byte maybeI8() { int o = __offset(6); return o != 0 ? bb.get(o + bb_pos) : 0; } + public byte defaultI8() { int o = __offset(8); return o != 0 ? bb.get(o + bb_pos) : 42; } + public int justU8() { int o = __offset(10); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 0; } + public boolean hasMaybeU8() { return 0 != __offset(12); } + public int maybeU8() { int o = __offset(12); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 0; } + public int defaultU8() { int o = __offset(14); return o != 0 ? bb.get(o + bb_pos) & 0xFF : 42; } + public short justI16() { int o = __offset(16); return o != 0 ? bb.getShort(o + bb_pos) : 0; } + public boolean hasMaybeI16() { return 0 != __offset(18); } + public short maybeI16() { int o = __offset(18); return o != 0 ? bb.getShort(o + bb_pos) : 0; } + public short defaultI16() { int o = __offset(20); return o != 0 ? bb.getShort(o + bb_pos) : 42; } + public int justU16() { int o = __offset(22); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + public boolean hasMaybeU16() { return 0 != __offset(24); } + public int maybeU16() { int o = __offset(24); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 0; } + public int defaultU16() { int o = __offset(26); return o != 0 ? bb.getShort(o + bb_pos) & 0xFFFF : 42; } + public int justI32() { int o = __offset(28); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean hasMaybeI32() { return 0 != __offset(30); } + public int maybeI32() { int o = __offset(30); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public int defaultI32() { int o = __offset(32); return o != 0 ? bb.getInt(o + bb_pos) : 42; } + public long justU32() { int o = __offset(34); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; } + public boolean hasMaybeU32() { return 0 != __offset(36); } + public long maybeU32() { int o = __offset(36); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 0L; } + public long defaultU32() { int o = __offset(38); return o != 0 ? (long)bb.getInt(o + bb_pos) & 0xFFFFFFFFL : 42L; } + public long justI64() { int o = __offset(40); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean hasMaybeI64() { return 0 != __offset(42); } + public long maybeI64() { int o = __offset(42); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public long defaultI64() { int o = __offset(44); return o != 0 ? bb.getLong(o + bb_pos) : 42L; } + public long justU64() { int o = __offset(46); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public boolean hasMaybeU64() { return 0 != __offset(48); } + public long maybeU64() { int o = __offset(48); return o != 0 ? bb.getLong(o + bb_pos) : 0L; } + public long defaultU64() { int o = __offset(50); return o != 0 ? bb.getLong(o + bb_pos) : 42L; } + public float justF32() { int o = __offset(52); return o != 0 ? bb.getFloat(o + bb_pos) : 0.0f; } + public boolean hasMaybeF32() { return 0 != __offset(54); } + public float maybeF32() { int o = __offset(54); return o != 0 ? bb.getFloat(o + bb_pos) : 0f; } + public float defaultF32() { int o = __offset(56); return o != 0 ? bb.getFloat(o + bb_pos) : 42.0f; } + public double justF64() { int o = __offset(58); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; } + public boolean hasMaybeF64() { return 0 != __offset(60); } + public double maybeF64() { int o = __offset(60); return o != 0 ? bb.getDouble(o + bb_pos) : 0.0; } + public double defaultF64() { int o = __offset(62); return o != 0 ? bb.getDouble(o + bb_pos) : 42.0; } + public boolean justBool() { int o = __offset(64); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public boolean hasMaybeBool() { return 0 != __offset(66); } + public boolean maybeBool() { int o = __offset(66); return o != 0 ? 0!=bb.get(o + bb_pos) : false; } + public boolean defaultBool() { int o = __offset(68); return o != 0 ? 0!=bb.get(o + bb_pos) : true; } + public byte justEnum() { int o = __offset(70); return o != 0 ? bb.get(o + bb_pos) : 0; } + public boolean hasMaybeEnum() { return 0 != __offset(72); } + public byte maybeEnum() { int o = __offset(72); return o != 0 ? bb.get(o + bb_pos) : 0; } + public byte defaultEnum() { int o = __offset(74); return o != 0 ? bb.get(o + bb_pos) : 1; } + + public static int createScalarStuff(FlatBufferBuilder builder, + byte justI8, + byte maybeI8, + byte defaultI8, + int justU8, + int maybeU8, + int defaultU8, + short justI16, + short maybeI16, + short defaultI16, + int justU16, + int maybeU16, + int defaultU16, + int justI32, + int maybeI32, + int defaultI32, + long justU32, + long maybeU32, + long defaultU32, + long justI64, + long maybeI64, + long defaultI64, + long justU64, + long maybeU64, + long defaultU64, + float justF32, + float maybeF32, + float defaultF32, + double justF64, + double maybeF64, + double defaultF64, + boolean justBool, + boolean maybeBool, + boolean defaultBool, + byte justEnum, + byte maybeEnum, + byte defaultEnum) { + builder.startTable(36); + ScalarStuff.addDefaultF64(builder, defaultF64); + ScalarStuff.addMaybeF64(builder, maybeF64); + ScalarStuff.addJustF64(builder, justF64); + ScalarStuff.addDefaultU64(builder, defaultU64); + ScalarStuff.addMaybeU64(builder, maybeU64); + ScalarStuff.addJustU64(builder, justU64); + ScalarStuff.addDefaultI64(builder, defaultI64); + ScalarStuff.addMaybeI64(builder, maybeI64); + ScalarStuff.addJustI64(builder, justI64); + ScalarStuff.addDefaultF32(builder, defaultF32); + ScalarStuff.addMaybeF32(builder, maybeF32); + ScalarStuff.addJustF32(builder, justF32); + ScalarStuff.addDefaultU32(builder, defaultU32); + ScalarStuff.addMaybeU32(builder, maybeU32); + ScalarStuff.addJustU32(builder, justU32); + ScalarStuff.addDefaultI32(builder, defaultI32); + ScalarStuff.addMaybeI32(builder, maybeI32); + ScalarStuff.addJustI32(builder, justI32); + ScalarStuff.addDefaultU16(builder, defaultU16); + ScalarStuff.addMaybeU16(builder, maybeU16); + ScalarStuff.addJustU16(builder, justU16); + ScalarStuff.addDefaultI16(builder, defaultI16); + ScalarStuff.addMaybeI16(builder, maybeI16); + ScalarStuff.addJustI16(builder, justI16); + ScalarStuff.addDefaultEnum(builder, defaultEnum); + ScalarStuff.addMaybeEnum(builder, maybeEnum); + ScalarStuff.addJustEnum(builder, justEnum); + ScalarStuff.addDefaultBool(builder, defaultBool); + ScalarStuff.addMaybeBool(builder, maybeBool); + ScalarStuff.addJustBool(builder, justBool); + ScalarStuff.addDefaultU8(builder, defaultU8); + ScalarStuff.addMaybeU8(builder, maybeU8); + ScalarStuff.addJustU8(builder, justU8); + ScalarStuff.addDefaultI8(builder, defaultI8); + ScalarStuff.addMaybeI8(builder, maybeI8); + ScalarStuff.addJustI8(builder, justI8); + return ScalarStuff.endScalarStuff(builder); + } + + public static void startScalarStuff(FlatBufferBuilder builder) { builder.startTable(36); } + public static void addJustI8(FlatBufferBuilder builder, byte justI8) { builder.addByte(0, justI8, 0); } + public static void addMaybeI8(FlatBufferBuilder builder, byte maybeI8) { builder.addByte(1, maybeI8, 0); } + public static void addDefaultI8(FlatBufferBuilder builder, byte defaultI8) { builder.addByte(2, defaultI8, 42); } + public static void addJustU8(FlatBufferBuilder builder, int justU8) { builder.addByte(3, (byte) justU8, (byte) 0); } + public static void addMaybeU8(FlatBufferBuilder builder, int maybeU8) { builder.addByte(4, (byte) maybeU8, (byte) 0); } + public static void addDefaultU8(FlatBufferBuilder builder, int defaultU8) { builder.addByte(5, (byte) defaultU8, (byte) 42); } + public static void addJustI16(FlatBufferBuilder builder, short justI16) { builder.addShort(6, justI16, 0); } + public static void addMaybeI16(FlatBufferBuilder builder, short maybeI16) { builder.addShort(7, maybeI16, 0); } + public static void addDefaultI16(FlatBufferBuilder builder, short defaultI16) { builder.addShort(8, defaultI16, 42); } + public static void addJustU16(FlatBufferBuilder builder, int justU16) { builder.addShort(9, (short) justU16, (short) 0); } + public static void addMaybeU16(FlatBufferBuilder builder, int maybeU16) { builder.addShort(10, (short) maybeU16, (short) 0); } + public static void addDefaultU16(FlatBufferBuilder builder, int defaultU16) { builder.addShort(11, (short) defaultU16, (short) 42); } + public static void addJustI32(FlatBufferBuilder builder, int justI32) { builder.addInt(12, justI32, 0); } + public static void addMaybeI32(FlatBufferBuilder builder, int maybeI32) { builder.addInt(13, maybeI32, 0); } + public static void addDefaultI32(FlatBufferBuilder builder, int defaultI32) { builder.addInt(14, defaultI32, 42); } + public static void addJustU32(FlatBufferBuilder builder, long justU32) { builder.addInt(15, (int) justU32, (int) 0L); } + public static void addMaybeU32(FlatBufferBuilder builder, long maybeU32) { builder.addInt(16, (int) maybeU32, (int) 0L); } + public static void addDefaultU32(FlatBufferBuilder builder, long defaultU32) { builder.addInt(17, (int) defaultU32, (int) 42L); } + public static void addJustI64(FlatBufferBuilder builder, long justI64) { builder.addLong(18, justI64, 0L); } + public static void addMaybeI64(FlatBufferBuilder builder, long maybeI64) { builder.addLong(19, maybeI64, 0L); } + public static void addDefaultI64(FlatBufferBuilder builder, long defaultI64) { builder.addLong(20, defaultI64, 42L); } + public static void addJustU64(FlatBufferBuilder builder, long justU64) { builder.addLong(21, justU64, 0L); } + public static void addMaybeU64(FlatBufferBuilder builder, long maybeU64) { builder.addLong(22, maybeU64, 0L); } + public static void addDefaultU64(FlatBufferBuilder builder, long defaultU64) { builder.addLong(23, defaultU64, 42L); } + public static void addJustF32(FlatBufferBuilder builder, float justF32) { builder.addFloat(24, justF32, 0.0f); } + public static void addMaybeF32(FlatBufferBuilder builder, float maybeF32) { builder.addFloat(25, maybeF32, 0f); } + public static void addDefaultF32(FlatBufferBuilder builder, float defaultF32) { builder.addFloat(26, defaultF32, 42.0f); } + public static void addJustF64(FlatBufferBuilder builder, double justF64) { builder.addDouble(27, justF64, 0.0); } + public static void addMaybeF64(FlatBufferBuilder builder, double maybeF64) { builder.addDouble(28, maybeF64, 0.0); } + public static void addDefaultF64(FlatBufferBuilder builder, double defaultF64) { builder.addDouble(29, defaultF64, 42.0); } + public static void addJustBool(FlatBufferBuilder builder, boolean justBool) { builder.addBoolean(30, justBool, false); } + public static void addMaybeBool(FlatBufferBuilder builder, boolean maybeBool) { builder.addBoolean(31, maybeBool, false); } + public static void addDefaultBool(FlatBufferBuilder builder, boolean defaultBool) { builder.addBoolean(32, defaultBool, true); } + public static void addJustEnum(FlatBufferBuilder builder, byte justEnum) { builder.addByte(33, justEnum, 0); } + public static void addMaybeEnum(FlatBufferBuilder builder, byte maybeEnum) { builder.addByte(34, maybeEnum, 0); } + public static void addDefaultEnum(FlatBufferBuilder builder, byte defaultEnum) { builder.addByte(35, defaultEnum, 1); } + public static int endScalarStuff(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + public static void finishScalarStuffBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "NULL"); } + public static void finishSizePrefixedScalarStuffBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "NULL"); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public ScalarStuff get(int j) { return get(new ScalarStuff(), j); } + public ScalarStuff get(ScalarStuff obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } +} + diff --git a/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.kt b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.kt new file mode 100644 index 00000000000..7a45b2c0a82 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.kt @@ -0,0 +1,303 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +package optional_scalars + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class ScalarStuff : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : ScalarStuff { + __init(_i, _bb) + return this + } + val justI8 : Byte + get() { + val o = __offset(4) + return if(o != 0) bb.get(o + bb_pos) else 0 + } + val maybeI8 : Byte? + get() { + val o = __offset(6) + return if(o != 0) bb.get(o + bb_pos) else null + } + val defaultI8 : Byte + get() { + val o = __offset(8) + return if(o != 0) bb.get(o + bb_pos) else 42 + } + val justU8 : UByte + get() { + val o = __offset(10) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + val maybeU8 : UByte? + get() { + val o = __offset(12) + return if(o != 0) bb.get(o + bb_pos).toUByte() else null + } + val defaultU8 : UByte + get() { + val o = __offset(14) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 42u + } + val justI16 : Short + get() { + val o = __offset(16) + return if(o != 0) bb.getShort(o + bb_pos) else 0 + } + val maybeI16 : Short? + get() { + val o = __offset(18) + return if(o != 0) bb.getShort(o + bb_pos) else null + } + val defaultI16 : Short + get() { + val o = __offset(20) + return if(o != 0) bb.getShort(o + bb_pos) else 42 + } + val justU16 : UShort + get() { + val o = __offset(22) + return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 0u + } + val maybeU16 : UShort? + get() { + val o = __offset(24) + return if(o != 0) bb.getShort(o + bb_pos).toUShort() else null + } + val defaultU16 : UShort + get() { + val o = __offset(26) + return if(o != 0) bb.getShort(o + bb_pos).toUShort() else 42u + } + val justI32 : Int + get() { + val o = __offset(28) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + val maybeI32 : Int? + get() { + val o = __offset(30) + return if(o != 0) bb.getInt(o + bb_pos) else null + } + val defaultI32 : Int + get() { + val o = __offset(32) + return if(o != 0) bb.getInt(o + bb_pos) else 42 + } + val justU32 : UInt + get() { + val o = __offset(34) + return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 0u + } + val maybeU32 : UInt? + get() { + val o = __offset(36) + return if(o != 0) bb.getInt(o + bb_pos).toUInt() else null + } + val defaultU32 : UInt + get() { + val o = __offset(38) + return if(o != 0) bb.getInt(o + bb_pos).toUInt() else 42u + } + val justI64 : Long + get() { + val o = __offset(40) + return if(o != 0) bb.getLong(o + bb_pos) else 0L + } + val maybeI64 : Long? + get() { + val o = __offset(42) + return if(o != 0) bb.getLong(o + bb_pos) else null + } + val defaultI64 : Long + get() { + val o = __offset(44) + return if(o != 0) bb.getLong(o + bb_pos) else 42L + } + val justU64 : ULong + get() { + val o = __offset(46) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 0UL + } + val maybeU64 : ULong? + get() { + val o = __offset(48) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else null + } + val defaultU64 : ULong + get() { + val o = __offset(50) + return if(o != 0) bb.getLong(o + bb_pos).toULong() else 42UL + } + val justF32 : Float + get() { + val o = __offset(52) + return if(o != 0) bb.getFloat(o + bb_pos) else 0.0f + } + val maybeF32 : Float? + get() { + val o = __offset(54) + return if(o != 0) bb.getFloat(o + bb_pos) else null + } + val defaultF32 : Float + get() { + val o = __offset(56) + return if(o != 0) bb.getFloat(o + bb_pos) else 42.0f + } + val justF64 : Double + get() { + val o = __offset(58) + return if(o != 0) bb.getDouble(o + bb_pos) else 0.0 + } + val maybeF64 : Double? + get() { + val o = __offset(60) + return if(o != 0) bb.getDouble(o + bb_pos) else null + } + val defaultF64 : Double + get() { + val o = __offset(62) + return if(o != 0) bb.getDouble(o + bb_pos) else 42.0 + } + val justBool : Boolean + get() { + val o = __offset(64) + return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else false + } + val maybeBool : Boolean? + get() { + val o = __offset(66) + return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else null + } + val defaultBool : Boolean + get() { + val o = __offset(68) + return if(o != 0) 0.toByte() != bb.get(o + bb_pos) else true + } + val justEnum : Byte + get() { + val o = __offset(70) + return if(o != 0) bb.get(o + bb_pos) else 0 + } + val maybeEnum : Byte? + get() { + val o = __offset(72) + return if(o != 0) bb.get(o + bb_pos) else null + } + val defaultEnum : Byte + get() { + val o = __offset(74) + return if(o != 0) bb.get(o + bb_pos) else 1 + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsScalarStuff(_bb: ByteBuffer): ScalarStuff = getRootAsScalarStuff(_bb, ScalarStuff()) + fun getRootAsScalarStuff(_bb: ByteBuffer, obj: ScalarStuff): ScalarStuff { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun ScalarStuffBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "NULL") + fun createScalarStuff(builder: FlatBufferBuilder, justI8: Byte, maybeI8: Byte?, defaultI8: Byte, justU8: UByte, maybeU8: UByte?, defaultU8: UByte, justI16: Short, maybeI16: Short?, defaultI16: Short, justU16: UShort, maybeU16: UShort?, defaultU16: UShort, justI32: Int, maybeI32: Int?, defaultI32: Int, justU32: UInt, maybeU32: UInt?, defaultU32: UInt, justI64: Long, maybeI64: Long?, defaultI64: Long, justU64: ULong, maybeU64: ULong?, defaultU64: ULong, justF32: Float, maybeF32: Float?, defaultF32: Float, justF64: Double, maybeF64: Double?, defaultF64: Double, justBool: Boolean, maybeBool: Boolean?, defaultBool: Boolean, justEnum: Byte, maybeEnum: Byte?, defaultEnum: Byte) : Int { + builder.startTable(36) + addDefaultF64(builder, defaultF64) + maybeF64?.run { addMaybeF64(builder, maybeF64) } + addJustF64(builder, justF64) + addDefaultU64(builder, defaultU64) + maybeU64?.run { addMaybeU64(builder, maybeU64) } + addJustU64(builder, justU64) + addDefaultI64(builder, defaultI64) + maybeI64?.run { addMaybeI64(builder, maybeI64) } + addJustI64(builder, justI64) + addDefaultF32(builder, defaultF32) + maybeF32?.run { addMaybeF32(builder, maybeF32) } + addJustF32(builder, justF32) + addDefaultU32(builder, defaultU32) + maybeU32?.run { addMaybeU32(builder, maybeU32) } + addJustU32(builder, justU32) + addDefaultI32(builder, defaultI32) + maybeI32?.run { addMaybeI32(builder, maybeI32) } + addJustI32(builder, justI32) + addDefaultU16(builder, defaultU16) + maybeU16?.run { addMaybeU16(builder, maybeU16) } + addJustU16(builder, justU16) + addDefaultI16(builder, defaultI16) + maybeI16?.run { addMaybeI16(builder, maybeI16) } + addJustI16(builder, justI16) + addDefaultEnum(builder, defaultEnum) + maybeEnum?.run { addMaybeEnum(builder, maybeEnum) } + addJustEnum(builder, justEnum) + addDefaultBool(builder, defaultBool) + maybeBool?.run { addMaybeBool(builder, maybeBool) } + addJustBool(builder, justBool) + addDefaultU8(builder, defaultU8) + maybeU8?.run { addMaybeU8(builder, maybeU8) } + addJustU8(builder, justU8) + addDefaultI8(builder, defaultI8) + maybeI8?.run { addMaybeI8(builder, maybeI8) } + addJustI8(builder, justI8) + return endScalarStuff(builder) + } + fun startScalarStuff(builder: FlatBufferBuilder) = builder.startTable(36) + fun addJustI8(builder: FlatBufferBuilder, justI8: Byte) = builder.addByte(0, justI8, 0) + fun addMaybeI8(builder: FlatBufferBuilder, maybeI8: Byte) = builder.addByte(1, maybeI8, 0) + fun addDefaultI8(builder: FlatBufferBuilder, defaultI8: Byte) = builder.addByte(2, defaultI8, 42) + fun addJustU8(builder: FlatBufferBuilder, justU8: UByte) = builder.addByte(3, justU8.toByte(), 0) + fun addMaybeU8(builder: FlatBufferBuilder, maybeU8: UByte) = builder.addByte(4, maybeU8.toByte(), 0) + fun addDefaultU8(builder: FlatBufferBuilder, defaultU8: UByte) = builder.addByte(5, defaultU8.toByte(), 42) + fun addJustI16(builder: FlatBufferBuilder, justI16: Short) = builder.addShort(6, justI16, 0) + fun addMaybeI16(builder: FlatBufferBuilder, maybeI16: Short) = builder.addShort(7, maybeI16, 0) + fun addDefaultI16(builder: FlatBufferBuilder, defaultI16: Short) = builder.addShort(8, defaultI16, 42) + fun addJustU16(builder: FlatBufferBuilder, justU16: UShort) = builder.addShort(9, justU16.toShort(), 0) + fun addMaybeU16(builder: FlatBufferBuilder, maybeU16: UShort) = builder.addShort(10, maybeU16.toShort(), 0) + fun addDefaultU16(builder: FlatBufferBuilder, defaultU16: UShort) = builder.addShort(11, defaultU16.toShort(), 42) + fun addJustI32(builder: FlatBufferBuilder, justI32: Int) = builder.addInt(12, justI32, 0) + fun addMaybeI32(builder: FlatBufferBuilder, maybeI32: Int) = builder.addInt(13, maybeI32, 0) + fun addDefaultI32(builder: FlatBufferBuilder, defaultI32: Int) = builder.addInt(14, defaultI32, 42) + fun addJustU32(builder: FlatBufferBuilder, justU32: UInt) = builder.addInt(15, justU32.toInt(), 0) + fun addMaybeU32(builder: FlatBufferBuilder, maybeU32: UInt) = builder.addInt(16, maybeU32.toInt(), 0) + fun addDefaultU32(builder: FlatBufferBuilder, defaultU32: UInt) = builder.addInt(17, defaultU32.toInt(), 42) + fun addJustI64(builder: FlatBufferBuilder, justI64: Long) = builder.addLong(18, justI64, 0L) + fun addMaybeI64(builder: FlatBufferBuilder, maybeI64: Long) = builder.addLong(19, maybeI64, 0) + fun addDefaultI64(builder: FlatBufferBuilder, defaultI64: Long) = builder.addLong(20, defaultI64, 42L) + fun addJustU64(builder: FlatBufferBuilder, justU64: ULong) = builder.addLong(21, justU64.toLong(), 0) + fun addMaybeU64(builder: FlatBufferBuilder, maybeU64: ULong) = builder.addLong(22, maybeU64.toLong(), 0) + fun addDefaultU64(builder: FlatBufferBuilder, defaultU64: ULong) = builder.addLong(23, defaultU64.toLong(), 42) + fun addJustF32(builder: FlatBufferBuilder, justF32: Float) = builder.addFloat(24, justF32, 0.0) + fun addMaybeF32(builder: FlatBufferBuilder, maybeF32: Float) = builder.addFloat(25, maybeF32, 0.0) + fun addDefaultF32(builder: FlatBufferBuilder, defaultF32: Float) = builder.addFloat(26, defaultF32, 42.0) + fun addJustF64(builder: FlatBufferBuilder, justF64: Double) = builder.addDouble(27, justF64, 0.0) + fun addMaybeF64(builder: FlatBufferBuilder, maybeF64: Double) = builder.addDouble(28, maybeF64, 0.0) + fun addDefaultF64(builder: FlatBufferBuilder, defaultF64: Double) = builder.addDouble(29, defaultF64, 42.0) + fun addJustBool(builder: FlatBufferBuilder, justBool: Boolean) = builder.addBoolean(30, justBool, false) + fun addMaybeBool(builder: FlatBufferBuilder, maybeBool: Boolean) = builder.addBoolean(31, maybeBool, false) + fun addDefaultBool(builder: FlatBufferBuilder, defaultBool: Boolean) = builder.addBoolean(32, defaultBool, true) + fun addJustEnum(builder: FlatBufferBuilder, justEnum: Byte) = builder.addByte(33, justEnum, 0) + fun addMaybeEnum(builder: FlatBufferBuilder, maybeEnum: Byte) = builder.addByte(34, maybeEnum, 0) + fun addDefaultEnum(builder: FlatBufferBuilder, defaultEnum: Byte) = builder.addByte(35, defaultEnum, 1) + fun endScalarStuff(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun finishScalarStuffBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset, "NULL") + fun finishSizePrefixedScalarStuffBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset, "NULL") + } +} diff --git a/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.nim b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.nim new file mode 100644 index 00000000000..b849588b491 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.nim @@ -0,0 +1,331 @@ +#[ optional_scalars.ScalarStuff + Automatically generated by the FlatBuffers compiler, do not modify. + Or modify. I'm a message, not a cop. + + flatc version: 25.2.10 + + Declared by : + Rooting type : optional_scalars.ScalarStuff () +]# + +import OptionalByte as optional_scalars_OptionalByte +import flatbuffers +import std/options + +type ScalarStuff* = object of FlatObj +func justI8*(self: ScalarStuff): int8 = + let o = self.tab.Offset(4) + if o != 0: + return Get[int8](self.tab, self.tab.Pos + o) + return 0 +func `justI8=`*(self: var ScalarStuff, n: int8): bool = + return self.tab.MutateSlot(4, n) +func maybeI8*(self: ScalarStuff): Option[int8] = + let o = self.tab.Offset(6) + if o != 0: + return some(Get[int8](self.tab, self.tab.Pos + o)) +func `maybeI8=`*(self: var ScalarStuff, n: Option[int8]): bool = + return self.tab.MutateSlot(6, n) +func defaultI8*(self: ScalarStuff): int8 = + let o = self.tab.Offset(8) + if o != 0: + return Get[int8](self.tab, self.tab.Pos + o) + return 42 +func `defaultI8=`*(self: var ScalarStuff, n: int8): bool = + return self.tab.MutateSlot(8, n) +func justU8*(self: ScalarStuff): uint8 = + let o = self.tab.Offset(10) + if o != 0: + return Get[uint8](self.tab, self.tab.Pos + o) + return 0 +func `justU8=`*(self: var ScalarStuff, n: uint8): bool = + return self.tab.MutateSlot(10, n) +func maybeU8*(self: ScalarStuff): Option[uint8] = + let o = self.tab.Offset(12) + if o != 0: + return some(Get[uint8](self.tab, self.tab.Pos + o)) +func `maybeU8=`*(self: var ScalarStuff, n: Option[uint8]): bool = + return self.tab.MutateSlot(12, n) +func defaultU8*(self: ScalarStuff): uint8 = + let o = self.tab.Offset(14) + if o != 0: + return Get[uint8](self.tab, self.tab.Pos + o) + return 42 +func `defaultU8=`*(self: var ScalarStuff, n: uint8): bool = + return self.tab.MutateSlot(14, n) +func justI16*(self: ScalarStuff): int16 = + let o = self.tab.Offset(16) + if o != 0: + return Get[int16](self.tab, self.tab.Pos + o) + return 0 +func `justI16=`*(self: var ScalarStuff, n: int16): bool = + return self.tab.MutateSlot(16, n) +func maybeI16*(self: ScalarStuff): Option[int16] = + let o = self.tab.Offset(18) + if o != 0: + return some(Get[int16](self.tab, self.tab.Pos + o)) +func `maybeI16=`*(self: var ScalarStuff, n: Option[int16]): bool = + return self.tab.MutateSlot(18, n) +func defaultI16*(self: ScalarStuff): int16 = + let o = self.tab.Offset(20) + if o != 0: + return Get[int16](self.tab, self.tab.Pos + o) + return 42 +func `defaultI16=`*(self: var ScalarStuff, n: int16): bool = + return self.tab.MutateSlot(20, n) +func justU16*(self: ScalarStuff): uint16 = + let o = self.tab.Offset(22) + if o != 0: + return Get[uint16](self.tab, self.tab.Pos + o) + return 0 +func `justU16=`*(self: var ScalarStuff, n: uint16): bool = + return self.tab.MutateSlot(22, n) +func maybeU16*(self: ScalarStuff): Option[uint16] = + let o = self.tab.Offset(24) + if o != 0: + return some(Get[uint16](self.tab, self.tab.Pos + o)) +func `maybeU16=`*(self: var ScalarStuff, n: Option[uint16]): bool = + return self.tab.MutateSlot(24, n) +func defaultU16*(self: ScalarStuff): uint16 = + let o = self.tab.Offset(26) + if o != 0: + return Get[uint16](self.tab, self.tab.Pos + o) + return 42 +func `defaultU16=`*(self: var ScalarStuff, n: uint16): bool = + return self.tab.MutateSlot(26, n) +func justI32*(self: ScalarStuff): int32 = + let o = self.tab.Offset(28) + if o != 0: + return Get[int32](self.tab, self.tab.Pos + o) + return 0 +func `justI32=`*(self: var ScalarStuff, n: int32): bool = + return self.tab.MutateSlot(28, n) +func maybeI32*(self: ScalarStuff): Option[int32] = + let o = self.tab.Offset(30) + if o != 0: + return some(Get[int32](self.tab, self.tab.Pos + o)) +func `maybeI32=`*(self: var ScalarStuff, n: Option[int32]): bool = + return self.tab.MutateSlot(30, n) +func defaultI32*(self: ScalarStuff): int32 = + let o = self.tab.Offset(32) + if o != 0: + return Get[int32](self.tab, self.tab.Pos + o) + return 42 +func `defaultI32=`*(self: var ScalarStuff, n: int32): bool = + return self.tab.MutateSlot(32, n) +func justU32*(self: ScalarStuff): uint32 = + let o = self.tab.Offset(34) + if o != 0: + return Get[uint32](self.tab, self.tab.Pos + o) + return 0 +func `justU32=`*(self: var ScalarStuff, n: uint32): bool = + return self.tab.MutateSlot(34, n) +func maybeU32*(self: ScalarStuff): Option[uint32] = + let o = self.tab.Offset(36) + if o != 0: + return some(Get[uint32](self.tab, self.tab.Pos + o)) +func `maybeU32=`*(self: var ScalarStuff, n: Option[uint32]): bool = + return self.tab.MutateSlot(36, n) +func defaultU32*(self: ScalarStuff): uint32 = + let o = self.tab.Offset(38) + if o != 0: + return Get[uint32](self.tab, self.tab.Pos + o) + return 42 +func `defaultU32=`*(self: var ScalarStuff, n: uint32): bool = + return self.tab.MutateSlot(38, n) +func justI64*(self: ScalarStuff): int64 = + let o = self.tab.Offset(40) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 0 +func `justI64=`*(self: var ScalarStuff, n: int64): bool = + return self.tab.MutateSlot(40, n) +func maybeI64*(self: ScalarStuff): Option[int64] = + let o = self.tab.Offset(42) + if o != 0: + return some(Get[int64](self.tab, self.tab.Pos + o)) +func `maybeI64=`*(self: var ScalarStuff, n: Option[int64]): bool = + return self.tab.MutateSlot(42, n) +func defaultI64*(self: ScalarStuff): int64 = + let o = self.tab.Offset(44) + if o != 0: + return Get[int64](self.tab, self.tab.Pos + o) + return 42 +func `defaultI64=`*(self: var ScalarStuff, n: int64): bool = + return self.tab.MutateSlot(44, n) +func justU64*(self: ScalarStuff): uint64 = + let o = self.tab.Offset(46) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 0 +func `justU64=`*(self: var ScalarStuff, n: uint64): bool = + return self.tab.MutateSlot(46, n) +func maybeU64*(self: ScalarStuff): Option[uint64] = + let o = self.tab.Offset(48) + if o != 0: + return some(Get[uint64](self.tab, self.tab.Pos + o)) +func `maybeU64=`*(self: var ScalarStuff, n: Option[uint64]): bool = + return self.tab.MutateSlot(48, n) +func defaultU64*(self: ScalarStuff): uint64 = + let o = self.tab.Offset(50) + if o != 0: + return Get[uint64](self.tab, self.tab.Pos + o) + return 42 +func `defaultU64=`*(self: var ScalarStuff, n: uint64): bool = + return self.tab.MutateSlot(50, n) +func justF32*(self: ScalarStuff): float32 = + let o = self.tab.Offset(52) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return 0.0 +func `justF32=`*(self: var ScalarStuff, n: float32): bool = + return self.tab.MutateSlot(52, n) +func maybeF32*(self: ScalarStuff): Option[float32] = + let o = self.tab.Offset(54) + if o != 0: + return some(Get[float32](self.tab, self.tab.Pos + o)) +func `maybeF32=`*(self: var ScalarStuff, n: Option[float32]): bool = + return self.tab.MutateSlot(54, n) +func defaultF32*(self: ScalarStuff): float32 = + let o = self.tab.Offset(56) + if o != 0: + return Get[float32](self.tab, self.tab.Pos + o) + return 42.0 +func `defaultF32=`*(self: var ScalarStuff, n: float32): bool = + return self.tab.MutateSlot(56, n) +func justF64*(self: ScalarStuff): float64 = + let o = self.tab.Offset(58) + if o != 0: + return Get[float64](self.tab, self.tab.Pos + o) + return 0.0 +func `justF64=`*(self: var ScalarStuff, n: float64): bool = + return self.tab.MutateSlot(58, n) +func maybeF64*(self: ScalarStuff): Option[float64] = + let o = self.tab.Offset(60) + if o != 0: + return some(Get[float64](self.tab, self.tab.Pos + o)) +func `maybeF64=`*(self: var ScalarStuff, n: Option[float64]): bool = + return self.tab.MutateSlot(60, n) +func defaultF64*(self: ScalarStuff): float64 = + let o = self.tab.Offset(62) + if o != 0: + return Get[float64](self.tab, self.tab.Pos + o) + return 42.0 +func `defaultF64=`*(self: var ScalarStuff, n: float64): bool = + return self.tab.MutateSlot(62, n) +func justBool*(self: ScalarStuff): bool = + let o = self.tab.Offset(64) + if o != 0: + return Get[bool](self.tab, self.tab.Pos + o) + return false +func `justBool=`*(self: var ScalarStuff, n: bool): bool = + return self.tab.MutateSlot(64, n) +func maybeBool*(self: ScalarStuff): Option[bool] = + let o = self.tab.Offset(66) + if o != 0: + return some(Get[bool](self.tab, self.tab.Pos + o)) +func `maybeBool=`*(self: var ScalarStuff, n: Option[bool]): bool = + return self.tab.MutateSlot(66, n) +func defaultBool*(self: ScalarStuff): bool = + let o = self.tab.Offset(68) + if o != 0: + return Get[bool](self.tab, self.tab.Pos + o) + return true +func `defaultBool=`*(self: var ScalarStuff, n: bool): bool = + return self.tab.MutateSlot(68, n) +func justEnum*(self: ScalarStuff): optional_scalars_OptionalByte.OptionalByte = + let o = self.tab.Offset(70) + if o != 0: + return optional_scalars_OptionalByte.OptionalByte(Get[int8](self.tab, self.tab.Pos + o)) + return type(result)(0) +func `justEnum=`*(self: var ScalarStuff, n: optional_scalars_OptionalByte.OptionalByte): bool = + return self.tab.MutateSlot(70, n) +func maybeEnum*(self: ScalarStuff): Option[optional_scalars_OptionalByte.OptionalByte] = + let o = self.tab.Offset(72) + if o != 0: + return some(optional_scalars_OptionalByte.OptionalByte(Get[int8](self.tab, self.tab.Pos + o))) +func `maybeEnum=`*(self: var ScalarStuff, n: Option[optional_scalars_OptionalByte.OptionalByte]): bool = + return self.tab.MutateSlot(72, n) +func defaultEnum*(self: ScalarStuff): optional_scalars_OptionalByte.OptionalByte = + let o = self.tab.Offset(74) + if o != 0: + return optional_scalars_OptionalByte.OptionalByte(Get[int8](self.tab, self.tab.Pos + o)) + return type(result)(1) +func `defaultEnum=`*(self: var ScalarStuff, n: optional_scalars_OptionalByte.OptionalByte): bool = + return self.tab.MutateSlot(74, n) +proc ScalarStuffStart*(builder: var Builder) = + builder.StartObject(36) +proc ScalarStuffAddjustI8*(builder: var Builder, justI8: int8) = + builder.PrependSlot(0, justI8, default(int8)) +proc ScalarStuffAddmaybeI8*(builder: var Builder, maybeI8: int8) = + builder.PrependSlot(1, maybeI8, default(int8)) +proc ScalarStuffAdddefaultI8*(builder: var Builder, defaultI8: int8) = + builder.PrependSlot(2, defaultI8, default(int8)) +proc ScalarStuffAddjustU8*(builder: var Builder, justU8: uint8) = + builder.PrependSlot(3, justU8, default(uint8)) +proc ScalarStuffAddmaybeU8*(builder: var Builder, maybeU8: uint8) = + builder.PrependSlot(4, maybeU8, default(uint8)) +proc ScalarStuffAdddefaultU8*(builder: var Builder, defaultU8: uint8) = + builder.PrependSlot(5, defaultU8, default(uint8)) +proc ScalarStuffAddjustI16*(builder: var Builder, justI16: int16) = + builder.PrependSlot(6, justI16, default(int16)) +proc ScalarStuffAddmaybeI16*(builder: var Builder, maybeI16: int16) = + builder.PrependSlot(7, maybeI16, default(int16)) +proc ScalarStuffAdddefaultI16*(builder: var Builder, defaultI16: int16) = + builder.PrependSlot(8, defaultI16, default(int16)) +proc ScalarStuffAddjustU16*(builder: var Builder, justU16: uint16) = + builder.PrependSlot(9, justU16, default(uint16)) +proc ScalarStuffAddmaybeU16*(builder: var Builder, maybeU16: uint16) = + builder.PrependSlot(10, maybeU16, default(uint16)) +proc ScalarStuffAdddefaultU16*(builder: var Builder, defaultU16: uint16) = + builder.PrependSlot(11, defaultU16, default(uint16)) +proc ScalarStuffAddjustI32*(builder: var Builder, justI32: int32) = + builder.PrependSlot(12, justI32, default(int32)) +proc ScalarStuffAddmaybeI32*(builder: var Builder, maybeI32: int32) = + builder.PrependSlot(13, maybeI32, default(int32)) +proc ScalarStuffAdddefaultI32*(builder: var Builder, defaultI32: int32) = + builder.PrependSlot(14, defaultI32, default(int32)) +proc ScalarStuffAddjustU32*(builder: var Builder, justU32: uint32) = + builder.PrependSlot(15, justU32, default(uint32)) +proc ScalarStuffAddmaybeU32*(builder: var Builder, maybeU32: uint32) = + builder.PrependSlot(16, maybeU32, default(uint32)) +proc ScalarStuffAdddefaultU32*(builder: var Builder, defaultU32: uint32) = + builder.PrependSlot(17, defaultU32, default(uint32)) +proc ScalarStuffAddjustI64*(builder: var Builder, justI64: int64) = + builder.PrependSlot(18, justI64, default(int64)) +proc ScalarStuffAddmaybeI64*(builder: var Builder, maybeI64: int64) = + builder.PrependSlot(19, maybeI64, default(int64)) +proc ScalarStuffAdddefaultI64*(builder: var Builder, defaultI64: int64) = + builder.PrependSlot(20, defaultI64, default(int64)) +proc ScalarStuffAddjustU64*(builder: var Builder, justU64: uint64) = + builder.PrependSlot(21, justU64, default(uint64)) +proc ScalarStuffAddmaybeU64*(builder: var Builder, maybeU64: uint64) = + builder.PrependSlot(22, maybeU64, default(uint64)) +proc ScalarStuffAdddefaultU64*(builder: var Builder, defaultU64: uint64) = + builder.PrependSlot(23, defaultU64, default(uint64)) +proc ScalarStuffAddjustF32*(builder: var Builder, justF32: float32) = + builder.PrependSlot(24, justF32, default(float32)) +proc ScalarStuffAddmaybeF32*(builder: var Builder, maybeF32: float32) = + builder.PrependSlot(25, maybeF32, default(float32)) +proc ScalarStuffAdddefaultF32*(builder: var Builder, defaultF32: float32) = + builder.PrependSlot(26, defaultF32, default(float32)) +proc ScalarStuffAddjustF64*(builder: var Builder, justF64: float64) = + builder.PrependSlot(27, justF64, default(float64)) +proc ScalarStuffAddmaybeF64*(builder: var Builder, maybeF64: float64) = + builder.PrependSlot(28, maybeF64, default(float64)) +proc ScalarStuffAdddefaultF64*(builder: var Builder, defaultF64: float64) = + builder.PrependSlot(29, defaultF64, default(float64)) +proc ScalarStuffAddjustBool*(builder: var Builder, justBool: bool) = + builder.PrependSlot(30, justBool, default(bool)) +proc ScalarStuffAddmaybeBool*(builder: var Builder, maybeBool: bool) = + builder.PrependSlot(31, maybeBool, default(bool)) +proc ScalarStuffAdddefaultBool*(builder: var Builder, defaultBool: bool) = + builder.PrependSlot(32, defaultBool, default(bool)) +proc ScalarStuffAddjustEnum*(builder: var Builder, justEnum: int8) = + builder.PrependSlot(33, justEnum, default(int8)) +proc ScalarStuffAddmaybeEnum*(builder: var Builder, maybeEnum: int8) = + builder.PrependSlot(34, maybeEnum, default(int8)) +proc ScalarStuffAdddefaultEnum*(builder: var Builder, defaultEnum: int8) = + builder.PrependSlot(35, defaultEnum, default(int8)) +proc ScalarStuffEnd*(builder: var Builder): uoffset = + return builder.EndObject() diff --git a/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.py b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.py new file mode 100644 index 00000000000..dda052f36db --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/ScalarStuff.py @@ -0,0 +1,651 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: optional_scalars + +import flatbuffers +from flatbuffers.compat import import_numpy +np = import_numpy() + +class ScalarStuff(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = ScalarStuff() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsScalarStuff(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + @classmethod + def ScalarStuffBufferHasIdentifier(cls, buf, offset, size_prefixed=False): + return flatbuffers.util.BufferHasIdentifier(buf, offset, b"\x4E\x55\x4C\x4C", size_prefixed=size_prefixed) + + # ScalarStuff + def Init(self, buf, pos): + self._tab = flatbuffers.table.Table(buf, pos) + + # ScalarStuff + def JustI8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(4)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeI8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(6)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultI8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(8)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustU8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(10)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeU8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(12)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultU8(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(14)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint8Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustI16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(16)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeI16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(18)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultI16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(20)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int16Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustU16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(22)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeU16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(24)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultU16(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(26)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint16Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustI32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(28)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeI32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(30)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultI32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(32)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int32Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustU32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(34)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeU32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(36)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultU32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(38)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint32Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustI64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(40)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeI64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(42)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultI64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(44)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int64Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustU64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(46)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeU64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(48)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultU64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(50)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Uint64Flags, o + self._tab.Pos) + return 42 + + # ScalarStuff + def JustF32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(52)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 0.0 + + # ScalarStuff + def MaybeF32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(54)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultF32(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(56)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float32Flags, o + self._tab.Pos) + return 42.0 + + # ScalarStuff + def JustF64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(58)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 0.0 + + # ScalarStuff + def MaybeF64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(60)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultF64(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(62)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Float64Flags, o + self._tab.Pos) + return 42.0 + + # ScalarStuff + def JustBool(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(64)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return False + + # ScalarStuff + def MaybeBool(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(66)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return None + + # ScalarStuff + def DefaultBool(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(68)) + if o != 0: + return bool(self._tab.Get(flatbuffers.number_types.BoolFlags, o + self._tab.Pos)) + return True + + # ScalarStuff + def JustEnum(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(70)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 0 + + # ScalarStuff + def MaybeEnum(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(72)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return None + + # ScalarStuff + def DefaultEnum(self): + o = flatbuffers.number_types.UOffsetTFlags.py_type(self._tab.Offset(74)) + if o != 0: + return self._tab.Get(flatbuffers.number_types.Int8Flags, o + self._tab.Pos) + return 1 + +def ScalarStuffStart(builder): + builder.StartObject(36) + +def Start(builder): + ScalarStuffStart(builder) + +def ScalarStuffAddJustI8(builder, justI8): + builder.PrependInt8Slot(0, justI8, 0) + +def AddJustI8(builder, justI8): + ScalarStuffAddJustI8(builder, justI8) + +def ScalarStuffAddMaybeI8(builder, maybeI8): + builder.PrependInt8Slot(1, maybeI8, None) + +def AddMaybeI8(builder, maybeI8): + ScalarStuffAddMaybeI8(builder, maybeI8) + +def ScalarStuffAddDefaultI8(builder, defaultI8): + builder.PrependInt8Slot(2, defaultI8, 42) + +def AddDefaultI8(builder, defaultI8): + ScalarStuffAddDefaultI8(builder, defaultI8) + +def ScalarStuffAddJustU8(builder, justU8): + builder.PrependUint8Slot(3, justU8, 0) + +def AddJustU8(builder, justU8): + ScalarStuffAddJustU8(builder, justU8) + +def ScalarStuffAddMaybeU8(builder, maybeU8): + builder.PrependUint8Slot(4, maybeU8, None) + +def AddMaybeU8(builder, maybeU8): + ScalarStuffAddMaybeU8(builder, maybeU8) + +def ScalarStuffAddDefaultU8(builder, defaultU8): + builder.PrependUint8Slot(5, defaultU8, 42) + +def AddDefaultU8(builder, defaultU8): + ScalarStuffAddDefaultU8(builder, defaultU8) + +def ScalarStuffAddJustI16(builder, justI16): + builder.PrependInt16Slot(6, justI16, 0) + +def AddJustI16(builder, justI16): + ScalarStuffAddJustI16(builder, justI16) + +def ScalarStuffAddMaybeI16(builder, maybeI16): + builder.PrependInt16Slot(7, maybeI16, None) + +def AddMaybeI16(builder, maybeI16): + ScalarStuffAddMaybeI16(builder, maybeI16) + +def ScalarStuffAddDefaultI16(builder, defaultI16): + builder.PrependInt16Slot(8, defaultI16, 42) + +def AddDefaultI16(builder, defaultI16): + ScalarStuffAddDefaultI16(builder, defaultI16) + +def ScalarStuffAddJustU16(builder, justU16): + builder.PrependUint16Slot(9, justU16, 0) + +def AddJustU16(builder, justU16): + ScalarStuffAddJustU16(builder, justU16) + +def ScalarStuffAddMaybeU16(builder, maybeU16): + builder.PrependUint16Slot(10, maybeU16, None) + +def AddMaybeU16(builder, maybeU16): + ScalarStuffAddMaybeU16(builder, maybeU16) + +def ScalarStuffAddDefaultU16(builder, defaultU16): + builder.PrependUint16Slot(11, defaultU16, 42) + +def AddDefaultU16(builder, defaultU16): + ScalarStuffAddDefaultU16(builder, defaultU16) + +def ScalarStuffAddJustI32(builder, justI32): + builder.PrependInt32Slot(12, justI32, 0) + +def AddJustI32(builder, justI32): + ScalarStuffAddJustI32(builder, justI32) + +def ScalarStuffAddMaybeI32(builder, maybeI32): + builder.PrependInt32Slot(13, maybeI32, None) + +def AddMaybeI32(builder, maybeI32): + ScalarStuffAddMaybeI32(builder, maybeI32) + +def ScalarStuffAddDefaultI32(builder, defaultI32): + builder.PrependInt32Slot(14, defaultI32, 42) + +def AddDefaultI32(builder, defaultI32): + ScalarStuffAddDefaultI32(builder, defaultI32) + +def ScalarStuffAddJustU32(builder, justU32): + builder.PrependUint32Slot(15, justU32, 0) + +def AddJustU32(builder, justU32): + ScalarStuffAddJustU32(builder, justU32) + +def ScalarStuffAddMaybeU32(builder, maybeU32): + builder.PrependUint32Slot(16, maybeU32, None) + +def AddMaybeU32(builder, maybeU32): + ScalarStuffAddMaybeU32(builder, maybeU32) + +def ScalarStuffAddDefaultU32(builder, defaultU32): + builder.PrependUint32Slot(17, defaultU32, 42) + +def AddDefaultU32(builder, defaultU32): + ScalarStuffAddDefaultU32(builder, defaultU32) + +def ScalarStuffAddJustI64(builder, justI64): + builder.PrependInt64Slot(18, justI64, 0) + +def AddJustI64(builder, justI64): + ScalarStuffAddJustI64(builder, justI64) + +def ScalarStuffAddMaybeI64(builder, maybeI64): + builder.PrependInt64Slot(19, maybeI64, None) + +def AddMaybeI64(builder, maybeI64): + ScalarStuffAddMaybeI64(builder, maybeI64) + +def ScalarStuffAddDefaultI64(builder, defaultI64): + builder.PrependInt64Slot(20, defaultI64, 42) + +def AddDefaultI64(builder, defaultI64): + ScalarStuffAddDefaultI64(builder, defaultI64) + +def ScalarStuffAddJustU64(builder, justU64): + builder.PrependUint64Slot(21, justU64, 0) + +def AddJustU64(builder, justU64): + ScalarStuffAddJustU64(builder, justU64) + +def ScalarStuffAddMaybeU64(builder, maybeU64): + builder.PrependUint64Slot(22, maybeU64, None) + +def AddMaybeU64(builder, maybeU64): + ScalarStuffAddMaybeU64(builder, maybeU64) + +def ScalarStuffAddDefaultU64(builder, defaultU64): + builder.PrependUint64Slot(23, defaultU64, 42) + +def AddDefaultU64(builder, defaultU64): + ScalarStuffAddDefaultU64(builder, defaultU64) + +def ScalarStuffAddJustF32(builder, justF32): + builder.PrependFloat32Slot(24, justF32, 0.0) + +def AddJustF32(builder, justF32): + ScalarStuffAddJustF32(builder, justF32) + +def ScalarStuffAddMaybeF32(builder, maybeF32): + builder.PrependFloat32Slot(25, maybeF32, None) + +def AddMaybeF32(builder, maybeF32): + ScalarStuffAddMaybeF32(builder, maybeF32) + +def ScalarStuffAddDefaultF32(builder, defaultF32): + builder.PrependFloat32Slot(26, defaultF32, 42.0) + +def AddDefaultF32(builder, defaultF32): + ScalarStuffAddDefaultF32(builder, defaultF32) + +def ScalarStuffAddJustF64(builder, justF64): + builder.PrependFloat64Slot(27, justF64, 0.0) + +def AddJustF64(builder, justF64): + ScalarStuffAddJustF64(builder, justF64) + +def ScalarStuffAddMaybeF64(builder, maybeF64): + builder.PrependFloat64Slot(28, maybeF64, None) + +def AddMaybeF64(builder, maybeF64): + ScalarStuffAddMaybeF64(builder, maybeF64) + +def ScalarStuffAddDefaultF64(builder, defaultF64): + builder.PrependFloat64Slot(29, defaultF64, 42.0) + +def AddDefaultF64(builder, defaultF64): + ScalarStuffAddDefaultF64(builder, defaultF64) + +def ScalarStuffAddJustBool(builder, justBool): + builder.PrependBoolSlot(30, justBool, 0) + +def AddJustBool(builder, justBool): + ScalarStuffAddJustBool(builder, justBool) + +def ScalarStuffAddMaybeBool(builder, maybeBool): + builder.PrependBoolSlot(31, maybeBool, None) + +def AddMaybeBool(builder, maybeBool): + ScalarStuffAddMaybeBool(builder, maybeBool) + +def ScalarStuffAddDefaultBool(builder, defaultBool): + builder.PrependBoolSlot(32, defaultBool, 1) + +def AddDefaultBool(builder, defaultBool): + ScalarStuffAddDefaultBool(builder, defaultBool) + +def ScalarStuffAddJustEnum(builder, justEnum): + builder.PrependInt8Slot(33, justEnum, 0) + +def AddJustEnum(builder, justEnum): + ScalarStuffAddJustEnum(builder, justEnum) + +def ScalarStuffAddMaybeEnum(builder, maybeEnum): + builder.PrependInt8Slot(34, maybeEnum, None) + +def AddMaybeEnum(builder, maybeEnum): + ScalarStuffAddMaybeEnum(builder, maybeEnum) + +def ScalarStuffAddDefaultEnum(builder, defaultEnum): + builder.PrependInt8Slot(35, defaultEnum, 1) + +def AddDefaultEnum(builder, defaultEnum): + ScalarStuffAddDefaultEnum(builder, defaultEnum) + +def ScalarStuffEnd(builder): + return builder.EndObject() + +def End(builder): + return ScalarStuffEnd(builder) + + +class ScalarStuffT(object): + + # ScalarStuffT + def __init__(self): + self.justI8 = 0 # type: int + self.maybeI8 = None # type: Optional[int] + self.defaultI8 = 42 # type: int + self.justU8 = 0 # type: int + self.maybeU8 = None # type: Optional[int] + self.defaultU8 = 42 # type: int + self.justI16 = 0 # type: int + self.maybeI16 = None # type: Optional[int] + self.defaultI16 = 42 # type: int + self.justU16 = 0 # type: int + self.maybeU16 = None # type: Optional[int] + self.defaultU16 = 42 # type: int + self.justI32 = 0 # type: int + self.maybeI32 = None # type: Optional[int] + self.defaultI32 = 42 # type: int + self.justU32 = 0 # type: int + self.maybeU32 = None # type: Optional[int] + self.defaultU32 = 42 # type: int + self.justI64 = 0 # type: int + self.maybeI64 = None # type: Optional[int] + self.defaultI64 = 42 # type: int + self.justU64 = 0 # type: int + self.maybeU64 = None # type: Optional[int] + self.defaultU64 = 42 # type: int + self.justF32 = 0.0 # type: float + self.maybeF32 = None # type: Optional[float] + self.defaultF32 = 42.0 # type: float + self.justF64 = 0.0 # type: float + self.maybeF64 = None # type: Optional[float] + self.defaultF64 = 42.0 # type: float + self.justBool = False # type: bool + self.maybeBool = None # type: Optional[bool] + self.defaultBool = True # type: bool + self.justEnum = 0 # type: int + self.maybeEnum = None # type: Optional[int] + self.defaultEnum = 1 # type: int + + @classmethod + def InitFromBuf(cls, buf, pos): + scalarStuff = ScalarStuff() + scalarStuff.Init(buf, pos) + return cls.InitFromObj(scalarStuff) + + @classmethod + def InitFromPackedBuf(cls, buf, pos=0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, pos) + return cls.InitFromBuf(buf, pos+n) + + @classmethod + def InitFromObj(cls, scalarStuff): + x = ScalarStuffT() + x._UnPack(scalarStuff) + return x + + # ScalarStuffT + def _UnPack(self, scalarStuff): + if scalarStuff is None: + return + self.justI8 = scalarStuff.JustI8() + self.maybeI8 = scalarStuff.MaybeI8() + self.defaultI8 = scalarStuff.DefaultI8() + self.justU8 = scalarStuff.JustU8() + self.maybeU8 = scalarStuff.MaybeU8() + self.defaultU8 = scalarStuff.DefaultU8() + self.justI16 = scalarStuff.JustI16() + self.maybeI16 = scalarStuff.MaybeI16() + self.defaultI16 = scalarStuff.DefaultI16() + self.justU16 = scalarStuff.JustU16() + self.maybeU16 = scalarStuff.MaybeU16() + self.defaultU16 = scalarStuff.DefaultU16() + self.justI32 = scalarStuff.JustI32() + self.maybeI32 = scalarStuff.MaybeI32() + self.defaultI32 = scalarStuff.DefaultI32() + self.justU32 = scalarStuff.JustU32() + self.maybeU32 = scalarStuff.MaybeU32() + self.defaultU32 = scalarStuff.DefaultU32() + self.justI64 = scalarStuff.JustI64() + self.maybeI64 = scalarStuff.MaybeI64() + self.defaultI64 = scalarStuff.DefaultI64() + self.justU64 = scalarStuff.JustU64() + self.maybeU64 = scalarStuff.MaybeU64() + self.defaultU64 = scalarStuff.DefaultU64() + self.justF32 = scalarStuff.JustF32() + self.maybeF32 = scalarStuff.MaybeF32() + self.defaultF32 = scalarStuff.DefaultF32() + self.justF64 = scalarStuff.JustF64() + self.maybeF64 = scalarStuff.MaybeF64() + self.defaultF64 = scalarStuff.DefaultF64() + self.justBool = scalarStuff.JustBool() + self.maybeBool = scalarStuff.MaybeBool() + self.defaultBool = scalarStuff.DefaultBool() + self.justEnum = scalarStuff.JustEnum() + self.maybeEnum = scalarStuff.MaybeEnum() + self.defaultEnum = scalarStuff.DefaultEnum() + + # ScalarStuffT + def Pack(self, builder): + ScalarStuffStart(builder) + ScalarStuffAddJustI8(builder, self.justI8) + ScalarStuffAddMaybeI8(builder, self.maybeI8) + ScalarStuffAddDefaultI8(builder, self.defaultI8) + ScalarStuffAddJustU8(builder, self.justU8) + ScalarStuffAddMaybeU8(builder, self.maybeU8) + ScalarStuffAddDefaultU8(builder, self.defaultU8) + ScalarStuffAddJustI16(builder, self.justI16) + ScalarStuffAddMaybeI16(builder, self.maybeI16) + ScalarStuffAddDefaultI16(builder, self.defaultI16) + ScalarStuffAddJustU16(builder, self.justU16) + ScalarStuffAddMaybeU16(builder, self.maybeU16) + ScalarStuffAddDefaultU16(builder, self.defaultU16) + ScalarStuffAddJustI32(builder, self.justI32) + ScalarStuffAddMaybeI32(builder, self.maybeI32) + ScalarStuffAddDefaultI32(builder, self.defaultI32) + ScalarStuffAddJustU32(builder, self.justU32) + ScalarStuffAddMaybeU32(builder, self.maybeU32) + ScalarStuffAddDefaultU32(builder, self.defaultU32) + ScalarStuffAddJustI64(builder, self.justI64) + ScalarStuffAddMaybeI64(builder, self.maybeI64) + ScalarStuffAddDefaultI64(builder, self.defaultI64) + ScalarStuffAddJustU64(builder, self.justU64) + ScalarStuffAddMaybeU64(builder, self.maybeU64) + ScalarStuffAddDefaultU64(builder, self.defaultU64) + ScalarStuffAddJustF32(builder, self.justF32) + ScalarStuffAddMaybeF32(builder, self.maybeF32) + ScalarStuffAddDefaultF32(builder, self.defaultF32) + ScalarStuffAddJustF64(builder, self.justF64) + ScalarStuffAddMaybeF64(builder, self.maybeF64) + ScalarStuffAddDefaultF64(builder, self.defaultF64) + ScalarStuffAddJustBool(builder, self.justBool) + ScalarStuffAddMaybeBool(builder, self.maybeBool) + ScalarStuffAddDefaultBool(builder, self.defaultBool) + ScalarStuffAddJustEnum(builder, self.justEnum) + ScalarStuffAddMaybeEnum(builder, self.maybeEnum) + ScalarStuffAddDefaultEnum(builder, self.defaultEnum) + scalarStuff = ScalarStuffEnd(builder) + return scalarStuff diff --git a/third_party/flatbuffers/tests/optional_scalars/__init__.py b/third_party/flatbuffers/tests/optional_scalars/__init__.py new file mode 100644 index 00000000000..e69de29bb2d diff --git a/third_party/flatbuffers/tests/optional_scalars/mod.rs b/third_party/flatbuffers/tests/optional_scalars/mod.rs new file mode 100644 index 00000000000..84291e3ef74 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/mod.rs @@ -0,0 +1,9 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod optional_scalars { + use super::*; + mod optional_byte_generated; + pub use self::optional_byte_generated::*; + mod scalar_stuff_generated; + pub use self::scalar_stuff_generated::*; +} // optional_scalars diff --git a/third_party/flatbuffers/tests/optional_scalars/optional_scalars/optional_byte_generated.rs b/third_party/flatbuffers/tests/optional_scalars/optional_scalars/optional_byte_generated.rs new file mode 100644 index 00000000000..9cb47c699f2 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/optional_scalars/optional_byte_generated.rs @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_OPTIONAL_BYTE: i8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_OPTIONAL_BYTE: i8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_OPTIONAL_BYTE: [OptionalByte; 3] = [ + OptionalByte::None, + OptionalByte::One, + OptionalByte::Two, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct OptionalByte(pub i8); +#[allow(non_upper_case_globals)] +impl OptionalByte { + pub const None: Self = Self(0); + pub const One: Self = Self(1); + pub const Two: Self = Self(2); + + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::None, + Self::One, + Self::Two, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::None => Some("None"), + Self::One => Some("One"), + Self::Two => Some("Two"), + _ => None, + } + } +} +impl core::fmt::Debug for OptionalByte { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for OptionalByte { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for OptionalByte { + type Output = OptionalByte; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for OptionalByte { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for OptionalByte { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for OptionalByte {} diff --git a/third_party/flatbuffers/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs b/third_party/flatbuffers/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs new file mode 100644 index 00000000000..f5e71f80248 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars/optional_scalars/scalar_stuff_generated.rs @@ -0,0 +1,1031 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum ScalarStuffOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct ScalarStuff<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for ScalarStuff<'a> { + type Inner = ScalarStuff<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> ScalarStuff<'a> { + pub const VT_JUST_I8: flatbuffers::VOffsetT = 4; + pub const VT_MAYBE_I8: flatbuffers::VOffsetT = 6; + pub const VT_DEFAULT_I8: flatbuffers::VOffsetT = 8; + pub const VT_JUST_U8: flatbuffers::VOffsetT = 10; + pub const VT_MAYBE_U8: flatbuffers::VOffsetT = 12; + pub const VT_DEFAULT_U8: flatbuffers::VOffsetT = 14; + pub const VT_JUST_I16: flatbuffers::VOffsetT = 16; + pub const VT_MAYBE_I16: flatbuffers::VOffsetT = 18; + pub const VT_DEFAULT_I16: flatbuffers::VOffsetT = 20; + pub const VT_JUST_U16: flatbuffers::VOffsetT = 22; + pub const VT_MAYBE_U16: flatbuffers::VOffsetT = 24; + pub const VT_DEFAULT_U16: flatbuffers::VOffsetT = 26; + pub const VT_JUST_I32: flatbuffers::VOffsetT = 28; + pub const VT_MAYBE_I32: flatbuffers::VOffsetT = 30; + pub const VT_DEFAULT_I32: flatbuffers::VOffsetT = 32; + pub const VT_JUST_U32: flatbuffers::VOffsetT = 34; + pub const VT_MAYBE_U32: flatbuffers::VOffsetT = 36; + pub const VT_DEFAULT_U32: flatbuffers::VOffsetT = 38; + pub const VT_JUST_I64: flatbuffers::VOffsetT = 40; + pub const VT_MAYBE_I64: flatbuffers::VOffsetT = 42; + pub const VT_DEFAULT_I64: flatbuffers::VOffsetT = 44; + pub const VT_JUST_U64: flatbuffers::VOffsetT = 46; + pub const VT_MAYBE_U64: flatbuffers::VOffsetT = 48; + pub const VT_DEFAULT_U64: flatbuffers::VOffsetT = 50; + pub const VT_JUST_F32: flatbuffers::VOffsetT = 52; + pub const VT_MAYBE_F32: flatbuffers::VOffsetT = 54; + pub const VT_DEFAULT_F32: flatbuffers::VOffsetT = 56; + pub const VT_JUST_F64: flatbuffers::VOffsetT = 58; + pub const VT_MAYBE_F64: flatbuffers::VOffsetT = 60; + pub const VT_DEFAULT_F64: flatbuffers::VOffsetT = 62; + pub const VT_JUST_BOOL: flatbuffers::VOffsetT = 64; + pub const VT_MAYBE_BOOL: flatbuffers::VOffsetT = 66; + pub const VT_DEFAULT_BOOL: flatbuffers::VOffsetT = 68; + pub const VT_JUST_ENUM: flatbuffers::VOffsetT = 70; + pub const VT_MAYBE_ENUM: flatbuffers::VOffsetT = 72; + pub const VT_DEFAULT_ENUM: flatbuffers::VOffsetT = 74; + + pub const fn get_fully_qualified_name() -> &'static str { + "optional_scalars.ScalarStuff" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + ScalarStuff { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args ScalarStuffArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = ScalarStuffBuilder::new(_fbb); + builder.add_default_f64(args.default_f64); + if let Some(x) = args.maybe_f64 { builder.add_maybe_f64(x); } + builder.add_just_f64(args.just_f64); + builder.add_default_u64(args.default_u64); + if let Some(x) = args.maybe_u64 { builder.add_maybe_u64(x); } + builder.add_just_u64(args.just_u64); + builder.add_default_i64(args.default_i64); + if let Some(x) = args.maybe_i64 { builder.add_maybe_i64(x); } + builder.add_just_i64(args.just_i64); + builder.add_default_f32(args.default_f32); + if let Some(x) = args.maybe_f32 { builder.add_maybe_f32(x); } + builder.add_just_f32(args.just_f32); + builder.add_default_u32(args.default_u32); + if let Some(x) = args.maybe_u32 { builder.add_maybe_u32(x); } + builder.add_just_u32(args.just_u32); + builder.add_default_i32(args.default_i32); + if let Some(x) = args.maybe_i32 { builder.add_maybe_i32(x); } + builder.add_just_i32(args.just_i32); + builder.add_default_u16(args.default_u16); + if let Some(x) = args.maybe_u16 { builder.add_maybe_u16(x); } + builder.add_just_u16(args.just_u16); + builder.add_default_i16(args.default_i16); + if let Some(x) = args.maybe_i16 { builder.add_maybe_i16(x); } + builder.add_just_i16(args.just_i16); + builder.add_default_enum(args.default_enum); + if let Some(x) = args.maybe_enum { builder.add_maybe_enum(x); } + builder.add_just_enum(args.just_enum); + builder.add_default_bool(args.default_bool); + if let Some(x) = args.maybe_bool { builder.add_maybe_bool(x); } + builder.add_just_bool(args.just_bool); + builder.add_default_u8(args.default_u8); + if let Some(x) = args.maybe_u8 { builder.add_maybe_u8(x); } + builder.add_just_u8(args.just_u8); + builder.add_default_i8(args.default_i8); + if let Some(x) = args.maybe_i8 { builder.add_maybe_i8(x); } + builder.add_just_i8(args.just_i8); + builder.finish() + } + + pub fn unpack(&self) -> ScalarStuffT { + let just_i8 = self.just_i8(); + let maybe_i8 = self.maybe_i8(); + let default_i8 = self.default_i8(); + let just_u8 = self.just_u8(); + let maybe_u8 = self.maybe_u8(); + let default_u8 = self.default_u8(); + let just_i16 = self.just_i16(); + let maybe_i16 = self.maybe_i16(); + let default_i16 = self.default_i16(); + let just_u16 = self.just_u16(); + let maybe_u16 = self.maybe_u16(); + let default_u16 = self.default_u16(); + let just_i32 = self.just_i32(); + let maybe_i32 = self.maybe_i32(); + let default_i32 = self.default_i32(); + let just_u32 = self.just_u32(); + let maybe_u32 = self.maybe_u32(); + let default_u32 = self.default_u32(); + let just_i64 = self.just_i64(); + let maybe_i64 = self.maybe_i64(); + let default_i64 = self.default_i64(); + let just_u64 = self.just_u64(); + let maybe_u64 = self.maybe_u64(); + let default_u64 = self.default_u64(); + let just_f32 = self.just_f32(); + let maybe_f32 = self.maybe_f32(); + let default_f32 = self.default_f32(); + let just_f64 = self.just_f64(); + let maybe_f64 = self.maybe_f64(); + let default_f64 = self.default_f64(); + let just_bool = self.just_bool(); + let maybe_bool = self.maybe_bool(); + let default_bool = self.default_bool(); + let just_enum = self.just_enum(); + let maybe_enum = self.maybe_enum(); + let default_enum = self.default_enum(); + ScalarStuffT { + just_i8, + maybe_i8, + default_i8, + just_u8, + maybe_u8, + default_u8, + just_i16, + maybe_i16, + default_i16, + just_u16, + maybe_u16, + default_u16, + just_i32, + maybe_i32, + default_i32, + just_u32, + maybe_u32, + default_u32, + just_i64, + maybe_i64, + default_i64, + just_u64, + maybe_u64, + default_u64, + just_f32, + maybe_f32, + default_f32, + just_f64, + maybe_f64, + default_f64, + just_bool, + maybe_bool, + default_bool, + just_enum, + maybe_enum, + default_enum, + } + } + + #[inline] + pub fn just_i8(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I8, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i8(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I8, None)} + } + #[inline] + pub fn default_i8(&self) -> i8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I8, Some(42)).unwrap()} + } + #[inline] + pub fn just_u8(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U8, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u8(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U8, None)} + } + #[inline] + pub fn default_u8(&self) -> u8 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U8, Some(42)).unwrap()} + } + #[inline] + pub fn just_i16(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I16, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i16(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I16, None)} + } + #[inline] + pub fn default_i16(&self) -> i16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I16, Some(42)).unwrap()} + } + #[inline] + pub fn just_u16(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U16, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u16(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U16, None)} + } + #[inline] + pub fn default_u16(&self) -> u16 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U16, Some(42)).unwrap()} + } + #[inline] + pub fn just_i32(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I32, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i32(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I32, None)} + } + #[inline] + pub fn default_i32(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I32, Some(42)).unwrap()} + } + #[inline] + pub fn just_u32(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U32, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u32(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U32, None)} + } + #[inline] + pub fn default_u32(&self) -> u32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U32, Some(42)).unwrap()} + } + #[inline] + pub fn just_i64(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_I64, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_i64(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_I64, None)} + } + #[inline] + pub fn default_i64(&self) -> i64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_I64, Some(42)).unwrap()} + } + #[inline] + pub fn just_u64(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_U64, Some(0)).unwrap()} + } + #[inline] + pub fn maybe_u64(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_U64, None)} + } + #[inline] + pub fn default_u64(&self) -> u64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_U64, Some(42)).unwrap()} + } + #[inline] + pub fn just_f32(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_F32, Some(0.0)).unwrap()} + } + #[inline] + pub fn maybe_f32(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_F32, None)} + } + #[inline] + pub fn default_f32(&self) -> f32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_F32, Some(42.0)).unwrap()} + } + #[inline] + pub fn just_f64(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_F64, Some(0.0)).unwrap()} + } + #[inline] + pub fn maybe_f64(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_F64, None)} + } + #[inline] + pub fn default_f64(&self) -> f64 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_F64, Some(42.0)).unwrap()} + } + #[inline] + pub fn just_bool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_BOOL, Some(false)).unwrap()} + } + #[inline] + pub fn maybe_bool(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_BOOL, None)} + } + #[inline] + pub fn default_bool(&self) -> bool { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_BOOL, Some(true)).unwrap()} + } + #[inline] + pub fn just_enum(&self) -> OptionalByte { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_JUST_ENUM, Some(OptionalByte::None)).unwrap()} + } + #[inline] + pub fn maybe_enum(&self) -> Option { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_MAYBE_ENUM, None)} + } + #[inline] + pub fn default_enum(&self) -> OptionalByte { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(ScalarStuff::VT_DEFAULT_ENUM, Some(OptionalByte::One)).unwrap()} + } +} + +impl flatbuffers::Verifiable for ScalarStuff<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("just_i8", Self::VT_JUST_I8, false)? + .visit_field::("maybe_i8", Self::VT_MAYBE_I8, false)? + .visit_field::("default_i8", Self::VT_DEFAULT_I8, false)? + .visit_field::("just_u8", Self::VT_JUST_U8, false)? + .visit_field::("maybe_u8", Self::VT_MAYBE_U8, false)? + .visit_field::("default_u8", Self::VT_DEFAULT_U8, false)? + .visit_field::("just_i16", Self::VT_JUST_I16, false)? + .visit_field::("maybe_i16", Self::VT_MAYBE_I16, false)? + .visit_field::("default_i16", Self::VT_DEFAULT_I16, false)? + .visit_field::("just_u16", Self::VT_JUST_U16, false)? + .visit_field::("maybe_u16", Self::VT_MAYBE_U16, false)? + .visit_field::("default_u16", Self::VT_DEFAULT_U16, false)? + .visit_field::("just_i32", Self::VT_JUST_I32, false)? + .visit_field::("maybe_i32", Self::VT_MAYBE_I32, false)? + .visit_field::("default_i32", Self::VT_DEFAULT_I32, false)? + .visit_field::("just_u32", Self::VT_JUST_U32, false)? + .visit_field::("maybe_u32", Self::VT_MAYBE_U32, false)? + .visit_field::("default_u32", Self::VT_DEFAULT_U32, false)? + .visit_field::("just_i64", Self::VT_JUST_I64, false)? + .visit_field::("maybe_i64", Self::VT_MAYBE_I64, false)? + .visit_field::("default_i64", Self::VT_DEFAULT_I64, false)? + .visit_field::("just_u64", Self::VT_JUST_U64, false)? + .visit_field::("maybe_u64", Self::VT_MAYBE_U64, false)? + .visit_field::("default_u64", Self::VT_DEFAULT_U64, false)? + .visit_field::("just_f32", Self::VT_JUST_F32, false)? + .visit_field::("maybe_f32", Self::VT_MAYBE_F32, false)? + .visit_field::("default_f32", Self::VT_DEFAULT_F32, false)? + .visit_field::("just_f64", Self::VT_JUST_F64, false)? + .visit_field::("maybe_f64", Self::VT_MAYBE_F64, false)? + .visit_field::("default_f64", Self::VT_DEFAULT_F64, false)? + .visit_field::("just_bool", Self::VT_JUST_BOOL, false)? + .visit_field::("maybe_bool", Self::VT_MAYBE_BOOL, false)? + .visit_field::("default_bool", Self::VT_DEFAULT_BOOL, false)? + .visit_field::("just_enum", Self::VT_JUST_ENUM, false)? + .visit_field::("maybe_enum", Self::VT_MAYBE_ENUM, false)? + .visit_field::("default_enum", Self::VT_DEFAULT_ENUM, false)? + .finish(); + Ok(()) + } +} +pub struct ScalarStuffArgs { + pub just_i8: i8, + pub maybe_i8: Option, + pub default_i8: i8, + pub just_u8: u8, + pub maybe_u8: Option, + pub default_u8: u8, + pub just_i16: i16, + pub maybe_i16: Option, + pub default_i16: i16, + pub just_u16: u16, + pub maybe_u16: Option, + pub default_u16: u16, + pub just_i32: i32, + pub maybe_i32: Option, + pub default_i32: i32, + pub just_u32: u32, + pub maybe_u32: Option, + pub default_u32: u32, + pub just_i64: i64, + pub maybe_i64: Option, + pub default_i64: i64, + pub just_u64: u64, + pub maybe_u64: Option, + pub default_u64: u64, + pub just_f32: f32, + pub maybe_f32: Option, + pub default_f32: f32, + pub just_f64: f64, + pub maybe_f64: Option, + pub default_f64: f64, + pub just_bool: bool, + pub maybe_bool: Option, + pub default_bool: bool, + pub just_enum: OptionalByte, + pub maybe_enum: Option, + pub default_enum: OptionalByte, +} +impl<'a> Default for ScalarStuffArgs { + #[inline] + fn default() -> Self { + ScalarStuffArgs { + just_i8: 0, + maybe_i8: None, + default_i8: 42, + just_u8: 0, + maybe_u8: None, + default_u8: 42, + just_i16: 0, + maybe_i16: None, + default_i16: 42, + just_u16: 0, + maybe_u16: None, + default_u16: 42, + just_i32: 0, + maybe_i32: None, + default_i32: 42, + just_u32: 0, + maybe_u32: None, + default_u32: 42, + just_i64: 0, + maybe_i64: None, + default_i64: 42, + just_u64: 0, + maybe_u64: None, + default_u64: 42, + just_f32: 0.0, + maybe_f32: None, + default_f32: 42.0, + just_f64: 0.0, + maybe_f64: None, + default_f64: 42.0, + just_bool: false, + maybe_bool: None, + default_bool: true, + just_enum: OptionalByte::None, + maybe_enum: None, + default_enum: OptionalByte::One, + } + } +} + +pub struct ScalarStuffBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> ScalarStuffBuilder<'a, 'b, A> { + #[inline] + pub fn add_just_i8(&mut self, just_i8: i8) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I8, just_i8, 0); + } + #[inline] + pub fn add_maybe_i8(&mut self, maybe_i8: i8) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I8, maybe_i8); + } + #[inline] + pub fn add_default_i8(&mut self, default_i8: i8) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I8, default_i8, 42); + } + #[inline] + pub fn add_just_u8(&mut self, just_u8: u8) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U8, just_u8, 0); + } + #[inline] + pub fn add_maybe_u8(&mut self, maybe_u8: u8) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U8, maybe_u8); + } + #[inline] + pub fn add_default_u8(&mut self, default_u8: u8) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U8, default_u8, 42); + } + #[inline] + pub fn add_just_i16(&mut self, just_i16: i16) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I16, just_i16, 0); + } + #[inline] + pub fn add_maybe_i16(&mut self, maybe_i16: i16) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I16, maybe_i16); + } + #[inline] + pub fn add_default_i16(&mut self, default_i16: i16) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I16, default_i16, 42); + } + #[inline] + pub fn add_just_u16(&mut self, just_u16: u16) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U16, just_u16, 0); + } + #[inline] + pub fn add_maybe_u16(&mut self, maybe_u16: u16) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U16, maybe_u16); + } + #[inline] + pub fn add_default_u16(&mut self, default_u16: u16) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U16, default_u16, 42); + } + #[inline] + pub fn add_just_i32(&mut self, just_i32: i32) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I32, just_i32, 0); + } + #[inline] + pub fn add_maybe_i32(&mut self, maybe_i32: i32) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I32, maybe_i32); + } + #[inline] + pub fn add_default_i32(&mut self, default_i32: i32) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I32, default_i32, 42); + } + #[inline] + pub fn add_just_u32(&mut self, just_u32: u32) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U32, just_u32, 0); + } + #[inline] + pub fn add_maybe_u32(&mut self, maybe_u32: u32) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U32, maybe_u32); + } + #[inline] + pub fn add_default_u32(&mut self, default_u32: u32) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U32, default_u32, 42); + } + #[inline] + pub fn add_just_i64(&mut self, just_i64: i64) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_I64, just_i64, 0); + } + #[inline] + pub fn add_maybe_i64(&mut self, maybe_i64: i64) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_I64, maybe_i64); + } + #[inline] + pub fn add_default_i64(&mut self, default_i64: i64) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_I64, default_i64, 42); + } + #[inline] + pub fn add_just_u64(&mut self, just_u64: u64) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_U64, just_u64, 0); + } + #[inline] + pub fn add_maybe_u64(&mut self, maybe_u64: u64) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_U64, maybe_u64); + } + #[inline] + pub fn add_default_u64(&mut self, default_u64: u64) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_U64, default_u64, 42); + } + #[inline] + pub fn add_just_f32(&mut self, just_f32: f32) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_F32, just_f32, 0.0); + } + #[inline] + pub fn add_maybe_f32(&mut self, maybe_f32: f32) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_F32, maybe_f32); + } + #[inline] + pub fn add_default_f32(&mut self, default_f32: f32) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0); + } + #[inline] + pub fn add_just_f64(&mut self, just_f64: f64) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_F64, just_f64, 0.0); + } + #[inline] + pub fn add_maybe_f64(&mut self, maybe_f64: f64) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_F64, maybe_f64); + } + #[inline] + pub fn add_default_f64(&mut self, default_f64: f64) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0); + } + #[inline] + pub fn add_just_bool(&mut self, just_bool: bool) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_BOOL, just_bool, false); + } + #[inline] + pub fn add_maybe_bool(&mut self, maybe_bool: bool) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_BOOL, maybe_bool); + } + #[inline] + pub fn add_default_bool(&mut self, default_bool: bool) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_BOOL, default_bool, true); + } + #[inline] + pub fn add_just_enum(&mut self, just_enum: OptionalByte) { + self.fbb_.push_slot::(ScalarStuff::VT_JUST_ENUM, just_enum, OptionalByte::None); + } + #[inline] + pub fn add_maybe_enum(&mut self, maybe_enum: OptionalByte) { + self.fbb_.push_slot_always::(ScalarStuff::VT_MAYBE_ENUM, maybe_enum); + } + #[inline] + pub fn add_default_enum(&mut self, default_enum: OptionalByte) { + self.fbb_.push_slot::(ScalarStuff::VT_DEFAULT_ENUM, default_enum, OptionalByte::One); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> ScalarStuffBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + ScalarStuffBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for ScalarStuff<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("ScalarStuff"); + ds.field("just_i8", &self.just_i8()); + ds.field("maybe_i8", &self.maybe_i8()); + ds.field("default_i8", &self.default_i8()); + ds.field("just_u8", &self.just_u8()); + ds.field("maybe_u8", &self.maybe_u8()); + ds.field("default_u8", &self.default_u8()); + ds.field("just_i16", &self.just_i16()); + ds.field("maybe_i16", &self.maybe_i16()); + ds.field("default_i16", &self.default_i16()); + ds.field("just_u16", &self.just_u16()); + ds.field("maybe_u16", &self.maybe_u16()); + ds.field("default_u16", &self.default_u16()); + ds.field("just_i32", &self.just_i32()); + ds.field("maybe_i32", &self.maybe_i32()); + ds.field("default_i32", &self.default_i32()); + ds.field("just_u32", &self.just_u32()); + ds.field("maybe_u32", &self.maybe_u32()); + ds.field("default_u32", &self.default_u32()); + ds.field("just_i64", &self.just_i64()); + ds.field("maybe_i64", &self.maybe_i64()); + ds.field("default_i64", &self.default_i64()); + ds.field("just_u64", &self.just_u64()); + ds.field("maybe_u64", &self.maybe_u64()); + ds.field("default_u64", &self.default_u64()); + ds.field("just_f32", &self.just_f32()); + ds.field("maybe_f32", &self.maybe_f32()); + ds.field("default_f32", &self.default_f32()); + ds.field("just_f64", &self.just_f64()); + ds.field("maybe_f64", &self.maybe_f64()); + ds.field("default_f64", &self.default_f64()); + ds.field("just_bool", &self.just_bool()); + ds.field("maybe_bool", &self.maybe_bool()); + ds.field("default_bool", &self.default_bool()); + ds.field("just_enum", &self.just_enum()); + ds.field("maybe_enum", &self.maybe_enum()); + ds.field("default_enum", &self.default_enum()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct ScalarStuffT { + pub just_i8: i8, + pub maybe_i8: Option, + pub default_i8: i8, + pub just_u8: u8, + pub maybe_u8: Option, + pub default_u8: u8, + pub just_i16: i16, + pub maybe_i16: Option, + pub default_i16: i16, + pub just_u16: u16, + pub maybe_u16: Option, + pub default_u16: u16, + pub just_i32: i32, + pub maybe_i32: Option, + pub default_i32: i32, + pub just_u32: u32, + pub maybe_u32: Option, + pub default_u32: u32, + pub just_i64: i64, + pub maybe_i64: Option, + pub default_i64: i64, + pub just_u64: u64, + pub maybe_u64: Option, + pub default_u64: u64, + pub just_f32: f32, + pub maybe_f32: Option, + pub default_f32: f32, + pub just_f64: f64, + pub maybe_f64: Option, + pub default_f64: f64, + pub just_bool: bool, + pub maybe_bool: Option, + pub default_bool: bool, + pub just_enum: OptionalByte, + pub maybe_enum: Option, + pub default_enum: OptionalByte, +} +impl Default for ScalarStuffT { + fn default() -> Self { + Self { + just_i8: 0, + maybe_i8: None, + default_i8: 42, + just_u8: 0, + maybe_u8: None, + default_u8: 42, + just_i16: 0, + maybe_i16: None, + default_i16: 42, + just_u16: 0, + maybe_u16: None, + default_u16: 42, + just_i32: 0, + maybe_i32: None, + default_i32: 42, + just_u32: 0, + maybe_u32: None, + default_u32: 42, + just_i64: 0, + maybe_i64: None, + default_i64: 42, + just_u64: 0, + maybe_u64: None, + default_u64: 42, + just_f32: 0.0, + maybe_f32: None, + default_f32: 42.0, + just_f64: 0.0, + maybe_f64: None, + default_f64: 42.0, + just_bool: false, + maybe_bool: None, + default_bool: true, + just_enum: OptionalByte::None, + maybe_enum: None, + default_enum: OptionalByte::One, + } + } +} +impl ScalarStuffT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let just_i8 = self.just_i8; + let maybe_i8 = self.maybe_i8; + let default_i8 = self.default_i8; + let just_u8 = self.just_u8; + let maybe_u8 = self.maybe_u8; + let default_u8 = self.default_u8; + let just_i16 = self.just_i16; + let maybe_i16 = self.maybe_i16; + let default_i16 = self.default_i16; + let just_u16 = self.just_u16; + let maybe_u16 = self.maybe_u16; + let default_u16 = self.default_u16; + let just_i32 = self.just_i32; + let maybe_i32 = self.maybe_i32; + let default_i32 = self.default_i32; + let just_u32 = self.just_u32; + let maybe_u32 = self.maybe_u32; + let default_u32 = self.default_u32; + let just_i64 = self.just_i64; + let maybe_i64 = self.maybe_i64; + let default_i64 = self.default_i64; + let just_u64 = self.just_u64; + let maybe_u64 = self.maybe_u64; + let default_u64 = self.default_u64; + let just_f32 = self.just_f32; + let maybe_f32 = self.maybe_f32; + let default_f32 = self.default_f32; + let just_f64 = self.just_f64; + let maybe_f64 = self.maybe_f64; + let default_f64 = self.default_f64; + let just_bool = self.just_bool; + let maybe_bool = self.maybe_bool; + let default_bool = self.default_bool; + let just_enum = self.just_enum; + let maybe_enum = self.maybe_enum; + let default_enum = self.default_enum; + ScalarStuff::create(_fbb, &ScalarStuffArgs{ + just_i8, + maybe_i8, + default_i8, + just_u8, + maybe_u8, + default_u8, + just_i16, + maybe_i16, + default_i16, + just_u16, + maybe_u16, + default_u16, + just_i32, + maybe_i32, + default_i32, + just_u32, + maybe_u32, + default_u32, + just_i64, + maybe_i64, + default_i64, + just_u64, + maybe_u64, + default_u64, + just_f32, + maybe_f32, + default_f32, + just_f64, + maybe_f64, + default_f64, + just_bool, + maybe_bool, + default_bool, + just_enum, + maybe_enum, + default_enum, + }) + } +} +#[inline] +/// Verifies that a buffer of bytes contains a `ScalarStuff` +/// and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_scalar_stuff_unchecked`. +pub fn root_as_scalar_stuff(buf: &[u8]) -> Result { + flatbuffers::root::(buf) +} +#[inline] +/// Verifies that a buffer of bytes contains a size prefixed +/// `ScalarStuff` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `size_prefixed_root_as_scalar_stuff_unchecked`. +pub fn size_prefixed_root_as_scalar_stuff(buf: &[u8]) -> Result { + flatbuffers::size_prefixed_root::(buf) +} +#[inline] +/// Verifies, with the given options, that a buffer of bytes +/// contains a `ScalarStuff` and returns it. +/// Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_scalar_stuff_unchecked`. +pub fn root_as_scalar_stuff_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::root_with_opts::>(opts, buf) +} +#[inline] +/// Verifies, with the given verifier options, that a buffer of +/// bytes contains a size prefixed `ScalarStuff` and returns +/// it. Note that verification is still experimental and may not +/// catch every error, or be maximally performant. For the +/// previous, unchecked, behavior use +/// `root_as_scalar_stuff_unchecked`. +pub fn size_prefixed_root_as_scalar_stuff_with_opts<'b, 'o>( + opts: &'o flatbuffers::VerifierOptions, + buf: &'b [u8], +) -> Result, flatbuffers::InvalidFlatbuffer> { + flatbuffers::size_prefixed_root_with_opts::>(opts, buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a ScalarStuff and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid `ScalarStuff`. +pub unsafe fn root_as_scalar_stuff_unchecked(buf: &[u8]) -> ScalarStuff { + flatbuffers::root_unchecked::(buf) +} +#[inline] +/// Assumes, without verification, that a buffer of bytes contains a size prefixed ScalarStuff and returns it. +/// # Safety +/// Callers must trust the given bytes do indeed contain a valid size prefixed `ScalarStuff`. +pub unsafe fn size_prefixed_root_as_scalar_stuff_unchecked(buf: &[u8]) -> ScalarStuff { + flatbuffers::size_prefixed_root_unchecked::(buf) +} +pub const SCALAR_STUFF_IDENTIFIER: &str = "NULL"; + +#[inline] +pub fn scalar_stuff_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, false) +} + +#[inline] +pub fn scalar_stuff_size_prefixed_buffer_has_identifier(buf: &[u8]) -> bool { + flatbuffers::buffer_has_identifier(buf, SCALAR_STUFF_IDENTIFIER, true) +} + +pub const SCALAR_STUFF_EXTENSION: &str = "mon"; + +#[inline] +pub fn finish_scalar_stuff_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>( + fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + root: flatbuffers::WIPOffset>) { + fbb.finish(root, Some(SCALAR_STUFF_IDENTIFIER)); +} + +#[inline] +pub fn finish_size_prefixed_scalar_stuff_buffer<'a, 'b, A: flatbuffers::Allocator + 'a>(fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, root: flatbuffers::WIPOffset>) { + fbb.finish_size_prefixed(root, Some(SCALAR_STUFF_IDENTIFIER)); +} diff --git a/third_party/flatbuffers/tests/optional_scalars_defaults.json b/third_party/flatbuffers/tests/optional_scalars_defaults.json new file mode 100644 index 00000000000..1f44993f47b --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars_defaults.json @@ -0,0 +1,38 @@ +{ + just_i8: 4, + maybe_i8: null, + default_i8: 42, + just_u8: 0, + maybe_u8: 0, + default_u8: 0, + just_i16: 4, + maybe_i16: null, + default_i16: 42, + just_u16: 0, + maybe_u16: 0, + default_u16: 0, + just_i32: 4, + maybe_i32: null, + default_i32: 42, + just_u32: 0, + maybe_u32: 0, + default_u32: 0, + just_i64: 4, + maybe_i64: null, + default_i64: 42, + just_u64: 0, + maybe_u64: 0, + default_u64: 0, + just_f32: 4.0, + maybe_f32: null, + default_f32: 42.0, + just_f64: 0.0, + maybe_f64: 0.0, + default_f64: 0.0, + just_bool: true, + maybe_bool: null, + default_bool: false, + just_enum: "None", + maybe_enum: "One", + default_enum: "Two" +} diff --git a/third_party/flatbuffers/tests/optional_scalars_generated.h b/third_party/flatbuffers/tests/optional_scalars_generated.h new file mode 100644 index 00000000000..759f0dbb049 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars_generated.h @@ -0,0 +1,961 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_OPTIONALSCALARS_OPTIONAL_SCALARS_H_ +#define FLATBUFFERS_GENERATED_OPTIONALSCALARS_OPTIONAL_SCALARS_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace optional_scalars { + +struct ScalarStuff; +struct ScalarStuffBuilder; +struct ScalarStuffT; + +bool operator==(const ScalarStuffT &lhs, const ScalarStuffT &rhs); +bool operator!=(const ScalarStuffT &lhs, const ScalarStuffT &rhs); + +inline const ::flatbuffers::TypeTable *ScalarStuffTypeTable(); + +enum OptionalByte : int8_t { + OptionalByte_None = 0, + OptionalByte_One = 1, + OptionalByte_Two = 2, + OptionalByte_MIN = OptionalByte_None, + OptionalByte_MAX = OptionalByte_Two +}; + +inline const OptionalByte (&EnumValuesOptionalByte())[3] { + static const OptionalByte values[] = { + OptionalByte_None, + OptionalByte_One, + OptionalByte_Two + }; + return values; +} + +inline const char * const *EnumNamesOptionalByte() { + static const char * const names[4] = { + "None", + "One", + "Two", + nullptr + }; + return names; +} + +inline const char *EnumNameOptionalByte(OptionalByte e) { + if (::flatbuffers::IsOutRange(e, OptionalByte_None, OptionalByte_Two)) return ""; + const size_t index = static_cast(e); + return EnumNamesOptionalByte()[index]; +} + +struct ScalarStuffT : public ::flatbuffers::NativeTable { + typedef ScalarStuff TableType; + int8_t just_i8 = 0; + ::flatbuffers::Optional maybe_i8 = ::flatbuffers::nullopt; + int8_t default_i8 = 42; + uint8_t just_u8 = 0; + ::flatbuffers::Optional maybe_u8 = ::flatbuffers::nullopt; + uint8_t default_u8 = 42; + int16_t just_i16 = 0; + ::flatbuffers::Optional maybe_i16 = ::flatbuffers::nullopt; + int16_t default_i16 = 42; + uint16_t just_u16 = 0; + ::flatbuffers::Optional maybe_u16 = ::flatbuffers::nullopt; + uint16_t default_u16 = 42; + int32_t just_i32 = 0; + ::flatbuffers::Optional maybe_i32 = ::flatbuffers::nullopt; + int32_t default_i32 = 42; + uint32_t just_u32 = 0; + ::flatbuffers::Optional maybe_u32 = ::flatbuffers::nullopt; + uint32_t default_u32 = 42; + int64_t just_i64 = 0; + ::flatbuffers::Optional maybe_i64 = ::flatbuffers::nullopt; + int64_t default_i64 = 42LL; + uint64_t just_u64 = 0; + ::flatbuffers::Optional maybe_u64 = ::flatbuffers::nullopt; + uint64_t default_u64 = 42ULL; + float just_f32 = 0.0f; + ::flatbuffers::Optional maybe_f32 = ::flatbuffers::nullopt; + float default_f32 = 42.0f; + double just_f64 = 0.0; + ::flatbuffers::Optional maybe_f64 = ::flatbuffers::nullopt; + double default_f64 = 42.0; + bool just_bool = false; + ::flatbuffers::Optional maybe_bool = ::flatbuffers::nullopt; + bool default_bool = true; + optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte_None; + ::flatbuffers::Optional maybe_enum = ::flatbuffers::nullopt; + optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte_One; +}; + +struct ScalarStuff FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef ScalarStuffT NativeTableType; + typedef ScalarStuffBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ScalarStuffTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_JUST_I8 = 4, + VT_MAYBE_I8 = 6, + VT_DEFAULT_I8 = 8, + VT_JUST_U8 = 10, + VT_MAYBE_U8 = 12, + VT_DEFAULT_U8 = 14, + VT_JUST_I16 = 16, + VT_MAYBE_I16 = 18, + VT_DEFAULT_I16 = 20, + VT_JUST_U16 = 22, + VT_MAYBE_U16 = 24, + VT_DEFAULT_U16 = 26, + VT_JUST_I32 = 28, + VT_MAYBE_I32 = 30, + VT_DEFAULT_I32 = 32, + VT_JUST_U32 = 34, + VT_MAYBE_U32 = 36, + VT_DEFAULT_U32 = 38, + VT_JUST_I64 = 40, + VT_MAYBE_I64 = 42, + VT_DEFAULT_I64 = 44, + VT_JUST_U64 = 46, + VT_MAYBE_U64 = 48, + VT_DEFAULT_U64 = 50, + VT_JUST_F32 = 52, + VT_MAYBE_F32 = 54, + VT_DEFAULT_F32 = 56, + VT_JUST_F64 = 58, + VT_MAYBE_F64 = 60, + VT_DEFAULT_F64 = 62, + VT_JUST_BOOL = 64, + VT_MAYBE_BOOL = 66, + VT_DEFAULT_BOOL = 68, + VT_JUST_ENUM = 70, + VT_MAYBE_ENUM = 72, + VT_DEFAULT_ENUM = 74 + }; + int8_t just_i8() const { + return GetField(VT_JUST_I8, 0); + } + bool mutate_just_i8(int8_t _just_i8 = 0) { + return SetField(VT_JUST_I8, _just_i8, 0); + } + ::flatbuffers::Optional maybe_i8() const { + return GetOptional(VT_MAYBE_I8); + } + bool mutate_maybe_i8(int8_t _maybe_i8) { + return SetField(VT_MAYBE_I8, _maybe_i8); + } + int8_t default_i8() const { + return GetField(VT_DEFAULT_I8, 42); + } + bool mutate_default_i8(int8_t _default_i8 = 42) { + return SetField(VT_DEFAULT_I8, _default_i8, 42); + } + uint8_t just_u8() const { + return GetField(VT_JUST_U8, 0); + } + bool mutate_just_u8(uint8_t _just_u8 = 0) { + return SetField(VT_JUST_U8, _just_u8, 0); + } + ::flatbuffers::Optional maybe_u8() const { + return GetOptional(VT_MAYBE_U8); + } + bool mutate_maybe_u8(uint8_t _maybe_u8) { + return SetField(VT_MAYBE_U8, _maybe_u8); + } + uint8_t default_u8() const { + return GetField(VT_DEFAULT_U8, 42); + } + bool mutate_default_u8(uint8_t _default_u8 = 42) { + return SetField(VT_DEFAULT_U8, _default_u8, 42); + } + int16_t just_i16() const { + return GetField(VT_JUST_I16, 0); + } + bool mutate_just_i16(int16_t _just_i16 = 0) { + return SetField(VT_JUST_I16, _just_i16, 0); + } + ::flatbuffers::Optional maybe_i16() const { + return GetOptional(VT_MAYBE_I16); + } + bool mutate_maybe_i16(int16_t _maybe_i16) { + return SetField(VT_MAYBE_I16, _maybe_i16); + } + int16_t default_i16() const { + return GetField(VT_DEFAULT_I16, 42); + } + bool mutate_default_i16(int16_t _default_i16 = 42) { + return SetField(VT_DEFAULT_I16, _default_i16, 42); + } + uint16_t just_u16() const { + return GetField(VT_JUST_U16, 0); + } + bool mutate_just_u16(uint16_t _just_u16 = 0) { + return SetField(VT_JUST_U16, _just_u16, 0); + } + ::flatbuffers::Optional maybe_u16() const { + return GetOptional(VT_MAYBE_U16); + } + bool mutate_maybe_u16(uint16_t _maybe_u16) { + return SetField(VT_MAYBE_U16, _maybe_u16); + } + uint16_t default_u16() const { + return GetField(VT_DEFAULT_U16, 42); + } + bool mutate_default_u16(uint16_t _default_u16 = 42) { + return SetField(VT_DEFAULT_U16, _default_u16, 42); + } + int32_t just_i32() const { + return GetField(VT_JUST_I32, 0); + } + bool mutate_just_i32(int32_t _just_i32 = 0) { + return SetField(VT_JUST_I32, _just_i32, 0); + } + ::flatbuffers::Optional maybe_i32() const { + return GetOptional(VT_MAYBE_I32); + } + bool mutate_maybe_i32(int32_t _maybe_i32) { + return SetField(VT_MAYBE_I32, _maybe_i32); + } + int32_t default_i32() const { + return GetField(VT_DEFAULT_I32, 42); + } + bool mutate_default_i32(int32_t _default_i32 = 42) { + return SetField(VT_DEFAULT_I32, _default_i32, 42); + } + uint32_t just_u32() const { + return GetField(VT_JUST_U32, 0); + } + bool mutate_just_u32(uint32_t _just_u32 = 0) { + return SetField(VT_JUST_U32, _just_u32, 0); + } + ::flatbuffers::Optional maybe_u32() const { + return GetOptional(VT_MAYBE_U32); + } + bool mutate_maybe_u32(uint32_t _maybe_u32) { + return SetField(VT_MAYBE_U32, _maybe_u32); + } + uint32_t default_u32() const { + return GetField(VT_DEFAULT_U32, 42); + } + bool mutate_default_u32(uint32_t _default_u32 = 42) { + return SetField(VT_DEFAULT_U32, _default_u32, 42); + } + int64_t just_i64() const { + return GetField(VT_JUST_I64, 0); + } + bool mutate_just_i64(int64_t _just_i64 = 0) { + return SetField(VT_JUST_I64, _just_i64, 0); + } + ::flatbuffers::Optional maybe_i64() const { + return GetOptional(VT_MAYBE_I64); + } + bool mutate_maybe_i64(int64_t _maybe_i64) { + return SetField(VT_MAYBE_I64, _maybe_i64); + } + int64_t default_i64() const { + return GetField(VT_DEFAULT_I64, 42LL); + } + bool mutate_default_i64(int64_t _default_i64 = 42LL) { + return SetField(VT_DEFAULT_I64, _default_i64, 42LL); + } + uint64_t just_u64() const { + return GetField(VT_JUST_U64, 0); + } + bool mutate_just_u64(uint64_t _just_u64 = 0) { + return SetField(VT_JUST_U64, _just_u64, 0); + } + ::flatbuffers::Optional maybe_u64() const { + return GetOptional(VT_MAYBE_U64); + } + bool mutate_maybe_u64(uint64_t _maybe_u64) { + return SetField(VT_MAYBE_U64, _maybe_u64); + } + uint64_t default_u64() const { + return GetField(VT_DEFAULT_U64, 42ULL); + } + bool mutate_default_u64(uint64_t _default_u64 = 42ULL) { + return SetField(VT_DEFAULT_U64, _default_u64, 42ULL); + } + float just_f32() const { + return GetField(VT_JUST_F32, 0.0f); + } + bool mutate_just_f32(float _just_f32 = 0.0f) { + return SetField(VT_JUST_F32, _just_f32, 0.0f); + } + ::flatbuffers::Optional maybe_f32() const { + return GetOptional(VT_MAYBE_F32); + } + bool mutate_maybe_f32(float _maybe_f32) { + return SetField(VT_MAYBE_F32, _maybe_f32); + } + float default_f32() const { + return GetField(VT_DEFAULT_F32, 42.0f); + } + bool mutate_default_f32(float _default_f32 = 42.0f) { + return SetField(VT_DEFAULT_F32, _default_f32, 42.0f); + } + double just_f64() const { + return GetField(VT_JUST_F64, 0.0); + } + bool mutate_just_f64(double _just_f64 = 0.0) { + return SetField(VT_JUST_F64, _just_f64, 0.0); + } + ::flatbuffers::Optional maybe_f64() const { + return GetOptional(VT_MAYBE_F64); + } + bool mutate_maybe_f64(double _maybe_f64) { + return SetField(VT_MAYBE_F64, _maybe_f64); + } + double default_f64() const { + return GetField(VT_DEFAULT_F64, 42.0); + } + bool mutate_default_f64(double _default_f64 = 42.0) { + return SetField(VT_DEFAULT_F64, _default_f64, 42.0); + } + bool just_bool() const { + return GetField(VT_JUST_BOOL, 0) != 0; + } + bool mutate_just_bool(bool _just_bool = 0) { + return SetField(VT_JUST_BOOL, static_cast(_just_bool), 0); + } + ::flatbuffers::Optional maybe_bool() const { + return GetOptional(VT_MAYBE_BOOL); + } + bool mutate_maybe_bool(bool _maybe_bool) { + return SetField(VT_MAYBE_BOOL, static_cast(_maybe_bool)); + } + bool default_bool() const { + return GetField(VT_DEFAULT_BOOL, 1) != 0; + } + bool mutate_default_bool(bool _default_bool = 1) { + return SetField(VT_DEFAULT_BOOL, static_cast(_default_bool), 1); + } + optional_scalars::OptionalByte just_enum() const { + return static_cast(GetField(VT_JUST_ENUM, 0)); + } + bool mutate_just_enum(optional_scalars::OptionalByte _just_enum = static_cast(0)) { + return SetField(VT_JUST_ENUM, static_cast(_just_enum), 0); + } + ::flatbuffers::Optional maybe_enum() const { + return GetOptional(VT_MAYBE_ENUM); + } + bool mutate_maybe_enum(optional_scalars::OptionalByte _maybe_enum) { + return SetField(VT_MAYBE_ENUM, static_cast(_maybe_enum)); + } + optional_scalars::OptionalByte default_enum() const { + return static_cast(GetField(VT_DEFAULT_ENUM, 1)); + } + bool mutate_default_enum(optional_scalars::OptionalByte _default_enum = static_cast(1)) { + return SetField(VT_DEFAULT_ENUM, static_cast(_default_enum), 1); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_JUST_I8, 1) && + VerifyField(verifier, VT_MAYBE_I8, 1) && + VerifyField(verifier, VT_DEFAULT_I8, 1) && + VerifyField(verifier, VT_JUST_U8, 1) && + VerifyField(verifier, VT_MAYBE_U8, 1) && + VerifyField(verifier, VT_DEFAULT_U8, 1) && + VerifyField(verifier, VT_JUST_I16, 2) && + VerifyField(verifier, VT_MAYBE_I16, 2) && + VerifyField(verifier, VT_DEFAULT_I16, 2) && + VerifyField(verifier, VT_JUST_U16, 2) && + VerifyField(verifier, VT_MAYBE_U16, 2) && + VerifyField(verifier, VT_DEFAULT_U16, 2) && + VerifyField(verifier, VT_JUST_I32, 4) && + VerifyField(verifier, VT_MAYBE_I32, 4) && + VerifyField(verifier, VT_DEFAULT_I32, 4) && + VerifyField(verifier, VT_JUST_U32, 4) && + VerifyField(verifier, VT_MAYBE_U32, 4) && + VerifyField(verifier, VT_DEFAULT_U32, 4) && + VerifyField(verifier, VT_JUST_I64, 8) && + VerifyField(verifier, VT_MAYBE_I64, 8) && + VerifyField(verifier, VT_DEFAULT_I64, 8) && + VerifyField(verifier, VT_JUST_U64, 8) && + VerifyField(verifier, VT_MAYBE_U64, 8) && + VerifyField(verifier, VT_DEFAULT_U64, 8) && + VerifyField(verifier, VT_JUST_F32, 4) && + VerifyField(verifier, VT_MAYBE_F32, 4) && + VerifyField(verifier, VT_DEFAULT_F32, 4) && + VerifyField(verifier, VT_JUST_F64, 8) && + VerifyField(verifier, VT_MAYBE_F64, 8) && + VerifyField(verifier, VT_DEFAULT_F64, 8) && + VerifyField(verifier, VT_JUST_BOOL, 1) && + VerifyField(verifier, VT_MAYBE_BOOL, 1) && + VerifyField(verifier, VT_DEFAULT_BOOL, 1) && + VerifyField(verifier, VT_JUST_ENUM, 1) && + VerifyField(verifier, VT_MAYBE_ENUM, 1) && + VerifyField(verifier, VT_DEFAULT_ENUM, 1) && + verifier.EndTable(); + } + ScalarStuffT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(ScalarStuffT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ScalarStuffBuilder { + typedef ScalarStuff Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_just_i8(int8_t just_i8) { + fbb_.AddElement(ScalarStuff::VT_JUST_I8, just_i8, 0); + } + void add_maybe_i8(int8_t maybe_i8) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I8, maybe_i8); + } + void add_default_i8(int8_t default_i8) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I8, default_i8, 42); + } + void add_just_u8(uint8_t just_u8) { + fbb_.AddElement(ScalarStuff::VT_JUST_U8, just_u8, 0); + } + void add_maybe_u8(uint8_t maybe_u8) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U8, maybe_u8); + } + void add_default_u8(uint8_t default_u8) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U8, default_u8, 42); + } + void add_just_i16(int16_t just_i16) { + fbb_.AddElement(ScalarStuff::VT_JUST_I16, just_i16, 0); + } + void add_maybe_i16(int16_t maybe_i16) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I16, maybe_i16); + } + void add_default_i16(int16_t default_i16) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I16, default_i16, 42); + } + void add_just_u16(uint16_t just_u16) { + fbb_.AddElement(ScalarStuff::VT_JUST_U16, just_u16, 0); + } + void add_maybe_u16(uint16_t maybe_u16) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U16, maybe_u16); + } + void add_default_u16(uint16_t default_u16) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U16, default_u16, 42); + } + void add_just_i32(int32_t just_i32) { + fbb_.AddElement(ScalarStuff::VT_JUST_I32, just_i32, 0); + } + void add_maybe_i32(int32_t maybe_i32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I32, maybe_i32); + } + void add_default_i32(int32_t default_i32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I32, default_i32, 42); + } + void add_just_u32(uint32_t just_u32) { + fbb_.AddElement(ScalarStuff::VT_JUST_U32, just_u32, 0); + } + void add_maybe_u32(uint32_t maybe_u32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U32, maybe_u32); + } + void add_default_u32(uint32_t default_u32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U32, default_u32, 42); + } + void add_just_i64(int64_t just_i64) { + fbb_.AddElement(ScalarStuff::VT_JUST_I64, just_i64, 0); + } + void add_maybe_i64(int64_t maybe_i64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_I64, maybe_i64); + } + void add_default_i64(int64_t default_i64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_I64, default_i64, 42LL); + } + void add_just_u64(uint64_t just_u64) { + fbb_.AddElement(ScalarStuff::VT_JUST_U64, just_u64, 0); + } + void add_maybe_u64(uint64_t maybe_u64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_U64, maybe_u64); + } + void add_default_u64(uint64_t default_u64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_U64, default_u64, 42ULL); + } + void add_just_f32(float just_f32) { + fbb_.AddElement(ScalarStuff::VT_JUST_F32, just_f32, 0.0f); + } + void add_maybe_f32(float maybe_f32) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_F32, maybe_f32); + } + void add_default_f32(float default_f32) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_F32, default_f32, 42.0f); + } + void add_just_f64(double just_f64) { + fbb_.AddElement(ScalarStuff::VT_JUST_F64, just_f64, 0.0); + } + void add_maybe_f64(double maybe_f64) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_F64, maybe_f64); + } + void add_default_f64(double default_f64) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_F64, default_f64, 42.0); + } + void add_just_bool(bool just_bool) { + fbb_.AddElement(ScalarStuff::VT_JUST_BOOL, static_cast(just_bool), 0); + } + void add_maybe_bool(bool maybe_bool) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_BOOL, static_cast(maybe_bool)); + } + void add_default_bool(bool default_bool) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_BOOL, static_cast(default_bool), 1); + } + void add_just_enum(optional_scalars::OptionalByte just_enum) { + fbb_.AddElement(ScalarStuff::VT_JUST_ENUM, static_cast(just_enum), 0); + } + void add_maybe_enum(optional_scalars::OptionalByte maybe_enum) { + fbb_.AddElement(ScalarStuff::VT_MAYBE_ENUM, static_cast(maybe_enum)); + } + void add_default_enum(optional_scalars::OptionalByte default_enum) { + fbb_.AddElement(ScalarStuff::VT_DEFAULT_ENUM, static_cast(default_enum), 1); + } + explicit ScalarStuffBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateScalarStuff( + ::flatbuffers::FlatBufferBuilder &_fbb, + int8_t just_i8 = 0, + ::flatbuffers::Optional maybe_i8 = ::flatbuffers::nullopt, + int8_t default_i8 = 42, + uint8_t just_u8 = 0, + ::flatbuffers::Optional maybe_u8 = ::flatbuffers::nullopt, + uint8_t default_u8 = 42, + int16_t just_i16 = 0, + ::flatbuffers::Optional maybe_i16 = ::flatbuffers::nullopt, + int16_t default_i16 = 42, + uint16_t just_u16 = 0, + ::flatbuffers::Optional maybe_u16 = ::flatbuffers::nullopt, + uint16_t default_u16 = 42, + int32_t just_i32 = 0, + ::flatbuffers::Optional maybe_i32 = ::flatbuffers::nullopt, + int32_t default_i32 = 42, + uint32_t just_u32 = 0, + ::flatbuffers::Optional maybe_u32 = ::flatbuffers::nullopt, + uint32_t default_u32 = 42, + int64_t just_i64 = 0, + ::flatbuffers::Optional maybe_i64 = ::flatbuffers::nullopt, + int64_t default_i64 = 42LL, + uint64_t just_u64 = 0, + ::flatbuffers::Optional maybe_u64 = ::flatbuffers::nullopt, + uint64_t default_u64 = 42ULL, + float just_f32 = 0.0f, + ::flatbuffers::Optional maybe_f32 = ::flatbuffers::nullopt, + float default_f32 = 42.0f, + double just_f64 = 0.0, + ::flatbuffers::Optional maybe_f64 = ::flatbuffers::nullopt, + double default_f64 = 42.0, + bool just_bool = false, + ::flatbuffers::Optional maybe_bool = ::flatbuffers::nullopt, + bool default_bool = true, + optional_scalars::OptionalByte just_enum = optional_scalars::OptionalByte_None, + ::flatbuffers::Optional maybe_enum = ::flatbuffers::nullopt, + optional_scalars::OptionalByte default_enum = optional_scalars::OptionalByte_One) { + ScalarStuffBuilder builder_(_fbb); + builder_.add_default_f64(default_f64); + if(maybe_f64) { builder_.add_maybe_f64(*maybe_f64); } + builder_.add_just_f64(just_f64); + builder_.add_default_u64(default_u64); + if(maybe_u64) { builder_.add_maybe_u64(*maybe_u64); } + builder_.add_just_u64(just_u64); + builder_.add_default_i64(default_i64); + if(maybe_i64) { builder_.add_maybe_i64(*maybe_i64); } + builder_.add_just_i64(just_i64); + builder_.add_default_f32(default_f32); + if(maybe_f32) { builder_.add_maybe_f32(*maybe_f32); } + builder_.add_just_f32(just_f32); + builder_.add_default_u32(default_u32); + if(maybe_u32) { builder_.add_maybe_u32(*maybe_u32); } + builder_.add_just_u32(just_u32); + builder_.add_default_i32(default_i32); + if(maybe_i32) { builder_.add_maybe_i32(*maybe_i32); } + builder_.add_just_i32(just_i32); + builder_.add_default_u16(default_u16); + if(maybe_u16) { builder_.add_maybe_u16(*maybe_u16); } + builder_.add_just_u16(just_u16); + builder_.add_default_i16(default_i16); + if(maybe_i16) { builder_.add_maybe_i16(*maybe_i16); } + builder_.add_just_i16(just_i16); + builder_.add_default_enum(default_enum); + if(maybe_enum) { builder_.add_maybe_enum(*maybe_enum); } + builder_.add_just_enum(just_enum); + builder_.add_default_bool(default_bool); + if(maybe_bool) { builder_.add_maybe_bool(*maybe_bool); } + builder_.add_just_bool(just_bool); + builder_.add_default_u8(default_u8); + if(maybe_u8) { builder_.add_maybe_u8(*maybe_u8); } + builder_.add_just_u8(just_u8); + builder_.add_default_i8(default_i8); + if(maybe_i8) { builder_.add_maybe_i8(*maybe_i8); } + builder_.add_just_i8(just_i8); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateScalarStuff(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const ScalarStuffT &lhs, const ScalarStuffT &rhs) { + return + (lhs.just_i8 == rhs.just_i8) && + (lhs.maybe_i8 == rhs.maybe_i8) && + (lhs.default_i8 == rhs.default_i8) && + (lhs.just_u8 == rhs.just_u8) && + (lhs.maybe_u8 == rhs.maybe_u8) && + (lhs.default_u8 == rhs.default_u8) && + (lhs.just_i16 == rhs.just_i16) && + (lhs.maybe_i16 == rhs.maybe_i16) && + (lhs.default_i16 == rhs.default_i16) && + (lhs.just_u16 == rhs.just_u16) && + (lhs.maybe_u16 == rhs.maybe_u16) && + (lhs.default_u16 == rhs.default_u16) && + (lhs.just_i32 == rhs.just_i32) && + (lhs.maybe_i32 == rhs.maybe_i32) && + (lhs.default_i32 == rhs.default_i32) && + (lhs.just_u32 == rhs.just_u32) && + (lhs.maybe_u32 == rhs.maybe_u32) && + (lhs.default_u32 == rhs.default_u32) && + (lhs.just_i64 == rhs.just_i64) && + (lhs.maybe_i64 == rhs.maybe_i64) && + (lhs.default_i64 == rhs.default_i64) && + (lhs.just_u64 == rhs.just_u64) && + (lhs.maybe_u64 == rhs.maybe_u64) && + (lhs.default_u64 == rhs.default_u64) && + (lhs.just_f32 == rhs.just_f32) && + (lhs.maybe_f32 == rhs.maybe_f32) && + (lhs.default_f32 == rhs.default_f32) && + (lhs.just_f64 == rhs.just_f64) && + (lhs.maybe_f64 == rhs.maybe_f64) && + (lhs.default_f64 == rhs.default_f64) && + (lhs.just_bool == rhs.just_bool) && + (lhs.maybe_bool == rhs.maybe_bool) && + (lhs.default_bool == rhs.default_bool) && + (lhs.just_enum == rhs.just_enum) && + (lhs.maybe_enum == rhs.maybe_enum) && + (lhs.default_enum == rhs.default_enum); +} + +inline bool operator!=(const ScalarStuffT &lhs, const ScalarStuffT &rhs) { + return !(lhs == rhs); +} + + +inline ScalarStuffT *ScalarStuff::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new ScalarStuffT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void ScalarStuff::UnPackTo(ScalarStuffT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = just_i8(); _o->just_i8 = _e; } + { auto _e = maybe_i8(); _o->maybe_i8 = _e; } + { auto _e = default_i8(); _o->default_i8 = _e; } + { auto _e = just_u8(); _o->just_u8 = _e; } + { auto _e = maybe_u8(); _o->maybe_u8 = _e; } + { auto _e = default_u8(); _o->default_u8 = _e; } + { auto _e = just_i16(); _o->just_i16 = _e; } + { auto _e = maybe_i16(); _o->maybe_i16 = _e; } + { auto _e = default_i16(); _o->default_i16 = _e; } + { auto _e = just_u16(); _o->just_u16 = _e; } + { auto _e = maybe_u16(); _o->maybe_u16 = _e; } + { auto _e = default_u16(); _o->default_u16 = _e; } + { auto _e = just_i32(); _o->just_i32 = _e; } + { auto _e = maybe_i32(); _o->maybe_i32 = _e; } + { auto _e = default_i32(); _o->default_i32 = _e; } + { auto _e = just_u32(); _o->just_u32 = _e; } + { auto _e = maybe_u32(); _o->maybe_u32 = _e; } + { auto _e = default_u32(); _o->default_u32 = _e; } + { auto _e = just_i64(); _o->just_i64 = _e; } + { auto _e = maybe_i64(); _o->maybe_i64 = _e; } + { auto _e = default_i64(); _o->default_i64 = _e; } + { auto _e = just_u64(); _o->just_u64 = _e; } + { auto _e = maybe_u64(); _o->maybe_u64 = _e; } + { auto _e = default_u64(); _o->default_u64 = _e; } + { auto _e = just_f32(); _o->just_f32 = _e; } + { auto _e = maybe_f32(); _o->maybe_f32 = _e; } + { auto _e = default_f32(); _o->default_f32 = _e; } + { auto _e = just_f64(); _o->just_f64 = _e; } + { auto _e = maybe_f64(); _o->maybe_f64 = _e; } + { auto _e = default_f64(); _o->default_f64 = _e; } + { auto _e = just_bool(); _o->just_bool = _e; } + { auto _e = maybe_bool(); _o->maybe_bool = _e; } + { auto _e = default_bool(); _o->default_bool = _e; } + { auto _e = just_enum(); _o->just_enum = _e; } + { auto _e = maybe_enum(); _o->maybe_enum = _e; } + { auto _e = default_enum(); _o->default_enum = _e; } +} + +inline ::flatbuffers::Offset ScalarStuff::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateScalarStuff(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateScalarStuff(::flatbuffers::FlatBufferBuilder &_fbb, const ScalarStuffT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const ScalarStuffT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _just_i8 = _o->just_i8; + auto _maybe_i8 = _o->maybe_i8; + auto _default_i8 = _o->default_i8; + auto _just_u8 = _o->just_u8; + auto _maybe_u8 = _o->maybe_u8; + auto _default_u8 = _o->default_u8; + auto _just_i16 = _o->just_i16; + auto _maybe_i16 = _o->maybe_i16; + auto _default_i16 = _o->default_i16; + auto _just_u16 = _o->just_u16; + auto _maybe_u16 = _o->maybe_u16; + auto _default_u16 = _o->default_u16; + auto _just_i32 = _o->just_i32; + auto _maybe_i32 = _o->maybe_i32; + auto _default_i32 = _o->default_i32; + auto _just_u32 = _o->just_u32; + auto _maybe_u32 = _o->maybe_u32; + auto _default_u32 = _o->default_u32; + auto _just_i64 = _o->just_i64; + auto _maybe_i64 = _o->maybe_i64; + auto _default_i64 = _o->default_i64; + auto _just_u64 = _o->just_u64; + auto _maybe_u64 = _o->maybe_u64; + auto _default_u64 = _o->default_u64; + auto _just_f32 = _o->just_f32; + auto _maybe_f32 = _o->maybe_f32; + auto _default_f32 = _o->default_f32; + auto _just_f64 = _o->just_f64; + auto _maybe_f64 = _o->maybe_f64; + auto _default_f64 = _o->default_f64; + auto _just_bool = _o->just_bool; + auto _maybe_bool = _o->maybe_bool; + auto _default_bool = _o->default_bool; + auto _just_enum = _o->just_enum; + auto _maybe_enum = _o->maybe_enum; + auto _default_enum = _o->default_enum; + return optional_scalars::CreateScalarStuff( + _fbb, + _just_i8, + _maybe_i8, + _default_i8, + _just_u8, + _maybe_u8, + _default_u8, + _just_i16, + _maybe_i16, + _default_i16, + _just_u16, + _maybe_u16, + _default_u16, + _just_i32, + _maybe_i32, + _default_i32, + _just_u32, + _maybe_u32, + _default_u32, + _just_i64, + _maybe_i64, + _default_i64, + _just_u64, + _maybe_u64, + _default_u64, + _just_f32, + _maybe_f32, + _default_f32, + _just_f64, + _maybe_f64, + _default_f64, + _just_bool, + _maybe_bool, + _default_bool, + _just_enum, + _maybe_enum, + _default_enum); +} + +inline const ::flatbuffers::TypeTable *OptionalByteTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + optional_scalars::OptionalByteTypeTable + }; + static const char * const names[] = { + "None", + "One", + "Two" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_ENUM, 3, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ScalarStuffTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_UCHAR, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_SHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_USHORT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_INT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_UINT, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_LONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_ULONG, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_FLOAT, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_DOUBLE, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_BOOL, 0, -1 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 }, + { ::flatbuffers::ET_CHAR, 0, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + optional_scalars::OptionalByteTypeTable + }; + static const char * const names[] = { + "just_i8", + "maybe_i8", + "default_i8", + "just_u8", + "maybe_u8", + "default_u8", + "just_i16", + "maybe_i16", + "default_i16", + "just_u16", + "maybe_u16", + "default_u16", + "just_i32", + "maybe_i32", + "default_i32", + "just_u32", + "maybe_u32", + "default_u32", + "just_i64", + "maybe_i64", + "default_i64", + "just_u64", + "maybe_u64", + "default_u64", + "just_f32", + "maybe_f32", + "default_f32", + "just_f64", + "maybe_f64", + "default_f64", + "just_bool", + "maybe_bool", + "default_bool", + "just_enum", + "maybe_enum", + "default_enum" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 36, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const optional_scalars::ScalarStuff *GetScalarStuff(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const optional_scalars::ScalarStuff *GetSizePrefixedScalarStuff(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline ScalarStuff *GetMutableScalarStuff(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline optional_scalars::ScalarStuff *GetMutableSizePrefixedScalarStuff(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *ScalarStuffIdentifier() { + return "NULL"; +} + +inline bool ScalarStuffBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ScalarStuffIdentifier()); +} + +inline bool SizePrefixedScalarStuffBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, ScalarStuffIdentifier(), true); +} + +inline bool VerifyScalarStuffBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(ScalarStuffIdentifier()); +} + +inline bool VerifySizePrefixedScalarStuffBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(ScalarStuffIdentifier()); +} + +inline const char *ScalarStuffExtension() { + return "mon"; +} + +inline void FinishScalarStuffBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, ScalarStuffIdentifier()); +} + +inline void FinishSizePrefixedScalarStuffBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, ScalarStuffIdentifier()); +} + +inline std::unique_ptr UnPackScalarStuff( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetScalarStuff(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedScalarStuff( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedScalarStuff(buf)->UnPack(res)); +} + +} // namespace optional_scalars + +#endif // FLATBUFFERS_GENERATED_OPTIONALSCALARS_OPTIONAL_SCALARS_H_ diff --git a/third_party/flatbuffers/tests/optional_scalars_generated.lobster b/third_party/flatbuffers/tests/optional_scalars_generated.lobster new file mode 100644 index 00000000000..f1d72d84d6f --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars_generated.lobster @@ -0,0 +1,204 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import flatbuffers + +namespace optional_scalars + +enum OptionalByte: + OptionalByte_None = 0 + OptionalByte_One = 1 + OptionalByte_Two = 2 + +class ScalarStuff + +class ScalarStuff : flatbuffers.handle + def just_i8() -> int: + return flatbuffers.field_int8(buf_, pos_, 4, 0) + def maybe_i8() -> int, bool: + return flatbuffers.field_int8(buf_, pos_, 6, 0), flatbuffers.field_present(buf_, pos_, 6) + def default_i8() -> int: + return flatbuffers.field_int8(buf_, pos_, 8, 42) + def just_u8() -> int: + return flatbuffers.field_uint8(buf_, pos_, 10, 0) + def maybe_u8() -> int, bool: + return flatbuffers.field_uint8(buf_, pos_, 12, 0), flatbuffers.field_present(buf_, pos_, 12) + def default_u8() -> int: + return flatbuffers.field_uint8(buf_, pos_, 14, 42) + def just_i16() -> int: + return flatbuffers.field_int16(buf_, pos_, 16, 0) + def maybe_i16() -> int, bool: + return flatbuffers.field_int16(buf_, pos_, 18, 0), flatbuffers.field_present(buf_, pos_, 18) + def default_i16() -> int: + return flatbuffers.field_int16(buf_, pos_, 20, 42) + def just_u16() -> int: + return flatbuffers.field_uint16(buf_, pos_, 22, 0) + def maybe_u16() -> int, bool: + return flatbuffers.field_uint16(buf_, pos_, 24, 0), flatbuffers.field_present(buf_, pos_, 24) + def default_u16() -> int: + return flatbuffers.field_uint16(buf_, pos_, 26, 42) + def just_i32() -> int: + return flatbuffers.field_int32(buf_, pos_, 28, 0) + def maybe_i32() -> int, bool: + return flatbuffers.field_int32(buf_, pos_, 30, 0), flatbuffers.field_present(buf_, pos_, 30) + def default_i32() -> int: + return flatbuffers.field_int32(buf_, pos_, 32, 42) + def just_u32() -> int: + return flatbuffers.field_uint32(buf_, pos_, 34, 0) + def maybe_u32() -> int, bool: + return flatbuffers.field_uint32(buf_, pos_, 36, 0), flatbuffers.field_present(buf_, pos_, 36) + def default_u32() -> int: + return flatbuffers.field_uint32(buf_, pos_, 38, 42) + def just_i64() -> int: + return flatbuffers.field_int64(buf_, pos_, 40, 0) + def maybe_i64() -> int, bool: + return flatbuffers.field_int64(buf_, pos_, 42, 0), flatbuffers.field_present(buf_, pos_, 42) + def default_i64() -> int: + return flatbuffers.field_int64(buf_, pos_, 44, 42) + def just_u64() -> int: + return flatbuffers.field_uint64(buf_, pos_, 46, 0) + def maybe_u64() -> int, bool: + return flatbuffers.field_uint64(buf_, pos_, 48, 0), flatbuffers.field_present(buf_, pos_, 48) + def default_u64() -> int: + return flatbuffers.field_uint64(buf_, pos_, 50, 42) + def just_f32() -> float: + return flatbuffers.field_float32(buf_, pos_, 52, 0.0) + def maybe_f32() -> float, bool: + return flatbuffers.field_float32(buf_, pos_, 54, 0.0), flatbuffers.field_present(buf_, pos_, 54) + def default_f32() -> float: + return flatbuffers.field_float32(buf_, pos_, 56, 42.0) + def just_f64() -> float: + return flatbuffers.field_float64(buf_, pos_, 58, 0.0) + def maybe_f64() -> float, bool: + return flatbuffers.field_float64(buf_, pos_, 60, 0.0), flatbuffers.field_present(buf_, pos_, 60) + def default_f64() -> float: + return flatbuffers.field_float64(buf_, pos_, 62, 42.0) + def just_bool() -> bool: + return bool(flatbuffers.field_int8(buf_, pos_, 64, 0)) + def maybe_bool() -> bool, bool: + return bool(flatbuffers.field_int8(buf_, pos_, 66, 0)), flatbuffers.field_present(buf_, pos_, 66) + def default_bool() -> bool: + return bool(flatbuffers.field_int8(buf_, pos_, 68, 1)) + def just_enum() -> OptionalByte: + return OptionalByte(flatbuffers.field_int8(buf_, pos_, 70, 0)) + def maybe_enum() -> OptionalByte, bool: + return OptionalByte(flatbuffers.field_int8(buf_, pos_, 72, 0)), flatbuffers.field_present(buf_, pos_, 72) + def default_enum() -> OptionalByte: + return OptionalByte(flatbuffers.field_int8(buf_, pos_, 74, 1)) + +def GetRootAsScalarStuff(buf:string): return ScalarStuff { buf, flatbuffers.indirect(buf, 0) } + +struct ScalarStuffBuilder: + b_:flatbuffers.builder + def start(): + b_.StartObject(36) + return this + def add_just_i8(just_i8:int): + b_.PrependInt8Slot(0, just_i8, 0) + return this + def add_maybe_i8(maybe_i8:int): + b_.PrependInt8Slot(1, maybe_i8) + return this + def add_default_i8(default_i8:int): + b_.PrependInt8Slot(2, default_i8, 42) + return this + def add_just_u8(just_u8:int): + b_.PrependUint8Slot(3, just_u8, 0) + return this + def add_maybe_u8(maybe_u8:int): + b_.PrependUint8Slot(4, maybe_u8) + return this + def add_default_u8(default_u8:int): + b_.PrependUint8Slot(5, default_u8, 42) + return this + def add_just_i16(just_i16:int): + b_.PrependInt16Slot(6, just_i16, 0) + return this + def add_maybe_i16(maybe_i16:int): + b_.PrependInt16Slot(7, maybe_i16) + return this + def add_default_i16(default_i16:int): + b_.PrependInt16Slot(8, default_i16, 42) + return this + def add_just_u16(just_u16:int): + b_.PrependUint16Slot(9, just_u16, 0) + return this + def add_maybe_u16(maybe_u16:int): + b_.PrependUint16Slot(10, maybe_u16) + return this + def add_default_u16(default_u16:int): + b_.PrependUint16Slot(11, default_u16, 42) + return this + def add_just_i32(just_i32:int): + b_.PrependInt32Slot(12, just_i32, 0) + return this + def add_maybe_i32(maybe_i32:int): + b_.PrependInt32Slot(13, maybe_i32) + return this + def add_default_i32(default_i32:int): + b_.PrependInt32Slot(14, default_i32, 42) + return this + def add_just_u32(just_u32:int): + b_.PrependUint32Slot(15, just_u32, 0) + return this + def add_maybe_u32(maybe_u32:int): + b_.PrependUint32Slot(16, maybe_u32) + return this + def add_default_u32(default_u32:int): + b_.PrependUint32Slot(17, default_u32, 42) + return this + def add_just_i64(just_i64:int): + b_.PrependInt64Slot(18, just_i64, 0) + return this + def add_maybe_i64(maybe_i64:int): + b_.PrependInt64Slot(19, maybe_i64) + return this + def add_default_i64(default_i64:int): + b_.PrependInt64Slot(20, default_i64, 42) + return this + def add_just_u64(just_u64:int): + b_.PrependUint64Slot(21, just_u64, 0) + return this + def add_maybe_u64(maybe_u64:int): + b_.PrependUint64Slot(22, maybe_u64) + return this + def add_default_u64(default_u64:int): + b_.PrependUint64Slot(23, default_u64, 42) + return this + def add_just_f32(just_f32:float): + b_.PrependFloat32Slot(24, just_f32, 0.0) + return this + def add_maybe_f32(maybe_f32:float): + b_.PrependFloat32Slot(25, maybe_f32) + return this + def add_default_f32(default_f32:float): + b_.PrependFloat32Slot(26, default_f32, 42.0) + return this + def add_just_f64(just_f64:float): + b_.PrependFloat64Slot(27, just_f64, 0.0) + return this + def add_maybe_f64(maybe_f64:float): + b_.PrependFloat64Slot(28, maybe_f64) + return this + def add_default_f64(default_f64:float): + b_.PrependFloat64Slot(29, default_f64, 42.0) + return this + def add_just_bool(just_bool:bool): + b_.PrependBoolSlot(30, just_bool, 0) + return this + def add_maybe_bool(maybe_bool:bool): + b_.PrependBoolSlot(31, maybe_bool) + return this + def add_default_bool(default_bool:bool): + b_.PrependBoolSlot(32, default_bool, 1) + return this + def add_just_enum(just_enum:OptionalByte): + b_.PrependInt8Slot(33, just_enum, 0) + return this + def add_maybe_enum(maybe_enum:OptionalByte): + b_.PrependInt8Slot(34, maybe_enum) + return this + def add_default_enum(default_enum:OptionalByte): + b_.PrependInt8Slot(35, default_enum, 1) + return this + def end(): + return b_.EndObject() + diff --git a/third_party/flatbuffers/tests/optional_scalars_generated.ts b/third_party/flatbuffers/tests/optional_scalars_generated.ts new file mode 100644 index 00000000000..4a83c439fcf --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars_generated.ts @@ -0,0 +1,4 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +export { OptionalByte } from './optional-scalars/optional-byte'; +export { ScalarStuff } from './optional-scalars/scalar-stuff'; diff --git a/third_party/flatbuffers/tests/optional_scalars_test.cpp b/third_party/flatbuffers/tests/optional_scalars_test.cpp new file mode 100644 index 00000000000..7713eb558a8 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars_test.cpp @@ -0,0 +1,102 @@ +#include "optional_scalars_test.h" + +#include +#include + +#include "flatbuffers/idl.h" +#include "optional_scalars_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +void OptionalScalarsTest() { + // Simple schemas and a "has optional scalar" sentinal. + std::vector schemas; + schemas.push_back("table Monster { mana : int; }"); + schemas.push_back("table Monster { mana : int = 42; }"); + schemas.push_back("table Monster { mana : int = null; }"); + schemas.push_back("table Monster { mana : long; }"); + schemas.push_back("table Monster { mana : long = 42; }"); + schemas.push_back("table Monster { mana : long = null; }"); + schemas.push_back("table Monster { mana : float; }"); + schemas.push_back("table Monster { mana : float = 42; }"); + schemas.push_back("table Monster { mana : float = null; }"); + schemas.push_back("table Monster { mana : double; }"); + schemas.push_back("table Monster { mana : double = 42; }"); + schemas.push_back("table Monster { mana : double = null; }"); + schemas.push_back("table Monster { mana : bool; }"); + schemas.push_back("table Monster { mana : bool = 42; }"); + schemas.push_back("table Monster { mana : bool = null; }"); + schemas.push_back( + "enum Enum: int {A=0, B=1} " + "table Monster { mana : Enum; }"); + schemas.push_back( + "enum Enum: int {A=0, B=1} " + "table Monster { mana : Enum = B; }"); + schemas.push_back( + "enum Enum: int {A=0, B=1} " + "table Monster { mana : Enum = null; }"); + + // Check the FieldDef is correctly set. + for (auto schema = schemas.begin(); schema < schemas.end(); schema++) { + const bool has_null = schema->find("null") != std::string::npos; + flatbuffers::Parser parser; + TEST_ASSERT(parser.Parse(schema->c_str())); + const auto *mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana"); + TEST_EQ(mana->IsOptional(), has_null); + } + + // Test if nullable scalars are allowed for each language. + for (unsigned lang = 1; lang < flatbuffers::IDLOptions::kMAX; lang <<= 1) { + flatbuffers::IDLOptions opts; + opts.lang_to_generate = lang; + if (false == flatbuffers::Parser::SupportsOptionalScalars(opts)) { + continue; + } + for (auto schema = schemas.begin(); schema < schemas.end(); schema++) { + flatbuffers::Parser parser(opts); + auto done = parser.Parse(schema->c_str()); + TEST_EQ_STR(parser.error_.c_str(), ""); + TEST_ASSERT(done); + } + } + + // test C++ nullable + flatbuffers::FlatBufferBuilder fbb; + FinishScalarStuffBuffer( + fbb, optional_scalars::CreateScalarStuff(fbb, 1, static_cast(2))); + auto opts = optional_scalars::GetMutableScalarStuff(fbb.GetBufferPointer()); + TEST_ASSERT(!opts->maybe_bool()); + TEST_ASSERT(!opts->maybe_f32().has_value()); + TEST_ASSERT(opts->maybe_i8().has_value()); + TEST_EQ(opts->maybe_i8().value(), 2); + TEST_ASSERT(opts->mutate_maybe_i8(3)); + TEST_ASSERT(opts->maybe_i8().has_value()); + TEST_EQ(opts->maybe_i8().value(), 3); + TEST_ASSERT(!opts->mutate_maybe_i16(-10)); + + optional_scalars::ScalarStuffT obj; + TEST_ASSERT(!obj.maybe_bool); + TEST_ASSERT(!obj.maybe_f32.has_value()); + opts->UnPackTo(&obj); + TEST_ASSERT(!obj.maybe_bool); + TEST_ASSERT(!obj.maybe_f32.has_value()); + TEST_ASSERT(obj.maybe_i8.has_value() && obj.maybe_i8.value() == 3); + TEST_ASSERT(obj.maybe_i8 && *obj.maybe_i8 == 3); + obj.maybe_i32 = -1; + obj.maybe_enum = optional_scalars::OptionalByte_Two; + + fbb.Clear(); + FinishScalarStuffBuffer(fbb, optional_scalars::ScalarStuff::Pack(fbb, &obj)); + opts = optional_scalars::GetMutableScalarStuff(fbb.GetBufferPointer()); + TEST_ASSERT(opts->maybe_i8().has_value()); + TEST_EQ(opts->maybe_i8().value(), 3); + TEST_ASSERT(opts->maybe_i32().has_value()); + TEST_EQ(opts->maybe_i32().value(), -1); + TEST_EQ(opts->maybe_enum().value(), optional_scalars::OptionalByte_Two); + TEST_ASSERT(opts->maybe_i32() == flatbuffers::Optional(-1)); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/optional_scalars_test.h b/third_party/flatbuffers/tests/optional_scalars_test.h new file mode 100644 index 00000000000..922e52ca839 --- /dev/null +++ b/third_party/flatbuffers/tests/optional_scalars_test.h @@ -0,0 +1,13 @@ +#ifndef TESTS_OPTIONAL_SCALARS_TEST_H +#define TESTS_OPTIONAL_SCALARS_TEST_H + + +namespace flatbuffers { +namespace tests { + +void OptionalScalarsTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/order/Food.go b/third_party/flatbuffers/tests/order/Food.go new file mode 100644 index 00000000000..298d631202c --- /dev/null +++ b/third_party/flatbuffers/tests/order/Food.go @@ -0,0 +1,102 @@ +// Code generated by the FlatBuffers compiler. DO NOT EDIT. + +package order + +import ( + flatbuffers "github.com/google/flatbuffers/go" + + Pizza "Pizza" +) + +type FoodT struct { + Pizza *Pizza.PizzaT `json:"pizza"` + PizzaTest *Pizza.PizzaT `json:"pizza_test"` +} + +func (t *FoodT) Pack(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + if t == nil { return 0 } + pizzaOffset := t.Pizza.Pack(builder) + pizzaTestOffset := t.PizzaTest.Pack(builder) + FoodStart(builder) + FoodAddPizza(builder, pizzaOffset) + FoodAddPizzaTest(builder, pizzaTestOffset) + return FoodEnd(builder) +} + +func (rcv *Food) UnPackTo(t *FoodT) { + t.Pizza = rcv.Pizza(nil).UnPack() + t.PizzaTest = rcv.PizzaTest(nil).UnPack() +} + +func (rcv *Food) UnPack() *FoodT { + if rcv == nil { return nil } + t := &FoodT{} + rcv.UnPackTo(t) + return t +} + +type Food struct { + _tab flatbuffers.Table +} + +func GetRootAsFood(buf []byte, offset flatbuffers.UOffsetT) *Food { + n := flatbuffers.GetUOffsetT(buf[offset:]) + x := &Food{} + x.Init(buf, n+offset) + return x +} + +func GetSizePrefixedRootAsFood(buf []byte, offset flatbuffers.UOffsetT) *Food { + n := flatbuffers.GetUOffsetT(buf[offset+flatbuffers.SizeUint32:]) + x := &Food{} + x.Init(buf, n+offset+flatbuffers.SizeUint32) + return x +} + +func (rcv *Food) Init(buf []byte, i flatbuffers.UOffsetT) { + rcv._tab.Bytes = buf + rcv._tab.Pos = i +} + +func (rcv *Food) Table() flatbuffers.Table { + return rcv._tab +} + +func (rcv *Food) Pizza(obj *Pizza.Pizza) *Pizza.Pizza { + o := flatbuffers.UOffsetT(rcv._tab.Offset(4)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(Pizza.Pizza) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func (rcv *Food) PizzaTest(obj *Pizza.Pizza) *Pizza.Pizza { + o := flatbuffers.UOffsetT(rcv._tab.Offset(6)) + if o != 0 { + x := rcv._tab.Indirect(o + rcv._tab.Pos) + if obj == nil { + obj = new(Pizza.Pizza) + } + obj.Init(rcv._tab.Bytes, x) + return obj + } + return nil +} + +func FoodStart(builder *flatbuffers.Builder) { + builder.StartObject(2) +} +func FoodAddPizza(builder *flatbuffers.Builder, pizza flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(0, flatbuffers.UOffsetT(pizza), 0) +} +func FoodAddPizzaTest(builder *flatbuffers.Builder, pizzaTest flatbuffers.UOffsetT) { + builder.PrependUOffsetTSlot(1, flatbuffers.UOffsetT(pizzaTest), 0) +} +func FoodEnd(builder *flatbuffers.Builder) flatbuffers.UOffsetT { + return builder.EndObject() +} diff --git a/third_party/flatbuffers/tests/parser_test.cpp b/third_party/flatbuffers/tests/parser_test.cpp new file mode 100644 index 00000000000..33b1d6e1e6d --- /dev/null +++ b/third_party/flatbuffers/tests/parser_test.cpp @@ -0,0 +1,932 @@ +#include "parser_test.h" + +#include +#include +#include + +#include "flatbuffers/idl.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { +namespace { + +// Shortcuts for the infinity. +static const auto infinity_f = std::numeric_limits::infinity(); +static const auto infinity_d = std::numeric_limits::infinity(); + +// Test that parser errors are actually generated. +static void TestError_(const char *src, const char *error_substr, + bool strict_json, const char *file, int line, + const char *func) { + flatbuffers::IDLOptions opts; + opts.strict_json = strict_json; + flatbuffers::Parser parser(opts); + if (parser.Parse(src)) { + TestFail("true", "false", + ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line, + func); + } else if (!strstr(parser.error_.c_str(), error_substr)) { + TestFail(error_substr, parser.error_.c_str(), + ("parser.Parse(\"" + std::string(src) + "\")").c_str(), file, line, + func); + } +} + +static void TestError_(const char *src, const char *error_substr, + const char *file, int line, const char *func) { + TestError_(src, error_substr, false, file, line, func); +} + +#ifdef _WIN32 +# define TestError(src, ...) \ + TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __FUNCTION__) +#else +# define TestError(src, ...) \ + TestError_(src, __VA_ARGS__, __FILE__, __LINE__, __PRETTY_FUNCTION__) +#endif + +static bool FloatCompare(float a, float b) { return fabs(a - b) < 0.001; } + +} // namespace + +// Test that parsing errors occur as we'd expect. +// Also useful for coverage, making sure these paths are run. +void ErrorTest() { + // In order they appear in idl_parser.cpp + TestError("table X { Y:byte; } root_type X; { Y: 999 }", "does not fit"); + TestError("\"\0", "illegal"); + TestError("\"\\q", "escape code"); + TestError("table ///", "documentation"); + TestError("@", "illegal"); + TestError("table 1", "expecting"); + TestError("table X { Y:[[int]]; }", "nested vector"); + TestError("table X { Y:1; }", "illegal type"); + TestError("table X { Y:int; Y:int; }", "field already"); + TestError("table Y {} table X { Y:int; }", "same as table"); + TestError("struct X { Y:string; }", "only scalar"); + TestError("struct X { a:uint = 42; }", "default values"); + TestError("enum Y:byte { Z = 1 } table X { y:Y; }", "not part of enum"); + TestError("struct X { Y:int (deprecated); }", "deprecate"); + TestError("union Z { X } table X { Y:Z; } root_type X; { Y: {}, A:1 }", + "missing type field"); + TestError("union Z { X } table X { Y:Z; } root_type X; { Y_type: 99, Y: {", + "type id"); + TestError("table X { Y:int; } root_type X; { Z:", "unknown field"); + TestError("table X { Y:int; } root_type X; { Y:", "string constant", true); + TestError("table X { Y:int; } root_type X; { \"Y\":1, }", "string constant", + true); + TestError( + "struct X { Y:int; Z:int; } table W { V:X; } root_type W; " + "{ V:{ Y:1 } }", + "wrong number"); + TestError("enum E:byte { A } table X { Y:E; } root_type X; { Y:U }", + "unknown enum value"); + TestError("table X { Y:byte; } root_type X; { Y:; }", "starting"); + TestError("enum X:byte { Y } enum X {", "enum already"); + TestError("enum X:float {}", "underlying"); + TestError("enum X:byte { Y, Y }", "value already"); + TestError("enum X:byte { Y=2, Z=2 }", "unique"); + TestError("enum X:byte (force_align: 4) { Y }", "force_align"); + TestError("table X { Y:int; } table X {", "datatype already"); + TestError("table X { } union X { }", "datatype already"); + TestError("union X { } table X { }", "datatype already"); + TestError("namespace A; table X { } namespace A; union X { }", + "datatype already"); + TestError("namespace A; union X { } namespace A; table X { }", + "datatype already"); + TestError("struct X (force_align: 7) { Y:int; }", "force_align"); + TestError("struct X {}", "size 0"); + TestError("{}", "no root"); + TestError("table X { Y:byte; } root_type X; { Y:1 } { Y:1 }", "end of file"); + TestError("table X { Y:byte; } root_type X; { Y:1 } table Y{ Z:int }", + "end of file"); + TestError("root_type X;", "unknown root"); + TestError("struct X { Y:int; } root_type X;", "a table"); + TestError("union X { Y }", "referenced"); + TestError("union Z { X } struct X { Y:int; }", "only tables"); + TestError("table X { Y:[int]; YLength:int; }", "clash"); + TestError("table X { Y:byte; } root_type X; { Y:1, Y:2 }", "more than once"); + // float to integer conversion is forbidden + TestError("table X { Y:int; } root_type X; { Y:1.0 }", "float"); + TestError("table X { Y:bool; } root_type X; { Y:1.0 }", "float"); + TestError("enum X:bool { Y = true }", "must be integral"); + // Array of non-scalar + TestError("table X { x:int; } struct Y { y:[X:2]; }", + "may contain only scalar or struct fields"); + // Non-snake case field names + TestError("table X { Y: int; } root_type Y: {Y:1.0}", "snake_case"); + // Complex defaults + TestError("table X { y: string = 1; }", "expecting: string"); + TestError("table X { y: string = []; }", " Cannot assign token"); + TestError("table X { y: [int] = [1]; }", "Expected `]`"); + TestError("table X { y: [int] = [; }", "Expected `]`"); + TestError("table X { y: [int] = \"\"; }", "type mismatch"); + // An identifier can't start from sign (+|-) + TestError("table X { -Y: int; } root_type Y: {Y:1.0}", "identifier"); + TestError("table X { +Y: int; } root_type Y: {Y:1.0}", "identifier"); + + // Offset64 + TestError("table X { a:int (vector64); }", "`vector64` attribute"); + TestError("table X { a:int (offset64); }", "`offset64` attribute"); + TestError("table X { a:string (vector64); }", "`vector64` attribute"); + TestError("table y { a:int; } table X { a:y (offset64); }", + "`offset64` attribute"); + TestError("struct y { a:int; } table X { a:y (offset64); }", + "`offset64` attribute"); + TestError("table y { a:int; } table X { a:y (vector64); }", + "`vector64` attribute"); + TestError("union Y { } table X { ys:Y (offset64); }", "`offset64` attribute"); + + TestError("table Y { a:int; } table X { ys:[Y] (offset64); }", + "only vectors of scalars are allowed to be 64-bit."); + TestError("table Y { a:int; } table X { ys:[Y] (vector64); }", + "only vectors of scalars are allowed to be 64-bit."); + TestError("union Y { } table X { ys:[Y] (vector64); }", + "only vectors of scalars are allowed to be 64-bit."); + + // TOOD(derekbailey): the following three could be allowed once the code gen + // supports the output. + TestError("table X { y:[string] (offset64); }", + "only vectors of scalars are allowed to be 64-bit."); + TestError("table X { y:[string] (vector64); }", + "only vectors of scalars are allowed to be 64-bit."); + TestError("enum X:byte {Z} table X { y:[X] (offset64); }", + "only vectors of scalars are allowed to be 64-bit."); +} + +void EnumOutOfRangeTest() { + TestError("enum X:byte { Y = 128 }", "enum value does not fit"); + TestError("enum X:byte { Y = -129 }", "enum value does not fit"); + TestError("enum X:byte { Y = 126, Z0, Z1 }", "enum value does not fit"); + TestError("enum X:ubyte { Y = -1 }", "enum value does not fit"); + TestError("enum X:ubyte { Y = 256 }", "enum value does not fit"); + TestError("enum X:ubyte { Y = 255, Z }", "enum value does not fit"); + TestError("table Y{} union X { Y = -1 }", "enum value does not fit"); + TestError("table Y{} union X { Y = 256 }", "enum value does not fit"); + TestError("table Y{} union X { Y = 255, Z:Y }", "enum value does not fit"); + TestError("enum X:int { Y = -2147483649 }", "enum value does not fit"); + TestError("enum X:int { Y = 2147483648 }", "enum value does not fit"); + TestError("enum X:uint { Y = -1 }", "enum value does not fit"); + TestError("enum X:uint { Y = 4294967297 }", "enum value does not fit"); + TestError("enum X:long { Y = 9223372036854775808 }", "does not fit"); + TestError("enum X:long { Y = 9223372036854775807, Z }", + "enum value does not fit"); + TestError("enum X:ulong { Y = -1 }", "does not fit"); + TestError("enum X:ubyte (bit_flags) { Y=8 }", "bit flag out"); + TestError("enum X:byte (bit_flags) { Y=7 }", "must be unsigned"); // -128 + // bit_flgs out of range + TestError("enum X:ubyte (bit_flags) { Y0,Y1,Y2,Y3,Y4,Y5,Y6,Y7,Y8 }", + "out of range"); +} + +void IntegerOutOfRangeTest() { + TestError("table T { F:byte; } root_type T; { F:128 }", + "constant does not fit"); + TestError("table T { F:byte; } root_type T; { F:-129 }", + "constant does not fit"); + TestError("table T { F:ubyte; } root_type T; { F:256 }", + "constant does not fit"); + TestError("table T { F:ubyte; } root_type T; { F:-1 }", + "constant does not fit"); + TestError("table T { F:short; } root_type T; { F:32768 }", + "constant does not fit"); + TestError("table T { F:short; } root_type T; { F:-32769 }", + "constant does not fit"); + TestError("table T { F:ushort; } root_type T; { F:65536 }", + "constant does not fit"); + TestError("table T { F:ushort; } root_type T; { F:-1 }", + "constant does not fit"); + TestError("table T { F:int; } root_type T; { F:2147483648 }", + "constant does not fit"); + TestError("table T { F:int; } root_type T; { F:-2147483649 }", + "constant does not fit"); + TestError("table T { F:uint; } root_type T; { F:4294967296 }", + "constant does not fit"); + TestError("table T { F:uint; } root_type T; { F:-1 }", + "constant does not fit"); + // Check fixed width aliases + TestError("table X { Y:uint8; } root_type X; { Y: -1 }", "does not fit"); + TestError("table X { Y:uint8; } root_type X; { Y: 256 }", "does not fit"); + TestError("table X { Y:uint16; } root_type X; { Y: -1 }", "does not fit"); + TestError("table X { Y:uint16; } root_type X; { Y: 65536 }", "does not fit"); + TestError("table X { Y:uint32; } root_type X; { Y: -1 }", ""); + TestError("table X { Y:uint32; } root_type X; { Y: 4294967296 }", + "does not fit"); + TestError("table X { Y:uint64; } root_type X; { Y: -1 }", ""); + TestError("table X { Y:uint64; } root_type X; { Y: -9223372036854775809 }", + "does not fit"); + TestError("table X { Y:uint64; } root_type X; { Y: 18446744073709551616 }", + "does not fit"); + + TestError("table X { Y:int8; } root_type X; { Y: -129 }", "does not fit"); + TestError("table X { Y:int8; } root_type X; { Y: 128 }", "does not fit"); + TestError("table X { Y:int16; } root_type X; { Y: -32769 }", "does not fit"); + TestError("table X { Y:int16; } root_type X; { Y: 32768 }", "does not fit"); + TestError("table X { Y:int32; } root_type X; { Y: -2147483649 }", ""); + TestError("table X { Y:int32; } root_type X; { Y: 2147483648 }", + "does not fit"); + TestError("table X { Y:int64; } root_type X; { Y: -9223372036854775809 }", + "does not fit"); + TestError("table X { Y:int64; } root_type X; { Y: 9223372036854775808 }", + "does not fit"); + // check out-of-int64 as int8 + TestError("table X { Y:int8; } root_type X; { Y: -9223372036854775809 }", + "does not fit"); + TestError("table X { Y:int8; } root_type X; { Y: 9223372036854775808 }", + "does not fit"); + + // Check default values + TestError("table X { Y:int64=-9223372036854775809; } root_type X; {}", + "does not fit"); + TestError("table X { Y:int64= 9223372036854775808; } root_type X; {}", + "does not fit"); + TestError("table X { Y:uint64; } root_type X; { Y: -1 }", ""); + TestError("table X { Y:uint64=-9223372036854775809; } root_type X; {}", + "does not fit"); + TestError("table X { Y:uint64= 18446744073709551616; } root_type X; {}", + "does not fit"); +} + +void InvalidFloatTest() { + auto invalid_msg = "invalid number"; + auto comma_msg = "expecting: ,"; + TestError("table T { F:float; } root_type T; { F:1,0 }", ""); + TestError("table T { F:float; } root_type T; { F:. }", ""); + TestError("table T { F:float; } root_type T; { F:- }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:+ }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:-. }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:+. }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:.e }", ""); + TestError("table T { F:float; } root_type T; { F:-e }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:+e }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:-.e }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:+.e }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:-e1 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:+e1 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.0e+ }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.0e- }", invalid_msg); + // exponent pP is mandatory for hex-float + TestError("table T { F:float; } root_type T; { F:0x0 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:-0x. }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x. }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0Xe }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"0Xe\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"nan(1)\" }", invalid_msg); + // eE not exponent in hex-float! + TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0p }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0p+ }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0p- }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0pa1 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0e+ }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0e- }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0e+0 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0e-0 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0ep+ }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:0x0.0ep- }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.2.3 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.2.e3 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.2e.3 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.2e0.3 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.2e3. }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.2e3.0 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:+-1.0 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.0e+-1 }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"1.0e+-1\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:1.e0e }", comma_msg); + TestError("table T { F:float; } root_type T; { F:0x1.p0e }", comma_msg); + TestError("table T { F:float; } root_type T; { F:\" 0x10 \" }", invalid_msg); + // floats in string + TestError("table T { F:float; } root_type T; { F:\"1,2.\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"1.2e3.\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"0x1.p0e\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"0x1.0\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\" 0x1.0\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:\"+ 0\" }", invalid_msg); + // disable escapes for "number-in-string" + TestError("table T { F:float; } root_type T; { F:\"\\f1.2e3.\" }", "invalid"); + TestError("table T { F:float; } root_type T; { F:\"\\t1.2e3.\" }", "invalid"); + TestError("table T { F:float; } root_type T; { F:\"\\n1.2e3.\" }", "invalid"); + TestError("table T { F:float; } root_type T; { F:\"\\r1.2e3.\" }", "invalid"); + TestError("table T { F:float; } root_type T; { F:\"4\\x005\" }", "invalid"); + TestError("table T { F:float; } root_type T; { F:\"\'12\'\" }", invalid_msg); + // null is not a number constant! + TestError("table T { F:float; } root_type T; { F:\"null\" }", invalid_msg); + TestError("table T { F:float; } root_type T; { F:null }", invalid_msg); +} + +void UnicodeInvalidSurrogatesTest() { + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\uD800\"}", + "unpaired high surrogate"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\uD800abcd\"}", + "unpaired high surrogate"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\uD800\\n\"}", + "unpaired high surrogate"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\uD800\\uD800\"}", + "multiple high surrogates"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\uDC00\"}", + "unpaired low surrogate"); +} + +void InvalidUTF8Test() { + // "1 byte" pattern, under min length of 2 bytes + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\x80\"}", + "illegal UTF-8 sequence"); + // 2 byte pattern, string too short + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xDF\"}", + "illegal UTF-8 sequence"); + // 3 byte pattern, string too short + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xEF\xBF\"}", + "illegal UTF-8 sequence"); + // 4 byte pattern, string too short + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xF7\xBF\xBF\"}", + "illegal UTF-8 sequence"); + // "5 byte" pattern, string too short + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xFB\xBF\xBF\xBF\"}", + "illegal UTF-8 sequence"); + // "6 byte" pattern, string too short + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xFD\xBF\xBF\xBF\xBF\"}", + "illegal UTF-8 sequence"); + // "7 byte" pattern, string too short + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\"}", + "illegal UTF-8 sequence"); + // "5 byte" pattern, over max length of 4 bytes + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xFB\xBF\xBF\xBF\xBF\"}", + "illegal UTF-8 sequence"); + // "6 byte" pattern, over max length of 4 bytes + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xFD\xBF\xBF\xBF\xBF\xBF\"}", + "illegal UTF-8 sequence"); + // "7 byte" pattern, over max length of 4 bytes + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xFE\xBF\xBF\xBF\xBF\xBF\xBF\"}", + "illegal UTF-8 sequence"); + + // Three invalid encodings for U+000A (\n, aka NEWLINE) + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xC0\x8A\"}", + "illegal UTF-8 sequence"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xE0\x80\x8A\"}", + "illegal UTF-8 sequence"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xF0\x80\x80\x8A\"}", + "illegal UTF-8 sequence"); + + // Two invalid encodings for U+00A9 (COPYRIGHT SYMBOL) + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xE0\x81\xA9\"}", + "illegal UTF-8 sequence"); + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xF0\x80\x81\xA9\"}", + "illegal UTF-8 sequence"); + + // Invalid encoding for U+20AC (EURO SYMBOL) + TestError( + "table T { F:string; }" + "root_type T;" + "{ F:\"\xF0\x82\x82\xAC\"}", + "illegal UTF-8 sequence"); + + // UTF-16 surrogate values between U+D800 and U+DFFF cannot be encoded in + // UTF-8 + TestError( + "table T { F:string; }" + "root_type T;" + // U+10400 "encoded" as U+D801 U+DC00 + "{ F:\"\xED\xA0\x81\xED\xB0\x80\"}", + "illegal UTF-8 sequence"); + + // Check independence of identifier from locale. + std::string locale_ident; + locale_ident += "table T { F"; + locale_ident += static_cast(-32); // unsigned 0xE0 + locale_ident += " :string; }"; + locale_ident += "root_type T;"; + locale_ident += "{}"; + TestError(locale_ident.c_str(), ""); +} + +template +T TestValue(const char *json, const char *type_name, + const char *decls = nullptr) { + flatbuffers::Parser parser; + parser.builder_.ForceDefaults(true); // return defaults + auto check_default = json ? false : true; + if (check_default) { parser.opts.output_default_scalars_in_json = true; } + // Simple schema. + std::string schema = std::string(decls ? decls : "") + "\n" + + "table X { y:" + std::string(type_name) + + "; } root_type X;"; + auto schema_done = parser.Parse(schema.c_str()); + TEST_EQ_STR(parser.error_.c_str(), ""); + TEST_EQ(schema_done, true); + + auto done = parser.Parse(check_default ? "{}" : json); + TEST_EQ_STR(parser.error_.c_str(), ""); + TEST_EQ(done, true); + + // Check with print. + std::string print_back; + parser.opts.indent_step = -1; + TEST_NULL(GenText(parser, parser.builder_.GetBufferPointer(), &print_back)); + // restore value from its default + if (check_default) { TEST_EQ(parser.Parse(print_back.c_str()), true); } + + auto root = flatbuffers::GetRoot( + parser.builder_.GetBufferPointer()); + return root->GetField(flatbuffers::FieldIndexToOffset(0), 0); +} + +// Additional parser testing not covered elsewhere. +void ValueTest() { + // Test scientific notation numbers. + TEST_EQ( + FloatCompare(TestValue("{ y:0.0314159e+2 }", "float"), 3.14159f), + true); + // number in string + TEST_EQ(FloatCompare(TestValue("{ y:\"0.0314159e+2\" }", "float"), + 3.14159f), + true); + + // Test conversion functions. + TEST_EQ(FloatCompare(TestValue("{ y:cos(rad(180)) }", "float"), -1), + true); + + // int embedded to string + TEST_EQ(TestValue("{ y:\"-876\" }", "int=-123"), -876); + TEST_EQ(TestValue("{ y:\"876\" }", "int=-123"), 876); + + // Test negative hex constant. + TEST_EQ(TestValue("{ y:-0x8ea0 }", "int=-0x8ea0"), -36512); + TEST_EQ(TestValue(nullptr, "int=-0x8ea0"), -36512); + + // positive hex constant + TEST_EQ(TestValue("{ y:0x1abcdef }", "int=0x1"), 0x1abcdef); + // with optional '+' sign + TEST_EQ(TestValue("{ y:+0x1abcdef }", "int=+0x1"), 0x1abcdef); + // hex in string + TEST_EQ(TestValue("{ y:\"0x1abcdef\" }", "int=+0x1"), 0x1abcdef); + + // Make sure we do unsigned 64bit correctly. + TEST_EQ(TestValue("{ y:12335089644688340133 }", "ulong"), + 12335089644688340133ULL); + + // bool in string + TEST_EQ(TestValue("{ y:\"false\" }", "bool=true"), false); + TEST_EQ(TestValue("{ y:\"true\" }", "bool=\"true\""), true); + TEST_EQ(TestValue("{ y:'false' }", "bool=true"), false); + TEST_EQ(TestValue("{ y:'true' }", "bool=\"true\""), true); + + // check comments before and after json object + TEST_EQ(TestValue("/*before*/ { y:1 } /*after*/", "int"), 1); + TEST_EQ(TestValue("//before \n { y:1 } //after", "int"), 1); +} + +void NestedListTest() { + flatbuffers::Parser parser1; + TEST_EQ(parser1.Parse("struct Test { a:short; b:byte; } table T { F:[Test]; }" + "root_type T;" + "{ F:[ [10,20], [30,40]] }"), + true); +} + +void EnumStringsTest() { + flatbuffers::Parser parser1; + TEST_EQ(parser1.Parse("enum E:byte { A, B, C } table T { F:[E]; }" + "root_type T;" + "{ F:[ A, B, \"C\", \"A B C\" ] }"), + true); + flatbuffers::Parser parser2; + TEST_EQ(parser2.Parse("enum E:byte { A, B, C } table T { F:[int]; }" + "root_type T;" + "{ F:[ \"E.C\", \"E.A E.B E.C\" ] }"), + true); + // unsigned bit_flags + flatbuffers::Parser parser3; + TEST_EQ( + parser3.Parse("enum E:uint16 (bit_flags) { F0, F07=7, F08, F14=14, F15 }" + " table T { F: E = \"F15 F08\"; }" + "root_type T;"), + true); +} + +void EnumValueTest() { + // json: "{ Y:0 }", schema: table X { y: "E"} + // 0 in enum (V=0) E then Y=0 is valid. + TEST_EQ(TestValue("{ y:0 }", "E", "enum E:int { V }"), 0); + TEST_EQ(TestValue("{ y:V }", "E", "enum E:int { V }"), 0); + // A default value of Y is 0. + TEST_EQ(TestValue("{ }", "E", "enum E:int { V }"), 0); + TEST_EQ(TestValue("{ y:5 }", "E=V", "enum E:int { V=5 }"), 5); + // Generate json with defaults and check. + TEST_EQ(TestValue(nullptr, "E=V", "enum E:int { V=5 }"), 5); + // 5 in enum + TEST_EQ(TestValue("{ y:5 }", "E", "enum E:int { Z, V=5 }"), 5); + TEST_EQ(TestValue("{ y:5 }", "E=V", "enum E:int { Z, V=5 }"), 5); + // Generate json with defaults and check. + TEST_EQ(TestValue(nullptr, "E", "enum E:int { Z, V=5 }"), 0); + TEST_EQ(TestValue(nullptr, "E=V", "enum E:int { Z, V=5 }"), 5); + // u84 test + TEST_EQ(TestValue(nullptr, "E=V", + "enum E:ulong { V = 13835058055282163712 }"), + 13835058055282163712ULL); + TEST_EQ(TestValue(nullptr, "E=V", + "enum E:ulong { V = 18446744073709551615 }"), + 18446744073709551615ULL); + // Assign non-enum value to enum field. Is it right? + TEST_EQ(TestValue("{ y:7 }", "E", "enum E:int { V = 0 }"), 7); + // Check that non-ascending values are valid. + TEST_EQ(TestValue("{ y:5 }", "E=V", "enum E:int { Z=10, V=5 }"), 5); +} + +void IntegerBoundaryTest() { + // Check numerical compatibility with non-C++ languages. + // By the C++ standard, std::numerical_limits::min() == + // -9223372036854775807 (-2^63+1) or less* The Flatbuffers grammar and most of + // the languages (C#, Java, Rust) expect that minimum values are: -128, + // -32768,.., -9223372036854775808. Since C++20, + // static_cast(0x8000000000000000ULL) is well-defined two's complement + // cast. Therefore -9223372036854775808 should be valid negative value. + TEST_EQ(flatbuffers::numeric_limits::min(), -128); + TEST_EQ(flatbuffers::numeric_limits::max(), 127); + TEST_EQ(flatbuffers::numeric_limits::min(), -32768); + TEST_EQ(flatbuffers::numeric_limits::max(), 32767); + TEST_EQ(flatbuffers::numeric_limits::min() + 1, -2147483647); + TEST_EQ(flatbuffers::numeric_limits::max(), 2147483647ULL); + TEST_EQ(flatbuffers::numeric_limits::min() + 1LL, + -9223372036854775807LL); + TEST_EQ(flatbuffers::numeric_limits::max(), 9223372036854775807ULL); + TEST_EQ(flatbuffers::numeric_limits::max(), 255); + TEST_EQ(flatbuffers::numeric_limits::max(), 65535); + TEST_EQ(flatbuffers::numeric_limits::max(), 4294967295ULL); + TEST_EQ(flatbuffers::numeric_limits::max(), + 18446744073709551615ULL); + + TEST_EQ(TestValue("{ y:127 }", "byte"), 127); + TEST_EQ(TestValue("{ y:-128 }", "byte"), -128); + TEST_EQ(TestValue("{ y:255 }", "ubyte"), 255); + TEST_EQ(TestValue("{ y:0 }", "ubyte"), 0); + TEST_EQ(TestValue("{ y:32767 }", "short"), 32767); + TEST_EQ(TestValue("{ y:-32768 }", "short"), -32768); + TEST_EQ(TestValue("{ y:65535 }", "ushort"), 65535); + TEST_EQ(TestValue("{ y:0 }", "ushort"), 0); + TEST_EQ(TestValue("{ y:2147483647 }", "int"), 2147483647); + TEST_EQ(TestValue("{ y:-2147483648 }", "int") + 1, -2147483647); + TEST_EQ(TestValue("{ y:4294967295 }", "uint"), 4294967295); + TEST_EQ(TestValue("{ y:0 }", "uint"), 0); + TEST_EQ(TestValue("{ y:9223372036854775807 }", "long"), + 9223372036854775807LL); + TEST_EQ(TestValue("{ y:-9223372036854775808 }", "long") + 1LL, + -9223372036854775807LL); + TEST_EQ(TestValue("{ y:18446744073709551615 }", "ulong"), + 18446744073709551615ULL); + TEST_EQ(TestValue("{ y:0 }", "ulong"), 0); + TEST_EQ(TestValue("{ y: 18446744073709551615 }", "uint64"), + 18446744073709551615ULL); + // check that the default works + TEST_EQ(TestValue(nullptr, "uint64 = 18446744073709551615"), + 18446744073709551615ULL); +} + +void ValidFloatTest() { + // check rounding to infinity + TEST_EQ(TestValue("{ y:+3.4029e+38 }", "float"), +infinity_f); + TEST_EQ(TestValue("{ y:-3.4029e+38 }", "float"), -infinity_f); + TEST_EQ(TestValue("{ y:+1.7977e+308 }", "double"), +infinity_d); + TEST_EQ(TestValue("{ y:-1.7977e+308 }", "double"), -infinity_d); + + TEST_EQ( + FloatCompare(TestValue("{ y:0.0314159e+2 }", "float"), 3.14159f), + true); + // float in string + TEST_EQ(FloatCompare(TestValue("{ y:\" 0.0314159e+2 \" }", "float"), + 3.14159f), + true); + + TEST_EQ(TestValue("{ y:1 }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:1.0 }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:1. }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:+1. }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:-1. }", "float"), -1.0f); + TEST_EQ(TestValue("{ y:1.e0 }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:1.e+0 }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:1.e-0 }", "float"), 1.0f); + TEST_EQ(TestValue("{ y:0.125 }", "float"), 0.125f); + TEST_EQ(TestValue("{ y:.125 }", "float"), 0.125f); + TEST_EQ(TestValue("{ y:-.125 }", "float"), -0.125f); + TEST_EQ(TestValue("{ y:+.125 }", "float"), +0.125f); + TEST_EQ(TestValue("{ y:5 }", "float"), 5.0f); + TEST_EQ(TestValue("{ y:\"5\" }", "float"), 5.0f); + +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) + // Old MSVC versions may have problem with this check. + // https://www.exploringbinary.com/visual-c-plus-plus-strtod-still-broken/ + TEST_EQ(TestValue("{ y:6.9294956446009195e15 }", "double"), + 6929495644600920.0); + // check nan's + TEST_EQ(std::isnan(TestValue("{ y:nan }", "double")), true); + TEST_EQ(std::isnan(TestValue("{ y:nan }", "float")), true); + TEST_EQ(std::isnan(TestValue("{ y:\"nan\" }", "float")), true); + TEST_EQ(std::isnan(TestValue("{ y:\"+nan\" }", "float")), true); + TEST_EQ(std::isnan(TestValue("{ y:\"-nan\" }", "float")), true); + TEST_EQ(std::isnan(TestValue("{ y:+nan }", "float")), true); + TEST_EQ(std::isnan(TestValue("{ y:-nan }", "float")), true); + TEST_EQ(std::isnan(TestValue(nullptr, "float=nan")), true); + TEST_EQ(std::isnan(TestValue(nullptr, "float=-nan")), true); + // check inf + TEST_EQ(TestValue("{ y:inf }", "float"), infinity_f); + TEST_EQ(TestValue("{ y:\"inf\" }", "float"), infinity_f); + TEST_EQ(TestValue("{ y:\"-inf\" }", "float"), -infinity_f); + TEST_EQ(TestValue("{ y:\"+inf\" }", "float"), infinity_f); + TEST_EQ(TestValue("{ y:+inf }", "float"), infinity_f); + TEST_EQ(TestValue("{ y:-inf }", "float"), -infinity_f); + TEST_EQ(TestValue(nullptr, "float=inf"), infinity_f); + TEST_EQ(TestValue(nullptr, "float=-inf"), -infinity_f); + TestValue( + "{ y: [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, " + "3.0e2] }", + "[double]"); + TestValue( + "{ y: [0.2, .2, 1.0, -1.0, -2., 2., 1e0, -1e0, 1.0e0, -1.0e0, -3.e2, " + "3.0e2] }", + "[float]"); + + // Test binary format of float point. + // https://en.cppreference.com/w/cpp/language/floating_literal + // 0x11.12p-1 = (1*16^1 + 2*16^0 + 3*16^-1 + 4*16^-2) * 2^-1 = + TEST_EQ(TestValue("{ y:0x12.34p-1 }", "double"), 9.1015625); + // hex fraction 1.2 (decimal 1.125) scaled by 2^3, that is 9.0 + TEST_EQ(TestValue("{ y:-0x0.2p0 }", "float"), -0.125f); + TEST_EQ(TestValue("{ y:-0x.2p1 }", "float"), -0.25f); + TEST_EQ(TestValue("{ y:0x1.2p3 }", "float"), 9.0f); + TEST_EQ(TestValue("{ y:0x10.1p0 }", "float"), 16.0625f); + TEST_EQ(TestValue("{ y:0x1.2p3 }", "double"), 9.0); + TEST_EQ(TestValue("{ y:0x10.1p0 }", "double"), 16.0625); + TEST_EQ(TestValue("{ y:0xC.68p+2 }", "double"), 49.625); + TestValue("{ y: [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[double]"); + TestValue("{ y: [0x20.4ep1, +0x20.4ep1, -0x20.4ep1] }", "[float]"); + +#else // FLATBUFFERS_HAS_NEW_STRTOD + TEST_OUTPUT_LINE("FLATBUFFERS_HAS_NEW_STRTOD tests skipped"); +#endif // !FLATBUFFERS_HAS_NEW_STRTOD +} + +void UnicodeTest() { + flatbuffers::Parser parser; + // Without setting allow_non_utf8 = true, we treat \x sequences as byte + // sequences which are then validated as UTF-8. + TEST_EQ(parser.Parse("table T { F:string; }" + "root_type T;" + "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" + "\\u5225\\u30B5\\u30A4\\u30C8\\xE2\\x82\\xAC\\u0080\\uD8" + "3D\\uDE0E\" }"), + true); + std::string jsongen; + parser.opts.indent_step = -1; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), + "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" + "\\u5225\\u30B5\\u30A4\\u30C8\\u20AC\\u0080\\uD83D\\uDE0E\"}"); +} + +void UnicodeTestAllowNonUTF8() { + flatbuffers::Parser parser; + parser.opts.allow_non_utf8 = true; + TEST_EQ( + parser.Parse( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" + "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"), + true); + std::string jsongen; + parser.opts.indent_step = -1; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ_STR( + jsongen.c_str(), + "{F: \"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" + "\\u5225\\u30B5\\u30A4\\u30C8\\u0001\\x80\\u0080\\uD83D\\uDE0E\"}"); +} + +void UnicodeTestGenerateTextFailsOnNonUTF8() { + flatbuffers::Parser parser; + // Allow non-UTF-8 initially to model what happens when we load a binary + // flatbuffer from disk which contains non-UTF-8 strings. + parser.opts.allow_non_utf8 = true; + TEST_EQ( + parser.Parse( + "table T { F:string; }" + "root_type T;" + "{ F:\"\\u20AC\\u00A2\\u30E6\\u30FC\\u30B6\\u30FC" + "\\u5225\\u30B5\\u30A4\\u30C8\\x01\\x80\\u0080\\uD83D\\uDE0E\" }"), + true); + std::string jsongen; + parser.opts.indent_step = -1; + // Now, disallow non-UTF-8 (the default behavior) so GenText indicates + // failure. + parser.opts.allow_non_utf8 = false; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_EQ_STR(result, "string contains non-utf8 bytes"); +} + +void UnicodeSurrogatesTest() { + flatbuffers::Parser parser; + + TEST_EQ(parser.Parse("table T { F:string (id: 0); }" + "root_type T;" + "{ F:\"\\uD83D\\uDCA9\"}"), + true); + auto root = flatbuffers::GetRoot( + parser.builder_.GetBufferPointer()); + auto string = root->GetPointer( + flatbuffers::FieldIndexToOffset(0)); + TEST_EQ_STR(string->c_str(), "\xF0\x9F\x92\xA9"); +} + +void UnknownFieldsTest() { + flatbuffers::IDLOptions opts; + opts.skip_unexpected_fields_in_json = true; + flatbuffers::Parser parser(opts); + + TEST_EQ(parser.Parse("table T { str:string; i:int;}" + "root_type T;" + "{ str:\"test\"," + "unknown_string:\"test\"," + "\"unknown_string\":\"test\"," + "unknown_int:10," + "unknown_float:1.0," + "unknown_array: [ 1, 2, 3, 4]," + "unknown_object: { i: 10 }," + "\"unknown_object\": { \"i\": 10 }," + "i:10}"), + true); + + std::string jsongen; + parser.opts.indent_step = -1; + auto result = GenText(parser, parser.builder_.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), "{str: \"test\",i: 10}"); +} + +void ParseUnionTest() { + // Unions must be parseable with the type field following the object. + flatbuffers::Parser parser; + TEST_EQ(parser.Parse("table T { A:int; }" + "union U { T }" + "table V { X:U; }" + "root_type V;" + "{ X:{ A:1 }, X_type: T }"), + true); + // Unions must be parsable with prefixed namespace. + flatbuffers::Parser parser2; + TEST_EQ(parser2.Parse("namespace N; table A {} namespace; union U { N.A }" + "table B { e:U; } root_type B;" + "{ e_type: N_A, e: {} }"), + true); + + // Test union underlying type + const char *source = "table A {} table B {} union U : int {A, B} table C {test_union: U; test_vector_of_union: [U];}"; + flatbuffers::Parser parser3; + parser3.opts.lang_to_generate = flatbuffers::IDLOptions::kCpp | flatbuffers::IDLOptions::kTs; + TEST_EQ(parser3.Parse(source), true); + + parser3.opts.lang_to_generate &= flatbuffers::IDLOptions::kJava; + TEST_EQ(parser3.Parse(source), false); +} + +void ValidSameNameDifferentNamespaceTest() { + // Duplicate table names in different namespaces must be parsable + TEST_ASSERT(flatbuffers::Parser().Parse( + "namespace A; table X {} namespace B; table X {}")); + // Duplicate union names in different namespaces must be parsable + TEST_ASSERT(flatbuffers::Parser().Parse( + "namespace A; union X {} namespace B; union X {}")); + // Clashing table and union names in different namespaces must be parsable + TEST_ASSERT(flatbuffers::Parser().Parse( + "namespace A; table X {} namespace B; union X {}")); + TEST_ASSERT(flatbuffers::Parser().Parse( + "namespace A; union X {} namespace B; table X {}")); +} + +void WarningsAsErrorsTest() { + { + flatbuffers::IDLOptions opts; + // opts.warnings_as_errors should default to false + flatbuffers::Parser parser(opts); + TEST_EQ(parser.Parse("table T { THIS_NAME_CAUSES_A_WARNING:string;}\n" + "root_type T;"), + true); + } + { + flatbuffers::IDLOptions opts; + opts.warnings_as_errors = true; + flatbuffers::Parser parser(opts); + TEST_EQ(parser.Parse("table T { THIS_NAME_CAUSES_A_WARNING:string;}\n" + "root_type T;"), + false); + } +} + +void StringVectorDefaultsTest() { + std::vector schemas; + schemas.push_back("table Monster { mana: string = \"\"; }"); + schemas.push_back("table Monster { mana: string = \"mystr\"; }"); + schemas.push_back("table Monster { mana: string = \" \"; }"); + schemas.push_back("table Monster { mana: string = \"null\"; }"); + schemas.push_back("table Monster { mana: [int] = []; }"); + schemas.push_back("table Monster { mana: [uint] = [ ]; }"); + schemas.push_back("table Monster { mana: [byte] = [\t\t\n]; }"); + schemas.push_back("enum E:int{}table Monster{mana:[E]=[];}"); + for (auto s = schemas.begin(); s < schemas.end(); s++) { + flatbuffers::Parser parser; + TEST_ASSERT(parser.Parse(s->c_str())); + const auto *mana = parser.structs_.Lookup("Monster")->fields.Lookup("mana"); + TEST_EQ(mana->IsDefault(), true); + } +} + +void FieldIdentifierTest() { + using flatbuffers::Parser; + TEST_EQ(true, Parser().Parse("table T{ f: int (id:0); }")); + // non-integer `id` should be rejected + TEST_EQ(false, Parser().Parse("table T{ f: int (id:text); }")); + TEST_EQ(false, Parser().Parse("table T{ f: int (id:\"text\"); }")); + TEST_EQ(false, Parser().Parse("table T{ f: int (id:0text); }")); + TEST_EQ(false, Parser().Parse("table T{ f: int (id:1.0); }")); + TEST_EQ(false, Parser().Parse("table T{ f: int (id:-1); g: int (id:0); }")); + TEST_EQ(false, Parser().Parse("table T{ f: int (id:129496726); }")); + // A unuion filed occupys two ids: enumerator + pointer (offset). + TEST_EQ(false, + Parser().Parse("union X{} table T{ u: X(id:0); table F{x:int;\n}")); + // Positive tests for unions + TEST_EQ(true, Parser().Parse("union X{} table T{ u: X (id:1); }")); + TEST_EQ(true, Parser().Parse("union X{} table T{ u: X; }")); + // Test using 'inf' and 'nan' words both as identifiers and as default values. + TEST_EQ(true, Parser().Parse("table T{ nan: string; }")); + TEST_EQ(true, Parser().Parse("table T{ inf: string; }")); +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) + TEST_EQ(true, Parser().Parse("table T{ inf: float = inf; }")); + TEST_EQ(true, Parser().Parse("table T{ nan: float = inf; }")); +#endif +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/parser_test.h b/third_party/flatbuffers/tests/parser_test.h new file mode 100644 index 00000000000..d7908491298 --- /dev/null +++ b/third_party/flatbuffers/tests/parser_test.h @@ -0,0 +1,33 @@ +#ifndef TESTS_PARSER_TEST_H +#define TESTS_PARSER_TEST_H + +namespace flatbuffers { +namespace tests { + +void ErrorTest(); +void EnumOutOfRangeTest(); +void IntegerOutOfRangeTest(); +void InvalidFloatTest(); +void UnicodeInvalidSurrogatesTest(); +void InvalidUTF8Test(); +void ValueTest(); +void NestedListTest(); +void EnumStringsTest(); +void EnumValueTest(); +void IntegerBoundaryTest(); +void ValidFloatTest(); +void UnicodeTest(); +void UnicodeTestAllowNonUTF8(); +void UnicodeTestGenerateTextFailsOnNonUTF8(); +void UnicodeSurrogatesTest(); +void UnknownFieldsTest(); +void ParseUnionTest(); +void ValidSameNameDifferentNamespaceTest(); +void WarningsAsErrorsTest(); +void StringVectorDefaultsTest(); +void FieldIdentifierTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif // TESTS_PARSER_TEST_H diff --git a/third_party/flatbuffers/tests/phpTest.php b/third_party/flatbuffers/tests/phpTest.php new file mode 100644 index 00000000000..a854e783e35 --- /dev/null +++ b/third_party/flatbuffers/tests/phpTest.php @@ -0,0 +1,632 @@ +createString("MyMonster"); + $name = $fbb->createString('Fred'); + \MyGame\Example\Monster::startMonster($fbb); + \MyGame\Example\Monster::addName($fbb, $name); + $enemy = \MyGame\Example\Monster::endMonster($fbb); + + $inv = \MyGame\Example\Monster::CreateInventoryVector($fbb, array(0, 1, 2, 3, 4)); + + $fred = $fbb->createString('Fred'); + \MyGame\Example\Monster::StartMonster($fbb); + \MyGame\Example\Monster::AddName($fbb, $fred); + $mon2 = \MyGame\Example\Monster::EndMonster($fbb); + + \MyGame\Example\Monster::StartTest4Vector($fbb, 2); + \MyGame\Example\Test::CreateTest($fbb, 10, 20); + \MyGame\Example\Test::CreateTest($fbb, 30, 40); + $test4 = $fbb->endVector(); + + $testArrayOfString = \MyGame\Example\Monster::CreateTestarrayofstringVector($fbb, array( + $fbb->createString('test1'), + $fbb->createString('test2') + )); + + \MyGame\Example\Monster::StartMonster($fbb); + \MyGame\Example\Monster::AddPos($fbb, \MyGame\Example\Vec3::CreateVec3($fbb, + 1.0, 2.0, 3.0, //float + 3.0, // double + \MyGame\Example\Color::Green, + 5, //short + 6)); + \MyGame\Example\Monster::AddHp($fbb, 80); + \MyGame\Example\Monster::AddName($fbb, $str); + \MyGame\Example\Monster::AddInventory($fbb, $inv); + \MyGame\Example\Monster::AddTestType($fbb, \MyGame\Example\Any::Monster); + \MyGame\Example\Monster::AddTest($fbb, $mon2); + \MyGame\Example\Monster::AddTest4($fbb, $test4); + \MyGame\Example\Monster::AddTestarrayofstring($fbb, $testArrayOfString); + \MyGame\Example\Monster::AddEnemy($fbb, $enemy); + \MyGame\Example\Monster::AddTestbool($fbb, true); + $mon = \MyGame\Example\Monster::EndMonster($fbb); + + \MyGame\Example\Monster::FinishMonsterBuffer($fbb, $mon); + + // Test it: + test_buffer($assert, $fbb->dataBuffer()); + + testByteBuffer($assert); + fuzzTest1($assert); +// testUnicode($assert); + + echo 'FlatBuffers php test: completed successfully' . PHP_EOL; +} + +try { + main(); + exit(0); +} catch(Exception $e) { + printf("Fatal error: Uncaught exception '%s' with message '%s. in %s:%d\n", get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()); + printf("Stack trace:\n"); + echo $e->getTraceAsString() . PHP_EOL; + printf(" thrown in in %s:%d\n", $e->getFile(), $e->getLine()); + + die(-1); +} + +function test_buffer(Assert $assert, Google\FlatBuffers\ByteBuffer $bb) { + + $assert->ok(MyGame\Example\Monster::MonsterBufferHasIdentifier($bb)); + $monster = \MyGame\Example\Monster::GetRootAsMonster($bb); + + $assert->strictEqual($monster->GetHp(), 80); + $assert->strictEqual($monster->GetMana(), 150); // default + + $assert->strictEqual($monster->GetName(), 'MyMonster'); + + $pos = $monster->GetPos(); + $assert->strictEqual($pos->GetX(), 1.0); + $assert->strictEqual($pos->GetY(), 2.0); + $assert->strictEqual($pos->GetZ(), 3.0); + + $assert->Equal($pos->GetTest1(), 3.0); + $assert->strictEqual($pos->GetTest2(), \MyGame\Example\Color::Green); + + $t = $pos->GetTest3(); + $assert->strictEqual($t->GetA(), 5); + $assert->strictEqual($t->GetB(), 6); + $assert->strictEqual($monster->GetTestType(), \MyGame\Example\Any::Monster); + + $monster2 = new \MyGame\Example\Monster(); + $assert->strictEqual($monster->GetTest($monster2) != null, true); + $assert->strictEqual($monster2->GetName(), 'Fred'); + + $assert->strictEqual($monster->GetInventoryLength(), 5); + $invsum = 0; + for ($i = 0; $i < $monster->GetInventoryLength(); $i++) { + $invsum += $monster->GetInventory($i); + } + $assert->strictEqual($invsum, 10); + + $assert->strictEqual(bin2hex($monster->GetInventoryBytes()), "0001020304"); + + $test_0 = $monster->GetTest4(0); + $test_1 = $monster->GetTest4(1); + $assert->strictEqual($monster->GetTest4Length(), 2); + $assert->strictEqual($test_0->GetA() + $test_0->GetB() + $test_1->GetA() + $test_1->GetB(), 100); + + $assert->strictEqual($monster->GetTestarrayofstringLength(), 2); + $assert->strictEqual($monster->GetTestarrayofstring(0), 'test1'); + $assert->strictEqual($monster->GetTestarrayofstring(1), 'test2'); + + $fred = $monster->getEnemy(); + $assert->Equal('Fred', $fred->getName()); + + $assert->strictEqual($monster->GetTestbool(), true); +} + +//function testUnicode(Assert $assert) { +// // missing unicode_test.mon, implemented later +// $correct = file_get_contents('unicode_test.mon'); +// $json = json_decode(file_get_contents('unicode_test.json')); +// +// // Test reading +// $bb = flatbuffers\ByteBuffer::Wrap($correct); +// $monster = \MyGame\Example\Monster::GetRootAsMonster($bb); +// $assert->strictEqual($monster->GetName(), $json["name"]); +// +// //$assert->deepEqual(new Buffer(monster.name(flatbuffers.Encoding.UTF8_BYTES)), new Buffer(json.name)); +// //assert.strictEqual(monster.testarrayoftablesLength(), json.testarrayoftables.length); +// foreach ($json["testarrayoftables"]as $i => $table) { +// $value = $monster->GetTestArrayOfTables($i); +// $assert->strictEqual($value->GetName(), $table["name"]); +// //assert.deepEqual(new Buffer(value.name(flatbuffers.Encoding.UTF8_BYTES)), new Buffer(table.name)); +// } +// $assert->strictEqual($monster->GetTestarrayofstringLength(), $json["testarrayofstring"]["length"]); +// foreach ($json["testarrayofstring"] as $i => $string) { +// $assert->strictEqual($monster->GetTestarrayofstring($i), $string); +// //assert.deepEqual(new Buffer(monster.testarrayofstring(i, flatbuffers.Encoding.UTF8_BYTES)), new Buffer(string)); +// } +// +// // Test writing +// $fbb = new FlatBuffers\FlatBufferBuilder(1); +// $name = $fbb->CreateString($json["name"]); +// $testarrayoftablesOffsets = array_map(function($table) use($fbb) { +// $name = $fbb->CreateString($table["name"]); +// \MyGame\Example\Monster::StartMonster($fbb); +// \MyGame\Example\Monster::AddName($fbb, $name); +// return \MyGame\Example\Monster::EndMonster($fbb); +// }, $json["testarrayoftables"]); +// $testarrayoftablesOffset = \MyGame\Example\Monster::CreateTestarrayoftablesVector($fbb, +// $testarrayoftablesOffsets); +//// $testarrayofstringOffset = \MyGame\Example\Monster::CreateTestarrayofstringVector($fbb, +//// $json["testarrayofstring"].map(function(string) { return fbb.createString(string); })); +// +// \MyGame\Example\Monster::startMonster($fbb); +// \MyGame\Example\Monster::addTestarrayofstring($fbb, $testarrayoftablesOffset); +// \MyGame\Example\Monster::addTestarrayoftables($fbb, $testarrayoftablesOffset); +// \MyGame\Example\Monster::addName($fbb, $name); +// \MyGame\Example\Monster::finishMonsterBuffer($fbb, \MyGame\Example\Monster::endMonster($fbb)); +// //;assert.deepEqual(new Buffer(fbb.asUint8Array()), correct); +//} + +// Low level stress/fuzz test: serialize/deserialize a variety of +// different kinds of data in different combinations +function fuzzTest1(Assert $assert) +{ + + // Values we're testing against: chosen to ensure no bits get chopped + // off anywhere, and also be different from eachother. + $bool_val = true; + $char_val = -127; // 0x81 + $uchar_val = 0xFF; + $short_val = -32222; // 0x8222; + $ushort_val = 0xFEEE; + $int_val = 0x7fffffff | 0; + // for now + $uint_val = 1; + $long_val = 2; + $ulong_val = 3; + +// var uint_val = 0xFDDDDDDD; +// var long_val = new flatbuffers.Long(0x44444444, 0x84444444); +// var ulong_val = new flatbuffers.Long(0xCCCCCCCC, 0xFCCCCCCC); + + $float_val = 3.14159; + $double_val = 3.14159265359; + + $test_values_max = 11; + $fields_per_object = 4; + // current implementation is not good at encoding. + $num_fuzz_objects = 1000; + $builder = new Google\FlatBuffers\FlatBufferBuilder(1); + + // can't use same implementation due to PHP_INTMAX overflow issue. + // we use mt_rand function to reproduce fuzzy test. + mt_srand(48271); + $objects = array(); + // Generate num_fuzz_objects random objects each consisting of + // fields_per_object fields, each of a random type. + for ($i = 0; $i < $num_fuzz_objects; $i++) { + $builder->startObject($fields_per_object); + for ($f = 0; $f < $fields_per_object; $f++) { + $choice = mt_rand() % $test_values_max; + switch ($choice) { + case 0: + $builder->addBoolX($f, $bool_val, 0); + break; + case 1: + $builder->addByteX($f, $char_val, 0); + break; + case 2: + $builder->addSbyteX($f, $uchar_val, 0); + break; + case 3: + $builder->addShortX($f, $short_val, 0); + break; + case 4: + $builder->addUshortX($f, $ushort_val, 0); + break; + case 5: + $builder->addIntX($f, $int_val, 0); + break; + case 6: + $builder->addUintX($f, $uint_val, 0); + break; + case 7: + $builder->addLongX($f, $long_val, 0); + break; + case 8: + $builder->addUlongX($f, $ulong_val, 0); + break; + case 9: + $builder->addFloatX($f, $float_val, 0); + break; + case 10: + $builder->addDoubleX($f, $double_val, 0); + break; + } + } + $objects[] = $builder->endObject(); + } + $builder->prep(8, 0); // Align whole buffer. + + mt_srand(48271); // Reset + $builder->finish($objects[count($objects) - 1]); + + $view = Google\FlatBuffers\ByteBuffer::wrap($builder->sizedByteArray()); + for ($i = 0; $i < $num_fuzz_objects; $i++) { + $offset = $view->capacity() - $objects[$i]; + for ($f = 0; $f < $fields_per_object; $f++) { + $choice = mt_rand() % $test_values_max; + $vtable_offset = fieldIndexToOffset($f); + $vtable = $offset - $view->getInt($offset); + $assert->ok($vtable_offset < $view->getShort($vtable)); + $field_offset = $offset + $view->getShort($vtable + $vtable_offset); + switch ($choice) { + case 0: + $assert->strictEqual(!!$view->getBool($field_offset), $bool_val); + break; + case 1: + $assert->strictEqual($view->getSbyte($field_offset), $char_val); + break; + case 2: + $assert->strictEqual($view->getByte($field_offset), $uchar_val); + break; + case 3: + $assert->strictEqual($view->getShort($field_offset), $short_val); + break; + case 4: + $assert->strictEqual($view->getUShort($field_offset), $ushort_val); + break; + case 5: + $assert->strictEqual($view->getInt($field_offset), $int_val); + break; + case 6: + $assert->strictEqual($view->getUint($field_offset), $uint_val); + break; + case 7: + if (PHP_INT_SIZE <= 4) break; + $assert->strictEqual($view->getLong($field_offset), $long_val); + break; + case 8: + if (PHP_INT_SIZE <= 4) break; + $assert->strictEqual($view->getUlong($field_offset), $ulong_val); + break; + case 9: + $assert->strictEqual(floor($view->getFloat($field_offset)), floor($float_val)); + break; + case 10: + $assert->strictEqual($view->getDouble($field_offset), $double_val); + break; + } + } + } +} + +function fieldIndexToOffset($field_id) { + // Should correspond to what EndTable() below builds up. + $fixed_fields = 2; // Vtable size and Object Size. + return ($field_id + $fixed_fields) * 2; +} + +function testByteBuffer(Assert $assert) { + + //Test: ByteBuffer_Length_MatchesBufferLength + $buffer = str_repeat("\0", 100); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal($uut->capacity(), strlen($buffer)); + + //Test: ByteBuffer_PutBytePopulatesBufferAtZeroOffset + $buffer = "\0"; + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $uut->putByte(0, "\x63"); // 99 + $assert->Equal("\x63", $uut->_buffer[0]); // don't share buffer as php user might confuse reference. + + //Test: ByteBuffer_PutByteCannotPutAtOffsetPastLength + $buffer = "\0"; + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putByte(1, "\x63"); // 99 + }); + + //Test: ByteBuffer_PutShortPopulatesBufferCorrectly + $buffer = str_repeat("\0", 2); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $uut->putShort(0, 1); + + // Ensure Endiannes was written correctly + $assert->Equal(chr(0x01), $uut->_buffer[0]); + $assert->Equal(chr(0x00), $uut->_buffer[1]); + + $buffer = str_repeat("\0", 2); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $uut->putShort(0, -32768); + + // Ensure Endiannes was written correctly + $assert->Equal(chr(0x00), $uut->_buffer[0]); + $assert->Equal(chr(0x80), $uut->_buffer[1]); + + //Test: ByteBuffer_PutShortCannotPutAtOffsetPastLength + $buffer = "\0"; + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putShort(2, 2); // 99 + }); + + //Test: ByteBuffer_PutShortChecksLength + $buffer = "\0"; + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putShort(0, 2); // 99 + }); + + //Test: ByteBuffer_PutShortChecksLengthAndOffset + $buffer = str_repeat("\0", 2); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putShort(1, 2); // 99 + }); + + //Test: ByteBuffer_PutIntPopulatesBufferCorrectly + $buffer = str_repeat("\0", 4); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $uut->putInt(0, 0x0A0B0C0D); + $assert->Equal(chr(0x0D), $uut->_buffer[0]); + $assert->Equal(chr(0x0C), $uut->_buffer[1]); + $assert->Equal(chr(0x0B), $uut->_buffer[2]); + $assert->Equal(chr(0x0A), $uut->_buffer[3]); + + $buffer = str_repeat("\0", 4); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $uut->putInt(0, -2147483648); + $assert->Equal(chr(0x00), $uut->_buffer[0]); + $assert->Equal(chr(0x00), $uut->_buffer[1]); + $assert->Equal(chr(0x00), $uut->_buffer[2]); + $assert->Equal(chr(0x80), $uut->_buffer[3]); + + //Test: ByteBuffer_PutIntCannotPutAtOffsetPastLength + $buffer = str_repeat("\0", 4); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putInt(2, 0x0A0B0C0D); + }); + + //Test: ByteBuffer_PutIntChecksLength + $buffer = str_repeat("\0", 1); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putInt(0, 0x0A0B0C0D); + }); + + //Test: ByteBuffer_PutIntChecksLengthAndOffset + $buffer = str_repeat("\0", 4); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putInt(2, 0x0A0B0C0D); + }); + + if (PHP_INT_SIZE > 4) { + //Test: ByteBuffer_PutLongPopulatesBufferCorrectly + $buffer = str_repeat("\0", 8); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $uut->putLong(0, 0x010203040A0B0C0D); + $assert->Equal(chr(0x0D), $uut->_buffer[0]); + $assert->Equal(chr(0x0C), $uut->_buffer[1]); + $assert->Equal(chr(0x0B), $uut->_buffer[2]); + $assert->Equal(chr(0x0A), $uut->_buffer[3]); + $assert->Equal(chr(0x04), $uut->_buffer[4]); + $assert->Equal(chr(0x03), $uut->_buffer[5]); + $assert->Equal(chr(0x02), $uut->_buffer[6]); + $assert->Equal(chr(0x01), $uut->_buffer[7]); + + //Test: ByteBuffer_PutLongCannotPutAtOffsetPastLength + $buffer = str_repeat("\0", 8); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putLong(2, 0x010203040A0B0C0D); + }); + + //Test: ByteBuffer_PutLongCannotPutAtOffsetPastLength + $buffer = str_repeat("\0", 1); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putLong(0, 0x010203040A0B0C0D); + }); + + + //Test: ByteBuffer_PutLongChecksLengthAndOffset + $buffer = str_repeat("\0", 8); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->putLong(2, 0x010203040A0B0C0D); + }); + } + + //Test: ByteBuffer_GetByteReturnsCorrectData + $buffer = str_repeat("\0", 1); + $buffer[0] = "\x63"; + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal("\x63", $uut->get(0)); + + //Test: ByteBuffer_GetByteChecksOffset + $buffer = str_repeat("\0", 1); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->get(1); + }); + + //Test: ByteBuffer_GetShortReturnsCorrectData + $buffer = str_repeat("\0", 2); + $buffer[0] = chr(0x01); + $buffer[1] = chr(0x00); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(1, $uut->getShort(0)); + + //Test: ByteBuffer_GetShortReturnsCorrectData (signed value) + $buffer = str_repeat("\0", 2); + $buffer[0] = chr(0x00); + $buffer[1] = chr(0x80); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(-32768, $uut->getShort(0)); + + //Test: ByteBuffer_GetShortChecksOffset + $buffer = str_repeat("\0", 2); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->getShort(2); + }); + + //Test: ByteBuffer_GetShortChecksLength + $buffer = str_repeat("\0", 2); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->getShort(1); + }); + + //Test: ByteBuffer_GetIntReturnsCorrectData + $buffer = str_repeat("\0", 4); + $buffer[0] = chr(0x0D); + $buffer[1] = chr(0x0C); + $buffer[2] = chr(0x0B); + $buffer[3] = chr(0x0A); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(0x0A0B0C0D, $uut->getInt(0)); + + $buffer = str_repeat("\0", 4); + $buffer[0] = chr(0x00); + $buffer[1] = chr(0x00); + $buffer[2] = chr(0x00); + $buffer[3] = chr(0x80); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(-2147483648, $uut->getInt(0)); + + //Test: ByteBuffer_GetIntChecksOffset + $buffer = str_repeat("\0", 4); + + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->getInt(4); + }); + + //Test: ByteBuffer_GetIntChecksLength + $buffer = str_repeat("\0", 2); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->getInt(0); + }); + + if (PHP_INT_SIZE > 4) { + //Test: ByteBuffer_GetLongReturnsCorrectData + $buffer = str_repeat("\0", 8); + $buffer[0] = chr(0x0D); + $buffer[1] = chr(0x0C); + $buffer[2] = chr(0x0B); + $buffer[3] = chr(0x0A); + $buffer[4] = chr(0x04); + $buffer[5] = chr(0x03); + $buffer[6] = chr(0x02); + $buffer[7] = chr(0x01); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(0x010203040A0B0C0D, $uut->getLong(0)); + + //Test: Signed Long + $buffer = str_repeat("\0", 8); + $buffer[0] = chr(0x00); + $buffer[1] = chr(0x00); + $buffer[2] = chr(0x00); + $buffer[3] = chr(0x00); + $buffer[4] = chr(0x00); + $buffer[5] = chr(0x00); + $buffer[6] = chr(0x00); + $buffer[7] = chr(0x80); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(-1 << 63, $uut->getLong(0)); + } + + //Test: ByteBuffer_GetLongChecksOffset + $buffer = str_repeat("\0", 8); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->getLong(8); + }); + + //Test: ByteBuffer_GetLongChecksLength + $buffer = str_repeat("\0", 7); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Throws(new OutOfRangeException(), function() use ($uut) { + $uut->getLong(0); + }); + + //Test: big endian + $buffer = str_repeat("\0", 2); + // 0xFF 0x00 + // Little Endian: 255 + // Big Endian: 65280 + $buffer[0] = chr(0xff); + $buffer[1] = chr(0x00); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(65280, $uut->readLittleEndian(0, 2, true)); + + $buffer = str_repeat("\0", 4); + $buffer[0] = chr(0x0D); + $buffer[1] = chr(0x0C); + $buffer[2] = chr(0x0B); + $buffer[3] = chr(0x0A); + $uut = Google\FlatBuffers\ByteBuffer::wrap($buffer); + $assert->Equal(0x0D0C0B0A, $uut->readLittleEndian(0, 4, true)); + +} + +class Assert { + public function ok($result, $message = "") { + if (!$result){ + throw new Exception(!empty($message) ? $message : "{$result} is not true."); + } + } + + public function Equal($result, $expected, $message = "") { + if ($result != $expected) { + throw new Exception(!empty($message) ? $message : "given the result {$result} is not equals as {$expected}"); + } + } + + + public function strictEqual($result, $expected, $message = "") { + if ($result !== $expected) { + throw new Exception(!empty($message) ? $message : "given the result {$result} is not strict equals as {$expected}"); + } + } + + public function Throws($class, Callable $callback) { + try { + $callback(); + + throw new \Exception("passed statement don't throw an exception."); + } catch (\Exception $e) { + if (get_class($e) != get_class($class)) { + throw new Exception("passed statement doesn't throw " . get_class($class) . ". throws " . get_class($e) . ": {$e->getMessage()}"); + } + } + } +} diff --git a/third_party/flatbuffers/tests/phpUnionVectorTest.php b/third_party/flatbuffers/tests/phpUnionVectorTest.php new file mode 100644 index 00000000000..4b5e25885ee --- /dev/null +++ b/third_party/flatbuffers/tests/phpUnionVectorTest.php @@ -0,0 +1,109 @@ +dataBuffer()->data()); + + $movie = Movie::getRootAsMovie($buf); + + $assert->strictEqual($movie->getCharactersTypeLength(), count($charTypes)); + $assert->strictEqual($movie->getCharactersLength(), $movie->getCharactersTypeLength()); + + for ($i = 0; $i < count($charTypes); ++$i) { + $assert->strictEqual($movie->getCharactersType($i), $charTypes[$i]); + } + + $bookReader7 = $movie->getCharacters(0, new BookReader()); + $assert->strictEqual($bookReader7->getBooksRead(), 7); + + $attacker = $movie->getCharacters(1, new Attacker()); + $assert->strictEqual($attacker->getSwordAttackDamage(), 5); + + $bookReader2 = $movie->getCharacters(2, new BookReader()); + $assert->strictEqual($bookReader2->getBooksRead(), 2); +} + +try { + main(); + exit(0); +} catch(Exception $e) { + printf("Fatal error: Uncaught exception '%s' with message '%s. in %s:%d\n", get_class($e), $e->getMessage(), $e->getFile(), $e->getLine()); + printf("Stack trace:\n"); + echo $e->getTraceAsString() . PHP_EOL; + printf(" thrown in in %s:%d\n", $e->getFile(), $e->getLine()); + + die(-1); +} diff --git a/third_party/flatbuffers/tests/phpUnionVectorTest.sh b/third_party/flatbuffers/tests/phpUnionVectorTest.sh new file mode 100755 index 00000000000..a6c3f264401 --- /dev/null +++ b/third_party/flatbuffers/tests/phpUnionVectorTest.sh @@ -0,0 +1,8 @@ +#!/bin/bash + +set -e + +../flatc --php -o php union_vector/union_vector.fbs +php phpUnionVectorTest.php + +echo 'PHP union vector test passed' diff --git a/third_party/flatbuffers/tests/private_annotation_test.fbs b/third_party/flatbuffers/tests/private_annotation_test.fbs new file mode 100644 index 00000000000..434927b8413 --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test.fbs @@ -0,0 +1,18 @@ +enum AB:byte (private) { + A, + B, +} + +struct Object (private) { + value: int; +} + +union Any (private) { Game, Annotations } + +table Game (private) { + value: int; +} + +table Annotations (private) { + value: int; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/private_annotation_test/ab_generated.rs b/third_party/flatbuffers/tests/private_annotation_test/ab_generated.rs new file mode 100644 index 00000000000..f2246488f83 --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test/ab_generated.rs @@ -0,0 +1,96 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_AB: i8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_AB: i8 = 1; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_AB: [AB; 2] = [ + AB::A, + AB::B, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub(crate) struct AB(pub i8); +#[allow(non_upper_case_globals)] +impl AB { + pub const A: Self = Self(0); + pub const B: Self = Self(1); + + pub const ENUM_MIN: i8 = 0; + pub const ENUM_MAX: i8 = 1; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::A, + Self::B, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::A => Some("A"), + Self::B => Some("B"), + _ => None, + } + } +} +impl core::fmt::Debug for AB { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for AB { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for AB { + type Output = AB; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for AB { + type Scalar = i8; + #[inline] + fn to_little_endian(self) -> i8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: i8) -> Self { + let b = i8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for AB { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + i8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for AB {} diff --git a/third_party/flatbuffers/tests/private_annotation_test/annotations_generated.rs b/third_party/flatbuffers/tests/private_annotation_test/annotations_generated.rs new file mode 100644 index 00000000000..324475632db --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test/annotations_generated.rs @@ -0,0 +1,141 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub(crate) enum AnnotationsOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub(crate) struct Annotations<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Annotations<'a> { + type Inner = Annotations<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Annotations<'a> { + pub const VT_VALUE: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "Annotations" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Annotations { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args AnnotationsArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = AnnotationsBuilder::new(_fbb); + builder.add_value(args.value); + builder.finish() + } + + pub fn unpack(&self) -> AnnotationsT { + let value = self.value(); + AnnotationsT { + value, + } + } + + #[inline] + pub fn value(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Annotations::VT_VALUE, Some(0)).unwrap()} + } +} + +impl flatbuffers::Verifiable for Annotations<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("value", Self::VT_VALUE, false)? + .finish(); + Ok(()) + } +} +pub(crate) struct AnnotationsArgs { + pub value: i32, +} +impl<'a> Default for AnnotationsArgs { + #[inline] + fn default() -> Self { + AnnotationsArgs { + value: 0, + } + } +} + +pub(crate) struct AnnotationsBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> AnnotationsBuilder<'a, 'b, A> { + #[inline] + pub fn add_value(&mut self, value: i32) { + self.fbb_.push_slot::(Annotations::VT_VALUE, value, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> AnnotationsBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + AnnotationsBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Annotations<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Annotations"); + ds.field("value", &self.value()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct AnnotationsT { + pub value: i32, +} +impl Default for AnnotationsT { + fn default() -> Self { + Self { + value: 0, + } + } +} +impl AnnotationsT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let value = self.value; + Annotations::create(_fbb, &AnnotationsArgs{ + value, + }) + } +} diff --git a/third_party/flatbuffers/tests/private_annotation_test/any_generated.rs b/third_party/flatbuffers/tests/private_annotation_test/any_generated.rs new file mode 100644 index 00000000000..e7dcf9d903e --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test/any_generated.rs @@ -0,0 +1,173 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_ANY: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_ANY: u8 = 2; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_ANY: [Any; 3] = [ + Any::NONE, + Any::Game, + Any::Annotations, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub(crate) struct Any(pub u8); +#[allow(non_upper_case_globals)] +impl Any { + pub const NONE: Self = Self(0); + pub const Game: Self = Self(1); + pub const Annotations: Self = Self(2); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 2; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::Game, + Self::Annotations, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::Game => Some("Game"), + Self::Annotations => Some("Annotations"), + _ => None, + } + } +} +impl core::fmt::Debug for Any { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for Any { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for Any { + type Output = Any; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for Any { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for Any { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Any {} +pub(crate) struct AnyUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub(crate) enum AnyT { + NONE, + Game(Box), + Annotations(Box), +} +impl Default for AnyT { + fn default() -> Self { + Self::NONE + } +} +impl AnyT { + pub fn any_type(&self) -> Any { + match self { + Self::NONE => Any::NONE, + Self::Game(_) => Any::Game, + Self::Annotations(_) => Any::Annotations, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::Game(v) => Some(v.pack(fbb).as_union_value()), + Self::Annotations(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned GameT, setting the union to NONE. + pub fn take_game(&mut self) -> Option> { + if let Self::Game(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::Game(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the GameT. + pub fn as_game(&self) -> Option<&GameT> { + if let Self::Game(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the GameT. + pub fn as_game_mut(&mut self) -> Option<&mut GameT> { + if let Self::Game(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned AnnotationsT, setting the union to NONE. + pub fn take_annotations(&mut self) -> Option> { + if let Self::Annotations(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::Annotations(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the AnnotationsT. + pub fn as_annotations(&self) -> Option<&AnnotationsT> { + if let Self::Annotations(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the AnnotationsT. + pub fn as_annotations_mut(&mut self) -> Option<&mut AnnotationsT> { + if let Self::Annotations(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/private_annotation_test/game_generated.rs b/third_party/flatbuffers/tests/private_annotation_test/game_generated.rs new file mode 100644 index 00000000000..24d3b0f04a2 --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test/game_generated.rs @@ -0,0 +1,141 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub(crate) enum GameOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub(crate) struct Game<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for Game<'a> { + type Inner = Game<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> Game<'a> { + pub const VT_VALUE: flatbuffers::VOffsetT = 4; + + pub const fn get_fully_qualified_name() -> &'static str { + "Game" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + Game { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args GameArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = GameBuilder::new(_fbb); + builder.add_value(args.value); + builder.finish() + } + + pub fn unpack(&self) -> GameT { + let value = self.value(); + GameT { + value, + } + } + + #[inline] + pub fn value(&self) -> i32 { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(Game::VT_VALUE, Some(0)).unwrap()} + } +} + +impl flatbuffers::Verifiable for Game<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_field::("value", Self::VT_VALUE, false)? + .finish(); + Ok(()) + } +} +pub(crate) struct GameArgs { + pub value: i32, +} +impl<'a> Default for GameArgs { + #[inline] + fn default() -> Self { + GameArgs { + value: 0, + } + } +} + +pub(crate) struct GameBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GameBuilder<'a, 'b, A> { + #[inline] + pub fn add_value(&mut self, value: i32) { + self.fbb_.push_slot::(Game::VT_VALUE, value, 0); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> GameBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + GameBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for Game<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("Game"); + ds.field("value", &self.value()); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub(crate) struct GameT { + pub value: i32, +} +impl Default for GameT { + fn default() -> Self { + Self { + value: 0, + } + } +} +impl GameT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let value = self.value; + Game::create(_fbb, &GameArgs{ + value, + }) + } +} diff --git a/third_party/flatbuffers/tests/private_annotation_test/mod.rs b/third_party/flatbuffers/tests/private_annotation_test/mod.rs new file mode 100644 index 00000000000..def5184785d --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test/mod.rs @@ -0,0 +1,12 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +mod ab_generated; +pub use self::ab_generated::*; +mod any_generated; +pub use self::any_generated::*; +mod object_generated; +pub use self::object_generated::*; +mod game_generated; +pub use self::game_generated::*; +mod annotations_generated; +pub use self::annotations_generated::*; diff --git a/third_party/flatbuffers/tests/private_annotation_test/object_generated.rs b/third_party/flatbuffers/tests/private_annotation_test/object_generated.rs new file mode 100644 index 00000000000..382b0e42e92 --- /dev/null +++ b/third_party/flatbuffers/tests/private_annotation_test/object_generated.rs @@ -0,0 +1,128 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct Object, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub(crate) struct Object(pub [u8; 4]); +impl Default for Object { + fn default() -> Self { + Self([0; 4]) + } +} +impl core::fmt::Debug for Object { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("Object") + .field("value", &self.value()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for Object {} +impl<'a> flatbuffers::Follow<'a> for Object { + type Inner = &'a Object; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a Object>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a Object { + type Inner = &'a Object; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for Object { + type Output = Object; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const Object as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for Object { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> Object { + #[allow(clippy::too_many_arguments)] + pub fn new( + value: i32, + ) -> Self { + let mut s = Self([0; 4]); + s.set_value(value); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "Object" + } + + pub fn value(&self) -> i32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_value(&mut self, x: i32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> ObjectT { + ObjectT { + value: self.value(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub(crate) struct ObjectT { + pub value: i32, +} +impl ObjectT { + pub fn pack(&self) -> Object { + Object::new( + self.value, + ) + } +} + diff --git a/third_party/flatbuffers/tests/proto_test.cpp b/third_party/flatbuffers/tests/proto_test.cpp new file mode 100644 index 00000000000..90c70bdb211 --- /dev/null +++ b/third_party/flatbuffers/tests/proto_test.cpp @@ -0,0 +1,336 @@ +#include "proto_test.h" + +#include "flatbuffers/code_generator.h" +#include "idl_gen_fbs.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +void RunTest(const flatbuffers::IDLOptions &opts, const std::string &proto_path, + const std::string &proto_file, const std::string &golden_file, + const std::string import_proto_file) { + const char *include_directories[] = { proto_path.c_str(), nullptr }; + + // Parse proto. + flatbuffers::Parser parser(opts); + TEST_EQ(parser.Parse(proto_file.c_str(), include_directories), true); + + // Generate fbs. + std::unique_ptr fbs_generator = NewFBSCodeGenerator(true); + std::string fbs; + TEST_EQ(fbs_generator->GenerateCodeString(parser, "test", fbs), + CodeGenerator::Status::OK); + + // Ensure generated file is parsable. + flatbuffers::Parser parser2; + + if (!import_proto_file.empty()) { + // Generate fbs from import.proto + flatbuffers::Parser import_parser(opts); + TEST_EQ(import_parser.Parse(import_proto_file.c_str(), include_directories), + true); + std::string import_fbs; + TEST_EQ( + fbs_generator->GenerateCodeString(import_parser, "test", import_fbs), + CodeGenerator::Status::OK); + // auto import_fbs = flatbuffers::GenerateFBS(import_parser, "test", true); + // Since `imported.fbs` isn't in the filesystem AbsolutePath can't figure it + // out by itself. We manually construct it so Parser works. + std::string imported_fbs = flatbuffers::PosixPath( + flatbuffers::AbsolutePath(proto_path) + "/imported.fbs"); + TEST_EQ(parser2.Parse(import_fbs.c_str(), include_directories, + imported_fbs.c_str()), + true); + } + + TEST_EQ(parser2.Parse(fbs.c_str(), nullptr), true); + TEST_EQ_STR(fbs.c_str(), golden_file.c_str()); +} + +void proto_test(const std::string &proto_path, const std::string &proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = false; + opts.proto_mode = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + // load the .proto and the golden file from disk + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile((proto_path + "test.golden.fbs").c_str(), false, + &golden_file), + true); + + RunTest(opts, proto_path, proto_file, golden_file); +} + +void proto_test_id(const std::string &proto_path, + const std::string &proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = false; + opts.proto_mode = true; + opts.keep_proto_id = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + // load the .proto and the golden file from disk + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile((proto_path + "test_id.golden.fbs").c_str(), + false, &golden_file), + true); + + RunTest(opts, proto_path, proto_file, golden_file); +} + +void proto_test_union(const std::string &proto_path, + const std::string &proto_file) { + // Parse proto with --oneof-union option. + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = false; + opts.proto_mode = true; + opts.proto_oneof_union = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile((proto_path + "test_union.golden.fbs").c_str(), + false, &golden_file), + true); + RunTest(opts, proto_path, proto_file, golden_file); +} + +void proto_test_union_id(const std::string &proto_path, + const std::string &proto_file) { + // Parse proto with --oneof-union option. + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = false; + opts.proto_mode = true; + opts.proto_oneof_union = true; + opts.keep_proto_id = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ( + flatbuffers::LoadFile((proto_path + "test_union_id.golden.fbs").c_str(), + false, &golden_file), + true); + RunTest(opts, proto_path, proto_file, golden_file); +} + +void proto_test_union_suffix(const std::string &proto_path, + const std::string &proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = false; + opts.proto_mode = true; + opts.proto_namespace_suffix = "test_namespace_suffix"; + opts.proto_oneof_union = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile( + (proto_path + "test_union_suffix.golden.fbs").c_str(), false, + &golden_file), + true); + RunTest(opts, proto_path, proto_file, golden_file); +} + +void proto_test_union_suffix_id(const std::string &proto_path, + const std::string &proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = false; + opts.proto_mode = true; + opts.proto_namespace_suffix = "test_namespace_suffix"; + opts.proto_oneof_union = true; + opts.keep_proto_id = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile( + (proto_path + "test_union_suffix_id.golden.fbs").c_str(), false, + &golden_file), + true); + RunTest(opts, proto_path, proto_file, golden_file); +} + +void proto_test_include(const std::string &proto_path, + const std::string &proto_file, + const std::string &import_proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = true; + opts.proto_mode = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ( + flatbuffers::LoadFile((proto_path + "test_include.golden.fbs").c_str(), + false, &golden_file), + true); + + RunTest(opts, proto_path, proto_file, golden_file, import_proto_file); +} + +void proto_test_include_id(const std::string &proto_path, + const std::string &proto_file, + const std::string &import_proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = true; + opts.proto_mode = true; + opts.keep_proto_id = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ( + flatbuffers::LoadFile((proto_path + "test_include_id.golden.fbs").c_str(), + false, &golden_file), + true); + + RunTest(opts, proto_path, proto_file, golden_file, import_proto_file); +} + +void proto_test_include_union(const std::string &proto_path, + const std::string &proto_file, + const std::string &import_proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = true; + opts.proto_mode = true; + opts.proto_oneof_union = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile( + (proto_path + "test_union_include.golden.fbs").c_str(), false, + &golden_file), + true); + + RunTest(opts, proto_path, proto_file, golden_file, import_proto_file); +} + +void proto_test_include_union_id(const std::string &proto_path, + const std::string &proto_file, + const std::string &import_proto_file) { + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = true; + opts.proto_mode = true; + opts.proto_oneof_union = true; + opts.keep_proto_id = true; + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::NO_OP; + + std::string golden_file; + TEST_EQ(flatbuffers::LoadFile( + (proto_path + "test_union_include_id.golden.fbs").c_str(), false, + &golden_file), + true); + + RunTest(opts, proto_path, proto_file, golden_file, import_proto_file); +} + +void ParseCorruptedProto(const std::string &proto_path) { + const char *include_directories[] = { proto_path.c_str(), nullptr }; + + flatbuffers::IDLOptions opts; + opts.include_dependence_headers = true; + opts.proto_mode = true; + opts.proto_oneof_union = true; + + std::string proto_file; + + std::unique_ptr fbs_generator = NewFBSCodeGenerator(true); + + // Parse proto with non positive id. + { + flatbuffers::Parser parser(opts); + TEST_EQ( + flatbuffers::LoadFile((proto_path + "non-positive-id.proto").c_str(), + false, &proto_file), + true); + TEST_EQ(parser.Parse(proto_file.c_str(), include_directories), true); + TEST_NE(fbs_generator->GenerateCode(parser, "temp.fbs", "test"), + CodeGenerator::Status::OK); + } + + // Parse proto with twice id. + { + flatbuffers::Parser parser(opts); + TEST_EQ(flatbuffers::LoadFile((proto_path + "twice-id.proto").c_str(), + false, &proto_file), + true); + TEST_EQ(parser.Parse(proto_file.c_str(), include_directories), true); + TEST_NE(fbs_generator->GenerateCode(parser, "temp.fbs", "test"), + CodeGenerator::Status::OK); + } + + // Parse proto with using reserved id. + { + flatbuffers::Parser parser(opts); + TEST_EQ(flatbuffers::LoadFile((proto_path + "twice-id.proto").c_str(), + false, &proto_file), + true); + TEST_EQ(parser.Parse(proto_file.c_str(), include_directories), true); + TEST_NE(fbs_generator->GenerateCode(parser, "temp.fbs", "test"), + CodeGenerator::Status::OK); + } + + // Parse proto with error on gap. + { + opts.proto_id_gap_action = IDLOptions::ProtoIdGapAction::ERROR; + flatbuffers::Parser parser(opts); + TEST_EQ(flatbuffers::LoadFile((proto_path + "test.proto").c_str(), false, + &proto_file), + true); + TEST_EQ(parser.Parse(proto_file.c_str(), include_directories), true); + + TEST_NE(fbs_generator->GenerateCode(parser, "temp.fbs", "test"), + CodeGenerator::Status::OK); + } +} + +// Parse a .proto schema, output as .fbs +void ParseProtoTest(const std::string &tests_data_path) { + auto proto_path = tests_data_path + "prototest/"; + std::string proto_file; + TEST_EQ( + flatbuffers::LoadFile((tests_data_path + "prototest/test.proto").c_str(), + false, &proto_file), + true); + + std::string import_proto_file; + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "prototest/imported.proto").c_str(), false, + &import_proto_file), + true); + + proto_test(proto_path, proto_file); + proto_test_union(proto_path, proto_file); + proto_test_union_suffix(proto_path, proto_file); + proto_test_include(proto_path, proto_file, import_proto_file); + proto_test_include_union(proto_path, proto_file, import_proto_file); + + proto_test_id(proto_path, proto_file); + proto_test_union_id(proto_path, proto_file); + proto_test_union_suffix_id(proto_path, proto_file); + proto_test_include_id(proto_path, proto_file, import_proto_file); + proto_test_include_union_id(proto_path, proto_file, import_proto_file); + + ParseCorruptedProto(proto_path); +} + +void ParseProtoBufAsciiTest() { + // We can put the parser in a mode where it will accept JSON that looks more + // like Protobuf ASCII, for users that have data in that format. + // This uses no "" for field names (which we already support by default, + // omits `,`, `:` before `{` and a couple of other features. + flatbuffers::Parser parser; + parser.opts.protobuf_ascii_alike = true; + TEST_EQ( + parser.Parse("table S { B:int; } table T { A:[int]; C:S; } root_type T;"), + true); + TEST_EQ(parser.Parse("{ A [1 2] C { B:2 }}"), true); + // Similarly, in text output, it should omit these. + std::string text; + auto err = + flatbuffers::GenText( + parser, parser.builder_.GetBufferPointer(), &text); + TEST_NULL(err); + TEST_EQ_STR(text.c_str(), + "{\n A [\n 1\n 2\n ]\n C {\n B: 2\n }\n}\n"); +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/proto_test.h b/third_party/flatbuffers/tests/proto_test.h new file mode 100644 index 00000000000..fd6b1113833 --- /dev/null +++ b/third_party/flatbuffers/tests/proto_test.h @@ -0,0 +1,32 @@ +#ifndef TESTS_PROTO_TEST_H +#define TESTS_PROTO_TEST_H + +#include "flatbuffers/idl.h" + +#include + +namespace flatbuffers { +namespace tests { + +void RunTest(const flatbuffers::IDLOptions &opts, const std::string &proto_path, const std::string &proto_file, + const std::string &golden_file, const std::string import_proto_file = {}); +void proto_test(const std::string &proto_path, const std::string &proto_file); +void proto_test_union(const std::string &proto_path, const std::string &proto_file); +void proto_test_union_suffix(const std::string &proto_path, const std::string &proto_file); +void proto_test_include(const std::string &proto_path, const std::string &proto_file, const std::string &import_proto_file); +void proto_test_include_union(const std::string &proto_path, const std::string &proto_file, const std::string &import_proto_file); + +void proto_test_id(const std::string &proto_path, const std::string &proto_file); +void proto_test_union_id(const std::string &proto_path, const std::string &proto_file); +void proto_test_union_suffix_id(const std::string &proto_path, const std::string &proto_file); +void proto_test_include_id(const std::string &proto_path, const std::string &proto_file, const std::string &import_proto_file); +void proto_test_include_union_id(const std::string &proto_path, const std::string &proto_file, const std::string &import_proto_file); + +void ParseCorruptedProto(const std::string &proto_path); +void ParseProtoTest(const std::string& tests_data_path); +void ParseProtoBufAsciiTest(); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/prototest/GenerateProtoGoldens.sh b/third_party/flatbuffers/tests/prototest/GenerateProtoGoldens.sh new file mode 100755 index 00000000000..4fc91bfebf5 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/GenerateProtoGoldens.sh @@ -0,0 +1,31 @@ +#!/bin/bash +# +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +pushd "$(dirname $0)" >/dev/null + +./../../flatc --proto test.proto && mv test.fbs test_include.golden.fbs +./../../flatc --proto --gen-all test.proto && mv test.fbs test.golden.fbs +./../../flatc --proto --oneof-union test.proto && mv test.fbs test_union_include.golden.fbs +./../../flatc --proto --gen-all --oneof-union test.proto && mv test.fbs test_union.golden.fbs +./../../flatc --proto --gen-all --proto-namespace-suffix test_namespace_suffix test.proto && mv test.fbs test_suffix.golden.fbs +./../../flatc --proto --gen-all --proto-namespace-suffix test_namespace_suffix --oneof-union test.proto && mv test.fbs test_union_suffix.golden.fbs + +./../../flatc --proto --keep-proto-id test.proto && mv test.fbs test_include_id.golden.fbs +./../../flatc --proto --keep-proto-id --gen-all test.proto && mv test.fbs test_id.golden.fbs +./../../flatc --proto --keep-proto-id --oneof-union test.proto && mv test.fbs test_union_include_id.golden.fbs +./../../flatc --proto --keep-proto-id --gen-all --oneof-union test.proto && mv test.fbs test_union_id.golden.fbs +./../../flatc --proto --keep-proto-id --gen-all --proto-namespace-suffix test_namespace_suffix test.proto && mv test.fbs test_suffix_id.golden.fbs +./../../flatc --proto --keep-proto-id --gen-all --proto-namespace-suffix test_namespace_suffix --oneof-union test.proto && mv test.fbs test_union_suffix_id.golden.fbs diff --git a/third_party/flatbuffers/tests/prototest/imported.proto b/third_party/flatbuffers/tests/prototest/imported.proto new file mode 100644 index 00000000000..5b43e4b3487 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/imported.proto @@ -0,0 +1,5 @@ +package proto.test; + +message ImportedMessage { + optional int32 a = 26; +} diff --git a/third_party/flatbuffers/tests/prototest/non-positive-id.proto b/third_party/flatbuffers/tests/prototest/non-positive-id.proto new file mode 100644 index 00000000000..a42b8afa055 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/non-positive-id.proto @@ -0,0 +1,9 @@ +// Sample .proto file that we can not translate to the corresponding .fbs because it has non-positive ids. + +option some_option = is_ignored; + +package proto.test; + +message ProtoMessage { + optional uint64 NonPositiveId = -1; +} diff --git a/third_party/flatbuffers/tests/prototest/test.golden.fbs b/third_party/flatbuffers/tests/prototest/test.golden.fbs new file mode 100644 index 00000000000..4484b498218 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test.golden.fbs @@ -0,0 +1,87 @@ +// Generated from test.proto + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test; + +table ImportedMessage { + a:int; +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.ImportedMessage; + /// doc comment for r. + r:proto.test.ProtoMessage_.Anonymous0; + outer_enum:proto.test.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.ImportedMessage; + /// doc comment for t on 2 + /// lines. + t:proto.test.ProtoMessage_.OtherMessage; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test.proto b/third_party/flatbuffers/tests/prototest/test.proto new file mode 100644 index 00000000000..c3f0157fe21 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test.proto @@ -0,0 +1,78 @@ +// Sample .proto file that we can translate to the corresponding .fbs. + +option some_option = is_ignored; +import "imported.proto"; + +package proto.test; + +/// Enum doc comment. +enum ProtoEnum { + option allow_alias = true; + NUL = 0; + FOO = 1; + /// Enum 2nd value doc comment misaligned. + BAR = 5; + // Aliases + FOO_A1 = 1; + BAR_A1 = 5; + FOO_A2 = 1; +} + +/// 2nd table doc comment with +/// many lines. +message ProtoMessage { + // Ignored non-doc comment. + // A nested message declaration, will be moved to top level in .fbs + message OtherMessage { + reserved 2, 9 to 11, 15; + optional double a = 26; + /// doc comment for b. + optional float b = 32 [default = 3.14149]; + + // Nested enum that aliases the outer one. + enum ProtoEnum { + NUL = 0; + FOO = 1; + BAR = 2; + BAZ = 3; + } + + optional ProtoEnum foo_bar_baz = 33; + } + optional int32 c = 12 [default = 16]; + optional int64 d = 1 [default = 0]; + optional uint32 p = 40; + optional uint64 e = 2; + /// doc comment for f. + optional sint32 f = 3 [default = -1]; + optional sint64 g = 4; + optional fixed32 h = 5; + optional fixed64 q = 6; + optional sfixed32 i = 7; + optional sfixed64 j = 8; + /// doc comment for k. + optional bool k = 9; + /// doc comment for l on 2 + /// lines + required string l = 10; + optional bytes m = 11; + optional OtherMessage n = 41; + repeated string o = 14; + optional ImportedMessage z = 16; + /// doc comment for r. + oneof r { + /// doc comment for s. + ImportedMessage s = 17; + /// doc comment for t on 2 + /// lines. + OtherMessage t = 18; + } + optional ProtoEnum outer_enum = 33; + // Tests that `inf` and `+/-inf` can be parsed in proto options. + optional float u = 34 [default = inf]; + optional float v = 35 [default = +inf]; + optional float w = 36 [default = -inf]; + + map grades = 37; + map other_message_map = 38; +} diff --git a/third_party/flatbuffers/tests/prototest/test_id.golden.fbs b/third_party/flatbuffers/tests/prototest/test_id.golden.fbs new file mode 100644 index 00000000000..39d51cf95f5 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_id.golden.fbs @@ -0,0 +1,87 @@ +// Generated from test.proto + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test; + +table ImportedMessage { + a:int (id: 0); +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16 (id: 12); + d:long (id: 1); + p:uint (id: 21); + e:ulong (id: 2); + /// doc comment for f. + f:int = -1 (id: 3); + g:long (id: 4); + h:uint (id: 5); + q:ulong (id: 6); + i:int (id: 7); + j:long (id: 8); + /// doc comment for k. + k:bool (id: 9); + /// doc comment for l on 2 + /// lines + l:string (required,id: 10); + m:[ubyte] (id: 11); + n:proto.test.ProtoMessage_.OtherMessage (id: 22); + o:[string] (id: 13); + z:proto.test.ImportedMessage (id: 14); + /// doc comment for r. + r:proto.test.ProtoMessage_.Anonymous0 (id: 0); + outer_enum:proto.test.ProtoEnum (id: 15); + u:float = +inf (id: 16); + v:float = +inf (id: 17); + w:float = -inf (id: 18); + grades:[proto.test.ProtoMessage_.GradesEntry] (id: 19); + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry] (id: 20); +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double (id: 0); + /// doc comment for b. + b:float = 3.14149 (id: 1); + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum (id: 2); +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.ImportedMessage (id: 0); + /// doc comment for t on 2 + /// lines. + t:proto.test.ProtoMessage_.OtherMessage (id: 1); +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_include.golden.fbs b/third_party/flatbuffers/tests/prototest/test_include.golden.fbs new file mode 100644 index 00000000000..791f7f7b5c0 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_include.golden.fbs @@ -0,0 +1,85 @@ +// Generated from test.proto + +include "imported.fbs"; + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test; + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.ImportedMessage; + /// doc comment for r. + r:proto.test.ProtoMessage_.Anonymous0; + outer_enum:proto.test.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.ImportedMessage; + /// doc comment for t on 2 + /// lines. + t:proto.test.ProtoMessage_.OtherMessage; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_include_id.golden.fbs b/third_party/flatbuffers/tests/prototest/test_include_id.golden.fbs new file mode 100644 index 00000000000..e7f875f5138 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_include_id.golden.fbs @@ -0,0 +1,85 @@ +// Generated from test.proto + +include "imported.fbs"; + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test; + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16 (id: 12); + d:long (id: 1); + p:uint (id: 21); + e:ulong (id: 2); + /// doc comment for f. + f:int = -1 (id: 3); + g:long (id: 4); + h:uint (id: 5); + q:ulong (id: 6); + i:int (id: 7); + j:long (id: 8); + /// doc comment for k. + k:bool (id: 9); + /// doc comment for l on 2 + /// lines + l:string (required,id: 10); + m:[ubyte] (id: 11); + n:proto.test.ProtoMessage_.OtherMessage (id: 22); + o:[string] (id: 13); + z:proto.test.ImportedMessage (id: 14); + /// doc comment for r. + r:proto.test.ProtoMessage_.Anonymous0 (id: 0); + outer_enum:proto.test.ProtoEnum (id: 15); + u:float = +inf (id: 16); + v:float = +inf (id: 17); + w:float = -inf (id: 18); + grades:[proto.test.ProtoMessage_.GradesEntry] (id: 19); + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry] (id: 20); +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double (id: 0); + /// doc comment for b. + b:float = 3.14149 (id: 1); + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum (id: 2); +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.ImportedMessage (id: 0); + /// doc comment for t on 2 + /// lines. + t:proto.test.ProtoMessage_.OtherMessage (id: 1); +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_suffix.golden.fbs b/third_party/flatbuffers/tests/prototest/test_suffix.golden.fbs new file mode 100644 index 00000000000..b76acb7fbc8 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_suffix.golden.fbs @@ -0,0 +1,87 @@ +// Generated from test.proto + +namespace proto.test.test_namespace_suffix; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.test_namespace_suffix; + +table ImportedMessage { + a:int; +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.test_namespace_suffix.ImportedMessage; + /// doc comment for r. + r:proto.test.test_namespace_suffix.ProtoMessage_.Anonymous0; + outer_enum:proto.test.test_namespace_suffix.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.test_namespace_suffix.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.test_namespace_suffix.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.test_namespace_suffix.ImportedMessage; + /// doc comment for t on 2 + /// lines. + t:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_suffix_id.golden.fbs b/third_party/flatbuffers/tests/prototest/test_suffix_id.golden.fbs new file mode 100644 index 00000000000..c07f42b887a --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_suffix_id.golden.fbs @@ -0,0 +1,87 @@ +// Generated from test.proto + +namespace proto.test.test_namespace_suffix; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.test_namespace_suffix; + +table ImportedMessage { + a:int (id: 0); +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16 (id: 12); + d:long (id: 1); + p:uint (id: 21); + e:ulong (id: 2); + /// doc comment for f. + f:int = -1 (id: 3); + g:long (id: 4); + h:uint (id: 5); + q:ulong (id: 6); + i:int (id: 7); + j:long (id: 8); + /// doc comment for k. + k:bool (id: 9); + /// doc comment for l on 2 + /// lines + l:string (required,id: 10); + m:[ubyte] (id: 11); + n:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage (id: 22); + o:[string] (id: 13); + z:proto.test.test_namespace_suffix.ImportedMessage (id: 14); + /// doc comment for r. + r:proto.test.test_namespace_suffix.ProtoMessage_.Anonymous0 (id: 0); + outer_enum:proto.test.test_namespace_suffix.ProtoEnum (id: 15); + u:float = +inf (id: 16); + v:float = +inf (id: 17); + w:float = -inf (id: 18); + grades:[proto.test.test_namespace_suffix.ProtoMessage_.GradesEntry] (id: 19); + other_message_map:[proto.test.test_namespace_suffix.ProtoMessage_.OtherMessageMapEntry] (id: 20); +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_; + +table OtherMessage { + a:double (id: 0); + /// doc comment for b. + b:float = 3.14149 (id: 1); + foo_bar_baz:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_.ProtoEnum (id: 2); +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.test_namespace_suffix.ImportedMessage (id: 0); + /// doc comment for t on 2 + /// lines. + t:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage (id: 1); +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_union.golden.fbs b/third_party/flatbuffers/tests/prototest/test_union.golden.fbs new file mode 100644 index 00000000000..15d365b54b7 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_union.golden.fbs @@ -0,0 +1,89 @@ +// Generated from test.proto + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.ProtoMessage_; + +union RUnion { + /// doc comment for s. + proto.test.ImportedMessage, + /// doc comment for t on 2 + /// lines. + proto.test.ProtoMessage_.OtherMessage, +} + +namespace proto.test; + +table ImportedMessage { + a:int; +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.ImportedMessage; + /// doc comment for r. + r:proto.test.ProtoMessage_.RUnion; + outer_enum:proto.test.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_union_id.golden.fbs b/third_party/flatbuffers/tests/prototest/test_union_id.golden.fbs new file mode 100644 index 00000000000..fed93609440 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_union_id.golden.fbs @@ -0,0 +1,89 @@ +// Generated from test.proto + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.ProtoMessage_; + +union RUnion { + /// doc comment for s. + proto.test.ImportedMessage, + /// doc comment for t on 2 + /// lines. + proto.test.ProtoMessage_.OtherMessage, +} + +namespace proto.test; + +table ImportedMessage { + a:int (id: 0); +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16 (id: 13); + d:long (id: 2); + p:uint (id: 22); + e:ulong (id: 3); + /// doc comment for f. + f:int = -1 (id: 4); + g:long (id: 5); + h:uint (id: 6); + q:ulong (id: 7); + i:int (id: 8); + j:long (id: 9); + /// doc comment for k. + k:bool (id: 10); + /// doc comment for l on 2 + /// lines + l:string (required,id: 11); + m:[ubyte] (id: 12); + n:proto.test.ProtoMessage_.OtherMessage (id: 23); + o:[string] (id: 14); + z:proto.test.ImportedMessage (id: 15); + /// doc comment for r. + r:proto.test.ProtoMessage_.RUnion (id: 1); + outer_enum:proto.test.ProtoEnum (id: 16); + u:float = +inf (id: 17); + v:float = +inf (id: 18); + w:float = -inf (id: 19); + grades:[proto.test.ProtoMessage_.GradesEntry] (id: 20); + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry] (id: 21); +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double (id: 0); + /// doc comment for b. + b:float = 3.14149 (id: 1); + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum (id: 2); +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_union_include.golden.fbs b/third_party/flatbuffers/tests/prototest/test_union_include.golden.fbs new file mode 100644 index 00000000000..ce36463567b --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_union_include.golden.fbs @@ -0,0 +1,87 @@ +// Generated from test.proto + +include "imported.fbs"; + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.ProtoMessage_; + +union RUnion { + /// doc comment for s. + proto.test.ImportedMessage, + /// doc comment for t on 2 + /// lines. + proto.test.ProtoMessage_.OtherMessage, +} + +namespace proto.test; + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.ImportedMessage; + /// doc comment for r. + r:proto.test.ProtoMessage_.RUnion; + outer_enum:proto.test.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_union_include_id.golden.fbs b/third_party/flatbuffers/tests/prototest/test_union_include_id.golden.fbs new file mode 100644 index 00000000000..ceb785d24b0 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_union_include_id.golden.fbs @@ -0,0 +1,87 @@ +// Generated from test.proto + +include "imported.fbs"; + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.ProtoMessage_; + +union RUnion { + /// doc comment for s. + proto.test.ImportedMessage, + /// doc comment for t on 2 + /// lines. + proto.test.ProtoMessage_.OtherMessage, +} + +namespace proto.test; + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16 (id: 13); + d:long (id: 2); + p:uint (id: 22); + e:ulong (id: 3); + /// doc comment for f. + f:int = -1 (id: 4); + g:long (id: 5); + h:uint (id: 6); + q:ulong (id: 7); + i:int (id: 8); + j:long (id: 9); + /// doc comment for k. + k:bool (id: 10); + /// doc comment for l on 2 + /// lines + l:string (required,id: 11); + m:[ubyte] (id: 12); + n:proto.test.ProtoMessage_.OtherMessage (id: 23); + o:[string] (id: 14); + z:proto.test.ImportedMessage (id: 15); + /// doc comment for r. + r:proto.test.ProtoMessage_.RUnion (id: 1); + outer_enum:proto.test.ProtoEnum (id: 16); + u:float = +inf (id: 17); + v:float = +inf (id: 18); + w:float = -inf (id: 19); + grades:[proto.test.ProtoMessage_.GradesEntry] (id: 20); + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry] (id: 21); +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double (id: 0); + /// doc comment for b. + b:float = 3.14149 (id: 1); + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum (id: 2); +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_union_suffix.golden.fbs b/third_party/flatbuffers/tests/prototest/test_union_suffix.golden.fbs new file mode 100644 index 00000000000..0c0c5e586c3 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_union_suffix.golden.fbs @@ -0,0 +1,89 @@ +// Generated from test.proto + +namespace proto.test.test_namespace_suffix; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_; + +union RUnion { + /// doc comment for s. + proto.test.test_namespace_suffix.ImportedMessage, + /// doc comment for t on 2 + /// lines. + proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage, +} + +namespace proto.test.test_namespace_suffix; + +table ImportedMessage { + a:int; +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.test_namespace_suffix.ImportedMessage; + /// doc comment for r. + r:proto.test.test_namespace_suffix.ProtoMessage_.RUnion; + outer_enum:proto.test.test_namespace_suffix.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.test_namespace_suffix.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.test_namespace_suffix.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/test_union_suffix_id.golden.fbs b/third_party/flatbuffers/tests/prototest/test_union_suffix_id.golden.fbs new file mode 100644 index 00000000000..adbb4b34f66 --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/test_union_suffix_id.golden.fbs @@ -0,0 +1,89 @@ +// Generated from test.proto + +namespace proto.test.test_namespace_suffix; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_; + +union RUnion { + /// doc comment for s. + proto.test.test_namespace_suffix.ImportedMessage, + /// doc comment for t on 2 + /// lines. + proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage, +} + +namespace proto.test.test_namespace_suffix; + +table ImportedMessage { + a:int (id: 0); +} + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16 (id: 13); + d:long (id: 2); + p:uint (id: 22); + e:ulong (id: 3); + /// doc comment for f. + f:int = -1 (id: 4); + g:long (id: 5); + h:uint (id: 6); + q:ulong (id: 7); + i:int (id: 8); + j:long (id: 9); + /// doc comment for k. + k:bool (id: 10); + /// doc comment for l on 2 + /// lines + l:string (required,id: 11); + m:[ubyte] (id: 12); + n:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage (id: 23); + o:[string] (id: 14); + z:proto.test.test_namespace_suffix.ImportedMessage (id: 15); + /// doc comment for r. + r:proto.test.test_namespace_suffix.ProtoMessage_.RUnion (id: 1); + outer_enum:proto.test.test_namespace_suffix.ProtoEnum (id: 16); + u:float = +inf (id: 17); + v:float = +inf (id: 18); + w:float = -inf (id: 19); + grades:[proto.test.test_namespace_suffix.ProtoMessage_.GradesEntry] (id: 20); + other_message_map:[proto.test.test_namespace_suffix.ProtoMessage_.OtherMessageMapEntry] (id: 21); +} + +namespace proto.test.test_namespace_suffix.ProtoMessage_; + +table OtherMessage { + a:double (id: 0); + /// doc comment for b. + b:float = 3.14149 (id: 1); + foo_bar_baz:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage_.ProtoEnum (id: 2); +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.test_namespace_suffix.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/prototest/twice-id.proto b/third_party/flatbuffers/tests/prototest/twice-id.proto new file mode 100644 index 00000000000..aac4bd49eee --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/twice-id.proto @@ -0,0 +1,10 @@ +// Sample .proto file that we can not translate to the corresponding .fbs because it has used an id twice + +option some_option = is_ignored; + +package proto.test; + +message ProtoMessage { + optional sint32 e = 2; + optional uint64 twice = 2; +} diff --git a/third_party/flatbuffers/tests/prototest/use-reserved-id.proto b/third_party/flatbuffers/tests/prototest/use-reserved-id.proto new file mode 100644 index 00000000000..fd0ce2a3bfe --- /dev/null +++ b/third_party/flatbuffers/tests/prototest/use-reserved-id.proto @@ -0,0 +1,10 @@ +// Sample .proto file that we can not translate to the corresponding .fbs because it has used ids from reserved ids. + +option some_option = is_ignored; + +package proto.test; + +message ProtoMessage { + reserved 200, 9 to 11, 1500; + optional sint32 reserved_id_usage = 10; +} diff --git a/third_party/flatbuffers/tests/py_flexbuffers_test.py b/third_party/flatbuffers/tests/py_flexbuffers_test.py new file mode 100644 index 00000000000..fcd17faaa37 --- /dev/null +++ b/third_party/flatbuffers/tests/py_flexbuffers_test.py @@ -0,0 +1,1523 @@ +# Lint as: python3 +# Copyright 2020 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +"""Unit tests for flexbuffers.py.""" + +import array +import os.path +import struct +import unittest + +from flatbuffers import flexbuffers + +Type = flexbuffers.Type + +LOG2 = {1: 0, 2: 1, 4: 2, 8: 3} + +GOLD_FLEXBUFFER_OBJ = { + 'bar': [1, 2, 3], + 'bar3': [1, 2, 3], + 'bool': True, + 'bools': [True, False, True, False], + 'foo': 100.0, + 'mymap': {'foo': 'Fred'}, + 'vec': [-100, 'Fred', 4.0, b'M', False, 4.0] +} + +GOLD_FLEXBUFFER_FILE = 'gold_flexbuffer_example.bin' + + +def read_test_file(name): + with open(os.path.join(os.path.dirname(__file__), name), 'rb') as f: + return f.read() + + +def packed_type(type_, i): + return (type_ << 2) | LOG2[i] + + +def uint_size(value): + """Returns number of bytes (power of two) to represent unsigned value.""" + assert value >= 0 + + n = 8 + while not value < (1 << n): + n *= 2 + return n // 8 + + +def int_size(value): + """Returns number of bytes (power of two) to represent signed value.""" + n = 8 + while not -(1 << (n - 1)) <= value < (1 << (n - 1)): + n *= 2 + return n // 8 + + +def uint_sizes(value): + return tuple(1 << i for i in range(LOG2[uint_size(value)], 4)) + + +def int_sizes(value): + return tuple(1 << i for i in range(LOG2[int_size(value)], 4)) + + +def int_bytes(value, byte_width): + return struct.pack('<%s' % {1: 'b', 2: 'h', 4: 'i', 8: 'q'}[byte_width], value) + + +def uint_bytes(value, byte_width): + return struct.pack('<%s' % {1: 'B', 2: 'H', 4: 'I', 8: 'Q'}[byte_width], value) + + +def float_bytes(value, byte_width): + return struct.pack('<%s' % {4: 'f', 8: 'd'}[byte_width], value) + + +def min_value(type_, byte_width): + assert byte_width > 0 + + if type_ in (Type.INT, Type.INDIRECT_INT): + return -(1 << (8 * byte_width - 1)) + elif type_ in (Type.UINT, Type.INDIRECT_UINT): + return 0 + else: + raise ValueError('Unsupported type %s' % type_) + + +def max_value(type_, byte_width): + assert byte_width > 0 + + if type_ in (Type.INT, Type.INDIRECT_INT): + return (1 << (8 * byte_width - 1)) - 1 + elif type_ in (Type.UINT, Type.INDIRECT_UINT): + return (1 << 8 * byte_width) - 1 + else: + raise ValueError('Unsupported type %s' % type_) + + +def str_bytes(value, byte_width): + value_bytes = value.encode('utf-8') + return [*uint_bytes(len(value_bytes), byte_width), *value_bytes, 0] + + +def key_bytes(value): + return [*value.encode('ascii'), 0] + + +def encode_type(type_, value, byte_width=None): + fbb = flexbuffers.Builder() + add = fbb.Adder(type_) + if byte_width: + add(value, byte_width) + else: + add(value) + return fbb.Finish() + + +INT_MIN_MAX_VALUES = (min_value(Type.INT, 1), max_value(Type.INT, 1), + min_value(Type.INT, 2), max_value(Type.INT, 2), + min_value(Type.INT, 4), max_value(Type.INT, 4), + min_value(Type.INT, 8), max_value(Type.INT, 8)) + +UINT_MIN_MAX_VALUES = (0, max_value(Type.UINT, 1), max_value(Type.UINT, 2), + max_value(Type.UINT, 4), max_value(Type.UINT, 8)) + + +class UtilTest(unittest.TestCase): + """Tests to check FlexBuffer utility functions.""" + + def _test_type_predicate(self, pred, types): + for type_ in types: + with self.subTest(type=type_, pred=pred): + self.assertTrue(pred(type_)) + + for type_ in set(Type).difference(types): + with self.subTest(type=type_, pred=pred): + self.assertFalse(pred(type_)) + + def test_inline_types(self): + self._test_type_predicate( + Type.IsInline, (Type.NULL, Type.INT, Type.UINT, Type.FLOAT, Type.BOOL)) + + def test_typed_vector(self): + self._test_type_predicate( + Type.IsTypedVector, + (Type.VECTOR_INT, Type.VECTOR_UINT, Type.VECTOR_FLOAT, Type.VECTOR_KEY, + Type.VECTOR_STRING_DEPRECATED, Type.VECTOR_BOOL)) + + self._test_type_predicate( + Type.IsTypedVectorElementType, + (Type.INT, Type.UINT, Type.FLOAT, Type.KEY, Type.STRING, Type.BOOL)) + + with self.assertRaises(ValueError): + Type.ToTypedVectorElementType(Type.VECTOR) + self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_INT), Type.INT) + self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_UINT), Type.UINT) + self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_FLOAT), Type.FLOAT) + self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_KEY), Type.KEY) + self.assertIs( + Type.ToTypedVectorElementType(Type.VECTOR_STRING_DEPRECATED), + Type.STRING) + self.assertIs(Type.ToTypedVectorElementType(Type.VECTOR_BOOL), Type.BOOL) + + with self.assertRaises(ValueError): + Type.ToTypedVector(Type.VECTOR) + self.assertIs(Type.ToTypedVector(Type.INT), Type.VECTOR_INT) + self.assertIs(Type.ToTypedVector(Type.UINT), Type.VECTOR_UINT) + self.assertIs(Type.ToTypedVector(Type.FLOAT), Type.VECTOR_FLOAT) + self.assertIs(Type.ToTypedVector(Type.KEY), Type.VECTOR_KEY) + self.assertIs( + Type.ToTypedVector(Type.STRING), Type.VECTOR_STRING_DEPRECATED) + self.assertIs(Type.ToTypedVector(Type.BOOL), Type.VECTOR_BOOL) + + def test_fixed_typed_vector(self): + self._test_type_predicate( + Type.IsFixedTypedVector, + (Type.VECTOR_INT2, Type.VECTOR_UINT2, Type.VECTOR_FLOAT2, + Type.VECTOR_INT3, Type.VECTOR_UINT3, Type.VECTOR_FLOAT3, + Type.VECTOR_INT4, Type.VECTOR_UINT4, Type.VECTOR_FLOAT4)) + + self._test_type_predicate(Type.IsFixedTypedVectorElementType, + (Type.INT, Type.UINT, Type.FLOAT)) + + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_INT2), (Type.INT, 2)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_UINT2), (Type.UINT, 2)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_FLOAT2), (Type.FLOAT, 2)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_INT3), (Type.INT, 3)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_UINT3), (Type.UINT, 3)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_FLOAT3), (Type.FLOAT, 3)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_INT4), (Type.INT, 4)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_UINT4), (Type.UINT, 4)) + self.assertEqual( + Type.ToFixedTypedVectorElementType(Type.VECTOR_FLOAT4), (Type.FLOAT, 4)) + + # Invalid size + for type_ in Type.INT, Type.UINT, Type.FLOAT: + with self.assertRaises(ValueError): + Type.ToTypedVector(type_, 1) + with self.assertRaises(ValueError): + Type.ToTypedVector(type_, 5) + + # Invalid element type + for length in 1, 2, 3, 4, 5: + with self.assertRaises(ValueError): + Type.ToTypedVector(Type.STRING, length) + + self.assertIs(Type.ToTypedVector(Type.INT, 2), Type.VECTOR_INT2) + self.assertIs(Type.ToTypedVector(Type.INT, 3), Type.VECTOR_INT3) + self.assertIs(Type.ToTypedVector(Type.INT, 4), Type.VECTOR_INT4) + + self.assertIs(Type.ToTypedVector(Type.UINT, 2), Type.VECTOR_UINT2) + self.assertIs(Type.ToTypedVector(Type.UINT, 3), Type.VECTOR_UINT3) + self.assertIs(Type.ToTypedVector(Type.UINT, 4), Type.VECTOR_UINT4) + + self.assertIs(Type.ToTypedVector(Type.FLOAT, 2), Type.VECTOR_FLOAT2) + self.assertIs(Type.ToTypedVector(Type.FLOAT, 3), Type.VECTOR_FLOAT3) + self.assertIs(Type.ToTypedVector(Type.FLOAT, 4), Type.VECTOR_FLOAT4) + + def test_width(self): + for x in range(1 << 10): + self.assertEqual(flexbuffers.BitWidth.U(x), LOG2[uint_size(x)]) + + for x in range(-(1 << 10), 1 << 10): + self.assertEqual(flexbuffers.BitWidth.I(x), LOG2[int_size(x)]) + + def test_padding(self): + self.assertEqual(flexbuffers._PaddingBytes(0, 4), 0) + self.assertEqual(flexbuffers._PaddingBytes(0, 8), 0) + self.assertEqual(flexbuffers._PaddingBytes(0, 16), 0) + + self.assertEqual(flexbuffers._PaddingBytes(1, 8), 7) + self.assertEqual(flexbuffers._PaddingBytes(17, 8), 7) + + self.assertEqual(flexbuffers._PaddingBytes(42, 2), 0) + + +class DecoderTest(unittest.TestCase): + """Tests to check FlexBuffer decoding functions. + + Common variable names used in the tests for compactness: + bw: byte_width + ebw: element_byte_width + kbw: key_byte_width + vbw: value_byte_width + tbw: type_byte_width + + Having '_ignored' suffix means that variable doesn't affect the constructed + byte buffer size. + """ + + def test_null(self): + for bw in 1, 2, 4, 8: + for ebw_ignored in 1, 2, 4, 8: + with self.subTest(bw=bw, ebw_ignored=ebw_ignored): + data = bytes([ + *uint_bytes(0, bw), + packed_type(Type.NULL, ebw_ignored), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsNull) + self.assertEqual(root.AsBool, False) + self.assertEqual(root.AsInt, 0) + self.assertEqual(root.AsFloat, 0.0) + + for prop in (type(root).AsKey, type(root).AsString, type(root).AsBlob, + type(root).AsVector, type(root).AsTypedVector, + type(root).AsFixedTypedVector, type(root).AsMap): + with self.assertRaises(TypeError): + prop.fget(root) + + self.assertEqual(root.Value, None) + + self.assertIsNone(flexbuffers.Loads(data)) + + def test_bool(self): + for value in False, True: + for bw in 1, 2, 4, 8: + for ebw_ignored in 1, 2, 4, 8: + with self.subTest(bw=bw, ebw_ignored=ebw_ignored): + data = bytes([ + *uint_bytes(int(value), bw), + packed_type(Type.BOOL, ebw_ignored), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsBool) + self.assertEqual(root.AsBool, value) + self.assertEqual(root.AsInt, int(value)) + self.assertEqual(root.AsFloat, float(value)) + + for prop in (type(root).AsKey, type(root).AsString, + type(root).AsBlob, + type(root).AsVector, type(root).AsTypedVector, + type(root).AsFixedTypedVector, type(root).AsMap): + with self.assertRaises(TypeError): + prop.fget(root) + + self.assertEqual(root.Value, value) + + self.assertEqual(flexbuffers.Loads(data), value) + + def test_mutate_bool(self): + root = flexbuffers.GetRoot(flexbuffers.Dumps(True)) + self.assertTrue(root.IsBool) + self.assertTrue(root.AsBool) + + self.assertTrue(root.MutateBool(False)) + self.assertTrue(root.IsBool) + self.assertFalse(root.AsBool) + + self.assertTrue(root.MutateBool(True)) + self.assertTrue(root.IsBool) + self.assertTrue(root.AsBool) + + def _check_int(self, data, value): + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsInt) + self.assertEqual(root.AsInt, value) + self.assertEqual(root.AsBool, bool(value)) + self.assertEqual(root.AsFloat, float(value)) + + for prop in (type(root).AsKey, type(root).AsString, type(root).AsBlob, + type(root).AsVector, type(root).AsTypedVector, + type(root).AsFixedTypedVector, type(root).AsMap): + with self.assertRaises(TypeError): + prop.fget(root) + + self.assertEqual(root.Value, value) + + self.assertEqual(flexbuffers.Loads(data), value) + + def test_int(self): + for value in (0, 1, -1, 15, -17, *INT_MIN_MAX_VALUES): + for bw in int_sizes(value): + for ebw_ignored in 1, 2, 4, 8: + with self.subTest(value=value, bw=bw, ebw_ignored=ebw_ignored): + data = bytes([ + *int_bytes(value, bw), + packed_type(Type.INT, ebw_ignored), + bw, + ]) + + self._check_int(data, value) + + def test_indirect_int(self): + for value in (0, 1, -1, 15, -17, *INT_MIN_MAX_VALUES): + for bw in 1, 2, 4, 8: + for ebw in int_sizes(value): + with self.subTest(value=value, bw=bw, ebw=ebw): + data = bytes([ + # Int + *int_bytes(value, ebw), + # Root + *uint_bytes(ebw, bw), + packed_type(Type.INDIRECT_INT, ebw), + bw, + ]) + self._check_int(data, value) + + def test_uint(self): + for value in (1, *UINT_MIN_MAX_VALUES): + for bw in uint_sizes(value): + for ebw_ignored in 1, 2, 4, 8: + with self.subTest(value=value, bw=bw, ebw_ignored=ebw_ignored): + data = bytes([ + *uint_bytes(value, bw), + packed_type(Type.UINT, ebw_ignored), + bw, + ]) + + self._check_int(data, value) + + def test_inidirect_uint(self): + for value in (1, *UINT_MIN_MAX_VALUES): + for bw in 1, 2, 4, 8: + for ebw in uint_sizes(value): + with self.subTest(value=value, bw=bw, ebw=ebw): + data = bytes([ + # UInt + *uint_bytes(value, ebw), + # Root + *uint_bytes(ebw, bw), + packed_type(Type.INDIRECT_UINT, ebw), + bw, + ]) + + self._check_int(data, value) + + def test_mutate_ints(self): + # Signed + for type_ in Type.INT, Type.INDIRECT_INT: + with self.subTest(type=type_): + root = flexbuffers.GetRoot(encode_type(type_, 56)) + self.assertEqual(root.AsInt, 56) + + for new_value in 0, 1, -1, -128, 127: + self.assertTrue(root.MutateInt(new_value)) + self.assertEqual(root.AsInt, new_value) + + for new_value in -129, 128: + self.assertFalse(root.MutateInt(new_value)) + + # Unsigned + for type_ in Type.UINT, Type.INDIRECT_UINT: + with self.subTest(type=type_): + root = flexbuffers.GetRoot(encode_type(type_, 1)) + self.assertEqual(root.AsInt, 1) + + for new_value in 0, 1, 255: + self.assertTrue(root.MutateInt(new_value)) + self.assertEqual(root.AsInt, new_value) + + self.assertFalse(root.MutateInt(256)) + + # Inside vector + fbb = flexbuffers.Builder() + fbb.VectorFromElements([13, 0, -15]) + data = fbb.Finish() + + self.assertEqual(flexbuffers.Loads(data), [13, 0, -15]) + self.assertTrue(flexbuffers.GetRoot(data).AsVector[0].MutateInt(0)) + self.assertTrue(flexbuffers.GetRoot(data).AsVector[1].MutateInt(-7)) + self.assertTrue(flexbuffers.GetRoot(data).AsVector[2].MutateInt(45)) + self.assertEqual(flexbuffers.Loads(data), [0, -7, 45]) + + # Inside map + fbb = flexbuffers.Builder() + fbb.MapFromElements({'x': -7, 'y': 46}) + data = fbb.Finish() + + self.assertEqual(flexbuffers.Loads(data), {'x': -7, 'y': 46}) + self.assertTrue(flexbuffers.GetRoot(data).AsMap['x'].MutateInt(14)) + self.assertTrue(flexbuffers.GetRoot(data).AsMap['y'].MutateInt(-1)) + self.assertEqual(flexbuffers.Loads(data), {'x': 14, 'y': -1}) + + def _check_float(self, data, value): + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsFloat) + self.assertAlmostEqual(root.AsFloat, value) + + for prop in (type(root).AsKey, type(root).AsString, type(root).AsBlob, + type(root).AsVector, type(root).AsTypedVector, + type(root).AsFixedTypedVector, type(root).AsMap): + with self.assertRaises(TypeError): + prop.fget(root) + + self.assertAlmostEqual(root.Value, value) + + self.assertAlmostEqual(flexbuffers.Loads(data), value) + + def test_float(self): + for value in -1.0, 0.0, 1.0, 3.141592, 1.5e6: + for bw in 4, 8: + for ebw_ignored in 1, 2, 4, 8: + with self.subTest(value=value, bw=bw, ebw_ignored=ebw_ignored): + data = bytes([ + *float_bytes(value, bw), + packed_type(Type.FLOAT, ebw_ignored), + bw, + ]) + + self._check_float(data, value) + + def test_indirect_float(self): + for value in -1.0, 0.0, 1.0, 3.141592, 1.5e6: + for bw in 1, 2, 4, 8: + for ebw in 4, 8: + with self.subTest(value=value, bw=bw, ebw=ebw): + data = bytes([ + # Float + *float_bytes(value, ebw), + # Root + *uint_bytes(ebw, bw), + packed_type(Type.INDIRECT_FLOAT, ebw), + bw, + ]) + + self._check_float(data, value) + + def test_mutate_float(self): + for type_ in Type.FLOAT, Type.INDIRECT_FLOAT: + for bw in 4, 8: + value = 3.141592 + root = flexbuffers.GetRoot(encode_type(type_, value, bw)) + self.assertAlmostEqual(root.AsFloat, value) + + value = 2.71828 + self.assertTrue(root.MutateFloat(value)) + self.assertAlmostEqual(root.AsFloat, value, places=5) + + # Inside vector + data = flexbuffers.Dumps([2.4, 1.5, -7.2]) + + self.assertTrue(flexbuffers.GetRoot(data).AsVector[0].MutateFloat(0.0)) + self.assertTrue(flexbuffers.GetRoot(data).AsVector[1].MutateFloat(15.2)) + self.assertTrue(flexbuffers.GetRoot(data).AsVector[2].MutateFloat(-5.1)) + + for a, b in zip(flexbuffers.Loads(data), [0.0, 15.2, -5.1]): + self.assertAlmostEqual(a, b) + + def test_string(self): + for value in 'red', 'green', 'blue', 'flatbuffers + flexbuffers': + value_bytes = value.encode('utf-8') + for bw in 1, 2, 4, 8: + for lbw in 1, 2, 4, 8: + with self.subTest(bw=bw, lbw=lbw): + data = bytes([ + # String + *uint_bytes(len(value_bytes), lbw), + *value_bytes, + 0, + # Root + *uint_bytes(len(value_bytes) + 1, bw), # offset + packed_type(Type.STRING, lbw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsString) + self.assertEqual(root.AsString, value) + self.assertEqual(root.Value, value) + self.assertEqual(root.AsInt, len(value)) + + self.assertEqual(flexbuffers.Loads(data), value) + + def test_mutate_string(self): + data = encode_type(Type.STRING, '12345') + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsString) + self.assertEqual(root.AsString, '12345') + + self.assertFalse(root.MutateString('543210')) + + self.assertTrue(root.MutateString('54321')) + self.assertTrue(root.IsString) + self.assertEqual(root.AsString, '54321') + + self.assertTrue(root.MutateString('543')) + self.assertTrue(root.IsString) + self.assertEqual(root.AsString, '543') + + self.assertFalse(root.MutateString('54321')) + + def test_empty_blob(self): + for bw in 1, 2, 4, 8: + for lbw in 1, 2, 4, 8: + with self.subTest(bw=bw, lbw=lbw): + data = bytes([ + # Blob + *uint_bytes(0, lbw), + # Root + *uint_bytes(0, bw), + packed_type(Type.BLOB, lbw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsBlob) + self.assertEqual(root.AsBlob, bytes()) + self.assertEqual(root.Value, bytes()) + self.assertEqual(flexbuffers.Loads(data), bytes()) + + def test_blob(self): + for blob in [], [215], [23, 75, 124, 0, 45, 15], 255 * [0]: + for bw in 1, 2, 4, 8: + for lbw in 1, 2, 4, 8: + with self.subTest(blob=blob, bw=bw, lbw=lbw): + data = bytes([ + # Blob + *uint_bytes(len(blob), lbw), + *blob, + # Root + *uint_bytes(len(blob), bw), + packed_type(Type.BLOB, lbw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsBlob) + self.assertEqual(root.AsBlob, bytes(blob)) + self.assertEqual(root.Value, bytes(blob)) + self.assertEqual(flexbuffers.Loads(data), bytes(blob)) + + def test_key(self): + for value in '', 'x', 'color': + for bw in 1, 2, 4, 8: + with self.subTest(value=value, bw=bw): + value_bytes = value.encode('ascii') + data = bytes([ + # Key + *value_bytes, + 0, + # Root + *uint_bytes(len(value_bytes) + 1, bw), + packed_type(Type.KEY, 1), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsKey) + self.assertEqual(root.AsKey, value) + self.assertEqual(root.Value, value) + self.assertEqual(flexbuffers.Loads(data), value) + + def _check_fixed_typed_vector(self, data, vector, type_): + self.assertEqual(flexbuffers.Loads(data), vector) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsFixedTypedVector) + + v = root.AsFixedTypedVector + self.assertEqual(len(v), len(vector)) + self.assertIs(v.ElementType, type_) + self.assertEqual([e.Value for e in v], vector) + self.assertSequenceEqual(v.Value, vector) + + self.assertEqual(root.AsInt, len(vector)) + + def test_fixed_typed_vector_float(self): + for type_, vector in ((Type.VECTOR_FLOAT2, [-75.0, 34.89]), + (Type.VECTOR_FLOAT3, [-75.0, 34.89, 12.0]), + (Type.VECTOR_FLOAT4, [-75.0, 34.89, -1.0, 1.0])): + for bw in 1, 2, 4, 8: + for ebw in 4, 8: + with self.subTest(type=type_, vector=vector, bw=bw, ebw=ebw): + data = bytes([ + # FixedTypedVector + *b''.join(float_bytes(e, ebw) for e in vector), + # Root + *uint_bytes(len(vector) * ebw, bw), + packed_type(type_, ebw), + bw, + ]) + + for a, b in zip(flexbuffers.Loads(data), vector): + self.assertAlmostEqual(a, b, places=2) + + def test_fixed_typed_vector_int(self): + for type_, vector in ((Type.VECTOR_INT2, [0, -13]), (Type.VECTOR_INT3, + [127, 0, -13]), + (Type.VECTOR_INT4, [127, 0, -13, 0])): + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + with self.subTest(type=type_, vector=vector, bw=bw, ebw=ebw): + data = bytes([ + # FixedTypeVector + *b''.join(int_bytes(e, ebw) for e in vector), + # Root + *uint_bytes(ebw * len(vector), bw), + packed_type(type_, ebw), + bw, + ]) + + self._check_fixed_typed_vector(data, vector, Type.INT) + + def test_fixed_typed_vector_uint(self): + for type_, vector in ((Type.VECTOR_UINT2, [0, 13]), + (Type.VECTOR_UINT3, [127, 0, 13]), (Type.VECTOR_UINT4, + [127, 0, 13, 0])): + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + with self.subTest(type=type_, vector=vector, bw=bw, ebw=ebw): + data = bytes([ + # FixedTypeVector + *b''.join(uint_bytes(e, ebw) for e in vector), + # Root + *uint_bytes(ebw * len(vector), bw), + packed_type(type_, ebw), + bw, + ]) + + self._check_fixed_typed_vector(data, vector, Type.UINT) + + def _check_typed_vector(self, data, vector, type_): + self.assertEqual(flexbuffers.Loads(data), vector) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsTypedVector) + + v = root.AsTypedVector + self.assertIs(v.ElementType, type_) + self.assertEqual(len(v), len(vector)) + self.assertEqual([e.Value for e in v], vector) + self.assertSequenceEqual(v.Value, vector) + + self.assertEqual(root.AsInt, len(vector)) + + def test_empty_typed_vector(self): + for type_ in (Type.VECTOR_BOOL, Type.VECTOR_INT, Type.VECTOR_UINT, + Type.VECTOR_FLOAT, Type.VECTOR_KEY, + Type.VECTOR_STRING_DEPRECATED): + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + with self.subTest(type=type_, bw=bw, ebw=ebw): + data = bytes([ + # TypedVector[type_] + *uint_bytes(0, ebw), + # Root + *uint_bytes(0, bw), + packed_type(type_, ebw), + bw + ]) + + element_type = Type.ToTypedVectorElementType(type_) + if element_type == Type.STRING: + element_type = Type.KEY + self._check_typed_vector(data, [], element_type) + + def test_typed_vector_bool(self): + vector = [True, False, False, False, True] + + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + with self.subTest(bw=bw, ebw=ebw): + data = bytes([ + # TypedVector[Type.BOOL] + *uint_bytes(len(vector), ebw), + *b''.join(uint_bytes(int(e), ebw) for e in vector), + # Root + *uint_bytes(len(vector) * ebw, bw), + packed_type(Type.VECTOR_BOOL, ebw), + bw, + ]) + self._check_typed_vector(data, vector, Type.BOOL) + + def test_typed_vector_int(self): + vector = [-100, 200, -300] + + for bw in 1, 2, 4, 8: + for ebw in 2, 4, 8: + with self.subTest(bw=bw, ebw=ebw): + data = bytes([ + # TypedVector[Type.INT] + *uint_bytes(len(vector), ebw), + *b''.join(int_bytes(e, ebw) for e in vector), + # Root + *uint_bytes(len(vector) * ebw, bw), + packed_type(Type.VECTOR_INT, ebw), + bw, + ]) + self._check_typed_vector(data, vector, Type.INT) + + def test_typed_vector_uint(self): + vector = [100, 200, 300, 400, 0] + + for bw in 1, 2, 4, 8: + for ebw in 2, 4, 8: + with self.subTest(bw=bw, ebw=ebw): + data = bytes([ + # TypedVector[Type.UINT] + *uint_bytes(len(vector), ebw), + *b''.join(int_bytes(e, ebw) for e in vector), + # Root + *uint_bytes(len(vector) * ebw, bw), + packed_type(Type.VECTOR_UINT, ebw), + bw, + ]) + self._check_typed_vector(data, vector, Type.UINT) + + def test_typed_vector_float(self): + vector = [3.64, -6.36, 3.14, 634.0, -42.0] + + for bw in 1, 2, 4, 8: + for ebw in 4, 8: + with self.subTest(bw=bw, ebw=ebw): + data = bytes([ + # TypedVector[Type.FLOAT] + *uint_bytes(len(vector), ebw), + *b''.join(float_bytes(e, ebw) for e in vector), + # Root + *uint_bytes(ebw * len(vector), bw), + packed_type(Type.VECTOR_FLOAT, ebw), + bw, + ]) + + for a, b in zip(flexbuffers.Loads(data), vector): + self.assertAlmostEqual(a, b, places=2) + + def test_typed_vector_key(self): + vector = ['red', 'green', 'blue'] + + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + with self.subTest(bw=bw, ebw=ebw): + data = bytes([ + # Keys + *key_bytes(vector[0]), + *key_bytes(vector[1]), + *key_bytes(vector[2]), + # TypedVector[Type.KEY] + *uint_bytes(len(vector), ebw), + *uint_bytes(15 + 1 * ebw, ebw), # offset to vector[0] + *uint_bytes(11 + 2 * ebw, ebw), # offset to vector[1] + *uint_bytes(5 + 3 * ebw, ebw), # offset to vector[2] + # Root + *uint_bytes(len(vector) * ebw, bw), # offset to vector + packed_type(Type.VECTOR_KEY, ebw), + bw, + ]) + self._check_typed_vector(data, vector, Type.KEY) + + def test_typed_vector_string(self): + vector = ['red', 'green', 'blue'] + + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + with self.subTest(bw=bw, ebw=ebw): + data = bytes([ + # Strings + *str_bytes(vector[0], 1), # 5 bytes + *str_bytes(vector[1], 1), # 7 bytes + *str_bytes(vector[2], 1), # 6 bytes + # TypedVector[Type.STRING] + *uint_bytes(len(vector), ebw), + *uint_bytes(17 + 1 * ebw, ebw), # offset to vector[0] + *uint_bytes(12 + 2 * ebw, ebw), # offset to vector[1] + *uint_bytes(5 + 3 * ebw, ebw), # offset to vector[2] + # Root + *uint_bytes(len(vector) * ebw, bw), # offset to vector + packed_type(Type.VECTOR_STRING_DEPRECATED, ebw), + bw, + ]) + + # We have to pass Type.KEY because of Type.VECTOR_STRING_DEPRECATED. + self._check_typed_vector(data, vector, Type.KEY) + + def test_typed_vector_string_deprecated(self): + # Check FlexBuffersDeprecatedTest() inside test.cpp for details. + vector = [300 * 'A', 'test'] + + fbb = flexbuffers.Builder() + with fbb.TypedVector(): + for e in vector: + fbb.String(e) + data = fbb.Finish() + + # We have to pass Type.KEY because of Type.VECTOR_STRING_DEPRECATED. + self._check_typed_vector(data, vector, Type.KEY) + + def test_typed_vector_invalid(self): + fbb = flexbuffers.Builder() + + with self.assertRaises(RuntimeError): + fbb.TypedVectorFromElements(['string', 423]) + + def test_empty_vector(self): + for bw in 1, 2, 4, 8: + for ebw in 1, 2, 4, 8: + data = bytes([ + *uint_bytes(0, ebw), + # Root + *uint_bytes(0, bw), + packed_type(Type.VECTOR, ebw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsVector) + self.assertEqual(len(root.AsVector), 0) + + self.assertEqual(flexbuffers.Loads(data), []) + + def test_vector1(self): + vector = [300, 400, 500] + + for bw in 1, 2, 4, 8: + for ebw in 2, 4, 8: + for tbw_ignored in 1, 2, 4, 8: + with self.subTest(bw=bw, ebw=ebw, ignore=tbw_ignored): + data = bytes([ + # Vector length + *uint_bytes(len(vector), ebw), + # Vector elements + *int_bytes(vector[0], ebw), + *int_bytes(vector[1], ebw), + *int_bytes(vector[2], ebw), + # Vector types + packed_type(Type.INT, tbw_ignored), + packed_type(Type.INT, tbw_ignored), + packed_type(Type.INT, tbw_ignored), + # Root + *uint_bytes(ebw * len(vector) + len(vector), bw), + packed_type(Type.VECTOR, ebw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsVector) + self.assertFalse(root.IsMap) + + v = root.AsVector + self.assertEqual(len(v), len(vector)) + + for i in range(len(v)): + self.assertTrue(v[i].IsInt) + self.assertEqual(v[i].AsInt, vector[i]) + + for i, e in enumerate(v): + self.assertTrue(e.IsInt) + self.assertEqual(e.AsInt, vector[i]) + + with self.assertRaises(IndexError): + v[-1].AsInt # pylint: disable=pointless-statement + + with self.assertRaises(IndexError): + v[3].AsInt # pylint: disable=pointless-statement + + with self.assertRaises(TypeError): + root.AsMap # pylint: disable=pointless-statement + + self.assertEqual(root.AsInt, len(vector)) + self.assertEqual(root.AsFloat, float(len(vector))) + + self.assertEqual(flexbuffers.Loads(data), vector) + + def test_vector2(self): + vector = [1984, 'August', True] + + for bw in 1, 2, 4, 8: + with self.subTest(bw=bw): + data = bytes([ + *str_bytes(vector[1], 1), + # Vector + *uint_bytes(len(vector), 2), + *int_bytes(vector[0], 2), + *uint_bytes(11, 2), # offset to 'August' + *uint_bytes(int(vector[2]), 2), + packed_type(Type.INT, 2), + packed_type(Type.STRING, 1), + packed_type(Type.BOOL, 2), + # Root + *uint_bytes(2 * len(vector) + len(vector), bw), # offset to vector + packed_type(Type.VECTOR, 2), + bw, + ]) + self.assertEqual(flexbuffers.Loads(data), vector) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsVector) + + v = root.AsVector + self.assertTrue(v[0].IsInt) + self.assertEqual(v[0].AsInt, 1984) + + self.assertTrue(v[1].IsString) + self.assertEqual(v[1].AsString, 'August') + + self.assertTrue(v[2].IsBool) + self.assertTrue(v[2].AsBool) + + self.assertEqual(v.Value, vector) + + self.assertEqual(root.AsInt, len(vector)) + + def test_empty_map(self): + for bw in 1, 2, 4, 8: + for kbw in 1, 2, 4, 8: + for vbw in 1, 2, 4, 8: + data = bytes([ + *uint_bytes(0, kbw), # Keys length + *uint_bytes(0, vbw), + *uint_bytes(kbw, vbw), + *uint_bytes(0, vbw), # Values length + # Root + *uint_bytes(0, bw), + packed_type(Type.MAP, vbw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsMap) + self.assertEqual(len(root.AsMap), 0) + + self.assertEqual(flexbuffers.Loads(data), {}) + + def test_map(self): + value = {'foo': 13, 'bar': 14} + + for bw in 1, 2, 4, 8: + for kbw in 1, 2, 4, 8: + for vbw in 1, 2, 4, 8: + with self.subTest(kbw=kbw, vbw=vbw, bw=bw): + data = bytes([ + *key_bytes('foo'), # 4 bytes + *key_bytes('bar'), # 4 bytes + # Map + *uint_bytes(len(value), kbw), + *uint_bytes(4 + 1 * kbw, kbw), # offset to 'bar' + *uint_bytes(8 + 2 * kbw, kbw), # offset to 'foo' + *uint_bytes(len(value) * kbw, vbw), # offset to keys + *uint_bytes(kbw, vbw), + *uint_bytes(len(value), vbw), + *int_bytes(value['bar'], vbw), + *int_bytes(value['foo'], vbw), + packed_type(Type.INT, vbw), + packed_type(Type.INT, vbw), + # Root + *uint_bytes(vbw * len(value) + len(value), + bw), # offset to values + packed_type(Type.MAP, vbw), + bw, + ]) + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsMap) + + m = root.AsMap + self.assertEqual(len(m), 2) + self.assertEqual(m[0].AsInt, 14) + self.assertEqual(m[1].AsInt, 13) + + self.assertEqual(m['bar'].AsInt, 14) + self.assertEqual(m['foo'].AsInt, 13) + + for invalid_key in 'a', 'b', 'no': + with self.assertRaises(KeyError): + m[invalid_key] # pylint: disable=pointless-statement + + values = m.Values + self.assertEqual(len(values), 2) + self.assertEqual(values[0].AsInt, 14) + self.assertEqual(values[1].AsInt, 13) + + keys = m.Keys + self.assertEqual(len(keys), 2) + self.assertEqual(len(keys[0].AsKey), 3) + self.assertEqual(keys[0].AsKey, 'bar') + self.assertEqual(len(keys[1].AsKey), 3) + self.assertEqual(keys[1].AsKey, 'foo') + + keys = [key.AsKey for key in keys] + self.assertEqual(sorted(keys), keys) + + self.assertEqual(root.AsInt, len(value)) + + self.assertEqual(flexbuffers.Loads(data), value) + + def test_alignment(self): + value = ['test', 7] + + data = bytes([ + *key_bytes('test'), # 5 bytes: 'test' and \0 + 0, + 0, + 0, # 3 bytes: alignment + # Vector + *uint_bytes(len(value), byte_width=8), + *uint_bytes(16, byte_width=8), + *uint_bytes(7, byte_width=8), + packed_type(Type.KEY, 1), + packed_type(Type.INT, 8), + # Root + *uint_bytes(8 * len(value) + len(value), 1), + packed_type(Type.VECTOR, 8), + 1, + ]) + + self.assertEqual(flexbuffers.Loads(data), value) + + +class EncoderTest(unittest.TestCase): + """Tests to check FlexBuffer encoding functions.""" + + def test_null(self): + def encode_null(): + fbb = flexbuffers.Builder() + fbb.Null() + return fbb.Finish() + + self.assertIsNone(flexbuffers.Loads(encode_null())) + + def test_bool(self): + for value in False, True: + data = encode_type(Type.BOOL, value) + self.assertEqual(flexbuffers.Loads(data), value) + + def test_int(self): + for byte_width in 1, 2, 4, 8: + for type_ in Type.INT, Type.INDIRECT_INT, Type.UINT, Type.INDIRECT_UINT: + with self.subTest(byte_width=byte_width, type=type_): + value = min_value(type_, byte_width) + data = encode_type(type_, value) + self.assertEqual(flexbuffers.Loads(data), value) + + value = max_value(type_, byte_width) + data = encode_type(type_, value) + self.assertEqual(flexbuffers.Loads(data), value) + + def test_float(self): + for value in 3.141592, 7.62, 999.99: + for type_ in Type.FLOAT, Type.INDIRECT_FLOAT: + with self.subTest(value=value, type=type_): + data = encode_type(type_, value) + self.assertEqual(flexbuffers.Loads(data), value) + + data = encode_type(type_, value, 4) + self.assertAlmostEqual(flexbuffers.Loads(data), value, places=4) + + data = encode_type(type_, value, 8) + self.assertEqual(flexbuffers.Loads(data), value) + + def test_string(self): + for value in '', 'x', 'color', 'hello world': + with self.subTest(value=value): + data = encode_type(Type.STRING, value) + self.assertEqual(flexbuffers.Loads(data), value) + + def test_blob(self): + for value in bytes(), bytes([240, 12, 143, 7]), bytes(1000 * [17]): + with self.subTest(value=value): + data = encode_type(Type.BLOB, value) + self.assertEqual(flexbuffers.Loads(data), value) + + def test_key(self): + for value in '', 'color', 'hello world': + with self.subTest(value=value): + data = encode_type(Type.KEY, value) + self.assertEqual(flexbuffers.Loads(data), value) + + with self.assertRaises(ValueError): + encode_type(Type.KEY, (b'\x00' * 10).decode('ascii')) + + def test_vector(self): + + def encode_vector(elements, element_type): + fbb = flexbuffers.Builder() + with fbb.Vector(): + add = fbb.Adder(element_type) + for e in elements: + add(e) + return fbb.Finish() + + def encode_vector_from_elements(elements): + fbb = flexbuffers.Builder() + fbb.VectorFromElements(elements) + return fbb.Finish() + + for elements in [], [1435], [56, 23, 0, 6783]: + data = encode_vector(elements, Type.INT) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_vector_from_elements(elements) + self.assertEqual(flexbuffers.Loads(data), elements) + + # Elements of different type: one by one + elements = [56.0, 'flexbuffers', 0, False, 75123] + + fbb = flexbuffers.Builder() + with fbb.Vector(): + fbb.Float(elements[0]) + fbb.String(elements[1]) + fbb.UInt(elements[2], 8) + fbb.Bool(elements[3]) + fbb.Int(elements[4]) + data = fbb.Finish() + self.assertEqual(flexbuffers.Loads(data), elements) + + # Elements of different type: all at once + fbb = flexbuffers.Builder() + fbb.VectorFromElements(elements) + data = fbb.Finish() + self.assertEqual(flexbuffers.Loads(data), elements) + + def test_nested_vectors(self): + fbb = flexbuffers.Builder() + with fbb.Vector(): + fbb.String('begin') + fbb.IndirectInt(42) + with fbb.Vector(): + for i in range(5): + fbb.Int(i) + fbb.String('end') + data = fbb.Finish() + + self.assertEqual( + flexbuffers.Loads(data), ['begin', 42, [0, 1, 2, 3, 4], 'end']) + + def test_big_vector(self): + n = 10 * 1000 + fbb = flexbuffers.Builder() + with fbb.Vector(): + for i in range(n): + fbb.Int(i) + self.assertEqual(flexbuffers.Loads(fbb.Finish()), list(range(n))) + + def test_typed_vector(self): + + def encode_typed_vector_from_elements(elements, element_type=None): + fbb = flexbuffers.Builder() + fbb.TypedVectorFromElements(elements, element_type) + return fbb.Finish() + + for elements in [], [False], [True], [False, True, True, False, False]: + data = encode_typed_vector_from_elements(elements, Type.BOOL) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_typed_vector_from_elements(elements) + self.assertEqual(flexbuffers.Loads(data), elements) + + for elements in [], [23455], [351, -2, 0, 6783, 0, -10]: + data = encode_typed_vector_from_elements(elements, Type.INT) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_typed_vector_from_elements(elements) + self.assertEqual(flexbuffers.Loads(data), elements) + + for elements in [], [23455], [351, 2, 0, 6783, 0, 10]: + data = encode_typed_vector_from_elements(elements) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_typed_vector_from_elements(elements, Type.INT) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_typed_vector_from_elements(elements, Type.UINT) + self.assertEqual(flexbuffers.Loads(data), elements) + + for elements in [], [7.0], [52.0, 51.2, 70.0, -4.0]: + data = encode_typed_vector_from_elements(elements, Type.FLOAT) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_typed_vector_from_elements(elements) + self.assertEqual(flexbuffers.Loads(data), elements) + + for elements in [], ['color'], ['x', 'y']: + data = encode_typed_vector_from_elements(elements, Type.KEY) + self.assertEqual(flexbuffers.Loads(data), elements) + + data = encode_typed_vector_from_elements(elements) + self.assertEqual(flexbuffers.Loads(data), elements) + + def test_typed_vector_from_array(self): + + def encode_array(typecode, values): + fbb = flexbuffers.Builder() + fbb.VectorFromElements(array.array(typecode, values)) + return fbb.Finish() + + values = [1.0, 3.14, -2.54, 0.0] + data = encode_array('f', values) + for a, b in zip(flexbuffers.Loads(data), values): + self.assertAlmostEqual(a, b, places=2) + + values = [1.0, 3.14, -2.54, 0.0] + data = encode_array('d', values) + self.assertEqual(flexbuffers.Loads(data), values) + + values = [1, -7, 9, 26, 12] + data = encode_array('i', values) + self.assertEqual(flexbuffers.Loads(data), values) + + values = [0, 1, 2, 3, 4, 5, 6] + data = encode_array('I', values) + self.assertEqual(flexbuffers.Loads(data), values) + + def test_fixed_typed_vector(self): + + def encode_fixed_typed_vector(elements, element_type=None): + fbb = flexbuffers.Builder() + fbb.FixedTypedVectorFromElements(elements, element_type) + return fbb.Finish() + + for elements in ((-2, 2), (1, 2, 3), (100, -100, 200, -200), (4.0, 7.0), + (0.0, 1.0, 8.0), (9.0, 7.0, 1.0, 5.5)): + with self.subTest(elements=elements): + data = encode_fixed_typed_vector(elements) + self.assertSequenceEqual(flexbuffers.Loads(data), elements) + + elements = [-170, 432, 0, -7] + data = encode_fixed_typed_vector(elements, Type.INT) + self.assertSequenceEqual(flexbuffers.Loads(data), elements) + + with self.assertRaises(ValueError): + encode_fixed_typed_vector([]) # Invalid input length + + with self.assertRaises(ValueError): + encode_fixed_typed_vector([1]) # Invalid input length + + with self.assertRaises(ValueError): + encode_fixed_typed_vector([1, 2, 3, 4, 5]) # Invalid input length + + with self.assertRaises(TypeError): + encode_fixed_typed_vector([1, 1.0]) # Invalid input types + + with self.assertRaises(TypeError): + encode_fixed_typed_vector(['', '']) # Invalid input types + + def test_map_builder(self): + + def get_keys(data): + return [key.AsKey for key in flexbuffers.GetRoot(data).AsMap.Keys] + + # Empty map + fbb = flexbuffers.Builder() + with fbb.Map(): + pass + data = fbb.Finish() + + self.assertEqual(flexbuffers.Loads(data), {}) + + # Two-element map of Int + fbb = flexbuffers.Builder() + with fbb.Map(): + fbb.Int('y', -2) + fbb.Int('x', 10) + data = fbb.Finish() + + self.assertEqual(flexbuffers.Loads(data), {'x': 10, 'y': -2}) + + # Multiple-element map of vectors + fbb = flexbuffers.Builder() + with fbb.Map(): + with fbb.Vector('v'): + fbb.Int(45) + with fbb.TypedVector('tv'): + fbb.Int(-7) + fbb.FixedTypedVectorFromElements('ftv', [-2.0, 1.0]) + data = fbb.Finish() + + self.assertEqual( + flexbuffers.Loads(data), { + 'v': [45], + 'tv': [-7], + 'ftv': [-2.0, 1.0] + }) + + keys = get_keys(data) + self.assertEqual(sorted(keys), keys) + + # Multiple-element map of different types + fbb = flexbuffers.Builder() + with fbb.Map(): + fbb.Null('n') + fbb.Bool('b', False) + fbb.Int('i', -27) + fbb.UInt('u', 27) + fbb.Float('f', -0.85) + fbb.String('s', 'String') + fbb.Blob('bb', b'data') + fbb.IndirectInt('ii', -9500) + fbb.IndirectUInt('iu', 540) + fbb.IndirectFloat('if', 0.0) + fbb.VectorFromElements('v', [2, 1, 0.0]) + fbb.TypedVectorFromElements('tv', [2, 1, 0]) + fbb.FixedTypedVectorFromElements('ftv', [2.0, -6.0]) + data = fbb.Finish() + + self.assertEqual( + flexbuffers.Loads(data), { + 'n': None, + 'b': False, + 'i': -27, + 'u': 27, + 'f': -0.85, + 's': 'String', + 'bb': b'data', + 'ii': -9500, + 'iu': 540, + 'if': 0.0, + 'v': [2, 1, 0.0], + 'tv': [2, 1, 0], + 'ftv': [2.0, -6.0] + }) + + keys = get_keys(data) + self.assertEqual(sorted(keys), keys) + + def test_map_python(self): + maps = [ + {}, + { + 'key': 'value' + }, + { + 'x': None, + 'y': 3400, + 'z': -7040 + }, + { + 'zzz': 100, + 'aaa': 5.0, + 'ccc': ['Test', 32, False, None, True] + }, + { + 'name': ['John', 'Smith'], + 'valid': True, + 'note': None, + 'address': { + 'lines': [175, 'Alhambra'], + 'city': 'San Francisco', + 'zip': 94123, + }, + }, + ] + + for m in maps: + self.assertEqual(flexbuffers.Loads(flexbuffers.Dumps(m)), m) + + def test_gold_from_file(self): + data = read_test_file(GOLD_FLEXBUFFER_FILE) + self.assertEqual(flexbuffers.Loads(data), GOLD_FLEXBUFFER_OBJ) + + def test_gold_from_builder(self): + fbb = flexbuffers.Builder() + with fbb.Map(): + with fbb.Vector('vec'): + fbb.Int(-100) + fbb.String('Fred') + fbb.IndirectFloat(4.0) + i_f = fbb.LastValue + fbb.Blob(bytes([77])) + fbb.Bool(False) + fbb.ReuseValue(i_f) + + vec = [1, 2, 3] + fbb.VectorFromElements('bar', vec) + fbb.FixedTypedVectorFromElements('bar3', [1, 2, 3]) + fbb.VectorFromElements('bools', [True, False, True, False]) + fbb.Bool('bool', True) + fbb.Float('foo', 100) + with fbb.Map('mymap'): + fbb.String('foo', 'Fred') + data = fbb.Finish() + + self.assertEqual(flexbuffers.Loads(data), GOLD_FLEXBUFFER_OBJ) + + def test_min_bit_width(self): + fbb = flexbuffers.Builder(force_min_bit_width=flexbuffers.BitWidth.W8) + fbb.TypedVectorFromElements([0, 1, 0, 1, 0]) + data = fbb.Finish() + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsTypedVector) + self.assertEqual(root.AsTypedVector.ByteWidth, 1) + + fbb = flexbuffers.Builder(force_min_bit_width=flexbuffers.BitWidth.W32) + fbb.TypedVectorFromElements([0, 1, 0, 1, 0]) + data = fbb.Finish() + + root = flexbuffers.GetRoot(data) + self.assertTrue(root.IsTypedVector) + self.assertEqual(root.AsTypedVector.ByteWidth, 4) + + def test_share_keys(self): + + def encode_key_vector(value, count, share_keys): + fbb = flexbuffers.Builder(share_keys=share_keys) + with fbb.Vector(): + for _ in range(count): + fbb.Key(value) + return fbb.Finish(), fbb.KeyPool.Elements + + data, pool = encode_key_vector('test', 10, share_keys=False) + self.assertEqual(len(pool), 0) + self.assertEqual(len(data), 74) + self.assertEqual(flexbuffers.Loads(data), 10 * ['test']) + + data, pool = encode_key_vector('test', 10, share_keys=True) + self.assertEqual(len(pool), 1) + self.assertEqual(pool[0], 'test'.encode('ascii')) + self.assertEqual(len(data), 29) + self.assertEqual(flexbuffers.Loads(data), 10 * ['test']) + + def test_share_strings(self): + + def encode_string_vector(value, count, share_strings): + fbb = flexbuffers.Builder(share_strings=share_strings) + with fbb.Vector(): + for _ in range(count): + fbb.String(value) + return fbb.Finish(), fbb.StringPool.Elements + + data, pool = encode_string_vector('test', 10, share_strings=False) + self.assertEqual(len(pool), 0) + self.assertEqual(len(data), 84) + self.assertEqual(flexbuffers.Loads(data), 10 * ['test']) + + data, pool = encode_string_vector('test', 10, share_strings=True) + self.assertEqual(len(pool), 1) + self.assertEqual(pool[0], 'test'.encode('utf-8')) + self.assertEqual(len(data), 30) + self.assertEqual(flexbuffers.Loads(data), 10 * ['test']) + + def test_invalid_stack_size(self): + fbb = flexbuffers.Builder() + + with self.assertRaises(RuntimeError): + fbb.Finish() + + fbb.Int(100) + fbb.Int(200) + with self.assertRaises(RuntimeError): + fbb.Finish() + + fbb.Clear() + fbb.Int(420) + fbb.Finish() + + +if __name__ == '__main__': + unittest.main() diff --git a/third_party/flatbuffers/tests/py_test.py b/third_party/flatbuffers/tests/py_test.py new file mode 100644 index 00000000000..7d6c0a37966 --- /dev/null +++ b/third_party/flatbuffers/tests/py_test.py @@ -0,0 +1,3044 @@ +# coding=utf-8 +# Copyright 2014 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import os.path +import sys +PY_VERSION = sys.version_info[:2] + +import ctypes +from collections import defaultdict +import math +import random +import timeit +import unittest + +from flatbuffers import compat +from flatbuffers import util +from flatbuffers.compat import range_func as compat_range +from flatbuffers.compat import NumpyRequiredForThisFeature + +import flatbuffers +from flatbuffers import number_types as N + +import MyGame # refers to generated code +import MyGame.Example # refers to generated code +import MyGame.Example.Any # refers to generated code +import MyGame.Example.Color # refers to generated code +import MyGame.Example.Monster # refers to generated code +import MyGame.Example.Test # refers to generated code +import MyGame.Example.Stat # refers to generated code +import MyGame.Example.Vec3 # refers to generated code +import MyGame.MonsterExtra # refers to generated code +import MyGame.InParentNamespace # refers to generated code +import MyGame.Example.ArrayTable # refers to generated code +import MyGame.Example.ArrayStruct # refers to generated code +import MyGame.Example.NestedStruct # refers to generated code +import MyGame.Example.TestEnum # refers to generated code +import MyGame.Example.NestedUnion.NestedUnionTest # refers to generated code +import MyGame.Example.NestedUnion.Vec3 # refers to generated code +import MyGame.Example.NestedUnion.Any # refers to generated code +import MyGame.Example.NestedUnion.Test # refers to generated code +import MyGame.Example.NestedUnion.Color # refers to generated code +import monster_test_generated # the one-file version +import optional_scalars +import optional_scalars.ScalarStuff + + +def create_namespace_shortcut(is_onefile): + # Create shortcut from either the one-file format or the multi-file format + global _ANY + global _COLOR + global _MONSTER + global _TEST + global _STAT + global _VEC3 + global _IN_PARENT_NAMESPACE + if is_onefile: + print('Testing with the one-file generated code') + _ANY = monster_test_generated + _COLOR = monster_test_generated + _MONSTER = monster_test_generated + _TEST = monster_test_generated + _STAT = monster_test_generated + _VEC3 = monster_test_generated + _IN_PARENT_NAMESPACE = monster_test_generated + else: + print('Testing with multi-file generated code') + _ANY = MyGame.Example.Any + _COLOR = MyGame.Example.Color + _MONSTER = MyGame.Example.Monster + _TEST = MyGame.Example.Test + _STAT = MyGame.Example.Stat + _VEC3 = MyGame.Example.Vec3 + _IN_PARENT_NAMESPACE = MyGame.InParentNamespace + + +def assertRaises(test_case, fn, exception_class): + """ Backwards-compatible assertion for exceptions raised. """ + + exc = None + try: + fn() + except Exception as e: + exc = e + test_case.assertTrue(exc is not None) + test_case.assertTrue(isinstance(exc, exception_class)) + + +class TestWireFormat(unittest.TestCase): + + def test_wire_format(self): + # Verify that using the generated Python code builds a buffer without + # returning errors, and is interpreted correctly, for size prefixed + # representation and regular: + for sizePrefix in [True, False]: + for file_identifier in [None, b'MONS']: + gen_buf, gen_off = make_monster_from_generated_code( + sizePrefix=sizePrefix, file_identifier=file_identifier) + CheckReadBuffer( + gen_buf, + gen_off, + sizePrefix=sizePrefix, + file_identifier=file_identifier) + + # Verify that the canonical flatbuffer file is readable by the + # generated Python code. Note that context managers are not part of + # Python 2.5, so we use the simpler open/close methods here: + f = open('monsterdata_test.mon', 'rb') + canonicalWireData = f.read() + f.close() + CheckReadBuffer(bytearray(canonicalWireData), 0, file_identifier=b'MONS') + + # Write the generated buffer out to a file: + f = open('monsterdata_python_wire.mon', 'wb') + f.write(gen_buf[gen_off:]) + f.close() + + +class TestObjectBasedAPI(unittest.TestCase): + """ Tests the generated object based API.""" + + def test_consistency_with_repeated_pack_and_unpack(self): + """ Checks the serialization and deserialization between a buffer and + + its python object. It tests in the same way as the C++ object API test, + ObjectFlatBuffersTest in test.cpp. + """ + + buf, off = make_monster_from_generated_code() + + # Turns a buffer into Python object (T class). + monster1 = _MONSTER.Monster.GetRootAs(buf, off) + monsterT1 = _MONSTER.MonsterT.InitFromObj(monster1) + + for sizePrefix in [True, False]: + # Re-serialize the data into a buffer. + b1 = flatbuffers.Builder(0) + if sizePrefix: + b1.FinishSizePrefixed(monsterT1.Pack(b1)) + else: + b1.Finish(monsterT1.Pack(b1)) + CheckReadBuffer(b1.Bytes, b1.Head(), sizePrefix) + + # Deserializes the buffer into Python object again. + monster2 = _MONSTER.Monster.GetRootAs(b1.Bytes, b1.Head()) + # Re-serializes the data into a buffer for one more time. + monsterT2 = _MONSTER.MonsterT.InitFromObj(monster2) + for sizePrefix in [True, False]: + # Re-serializes the data into a buffer + b2 = flatbuffers.Builder(0) + if sizePrefix: + b2.FinishSizePrefixed(monsterT2.Pack(b2)) + else: + b2.Finish(monsterT2.Pack(b2)) + CheckReadBuffer(b2.Bytes, b2.Head(), sizePrefix) + + def test_default_values_with_pack_and_unpack(self): + """ Serializes and deserializes between a buffer with default values (no + + specific values are filled when the buffer is created) and its python + object. + """ + # Creates a flatbuffer with default values. + b1 = flatbuffers.Builder(0) + _MONSTER.MonsterStart(b1) + gen_mon = _MONSTER.MonsterEnd(b1) + b1.Finish(gen_mon) + + # Converts the flatbuffer into the object class. + monster1 = _MONSTER.Monster.GetRootAs(b1.Bytes, b1.Head()) + monsterT1 = _MONSTER.MonsterT.InitFromObj(monster1) + + # Packs the object class into another flatbuffer. + b2 = flatbuffers.Builder(0) + b2.Finish(monsterT1.Pack(b2)) + monster2 = _MONSTER.Monster.GetRootAs(b2.Bytes, b2.Head()) + # Checks the default values. + self.assertTrue(monster2.Pos() is None) + self.assertEqual(monster2.Mana(), 150) + self.assertEqual(monster2.Hp(), 100) + self.assertTrue(monster2.Name() is None) + self.assertEqual(monster2.Inventory(0), 0) + self.assertEqual(monster2.InventoryAsNumpy(), 0) + self.assertEqual(monster2.InventoryLength(), 0) + self.assertTrue(monster2.InventoryIsNone()) + self.assertEqual(monster2.Color(), 8) + self.assertEqual(monster2.TestType(), 0) + self.assertTrue(monster2.Test() is None) + self.assertTrue(monster2.Test4(0) is None) + self.assertEqual(monster2.Test4Length(), 0) + self.assertTrue(monster2.Test4IsNone()) + self.assertEqual(monster2.Testarrayofstring(0), '') + self.assertEqual(monster2.TestarrayofstringLength(), 0) + self.assertTrue(monster2.TestarrayofstringIsNone()) + self.assertTrue(monster2.Testarrayoftables(0) is None) + self.assertEqual(monster2.TestarrayoftablesLength(), 0) + self.assertTrue(monster2.TestarrayoftablesIsNone()) + self.assertTrue(monster2.Enemy() is None) + self.assertEqual(monster2.Testnestedflatbuffer(0), 0) + self.assertEqual(monster2.TestnestedflatbufferAsNumpy(), 0) + self.assertEqual(monster2.TestnestedflatbufferLength(), 0) + self.assertTrue(monster2.TestnestedflatbufferIsNone()) + self.assertTrue(monster2.Testempty() is None) + self.assertFalse(monster2.Testbool()) + self.assertEqual(monster2.Testhashs32Fnv1(), 0) + self.assertEqual(monster2.Testhashu32Fnv1(), 0) + self.assertEqual(monster2.Testhashs64Fnv1(), 0) + self.assertEqual(monster2.Testhashu64Fnv1(), 0) + self.assertEqual(monster2.Testhashs32Fnv1a(), 0) + self.assertEqual(monster2.Testhashu32Fnv1a(), 0) + self.assertEqual(monster2.Testhashs64Fnv1a(), 0) + self.assertEqual(monster2.Testhashu64Fnv1a(), 0) + self.assertEqual(monster2.Testarrayofbools(0), 0) + self.assertEqual(monster2.TestarrayofboolsAsNumpy(), 0) + self.assertEqual(monster2.TestarrayofboolsLength(), 0) + self.assertTrue(monster2.TestarrayofboolsIsNone()) + self.assertEqual(monster2.Testf(), 3.14159) + self.assertEqual(monster2.Testf2(), 3.0) + self.assertEqual(monster2.Testf3(), 0.0) + self.assertEqual(monster2.Testarrayofstring2(0), '') + self.assertEqual(monster2.Testarrayofstring2Length(), 0) + self.assertTrue(monster2.Testarrayofstring2IsNone()) + self.assertTrue(monster2.Testarrayofsortedstruct(0) is None) + self.assertEqual(monster2.TestarrayofsortedstructLength(), 0) + self.assertTrue(monster2.TestarrayofsortedstructIsNone()) + self.assertEqual(monster2.Flex(0), 0) + self.assertEqual(monster2.FlexAsNumpy(), 0) + self.assertEqual(monster2.FlexLength(), 0) + self.assertTrue(monster2.FlexIsNone()) + self.assertTrue(monster2.Test5(0) is None) + self.assertEqual(monster2.Test5Length(), 0) + self.assertTrue(monster2.Test5IsNone()) + self.assertEqual(monster2.VectorOfLongs(0), 0) + self.assertEqual(monster2.VectorOfLongsAsNumpy(), 0) + self.assertEqual(monster2.VectorOfLongsLength(), 0) + self.assertTrue(monster2.VectorOfLongsIsNone()) + self.assertEqual(monster2.VectorOfDoubles(0), 0) + self.assertEqual(monster2.VectorOfDoublesAsNumpy(), 0) + self.assertEqual(monster2.VectorOfDoublesLength(), 0) + self.assertTrue(monster2.VectorOfDoublesIsNone()) + self.assertTrue(monster2.ParentNamespaceTest() is None) + self.assertTrue(monster2.VectorOfReferrables(0) is None) + self.assertEqual(monster2.VectorOfReferrablesLength(), 0) + self.assertTrue(monster2.VectorOfReferrablesIsNone()) + self.assertEqual(monster2.SingleWeakReference(), 0) + self.assertEqual(monster2.VectorOfWeakReferences(0), 0) + self.assertEqual(monster2.VectorOfWeakReferencesAsNumpy(), 0) + self.assertEqual(monster2.VectorOfWeakReferencesLength(), 0) + self.assertTrue(monster2.VectorOfWeakReferencesIsNone()) + self.assertTrue(monster2.VectorOfStrongReferrables(0) is None) + self.assertEqual(monster2.VectorOfStrongReferrablesLength(), 0) + self.assertTrue(monster2.VectorOfStrongReferrablesIsNone()) + self.assertEqual(monster2.CoOwningReference(), 0) + self.assertEqual(monster2.VectorOfCoOwningReferences(0), 0) + self.assertEqual(monster2.VectorOfCoOwningReferencesAsNumpy(), 0) + self.assertEqual(monster2.VectorOfCoOwningReferencesLength(), 0) + self.assertTrue(monster2.VectorOfCoOwningReferencesIsNone()) + self.assertEqual(monster2.NonOwningReference(), 0) + self.assertEqual(monster2.VectorOfNonOwningReferences(0), 0) + self.assertEqual(monster2.VectorOfNonOwningReferencesAsNumpy(), 0) + self.assertEqual(monster2.VectorOfNonOwningReferencesLength(), 0) + self.assertTrue(monster2.VectorOfNonOwningReferencesIsNone()) + self.assertEqual(monster2.AnyUniqueType(), 0) + self.assertTrue(monster2.AnyUnique() is None) + self.assertEqual(monster2.AnyAmbiguousType(), 0) + self.assertTrue(monster2.AnyAmbiguous() is None) + self.assertEqual(monster2.VectorOfEnums(0), 0) + self.assertEqual(monster2.VectorOfEnumsAsNumpy(), 0) + self.assertEqual(monster2.VectorOfEnumsLength(), 0) + self.assertTrue(monster2.VectorOfEnumsIsNone()) + + def test_optional_scalars_with_pack_and_unpack(self): + """ Serializes and deserializes between a buffer with optional values (no + specific values are filled when the buffer is created) and its python + object. + """ + # Creates a flatbuffer with optional values. + b1 = flatbuffers.Builder(0) + optional_scalars.ScalarStuff.ScalarStuffStart(b1) + gen_opt = optional_scalars.ScalarStuff.ScalarStuffEnd(b1) + b1.Finish(gen_opt) + + # Converts the flatbuffer into the object class. + opts1 = optional_scalars.ScalarStuff.ScalarStuff.GetRootAs(b1.Bytes, b1.Head()) + optsT1 = optional_scalars.ScalarStuff.ScalarStuffT.InitFromObj(opts1) + + # Packs the object class into another flatbuffer. + b2 = flatbuffers.Builder(0) + b2.Finish(optsT1.Pack(b2)) + opts2 = optional_scalars.ScalarStuff.ScalarStuff.GetRootAs(b2.Bytes, b2.Head()) + optsT2 = optional_scalars.ScalarStuff.ScalarStuffT.InitFromObj(opts2) + # Checks the default values. + self.assertTrue(opts2.JustI8() == 0) + self.assertTrue(opts2.MaybeF32() is None) + self.assertTrue(opts2.DefaultBool() is True) + self.assertTrue(optsT2.justU16 == 0) + self.assertTrue(optsT2.maybeEnum is None) + self.assertTrue(optsT2.defaultU64 == 42) + + + +class TestAllMutableCodePathsOfExampleSchema(unittest.TestCase): + """ Tests the object API generated for monster_test.fbs for mutation + + purposes. In each test, the default values will be changed through the + object API. We'll then pack the object class into the buf class and read + the updated values out from it to validate if the values are mutated as + expected. + """ + + def setUp(self, *args, **kwargs): + super(TestAllMutableCodePathsOfExampleSchema, self).setUp(*args, **kwargs) + # Creates an empty monster flatbuffer, and loads it into the object + # class for future tests. + b = flatbuffers.Builder(0) + _MONSTER.MonsterStart(b) + self.monsterT = self._create_and_load_object_class(b) + + def _pack_and_load_buf_class(self, monsterT): + """ Packs the object class into a flatbuffer and loads it into a buf + + class. + """ + b = flatbuffers.Builder(0) + b.Finish(monsterT.Pack(b)) + monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) + return monster + + def _create_and_load_object_class(self, b): + """ Finishs the creation of a monster flatbuffer and loads it into an + + object class. + """ + gen_mon = _MONSTER.MonsterEnd(b) + b.Finish(gen_mon) + monster = _MONSTER.Monster.GetRootAs(b.Bytes, b.Head()) + monsterT = _MONSTER.MonsterT() + monsterT.InitFromObj(monster) + return monsterT + + def test_mutate_pos(self): + posT = _VEC3.Vec3T() + posT.x = 4.0 + posT.y = 5.0 + posT.z = 6.0 + posT.test1 = 6.0 + posT.test2 = 7 + test3T = _TEST.TestT() + test3T.a = 8 + test3T.b = 9 + posT.test3 = test3T + self.monsterT.pos = posT + + # Packs the updated values. + monster = self._pack_and_load_buf_class(self.monsterT) + + # Checks if values are loaded correctly into the object class. + pos = monster.Pos() + + # Verifies the properties of the Vec3. + self.assertEqual(pos.X(), 4.0) + self.assertEqual(pos.Y(), 5.0) + self.assertEqual(pos.Z(), 6.0) + self.assertEqual(pos.Test1(), 6.0) + self.assertEqual(pos.Test2(), 7) + t3 = _TEST.Test() + t3 = pos.Test3(t3) + self.assertEqual(t3.A(), 8) + self.assertEqual(t3.B(), 9) + + def test_mutate_mana(self): + self.monsterT.mana = 200 + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Mana(), 200) + + def test_mutate_hp(self): + self.monsterT.hp = 200 + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Hp(), 200) + + def test_mutate_name(self): + self.monsterT.name = 'MyMonster' + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Name(), b'MyMonster') + + def test_mutate_inventory(self): + self.monsterT.inventory = [1, 7, 8] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Inventory(0), 1) + self.assertEqual(monster.Inventory(1), 7) + self.assertEqual(monster.Inventory(2), 8) + + def test_empty_inventory(self): + self.monsterT.inventory = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.InventoryIsNone()) + + def test_mutate_color(self): + self.monsterT.color = _COLOR.Color.Red + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Color(), _COLOR.Color.Red) + + def test_mutate_testtype(self): + self.monsterT.testType = _ANY.Any.Monster + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.TestType(), _ANY.Any.Monster) + + def test_mutate_test(self): + testT = _MONSTER.MonsterT() + testT.hp = 200 + self.monsterT.test = testT + monster = self._pack_and_load_buf_class(self.monsterT) + # Initializes a Table from a union field Test(...). + table = monster.Test() + + # Initializes a Monster from the Table from the union. + test_monster = _MONSTER.Monster() + test_monster.Init(table.Bytes, table.Pos) + self.assertEqual(test_monster.Hp(), 200) + + def test_mutate_test4(self): + test0T = _TEST.TestT() + test0T.a = 10 + test0T.b = 20 + test1T = _TEST.TestT() + test1T.a = 30 + test1T.b = 40 + self.monsterT.test4 = [test0T, test1T] + + monster = self._pack_and_load_buf_class(self.monsterT) + test0 = monster.Test4(0) + self.assertEqual(test0.A(), 10) + self.assertEqual(test0.B(), 20) + test1 = monster.Test4(1) + self.assertEqual(test1.A(), 30) + self.assertEqual(test1.B(), 40) + + def test_empty_test4(self): + self.monsterT.test4 = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.Test4IsNone()) + + def test_mutate_testarrayofstring(self): + self.monsterT.testarrayofstring = [] + self.monsterT.testarrayofstring.append('test1') + self.monsterT.testarrayofstring.append('test2') + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Testarrayofstring(0), b'test1') + self.assertEqual(monster.Testarrayofstring(1), b'test2') + + def test_empty_testarrayofstring(self): + self.monsterT.testarrayofstring = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.TestarrayofstringIsNone()) + + def test_mutate_testarrayoftables(self): + monsterT0 = _MONSTER.MonsterT() + monsterT0.hp = 200 + monsterT1 = _MONSTER.MonsterT() + monsterT1.hp = 400 + self.monsterT.testarrayoftables = [] + self.monsterT.testarrayoftables.append(monsterT0) + self.monsterT.testarrayoftables.append(monsterT1) + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Testarrayoftables(0).Hp(), 200) + self.assertEqual(monster.Testarrayoftables(1).Hp(), 400) + + def test_empty_testarrayoftables(self): + self.monsterT.testarrayoftables = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.TestarrayoftablesIsNone()) + + def test_mutate_enemy(self): + monsterT = _MONSTER.MonsterT() + monsterT.hp = 200 + self.monsterT.enemy = monsterT + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Enemy().Hp(), 200) + + def test_mutate_testnestedflatbuffer(self): + self.monsterT.testnestedflatbuffer = [8, 2, 4] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Testnestedflatbuffer(0), 8) + self.assertEqual(monster.Testnestedflatbuffer(1), 2) + self.assertEqual(monster.Testnestedflatbuffer(2), 4) + + def test_empty_testnestedflatbuffer(self): + self.monsterT.testnestedflatbuffer = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.TestnestedflatbufferIsNone()) + + def test_mutate_testbool(self): + self.monsterT.testbool = True + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertTrue(monster.Testbool()) + + def test_mutate_testhashes(self): + self.monsterT.testhashs32Fnv1 = 1 + self.monsterT.testhashu32Fnv1 = 2 + self.monsterT.testhashs64Fnv1 = 3 + self.monsterT.testhashu64Fnv1 = 4 + self.monsterT.testhashs32Fnv1a = 5 + self.monsterT.testhashu32Fnv1a = 6 + self.monsterT.testhashs64Fnv1a = 7 + self.monsterT.testhashu64Fnv1a = 8 + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Testhashs32Fnv1(), 1) + self.assertEqual(monster.Testhashu32Fnv1(), 2) + self.assertEqual(monster.Testhashs64Fnv1(), 3) + self.assertEqual(monster.Testhashu64Fnv1(), 4) + self.assertEqual(monster.Testhashs32Fnv1a(), 5) + self.assertEqual(monster.Testhashu32Fnv1a(), 6) + self.assertEqual(monster.Testhashs64Fnv1a(), 7) + self.assertEqual(monster.Testhashu64Fnv1a(), 8) + + def test_mutate_testarrayofbools(self): + self.monsterT.testarrayofbools = [] + self.monsterT.testarrayofbools.append(True) + self.monsterT.testarrayofbools.append(True) + self.monsterT.testarrayofbools.append(False) + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Testarrayofbools(0), True) + self.assertEqual(monster.Testarrayofbools(1), True) + self.assertEqual(monster.Testarrayofbools(2), False) + + def test_empty_testarrayofbools(self): + self.monsterT.testarrayofbools = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.TestarrayofboolsIsNone()) + + def test_mutate_testf(self): + self.monsterT.testf = 2.0 + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.Testf(), 2.0) + + def test_mutate_vectoroflongs(self): + self.monsterT.vectorOfLongs = [] + self.monsterT.vectorOfLongs.append(1) + self.monsterT.vectorOfLongs.append(100) + self.monsterT.vectorOfLongs.append(10000) + self.monsterT.vectorOfLongs.append(1000000) + self.monsterT.vectorOfLongs.append(100000000) + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.VectorOfLongs(0), 1) + self.assertEqual(monster.VectorOfLongs(1), 100) + self.assertEqual(monster.VectorOfLongs(2), 10000) + self.assertEqual(monster.VectorOfLongs(3), 1000000) + self.assertEqual(monster.VectorOfLongs(4), 100000000) + + def test_empty_vectoroflongs(self): + self.monsterT.vectorOfLongs = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.VectorOfLongsIsNone()) + + def test_mutate_vectorofdoubles(self): + self.monsterT.vectorOfDoubles = [] + self.monsterT.vectorOfDoubles.append(-1.7976931348623157e+308) + self.monsterT.vectorOfDoubles.append(0) + self.monsterT.vectorOfDoubles.append(1.7976931348623157e+308) + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.VectorOfDoubles(0), -1.7976931348623157e+308) + self.assertEqual(monster.VectorOfDoubles(1), 0) + self.assertEqual(monster.VectorOfDoubles(2), 1.7976931348623157e+308) + + def test_empty_vectorofdoubles(self): + self.monsterT.vectorOfDoubles = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.VectorOfDoublesIsNone()) + + def test_mutate_parentnamespacetest(self): + self.monsterT.parentNamespaceTest = _IN_PARENT_NAMESPACE.InParentNamespaceT( + ) + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertTrue( + isinstance(monster.ParentNamespaceTest(), + _IN_PARENT_NAMESPACE.InParentNamespace)) + + def test_mutate_vectorofEnums(self): + self.monsterT.vectorOfEnums = [] + self.monsterT.vectorOfEnums.append(_COLOR.Color.Red) + self.monsterT.vectorOfEnums.append(_COLOR.Color.Blue) + self.monsterT.vectorOfEnums.append(_COLOR.Color.Red) + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertEqual(monster.VectorOfEnums(0), _COLOR.Color.Red) + self.assertEqual(monster.VectorOfEnums(1), _COLOR.Color.Blue) + self.assertEqual(monster.VectorOfEnums(2), _COLOR.Color.Red) + + def test_empty_vectorofEnums(self): + self.monsterT.vectorOfEnums = [] + monster = self._pack_and_load_buf_class(self.monsterT) + self.assertFalse(monster.VectorOfEnumsIsNone()) + + +def CheckReadBuffer(buf, offset, sizePrefix=False, file_identifier=None): + """ CheckReadBuffer checks that the given buffer is evaluated correctly + + as the example Monster. + """ + + def asserter(stmt): + """ An assertion helper that is separated from TestCase classes. """ + if not stmt: + raise AssertionError('CheckReadBuffer case failed') + + if file_identifier: + # test prior to removal of size_prefix + asserter( + util.GetBufferIdentifier(buf, offset, size_prefixed=sizePrefix) == + file_identifier) + asserter( + util.BufferHasIdentifier( + buf, + offset, + file_identifier=file_identifier, + size_prefixed=sizePrefix)) + asserter( + _MONSTER.Monster.MonsterBufferHasIdentifier( + buf, offset, size_prefixed=sizePrefix)) + if sizePrefix: + size = util.GetSizePrefix(buf, offset) + asserter(size == len(buf[offset:]) - 4) + buf, offset = util.RemoveSizePrefix(buf, offset) + if file_identifier: + asserter(_MONSTER.Monster.MonsterBufferHasIdentifier(buf, offset)) + else: + asserter(not _MONSTER.Monster.MonsterBufferHasIdentifier(buf, offset)) + monster = _MONSTER.Monster.GetRootAs(buf, offset) + + asserter(monster.Hp() == 80) + asserter(monster.Mana() == 150) + asserter(monster.Name() == b'MyMonster') + + # initialize a Vec3 from Pos() + vec = monster.Pos() + asserter(vec is not None) + + # verify the properties of the Vec3 + asserter(vec.X() == 1.0) + asserter(vec.Y() == 2.0) + asserter(vec.Z() == 3.0) + asserter(vec.Test1() == 3.0) + asserter(vec.Test2() == 2) + + # initialize a Test from Test3(...) + t = _TEST.Test() + t = vec.Test3(t) + asserter(t is not None) + + # verify the properties of the Test + asserter(t.A() == 5) + asserter(t.B() == 6) + + # verify that the enum code matches the enum declaration: + union_type = _ANY.Any + asserter(monster.TestType() == union_type.Monster) + + # initialize a Table from a union field Test(...) + table2 = monster.Test() + asserter(type(table2) is flatbuffers.table.Table) + + # initialize a Monster from the Table from the union + monster2 = _MONSTER.Monster() + monster2.Init(table2.Bytes, table2.Pos) + + asserter(monster2.Name() == b'Fred') + + # iterate through the first monster's inventory: + asserter(monster.InventoryLength() == 5) + asserter(not monster.InventoryIsNone()) + + invsum = 0 + for i in compat_range(monster.InventoryLength()): + v = monster.Inventory(i) + invsum += int(v) + asserter(invsum == 10) + + for i in range(5): + asserter(monster.VectorOfLongs(i) == 10**(i * 2)) + + asserter(not monster.VectorOfDoublesIsNone()) + asserter(([-1.7976931348623157e+308, 0, 1.7976931348623157e+308] == [ + monster.VectorOfDoubles(i) for i in range(monster.VectorOfDoublesLength()) + ])) + + try: + # if numpy exists, then we should be able to get the + # vector as a numpy array + import numpy as np + + asserter(monster.InventoryAsNumpy().sum() == 10) + asserter(monster.InventoryAsNumpy().dtype == np.dtype(' 0: + self.assertEqual(init_buf, buf) + self.assertEqual(init_off, off) + else: + init_buf = buf + init_off = off + +def CheckAgainstGoldDataGo(): + try: + gen_buf, gen_off = make_monster_from_generated_code() + fn = 'monsterdata_go_wire.mon' + if not os.path.exists(fn): + print('Go-generated data does not exist, failed.') + return False + + # would like to use a context manager here, but it's less + # backwards-compatible: + f = open(fn, 'rb') + go_wire_data = f.read() + f.close() + + CheckReadBuffer(bytearray(go_wire_data), 0) + if not bytearray(gen_buf[gen_off:]) == bytearray(go_wire_data): + raise AssertionError('CheckAgainstGoldDataGo failed') + except: + print('Failed to test against Go-generated test data.') + return False + + print( + 'Can read Go-generated test data, and Python generates bytewise identical data.' + ) + return True + + +def CheckAgainstGoldDataJava(): + try: + gen_buf, gen_off = make_monster_from_generated_code() + fn = 'monsterdata_java_wire.mon' + if not os.path.exists(fn): + print('Java-generated data does not exist, failed.') + return False + f = open(fn, 'rb') + java_wire_data = f.read() + f.close() + + CheckReadBuffer(bytearray(java_wire_data), 0) + except: + print('Failed to read Java-generated test data.') + return False + + print('Can read Java-generated test data.') + return True + + +class LCG(object): + """ Include simple random number generator to ensure results will be the + + same cross platform. + http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator + """ + + __slots__ = ['n'] + + InitialLCGSeed = 48271 + + def __init__(self): + self.n = self.InitialLCGSeed + + def Reset(self): + self.n = self.InitialLCGSeed + + def Next(self): + self.n = ((self.n * 279470273) % 4294967291) & 0xFFFFFFFF + return self.n + + +def BenchmarkVtableDeduplication(count): + """ + BenchmarkVtableDeduplication measures the speed of vtable deduplication + by creating `prePop` vtables, then populating `count` objects with a + different single vtable. + + When count is large (as in long benchmarks), memory usage may be high. + """ + + for prePop in (1, 10, 100, 1000): + builder = flatbuffers.Builder(0) + n = 1 + int(math.log(prePop, 1.5)) + + # generate some layouts: + layouts = set() + r = list(compat_range(n)) + while len(layouts) < prePop: + layouts.add(tuple(sorted(random.sample(r, int(max(1, n / 2)))))) + + layouts = list(layouts) + + # pre-populate vtables: + for layout in layouts: + builder.StartObject(n) + for j in layout: + builder.PrependInt16Slot(j, j, 0) + builder.EndObject() + + # benchmark deduplication of a new vtable: + def f(): + layout = random.choice(layouts) + builder.StartObject(n) + for j in layout: + builder.PrependInt16Slot(j, j, 0) + builder.EndObject() + + duration = timeit.timeit(stmt=f, number=count) + rate = float(count) / duration + print(('vtable deduplication rate (n=%d, vtables=%d): %.2f sec' % + (prePop, len(builder.vtables), rate))) + + +def BenchmarkCheckReadBuffer(count, buf, off): + """ + BenchmarkCheckReadBuffer measures the speed of flatbuffer reading + by re-using the CheckReadBuffer function with the gold data. + """ + + def f(): + CheckReadBuffer(buf, off) + + duration = timeit.timeit(stmt=f, number=count) + rate = float(count) / duration + data = float(len(buf) * count) / float(1024 * 1024) + data_rate = data / float(duration) + + print(('traversed %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec') % + (count, len(buf), duration, rate, data_rate)) + + +def BenchmarkMakeMonsterFromGeneratedCode(count, length): + """ + BenchmarkMakeMonsterFromGeneratedCode measures the speed of flatbuffer + creation by re-using the make_monster_from_generated_code function for + generating gold data examples. + """ + + duration = timeit.timeit(stmt=make_monster_from_generated_code, number=count) + rate = float(count) / duration + data = float(length * count) / float(1024 * 1024) + data_rate = data / float(duration) + + print(('built %d %d-byte flatbuffers in %.2fsec: %.2f/sec, %.2fMB/sec' % \ + (count, length, duration, rate, data_rate))) + + +def BenchmarkBuilderClear(count, length): + b = flatbuffers.Builder(length) + duration = timeit.timeit(stmt=lambda: make_monster_from_generated_code(b), + number=count) + rate = float(count) / duration + data = float(length * count) / float(1024 * 1024) + data_rate = data / float(duration) + + print(('built %d %d-byte flatbuffers (reused buffer) in %.2fsec:' + ' %.2f/sec, %.2fMB/sec' % (count, length, duration, rate, data_rate))) + + +def backward_compatible_run_tests(**kwargs): + if PY_VERSION < (2, 6): + sys.stderr.write('Python version less than 2.6 are not supported') + sys.stderr.flush() + return False + + # python2.6 has a reduced-functionality unittest.main function: + if PY_VERSION == (2, 6): + try: + unittest.main(**kwargs) + except SystemExit as e: + if not e.code == 0: + return False + return True + + # python2.7 and above let us not exit once unittest.main is run: + kwargs['exit'] = False + kwargs['verbosity'] = 0 + ret = unittest.main(**kwargs) + if ret.result.errors or ret.result.failures: + return False + + return True + + +def main(): + import os + import sys + if not len(sys.argv) == 6: + sys.stderr.write('Usage: %s ' + ' ' + ' \n' % sys.argv[0]) + sys.stderr.write(' Provide COMPARE_GENERATED_TO_GO=1 to check' + 'for bytewise comparison to Go data.\n') + sys.stderr.write(' Provide COMPARE_GENERATED_TO_JAVA=1 to check' + 'for bytewise comparison to Java data.\n') + sys.stderr.flush() + sys.exit(1) + + kwargs = dict(argv=sys.argv[:-5]) + + create_namespace_shortcut(sys.argv[5].lower() == 'true') + + # show whether numpy is present, as it changes the test logic: + try: + import numpy + print('numpy available') + except ImportError: + print('numpy not available') + + # run tests, and run some language comparison checks if needed: + success = backward_compatible_run_tests(**kwargs) + if success and os.environ.get('COMPARE_GENERATED_TO_GO', 0) == '1': + success = success and CheckAgainstGoldDataGo() + if success and os.environ.get('COMPARE_GENERATED_TO_JAVA', 0) == '1': + success = success and CheckAgainstGoldDataJava() + + if not success: + sys.stderr.write('Tests failed, skipping benchmarks.\n') + sys.stderr.flush() + sys.exit(1) + + # run benchmarks (if 0, they will be a noop): + bench_vtable = int(sys.argv[1]) + bench_traverse = int(sys.argv[2]) + bench_build = int(sys.argv[3]) + bench_clear = int(sys.argv[4]) + if bench_vtable: + BenchmarkVtableDeduplication(bench_vtable) + if bench_traverse: + buf, off = make_monster_from_generated_code() + BenchmarkCheckReadBuffer(bench_traverse, buf, off) + if bench_build: + buf, off = make_monster_from_generated_code() + BenchmarkMakeMonsterFromGeneratedCode(bench_build, len(buf)) + if bench_clear: + buf, off = make_monster_from_generated_code() + BenchmarkBuilderClear(bench_build, len(buf)) + +if __name__ == '__main__': + main() diff --git a/third_party/flatbuffers/tests/reflection_test.cpp b/third_party/flatbuffers/tests/reflection_test.cpp new file mode 100644 index 00000000000..880f137e1bb --- /dev/null +++ b/third_party/flatbuffers/tests/reflection_test.cpp @@ -0,0 +1,327 @@ +#include "reflection_test.h" + +#include "tests/arrays_test_generated.h" +#include "flatbuffers/minireflect.h" +#include "flatbuffers/reflection.h" +#include "flatbuffers/reflection_generated.h" +#include "flatbuffers/verifier.h" +#include "monster_test.h" +#include "monster_test_generated.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { + +using namespace MyGame::Example; + +void ReflectionTest(const std::string &tests_data_path, uint8_t *flatbuf, + size_t length) { + // Load a binary schema. + std::string bfbsfile; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.bfbs").c_str(), + true, &bfbsfile), + true); + + // Verify it, just in case: + flatbuffers::Verifier verifier( + reinterpret_cast(bfbsfile.c_str()), bfbsfile.length()); + TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); + + // Make sure the schema is what we expect it to be. + auto &schema = *reflection::GetSchema(bfbsfile.c_str()); + auto root_table = schema.root_table(); + + // Check the declaration files. + TEST_EQ_STR(root_table->name()->c_str(), "MyGame.Example.Monster"); + TEST_EQ_STR(root_table->declaration_file()->c_str(), "//monster_test.fbs"); + TEST_EQ_STR( + schema.objects()->LookupByKey("TableA")->declaration_file()->c_str(), + "//include_test/include_test1.fbs"); + TEST_EQ_STR(schema.objects() + ->LookupByKey("MyGame.OtherNameSpace.Unused") + ->declaration_file() + ->c_str(), + "//include_test/sub/include_test2.fbs"); + TEST_EQ_STR(schema.enums() + ->LookupByKey("MyGame.OtherNameSpace.FromInclude") + ->declaration_file() + ->c_str(), + "//include_test/sub/include_test2.fbs"); + + // Check scheam filenames and their includes. + TEST_EQ(schema.fbs_files()->size(), 3); + + const auto fbs0 = schema.fbs_files()->Get(0); + TEST_EQ_STR(fbs0->filename()->c_str(), "//include_test/include_test1.fbs"); + const auto fbs0_includes = fbs0->included_filenames(); + TEST_EQ(fbs0_includes->size(), 2); + + // TODO(caspern): Should we force or disallow inclusion of self? + TEST_EQ_STR(fbs0_includes->Get(0)->c_str(), + "//include_test/include_test1.fbs"); + TEST_EQ_STR(fbs0_includes->Get(1)->c_str(), + "//include_test/sub/include_test2.fbs"); + + const auto fbs1 = schema.fbs_files()->Get(1); + TEST_EQ_STR(fbs1->filename()->c_str(), + "//include_test/sub/include_test2.fbs"); + const auto fbs1_includes = fbs1->included_filenames(); + TEST_EQ(fbs1_includes->size(), 2); + TEST_EQ_STR(fbs1_includes->Get(0)->c_str(), + "//include_test/include_test1.fbs"); + TEST_EQ_STR(fbs1_includes->Get(1)->c_str(), + "//include_test/sub/include_test2.fbs"); + + const auto fbs2 = schema.fbs_files()->Get(2); + TEST_EQ_STR(fbs2->filename()->c_str(), "//monster_test.fbs"); + const auto fbs2_includes = fbs2->included_filenames(); + TEST_EQ(fbs2_includes->size(), 1); + TEST_EQ_STR(fbs2_includes->Get(0)->c_str(), + "//include_test/include_test1.fbs"); + + // Check Root table fields + auto fields = root_table->fields(); + auto hp_field_ptr = fields->LookupByKey("hp"); + TEST_NOTNULL(hp_field_ptr); + auto &hp_field = *hp_field_ptr; + TEST_EQ_STR(hp_field.name()->c_str(), "hp"); + TEST_EQ(hp_field.id(), 2); + TEST_EQ(hp_field.type()->base_type(), reflection::Short); + + auto friendly_field_ptr = fields->LookupByKey("friendly"); + TEST_NOTNULL(friendly_field_ptr); + TEST_NOTNULL(friendly_field_ptr->attributes()); + TEST_NOTNULL(friendly_field_ptr->attributes()->LookupByKey("priority")); + + // Make sure the table index is what we expect it to be. + auto pos_field_ptr = fields->LookupByKey("pos"); + TEST_NOTNULL(pos_field_ptr); + TEST_EQ(pos_field_ptr->type()->base_type(), reflection::Obj); + auto pos_table_ptr = schema.objects()->Get(pos_field_ptr->type()->index()); + TEST_NOTNULL(pos_table_ptr); + TEST_EQ_STR(pos_table_ptr->name()->c_str(), "MyGame.Example.Vec3"); + + // Test nullability of fields: hp is a 0-default scalar, pos is a struct => + // optional, and name is a required string => not optional. + TEST_EQ(hp_field.optional(), false); + TEST_EQ(pos_field_ptr->optional(), true); + TEST_EQ(fields->LookupByKey("name")->optional(), false); + + // Now use it to dynamically access a buffer. + auto &root = *flatbuffers::GetAnyRoot(flatbuf); + + // Verify the buffer first using reflection based verification + TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length), + true); + + auto hp = flatbuffers::GetFieldI(root, hp_field); + TEST_EQ(hp, 80); + + // Rather than needing to know the type, we can also get the value of + // any field as an int64_t/double/string, regardless of what it actually is. + auto hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field); + TEST_EQ(hp_int64, 80); + auto hp_double = flatbuffers::GetAnyFieldF(root, hp_field); + TEST_EQ(hp_double, 80.0); + auto hp_string = flatbuffers::GetAnyFieldS(root, hp_field, &schema); + TEST_EQ_STR(hp_string.c_str(), "80"); + + // Get struct field through reflection + auto pos_struct = flatbuffers::GetFieldStruct(root, *pos_field_ptr); + TEST_NOTNULL(pos_struct); + TEST_EQ(flatbuffers::GetAnyFieldF(*pos_struct, + *pos_table_ptr->fields()->LookupByKey("z")), + 3.0f); + + auto test3_field = pos_table_ptr->fields()->LookupByKey("test3"); + auto test3_struct = flatbuffers::GetFieldStruct(*pos_struct, *test3_field); + TEST_NOTNULL(test3_struct); + auto test3_object = schema.objects()->Get(test3_field->type()->index()); + + TEST_EQ(flatbuffers::GetAnyFieldF(*test3_struct, + *test3_object->fields()->LookupByKey("a")), + 10); + + // We can also modify it. + flatbuffers::SetField(&root, hp_field, 200); + hp = flatbuffers::GetFieldI(root, hp_field); + TEST_EQ(hp, 200); + + // We can also set fields generically: + flatbuffers::SetAnyFieldI(&root, hp_field, 300); + hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field); + TEST_EQ(hp_int64, 300); + flatbuffers::SetAnyFieldF(&root, hp_field, 300.5); + hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field); + TEST_EQ(hp_int64, 300); + flatbuffers::SetAnyFieldS(&root, hp_field, "300"); + hp_int64 = flatbuffers::GetAnyFieldI(root, hp_field); + TEST_EQ(hp_int64, 300); + + // Test buffer is valid after the modifications + TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), flatbuf, length), + true); + + // Reset it, for further tests. + flatbuffers::SetField(&root, hp_field, 80); + + // More advanced functionality: changing the size of items in-line! + // First we put the FlatBuffer inside an std::vector. + std::vector resizingbuf(flatbuf, flatbuf + length); + // Find the field we want to modify. + auto &name_field = *fields->LookupByKey("name"); + // Get the root. + // This time we wrap the result from GetAnyRoot in a smartpointer that + // will keep rroot valid as resizingbuf resizes. + auto rroot = flatbuffers::piv(flatbuffers::GetAnyRoot(resizingbuf.data()), + resizingbuf); + SetString(schema, "totally new string", GetFieldS(**rroot, name_field), + &resizingbuf); + // Here resizingbuf has changed, but rroot is still valid. + TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "totally new string"); + // Now lets extend a vector by 100 elements (10 -> 110). + auto &inventory_field = *fields->LookupByKey("inventory"); + auto rinventory = flatbuffers::piv( + flatbuffers::GetFieldV(**rroot, inventory_field), resizingbuf); + flatbuffers::ResizeVector(schema, 110, 50, *rinventory, + &resizingbuf); + // rinventory still valid, so lets read from it. + TEST_EQ(rinventory->Get(10), 50); + + // For reflection uses not covered already, there is a more powerful way: + // we can simply generate whatever object we want to add/modify in a + // FlatBuffer of its own, then add that to an existing FlatBuffer: + // As an example, let's add a string to an array of strings. + // First, find our field: + auto &testarrayofstring_field = *fields->LookupByKey("testarrayofstring"); + // Find the vector value: + auto rtestarrayofstring = flatbuffers::piv( + flatbuffers::GetFieldV>( + **rroot, testarrayofstring_field), + resizingbuf); + // It's a vector of 2 strings, to which we add one more, initialized to + // offset 0. + flatbuffers::ResizeVector>( + schema, 3, 0, *rtestarrayofstring, &resizingbuf); + // Here we just create a buffer that contans a single string, but this + // could also be any complex set of tables and other values. + flatbuffers::FlatBufferBuilder stringfbb; + stringfbb.Finish(stringfbb.CreateString("hank")); + // Add the contents of it to our existing FlatBuffer. + // We do this last, so the pointer doesn't get invalidated (since it is + // at the end of the buffer): + auto string_ptr = flatbuffers::AddFlatBuffer( + resizingbuf, stringfbb.GetBufferPointer(), stringfbb.GetSize()); + // Finally, set the new value in the vector. + rtestarrayofstring->MutateOffset(2, string_ptr); + TEST_EQ_STR(rtestarrayofstring->Get(0)->c_str(), "bob"); + TEST_EQ_STR(rtestarrayofstring->Get(2)->c_str(), "hank"); + // Test integrity of all resize operations above. + flatbuffers::Verifier resize_verifier( + reinterpret_cast(resizingbuf.data()), + resizingbuf.size()); + TEST_EQ(VerifyMonsterBuffer(resize_verifier), true); + + // Test buffer is valid using reflection as well + TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), resizingbuf.data(), + resizingbuf.size()), + true); + + // As an additional test, also set it on the name field. + // Note: unlike the name change above, this just overwrites the offset, + // rather than changing the string in-place. + SetFieldT(*rroot, name_field, string_ptr); + TEST_EQ_STR(GetFieldS(**rroot, name_field)->c_str(), "hank"); + + // Using reflection, rather than mutating binary FlatBuffers, we can also copy + // tables and other things out of other FlatBuffers into a FlatBufferBuilder, + // either part or whole. + flatbuffers::FlatBufferBuilder fbb; + auto root_offset = flatbuffers::CopyTable( + fbb, schema, *root_table, *flatbuffers::GetAnyRoot(flatbuf), true); + fbb.Finish(root_offset, MonsterIdentifier()); + // Test that it was copied correctly: + AccessFlatBufferTest(fbb.GetBufferPointer(), fbb.GetSize()); + + // Test buffer is valid using reflection as well + TEST_EQ(flatbuffers::Verify(schema, *schema.root_table(), + fbb.GetBufferPointer(), fbb.GetSize()), + true); +} + +void MiniReflectFlatBuffersTest(uint8_t *flatbuf) { + auto s = + flatbuffers::FlatBufferToString(flatbuf, Monster::MiniReflectTypeTable()); + TEST_EQ_STR( + s.c_str(), + "{ " + "pos: { x: 1.0, y: 2.0, z: 3.0, test1: 0.0, test2: Red, test3: " + "{ a: 10, b: 20 } }, " + "hp: 80, " + "name: \"MyMonster\", " + "inventory: [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ], " + "test_type: Monster, " + "test: { name: \"Fred\" }, " + "test4: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], " + "testarrayofstring: [ \"bob\", \"fred\", \"bob\", \"fred\" ], " + "testarrayoftables: [ { hp: 1000, name: \"Barney\" }, { name: \"Fred\" " + "}, " + "{ name: \"Wilma\" } ], " + // TODO(wvo): should really print this nested buffer correctly. + "testnestedflatbuffer: [ 124, 0, 0, 0, 77, 79, 78, 83, 0, 0, 114, 0, 16, " + "0, 0, 0, 4, 0, 6, 0, 8, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, " + "0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 12, 0, 114, 0, 0, 0, 0, 0, 0, 0, " + "8, 0, 0, 0, 0, 0, 192, 127, 13, 0, 0, 0, 78, 101, 115, 116, 101, 100, " + "77, 111, 110, 115, 116, 101, 114, 0, 0, 0 ], " + "testarrayofstring2: [ \"jane\", \"mary\" ], " + "testarrayofsortedstruct: [ { id: 0, distance: 0 }, " + "{ id: 2, distance: 20 }, { id: 3, distance: 30 }, " + "{ id: 4, distance: 40 } ], " + "flex: [ 210, 4, 5, 2 ], " + "test5: [ { a: 10, b: 20 }, { a: 30, b: 40 } ], " + "vector_of_enums: [ Blue, Green ], " + "scalar_key_sorted_tables: [ { id: \"miss\" } ], " + "nan_default: nan " + "}"); + + Test test(16, 32); + Vec3 vec(1, 2, 3, 1.5, Color_Red, test); + flatbuffers::FlatBufferBuilder vec_builder; + vec_builder.Finish(vec_builder.CreateStruct(vec)); + auto vec_buffer = vec_builder.Release(); + auto vec_str = flatbuffers::FlatBufferToString(vec_buffer.data(), + Vec3::MiniReflectTypeTable()); + TEST_EQ_STR(vec_str.c_str(), + "{ x: 1.0, y: 2.0, z: 3.0, test1: 1.5, test2: Red, test3: { a: " + "16, b: 32 } }"); +} + +void MiniReflectFixedLengthArrayTest() { + // VS10 does not support typed enums, exclude from tests +#if !defined(_MSC_VER) || _MSC_VER >= 1700 + flatbuffers::FlatBufferBuilder fbb; + MyGame::Example::ArrayStruct aStruct(2, 12, 1); + auto aTable = MyGame::Example::CreateArrayTable(fbb, &aStruct); + fbb.Finish(aTable); + + auto flatbuf = fbb.Release(); + auto s = flatbuffers::FlatBufferToString( + flatbuf.data(), MyGame::Example::ArrayTableTypeTable()); + TEST_EQ_STR( + "{ " + "a: { a: 2.0, " + "b: [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 ], " + "c: 12, " + "d: [ { a: [ 0, 0 ], b: A, c: [ A, A ], d: [ 0, 0 ] }, " + "{ a: [ 0, 0 ], b: A, c: [ A, A ], d: [ 0, 0 ] } ], " + "e: 1, f: [ 0, 0 ] } " + "}", + s.c_str()); +#endif +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/reflection_test.h b/third_party/flatbuffers/tests/reflection_test.h new file mode 100644 index 00000000000..090871963ac --- /dev/null +++ b/third_party/flatbuffers/tests/reflection_test.h @@ -0,0 +1,17 @@ +#ifndef TESTS_REFLECTION_TEST_H +#define TESTS_REFLECTION_TEST_H + +#include +#include + +namespace flatbuffers { +namespace tests { + +void ReflectionTest(const std::string& tests_data_path, uint8_t *flatbuf, size_t length); +void MiniReflectFixedLengthArrayTest(); +void MiniReflectFlatBuffersTest(uint8_t *flatbuf); + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/required_strings.fbs b/third_party/flatbuffers/tests/required_strings.fbs new file mode 100644 index 00000000000..98556d4ff92 --- /dev/null +++ b/third_party/flatbuffers/tests/required_strings.fbs @@ -0,0 +1,12 @@ +namespace required_strings; + +/** + * Foo defines a type where both fields are mandatory. + * The creation of a Foo buffer must throw if either of the fields is missing. + * + * https://github.com/google/flatbuffers/issues/7739 + */ +table Foo { + str_a:string (required); + str_b:string (required); +} diff --git a/third_party/flatbuffers/tests/rust_namer_test.fbs b/third_party/flatbuffers/tests/rust_namer_test.fbs new file mode 100644 index 00000000000..bbd4b301df1 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test.fbs @@ -0,0 +1,37 @@ +namespace RustNamerTest; + +table FieldTable {} + +union FieldUnion { + f :FieldTable (id: 0), +} + +table RootTable { + field42 :FieldUnion (id: 1); +} + +table PlayerStatEvent {} +table PlayerSpectate {} +table PlayerInputChange {} + +union GameMessage +{ + PlayerStatEvent, + PlayerSpectate, + PlayerInputChange +} + +table GameMessageWrapper +{ + Message:GameMessage; +} + +struct PossiblyReservedWords +{ + // Keywords reserved by Rust namer + follow: float; + push: float; + // Keywords no longer reserved by Rust namer + size: float; + alignment: float; +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/mod.rs b/third_party/flatbuffers/tests/rust_namer_test/mod.rs new file mode 100644 index 00000000000..f395a500340 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/mod.rs @@ -0,0 +1,23 @@ +// Automatically generated by the Flatbuffers compiler. Do not modify. +// @generated +pub mod rust_namer_test { + use super::*; + mod field_union_generated; + pub use self::field_union_generated::*; + mod game_message_generated; + pub use self::game_message_generated::*; + mod field_table_generated; + pub use self::field_table_generated::*; + mod root_table_generated; + pub use self::root_table_generated::*; + mod player_stat_event_generated; + pub use self::player_stat_event_generated::*; + mod player_spectate_generated; + pub use self::player_spectate_generated::*; + mod player_input_change_generated; + pub use self::player_input_change_generated::*; + mod game_message_wrapper_generated; + pub use self::game_message_wrapper_generated::*; + mod possibly_reserved_words_generated; + pub use self::possibly_reserved_words_generated::*; +} // rust_namer_test diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/field_table_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/field_table_generated.rs new file mode 100644 index 00000000000..1355886f215 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/field_table_generated.rs @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum FieldTableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct FieldTable<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for FieldTable<'a> { + type Inner = FieldTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> FieldTable<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.FieldTable" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + FieldTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args FieldTableArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = FieldTableBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> FieldTableT { + FieldTableT { + } + } +} + +impl flatbuffers::Verifiable for FieldTable<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct FieldTableArgs { +} +impl<'a> Default for FieldTableArgs { + #[inline] + fn default() -> Self { + FieldTableArgs { + } + } +} + +pub struct FieldTableBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> FieldTableBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> FieldTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + FieldTableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for FieldTable<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("FieldTable"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct FieldTableT { +} +impl Default for FieldTableT { + fn default() -> Self { + Self { + } + } +} +impl FieldTableT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + FieldTable::create(_fbb, &FieldTableArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/field_union_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/field_union_generated.rs new file mode 100644 index 00000000000..706095e4fff --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/field_union_generated.rs @@ -0,0 +1,145 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_FIELD_UNION: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_FIELD_UNION: u8 = 1; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_FIELD_UNION: [FieldUnion; 2] = [ + FieldUnion::NONE, + FieldUnion::f, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct FieldUnion(pub u8); +#[allow(non_upper_case_globals)] +impl FieldUnion { + pub const NONE: Self = Self(0); + pub const f: Self = Self(1); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 1; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::f, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::f => Some("f"), + _ => None, + } + } +} +impl core::fmt::Debug for FieldUnion { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for FieldUnion { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for FieldUnion { + type Output = FieldUnion; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for FieldUnion { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for FieldUnion { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for FieldUnion {} +pub struct FieldUnionUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum FieldUnionT { + NONE, + F(Box), +} +impl Default for FieldUnionT { + fn default() -> Self { + Self::NONE + } +} +impl FieldUnionT { + pub fn field_union_type(&self) -> FieldUnion { + match self { + Self::NONE => FieldUnion::NONE, + Self::F(_) => FieldUnion::f, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::F(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned FieldTableT, setting the union to NONE. + pub fn take_f(&mut self) -> Option> { + if let Self::F(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::F(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the FieldTableT. + pub fn as_f(&self) -> Option<&FieldTableT> { + if let Self::F(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the FieldTableT. + pub fn as_f_mut(&mut self) -> Option<&mut FieldTableT> { + if let Self::F(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/game_message_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/game_message_generated.rs new file mode 100644 index 00000000000..dfab0ec3132 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/game_message_generated.rs @@ -0,0 +1,201 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MIN_GAME_MESSAGE: u8 = 0; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +pub const ENUM_MAX_GAME_MESSAGE: u8 = 3; +#[deprecated(since = "2.0.0", note = "Use associated constants instead. This will no longer be generated in 2021.")] +#[allow(non_camel_case_types)] +pub const ENUM_VALUES_GAME_MESSAGE: [GameMessage; 4] = [ + GameMessage::NONE, + GameMessage::PlayerStatEvent, + GameMessage::PlayerSpectate, + GameMessage::PlayerInputChange, +]; + +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] +#[repr(transparent)] +pub struct GameMessage(pub u8); +#[allow(non_upper_case_globals)] +impl GameMessage { + pub const NONE: Self = Self(0); + pub const PlayerStatEvent: Self = Self(1); + pub const PlayerSpectate: Self = Self(2); + pub const PlayerInputChange: Self = Self(3); + + pub const ENUM_MIN: u8 = 0; + pub const ENUM_MAX: u8 = 3; + pub const ENUM_VALUES: &'static [Self] = &[ + Self::NONE, + Self::PlayerStatEvent, + Self::PlayerSpectate, + Self::PlayerInputChange, + ]; + /// Returns the variant's name or "" if unknown. + pub fn variant_name(self) -> Option<&'static str> { + match self { + Self::NONE => Some("NONE"), + Self::PlayerStatEvent => Some("PlayerStatEvent"), + Self::PlayerSpectate => Some("PlayerSpectate"), + Self::PlayerInputChange => Some("PlayerInputChange"), + _ => None, + } + } +} +impl core::fmt::Debug for GameMessage { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + if let Some(name) = self.variant_name() { + f.write_str(name) + } else { + f.write_fmt(format_args!("", self.0)) + } + } +} +impl<'a> flatbuffers::Follow<'a> for GameMessage { + type Inner = Self; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + let b = flatbuffers::read_scalar_at::(buf, loc); + Self(b) + } +} + +impl flatbuffers::Push for GameMessage { + type Output = GameMessage; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + flatbuffers::emplace_scalar::(dst, self.0); + } +} + +impl flatbuffers::EndianScalar for GameMessage { + type Scalar = u8; + #[inline] + fn to_little_endian(self) -> u8 { + self.0.to_le() + } + #[inline] + #[allow(clippy::wrong_self_convention)] + fn from_little_endian(v: u8) -> Self { + let b = u8::from_le(v); + Self(b) + } +} + +impl<'a> flatbuffers::Verifiable for GameMessage { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + u8::run_verifier(v, pos) + } +} + +impl flatbuffers::SimpleToVerifyInSlice for GameMessage {} +pub struct GameMessageUnionTableOffset {} + +#[allow(clippy::upper_case_acronyms)] +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub enum GameMessageT { + NONE, + PlayerStatEvent(Box), + PlayerSpectate(Box), + PlayerInputChange(Box), +} +impl Default for GameMessageT { + fn default() -> Self { + Self::NONE + } +} +impl GameMessageT { + pub fn game_message_type(&self) -> GameMessage { + match self { + Self::NONE => GameMessage::NONE, + Self::PlayerStatEvent(_) => GameMessage::PlayerStatEvent, + Self::PlayerSpectate(_) => GameMessage::PlayerSpectate, + Self::PlayerInputChange(_) => GameMessage::PlayerInputChange, + } + } + pub fn pack<'b, A: flatbuffers::Allocator + 'b>(&self, fbb: &mut flatbuffers::FlatBufferBuilder<'b, A>) -> Option> { + match self { + Self::NONE => None, + Self::PlayerStatEvent(v) => Some(v.pack(fbb).as_union_value()), + Self::PlayerSpectate(v) => Some(v.pack(fbb).as_union_value()), + Self::PlayerInputChange(v) => Some(v.pack(fbb).as_union_value()), + } + } + /// If the union variant matches, return the owned PlayerStatEventT, setting the union to NONE. + pub fn take_player_stat_event(&mut self) -> Option> { + if let Self::PlayerStatEvent(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::PlayerStatEvent(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the PlayerStatEventT. + pub fn as_player_stat_event(&self) -> Option<&PlayerStatEventT> { + if let Self::PlayerStatEvent(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the PlayerStatEventT. + pub fn as_player_stat_event_mut(&mut self) -> Option<&mut PlayerStatEventT> { + if let Self::PlayerStatEvent(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned PlayerSpectateT, setting the union to NONE. + pub fn take_player_spectate(&mut self) -> Option> { + if let Self::PlayerSpectate(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::PlayerSpectate(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the PlayerSpectateT. + pub fn as_player_spectate(&self) -> Option<&PlayerSpectateT> { + if let Self::PlayerSpectate(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the PlayerSpectateT. + pub fn as_player_spectate_mut(&mut self) -> Option<&mut PlayerSpectateT> { + if let Self::PlayerSpectate(v) = self { Some(v.as_mut()) } else { None } + } + /// If the union variant matches, return the owned PlayerInputChangeT, setting the union to NONE. + pub fn take_player_input_change(&mut self) -> Option> { + if let Self::PlayerInputChange(_) = self { + let v = core::mem::replace(self, Self::NONE); + if let Self::PlayerInputChange(w) = v { + Some(w) + } else { + unreachable!() + } + } else { + None + } + } + /// If the union variant matches, return a reference to the PlayerInputChangeT. + pub fn as_player_input_change(&self) -> Option<&PlayerInputChangeT> { + if let Self::PlayerInputChange(v) = self { Some(v.as_ref()) } else { None } + } + /// If the union variant matches, return a mutable reference to the PlayerInputChangeT. + pub fn as_player_input_change_mut(&mut self) -> Option<&mut PlayerInputChangeT> { + if let Self::PlayerInputChange(v) = self { Some(v.as_mut()) } else { None } + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs new file mode 100644 index 00000000000..ea3c2b20873 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/game_message_wrapper_generated.rs @@ -0,0 +1,255 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum GameMessageWrapperOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct GameMessageWrapper<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for GameMessageWrapper<'a> { + type Inner = GameMessageWrapper<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> GameMessageWrapper<'a> { + pub const VT_MESSAGE_TYPE: flatbuffers::VOffsetT = 4; + pub const VT_MESSAGE: flatbuffers::VOffsetT = 6; + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.GameMessageWrapper" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + GameMessageWrapper { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args GameMessageWrapperArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = GameMessageWrapperBuilder::new(_fbb); + if let Some(x) = args.Message { builder.add_Message(x); } + builder.add_Message_type(args.Message_type); + builder.finish() + } + + pub fn unpack(&self) -> GameMessageWrapperT { + let Message = match self.Message_type() { + GameMessage::NONE => GameMessageT::NONE, + GameMessage::PlayerStatEvent => GameMessageT::PlayerStatEvent(Box::new( + self.Message_as_player_stat_event() + .expect("Invalid union table, expected `GameMessage::PlayerStatEvent`.") + .unpack() + )), + GameMessage::PlayerSpectate => GameMessageT::PlayerSpectate(Box::new( + self.Message_as_player_spectate() + .expect("Invalid union table, expected `GameMessage::PlayerSpectate`.") + .unpack() + )), + GameMessage::PlayerInputChange => GameMessageT::PlayerInputChange(Box::new( + self.Message_as_player_input_change() + .expect("Invalid union table, expected `GameMessage::PlayerInputChange`.") + .unpack() + )), + _ => GameMessageT::NONE, + }; + GameMessageWrapperT { + Message, + } + } + + #[inline] + pub fn Message_type(&self) -> GameMessage { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(GameMessageWrapper::VT_MESSAGE_TYPE, Some(GameMessage::NONE)).unwrap()} + } + #[inline] + pub fn Message(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(GameMessageWrapper::VT_MESSAGE, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn Message_as_player_stat_event(&self) -> Option> { + if self.Message_type() == GameMessage::PlayerStatEvent { + self.Message().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { PlayerStatEvent::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn Message_as_player_spectate(&self) -> Option> { + if self.Message_type() == GameMessage::PlayerSpectate { + self.Message().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { PlayerSpectate::init_from_table(t) } + }) + } else { + None + } + } + + #[inline] + #[allow(non_snake_case)] + pub fn Message_as_player_input_change(&self) -> Option> { + if self.Message_type() == GameMessage::PlayerInputChange { + self.Message().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { PlayerInputChange::init_from_table(t) } + }) + } else { + None + } + } + +} + +impl flatbuffers::Verifiable for GameMessageWrapper<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_union::("Message_type", Self::VT_MESSAGE_TYPE, "Message", Self::VT_MESSAGE, false, |key, v, pos| { + match key { + GameMessage::PlayerStatEvent => v.verify_union_variant::>("GameMessage::PlayerStatEvent", pos), + GameMessage::PlayerSpectate => v.verify_union_variant::>("GameMessage::PlayerSpectate", pos), + GameMessage::PlayerInputChange => v.verify_union_variant::>("GameMessage::PlayerInputChange", pos), + _ => Ok(()), + } + })? + .finish(); + Ok(()) + } +} +pub struct GameMessageWrapperArgs { + pub Message_type: GameMessage, + pub Message: Option>, +} +impl<'a> Default for GameMessageWrapperArgs { + #[inline] + fn default() -> Self { + GameMessageWrapperArgs { + Message_type: GameMessage::NONE, + Message: None, + } + } +} + +pub struct GameMessageWrapperBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> GameMessageWrapperBuilder<'a, 'b, A> { + #[inline] + pub fn add_Message_type(&mut self, Message_type: GameMessage) { + self.fbb_.push_slot::(GameMessageWrapper::VT_MESSAGE_TYPE, Message_type, GameMessage::NONE); + } + #[inline] + pub fn add_Message(&mut self, Message: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(GameMessageWrapper::VT_MESSAGE, Message); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> GameMessageWrapperBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + GameMessageWrapperBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for GameMessageWrapper<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("GameMessageWrapper"); + ds.field("Message_type", &self.Message_type()); + match self.Message_type() { + GameMessage::PlayerStatEvent => { + if let Some(x) = self.Message_as_player_stat_event() { + ds.field("Message", &x) + } else { + ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + GameMessage::PlayerSpectate => { + if let Some(x) = self.Message_as_player_spectate() { + ds.field("Message", &x) + } else { + ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + GameMessage::PlayerInputChange => { + if let Some(x) = self.Message_as_player_input_change() { + ds.field("Message", &x) + } else { + ds.field("Message", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("Message", &x) + }, + }; + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct GameMessageWrapperT { + pub Message: GameMessageT, +} +impl Default for GameMessageWrapperT { + fn default() -> Self { + Self { + Message: GameMessageT::NONE, + } + } +} +impl GameMessageWrapperT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let Message_type = self.Message.game_message_type(); + let Message = self.Message.pack(_fbb); + GameMessageWrapper::create(_fbb, &GameMessageWrapperArgs{ + Message_type, + Message, + }) + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs new file mode 100644 index 00000000000..76449d1bb76 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_input_change_generated.rs @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum PlayerInputChangeOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct PlayerInputChange<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for PlayerInputChange<'a> { + type Inner = PlayerInputChange<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> PlayerInputChange<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PlayerInputChange" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + PlayerInputChange { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args PlayerInputChangeArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = PlayerInputChangeBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> PlayerInputChangeT { + PlayerInputChangeT { + } + } +} + +impl flatbuffers::Verifiable for PlayerInputChange<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct PlayerInputChangeArgs { +} +impl<'a> Default for PlayerInputChangeArgs { + #[inline] + fn default() -> Self { + PlayerInputChangeArgs { + } + } +} + +pub struct PlayerInputChangeBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> PlayerInputChangeBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerInputChangeBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + PlayerInputChangeBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for PlayerInputChange<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("PlayerInputChange"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct PlayerInputChangeT { +} +impl Default for PlayerInputChangeT { + fn default() -> Self { + Self { + } + } +} +impl PlayerInputChangeT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + PlayerInputChange::create(_fbb, &PlayerInputChangeArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs new file mode 100644 index 00000000000..ae025c3311d --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_spectate_generated.rs @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum PlayerSpectateOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct PlayerSpectate<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for PlayerSpectate<'a> { + type Inner = PlayerSpectate<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> PlayerSpectate<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PlayerSpectate" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + PlayerSpectate { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args PlayerSpectateArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = PlayerSpectateBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> PlayerSpectateT { + PlayerSpectateT { + } + } +} + +impl flatbuffers::Verifiable for PlayerSpectate<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct PlayerSpectateArgs { +} +impl<'a> Default for PlayerSpectateArgs { + #[inline] + fn default() -> Self { + PlayerSpectateArgs { + } + } +} + +pub struct PlayerSpectateBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> PlayerSpectateBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerSpectateBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + PlayerSpectateBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for PlayerSpectate<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("PlayerSpectate"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct PlayerSpectateT { +} +impl Default for PlayerSpectateT { + fn default() -> Self { + Self { + } + } +} +impl PlayerSpectateT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + PlayerSpectate::create(_fbb, &PlayerSpectateArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs new file mode 100644 index 00000000000..9ab29dd2686 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/player_stat_event_generated.rs @@ -0,0 +1,117 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum PlayerStatEventOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct PlayerStatEvent<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for PlayerStatEvent<'a> { + type Inner = PlayerStatEvent<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> PlayerStatEvent<'a> { + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PlayerStatEvent" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + PlayerStatEvent { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + _args: &'args PlayerStatEventArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = PlayerStatEventBuilder::new(_fbb); + builder.finish() + } + + pub fn unpack(&self) -> PlayerStatEventT { + PlayerStatEventT { + } + } +} + +impl flatbuffers::Verifiable for PlayerStatEvent<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .finish(); + Ok(()) + } +} +pub struct PlayerStatEventArgs { +} +impl<'a> Default for PlayerStatEventArgs { + #[inline] + fn default() -> Self { + PlayerStatEventArgs { + } + } +} + +pub struct PlayerStatEventBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> PlayerStatEventBuilder<'a, 'b, A> { + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> PlayerStatEventBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + PlayerStatEventBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for PlayerStatEvent<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("PlayerStatEvent"); + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct PlayerStatEventT { +} +impl Default for PlayerStatEventT { + fn default() -> Self { + Self { + } + } +} +impl PlayerStatEventT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + PlayerStatEvent::create(_fbb, &PlayerStatEventArgs{ + }) + } +} diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs new file mode 100644 index 00000000000..3c21e0803ba --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/possibly_reserved_words_generated.rs @@ -0,0 +1,233 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +// struct PossiblyReservedWords, aligned to 4 +#[repr(transparent)] +#[derive(Clone, Copy, PartialEq)] +pub struct PossiblyReservedWords(pub [u8; 16]); +impl Default for PossiblyReservedWords { + fn default() -> Self { + Self([0; 16]) + } +} +impl core::fmt::Debug for PossiblyReservedWords { + fn fmt(&self, f: &mut core::fmt::Formatter) -> core::fmt::Result { + f.debug_struct("PossiblyReservedWords") + .field("follow_", &self.follow_()) + .field("push_", &self.push_()) + .field("size", &self.size()) + .field("alignment", &self.alignment()) + .finish() + } +} + +impl flatbuffers::SimpleToVerifyInSlice for PossiblyReservedWords {} +impl<'a> flatbuffers::Follow<'a> for PossiblyReservedWords { + type Inner = &'a PossiblyReservedWords; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a PossiblyReservedWords>::follow(buf, loc) + } +} +impl<'a> flatbuffers::Follow<'a> for &'a PossiblyReservedWords { + type Inner = &'a PossiblyReservedWords; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } +} +impl<'b> flatbuffers::Push for PossiblyReservedWords { + type Output = PossiblyReservedWords; + #[inline] + unsafe fn push(&self, dst: &mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(self as *const PossiblyReservedWords as *const u8, ::size()); + dst.copy_from_slice(src); + } + #[inline] + fn alignment() -> flatbuffers::PushAlignment { + flatbuffers::PushAlignment::new(4) + } +} + +impl<'a> flatbuffers::Verifiable for PossiblyReservedWords { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.in_buffer::(pos) + } +} + +impl<'a> PossiblyReservedWords { + #[allow(clippy::too_many_arguments)] + pub fn new( + follow_: f32, + push_: f32, + size: f32, + alignment: f32, + ) -> Self { + let mut s = Self([0; 16]); + s.set_follow_(follow_); + s.set_push_(push_); + s.set_size(size); + s.set_alignment(alignment); + s + } + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.PossiblyReservedWords" + } + + pub fn follow_(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[0..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_follow_(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[0..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn push_(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[4..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_push_(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[4..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn size(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[8..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_size(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[8..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn alignment(&self) -> f32 { + let mut mem = core::mem::MaybeUninit::<::Scalar>::uninit(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + EndianScalar::from_little_endian(unsafe { + core::ptr::copy_nonoverlapping( + self.0[12..].as_ptr(), + mem.as_mut_ptr() as *mut u8, + core::mem::size_of::<::Scalar>(), + ); + mem.assume_init() + }) + } + + pub fn set_alignment(&mut self, x: f32) { + let x_le = x.to_little_endian(); + // Safety: + // Created from a valid Table for this object + // Which contains a valid value in this slot + unsafe { + core::ptr::copy_nonoverlapping( + &x_le as *const _ as *const u8, + self.0[12..].as_mut_ptr(), + core::mem::size_of::<::Scalar>(), + ); + } + } + + pub fn unpack(&self) -> PossiblyReservedWordsT { + PossiblyReservedWordsT { + follow_: self.follow_(), + push_: self.push_(), + size: self.size(), + alignment: self.alignment(), + } + } +} + +#[derive(Debug, Clone, PartialEq, Default)] +pub struct PossiblyReservedWordsT { + pub follow_: f32, + pub push_: f32, + pub size: f32, + pub alignment: f32, +} +impl PossiblyReservedWordsT { + pub fn pack(&self) -> PossiblyReservedWords { + PossiblyReservedWords::new( + self.follow_, + self.push_, + self.size, + self.alignment, + ) + } +} + diff --git a/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/root_table_generated.rs b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/root_table_generated.rs new file mode 100644 index 00000000000..d49ae92abba --- /dev/null +++ b/third_party/flatbuffers/tests/rust_namer_test/rust_namer_test/root_table_generated.rs @@ -0,0 +1,199 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// @generated +extern crate alloc; +extern crate flatbuffers; +use alloc::boxed::Box; +use alloc::string::{String, ToString}; +use alloc::vec::Vec; +use core::mem; +use core::cmp::Ordering; +use self::flatbuffers::{EndianScalar, Follow}; +use super::*; +pub enum RootTableOffset {} +#[derive(Copy, Clone, PartialEq)] + +pub struct RootTable<'a> { + pub _tab: flatbuffers::Table<'a>, +} + +impl<'a> flatbuffers::Follow<'a> for RootTable<'a> { + type Inner = RootTable<'a>; + #[inline] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + Self { _tab: flatbuffers::Table::new(buf, loc) } + } +} + +impl<'a> RootTable<'a> { + pub const VT_FIELD42_TYPE: flatbuffers::VOffsetT = 4; + pub const VT_FIELD42: flatbuffers::VOffsetT = 6; + + pub const fn get_fully_qualified_name() -> &'static str { + "RustNamerTest.RootTable" + } + + #[inline] + pub unsafe fn init_from_table(table: flatbuffers::Table<'a>) -> Self { + RootTable { _tab: table } + } + #[allow(unused_mut)] + pub fn create<'bldr: 'args, 'args: 'mut_bldr, 'mut_bldr, A: flatbuffers::Allocator + 'bldr>( + _fbb: &'mut_bldr mut flatbuffers::FlatBufferBuilder<'bldr, A>, + args: &'args RootTableArgs + ) -> flatbuffers::WIPOffset> { + let mut builder = RootTableBuilder::new(_fbb); + if let Some(x) = args.field42 { builder.add_field42(x); } + builder.add_field42_type(args.field42_type); + builder.finish() + } + + pub fn unpack(&self) -> RootTableT { + let field42 = match self.field42_type() { + FieldUnion::NONE => FieldUnionT::NONE, + FieldUnion::f => FieldUnionT::F(Box::new( + self.field42_as_f() + .expect("Invalid union table, expected `FieldUnion::f`.") + .unpack() + )), + _ => FieldUnionT::NONE, + }; + RootTableT { + field42, + } + } + + #[inline] + pub fn field42_type(&self) -> FieldUnion { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::(RootTable::VT_FIELD42_TYPE, Some(FieldUnion::NONE)).unwrap()} + } + #[inline] + pub fn field42(&self) -> Option> { + // Safety: + // Created from valid Table for this object + // which contains a valid value in this slot + unsafe { self._tab.get::>>(RootTable::VT_FIELD42, None)} + } + #[inline] + #[allow(non_snake_case)] + pub fn field42_as_f(&self) -> Option> { + if self.field42_type() == FieldUnion::f { + self.field42().map(|t| { + // Safety: + // Created from a valid Table for this object + // Which contains a valid union in this slot + unsafe { FieldTable::init_from_table(t) } + }) + } else { + None + } + } + +} + +impl flatbuffers::Verifiable for RootTable<'_> { + #[inline] + fn run_verifier( + v: &mut flatbuffers::Verifier, pos: usize + ) -> Result<(), flatbuffers::InvalidFlatbuffer> { + use self::flatbuffers::Verifiable; + v.visit_table(pos)? + .visit_union::("field42_type", Self::VT_FIELD42_TYPE, "field42", Self::VT_FIELD42, false, |key, v, pos| { + match key { + FieldUnion::f => v.verify_union_variant::>("FieldUnion::f", pos), + _ => Ok(()), + } + })? + .finish(); + Ok(()) + } +} +pub struct RootTableArgs { + pub field42_type: FieldUnion, + pub field42: Option>, +} +impl<'a> Default for RootTableArgs { + #[inline] + fn default() -> Self { + RootTableArgs { + field42_type: FieldUnion::NONE, + field42: None, + } + } +} + +pub struct RootTableBuilder<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> { + fbb_: &'b mut flatbuffers::FlatBufferBuilder<'a, A>, + start_: flatbuffers::WIPOffset, +} +impl<'a: 'b, 'b, A: flatbuffers::Allocator + 'a> RootTableBuilder<'a, 'b, A> { + #[inline] + pub fn add_field42_type(&mut self, field42_type: FieldUnion) { + self.fbb_.push_slot::(RootTable::VT_FIELD42_TYPE, field42_type, FieldUnion::NONE); + } + #[inline] + pub fn add_field42(&mut self, field42: flatbuffers::WIPOffset) { + self.fbb_.push_slot_always::>(RootTable::VT_FIELD42, field42); + } + #[inline] + pub fn new(_fbb: &'b mut flatbuffers::FlatBufferBuilder<'a, A>) -> RootTableBuilder<'a, 'b, A> { + let start = _fbb.start_table(); + RootTableBuilder { + fbb_: _fbb, + start_: start, + } + } + #[inline] + pub fn finish(self) -> flatbuffers::WIPOffset> { + let o = self.fbb_.end_table(self.start_); + flatbuffers::WIPOffset::new(o.value()) + } +} + +impl core::fmt::Debug for RootTable<'_> { + fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result { + let mut ds = f.debug_struct("RootTable"); + ds.field("field42_type", &self.field42_type()); + match self.field42_type() { + FieldUnion::f => { + if let Some(x) = self.field42_as_f() { + ds.field("field42", &x) + } else { + ds.field("field42", &"InvalidFlatbuffer: Union discriminant does not match value.") + } + }, + _ => { + let x: Option<()> = None; + ds.field("field42", &x) + }, + }; + ds.finish() + } +} +#[non_exhaustive] +#[derive(Debug, Clone, PartialEq)] +pub struct RootTableT { + pub field42: FieldUnionT, +} +impl Default for RootTableT { + fn default() -> Self { + Self { + field42: FieldUnionT::NONE, + } + } +} +impl RootTableT { + pub fn pack<'b, A: flatbuffers::Allocator + 'b>( + &self, + _fbb: &mut flatbuffers::FlatBufferBuilder<'b, A> + ) -> flatbuffers::WIPOffset> { + let field42_type = self.field42.field_union_type(); + let field42 = self.field42.pack(_fbb); + RootTable::create(_fbb, &RootTableArgs{ + field42_type, + field42, + }) + } +} diff --git a/third_party/flatbuffers/tests/rust_no_std_compilation_test/.cargo/config.toml b/third_party/flatbuffers/tests/rust_no_std_compilation_test/.cargo/config.toml new file mode 100644 index 00000000000..4fc6b9a91e2 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_no_std_compilation_test/.cargo/config.toml @@ -0,0 +1,5 @@ +[build] +target = "thumbv7m-none-eabi" + +[unstable] +build-std = ["core", "alloc"] diff --git a/third_party/flatbuffers/tests/rust_no_std_compilation_test/Cargo.toml b/third_party/flatbuffers/tests/rust_no_std_compilation_test/Cargo.toml new file mode 100644 index 00000000000..86e650a26d4 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_no_std_compilation_test/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "rust_test_no_std_compilation" +version = "0.1.0" +edition = "2021" + +[dependencies] +flatbuffers = { path = "../../rust/flatbuffers", default-features = false } + +[profile.dev] +panic = "abort" + +[profile.release] +panic = "abort" diff --git a/third_party/flatbuffers/tests/rust_no_std_compilation_test/src/main.rs b/third_party/flatbuffers/tests/rust_no_std_compilation_test/src/main.rs new file mode 100644 index 00000000000..0430599dbe8 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_no_std_compilation_test/src/main.rs @@ -0,0 +1,34 @@ +#![no_std] +#![no_main] +#![feature(default_alloc_error_handler)] + +// Include flatbuffers purely to check that it compiles in a no_std binary +#[allow(unused_imports)] +use flatbuffers; + +// The rest is just no_std boilerplate + +use core::alloc::{GlobalAlloc, Layout}; + +struct NullAllocator; +unsafe impl GlobalAlloc for NullAllocator { + unsafe fn alloc(&self, _lt: Layout) -> *mut u8 { + core::ptr::null_mut() + } + unsafe fn dealloc(&self, _ptr: *mut u8, _lt: Layout) { + panic!("won't deallocate: we never allocated!"); + } +} + +#[global_allocator] +static A: NullAllocator = NullAllocator; + +#[panic_handler] +fn panic(_info: &core::panic::PanicInfo) -> ! { + loop {} +} + +#[no_mangle] +pub extern "C" fn main(_argc: i32, _argv: *const *const u8) -> i32 { + 0 +} diff --git a/third_party/flatbuffers/tests/rust_reflection_test/.gitignore b/third_party/flatbuffers/tests/rust_reflection_test/.gitignore new file mode 100644 index 00000000000..96ef6c0b944 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_reflection_test/.gitignore @@ -0,0 +1,2 @@ +/target +Cargo.lock diff --git a/third_party/flatbuffers/tests/rust_reflection_test/Cargo.toml b/third_party/flatbuffers/tests/rust_reflection_test/Cargo.toml new file mode 100644 index 00000000000..1e5328e126e --- /dev/null +++ b/third_party/flatbuffers/tests/rust_reflection_test/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "rust_reflection_test" +version = "0.1.0" +edition = "2018" + +[dependencies] +flatbuffers-reflection = { path = "../../rust/reflection" } +flatbuffers = { path = "../../rust/flatbuffers" } +assert_approx_eq = "1.1.0" diff --git a/third_party/flatbuffers/tests/rust_reflection_test/src/lib.rs b/third_party/flatbuffers/tests/rust_reflection_test/src/lib.rs new file mode 100644 index 00000000000..f403e0d9808 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_reflection_test/src/lib.rs @@ -0,0 +1,2136 @@ +use flatbuffers_reflection::reflection::{root_as_schema, BaseType, Field}; +use flatbuffers_reflection::{ + get_any_field_float, get_any_field_float_in_struct, get_any_field_integer, + get_any_field_integer_in_struct, get_any_field_string, get_any_field_string_in_struct, + get_any_root, get_field_float, get_field_integer, get_field_string, get_field_struct, + get_field_struct_in_struct, get_field_table, get_field_vector, set_any_field_float, + set_any_field_integer, set_any_field_string, set_field, set_string, FlatbufferError, +}; +use flatbuffers_reflection::{SafeBuffer, Struct}; + +use flatbuffers::{FlatBufferBuilder, Table, VerifierOptions}; + +use std::error::Error; +use std::fs::File; +use std::io::Read; + +use assert_approx_eq::assert_approx_eq; + +#[allow(dead_code, unused_imports)] +#[path = "../../monster_test/mod.rs"] +mod monster_test_generated; +pub use monster_test_generated::my_game; + +#[test] +fn test_schema_correct_root_table() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + + let root_table = schema.root_table().unwrap(); + + assert_eq!(root_table.name(), "MyGame.Example.Monster"); + assert_eq!(root_table.declaration_file().unwrap(), "//monster_test.fbs"); +} + +#[test] +fn test_schema_correct_object() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + + assert_eq!( + schema + .objects() + .lookup_by_key("TableA", |object, key| object.key_compare_with_value(key)) + .unwrap() + .declaration_file() + .unwrap(), + "//include_test/include_test1.fbs" + ); + assert_eq!( + schema + .objects() + .lookup_by_key("MyGame.OtherNameSpace.Unused", |object, key| object + .key_compare_with_value(key)) + .unwrap() + .declaration_file() + .unwrap(), + "//include_test/sub/include_test2.fbs" + ); +} + +#[test] +fn test_schema_correct_enum() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + + assert_eq!( + schema + .enums() + .lookup_by_key("MyGame.OtherNameSpace.FromInclude", |en, key| en + .key_compare_with_value(key)) + .unwrap() + .declaration_file() + .unwrap(), + "//include_test/sub/include_test2.fbs" + ); +} + +#[test] +fn test_schema_correct_file() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + + assert_eq!(schema.fbs_files().unwrap().len(), 3); + + let fbs0 = schema.fbs_files().unwrap().get(0); + assert_eq!(fbs0.filename(), "//include_test/include_test1.fbs"); + let fbs0_includes = fbs0.included_filenames().unwrap(); + assert_eq!(fbs0_includes.len(), 2); + assert_eq!(fbs0_includes.get(0), "//include_test/include_test1.fbs"); + assert_eq!(fbs0_includes.get(1), "//include_test/sub/include_test2.fbs"); + + let fbs1 = schema.fbs_files().unwrap().get(1); + assert_eq!(fbs1.filename(), "//include_test/sub/include_test2.fbs"); + let fbs1_includes = fbs1.included_filenames().unwrap(); + assert_eq!(fbs1_includes.len(), 2); + assert_eq!(fbs1_includes.get(0), "//include_test/include_test1.fbs"); + assert_eq!(fbs1_includes.get(1), "//include_test/sub/include_test2.fbs"); + + let fbs2 = schema.fbs_files().unwrap().get(2); + assert_eq!(fbs2.filename(), "//monster_test.fbs"); + let fbs2_includes = fbs2.included_filenames().unwrap(); + assert_eq!(fbs2_includes.len(), 1); + assert_eq!(fbs2_includes.get(0), "//include_test/include_test1.fbs"); +} + +#[test] +fn test_schema_correct_table_field() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let root_table = root_as_schema(schema_buffer.as_slice()) + .unwrap() + .root_table() + .unwrap(); + + let fields = root_table.fields(); + + let hp_field_option = + fields.lookup_by_key("hp", |field, key| field.key_compare_with_value(key)); + assert!(hp_field_option.is_some()); + let hp_field = hp_field_option.unwrap(); + assert_eq!(hp_field.name(), "hp"); + assert_eq!(hp_field.id(), 2); + assert_eq!(hp_field.type_().base_type(), BaseType::Short); + + let friendly_field_option = + fields.lookup_by_key("friendly", |field, key| field.key_compare_with_value(key)); + assert!(friendly_field_option.is_some()); + assert!(friendly_field_option.unwrap().attributes().is_some()); + assert!(friendly_field_option + .unwrap() + .attributes() + .unwrap() + .lookup_by_key("priority", |key_value, key| key_value + .key_compare_with_value(key)) + .is_some()); +} + +#[test] +fn test_schema_correct_table_field_nullability() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let root_table = root_as_schema(schema_buffer.as_slice()) + .unwrap() + .root_table() + .unwrap(); + + let fields = root_table.fields(); + + assert_eq!( + fields + .lookup_by_key("hp", |field, key| field.key_compare_with_value(key)) + .unwrap() + .optional(), + false + ); + assert_eq!( + fields + .lookup_by_key("pos", |field, key| field.key_compare_with_value(key)) + .unwrap() + .optional(), + true + ); + assert_eq!( + fields + .lookup_by_key("name", |field, key| field.key_compare_with_value(key)) + .unwrap() + .optional(), + false + ); +} + +#[test] +fn test_schema_correct_child_table_index() { + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let root_table = schema.root_table().unwrap(); + + let fields = root_table.fields(); + + let pos_field_option = + fields.lookup_by_key("pos", |field, key| field.key_compare_with_value(key)); + assert!(pos_field_option.is_some()); + let pos_field = pos_field_option.unwrap(); + assert_eq!(pos_field.type_().base_type(), BaseType::Obj); + let pos_table = schema.objects().get(pos_field.type_().index() as usize); + assert_eq!(pos_table.name(), "MyGame.Example.Vec3"); +} + +#[test] +fn test_buffer_integer_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let value = unsafe { get_field_integer::(&root_table, &i16_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some(32767)); +} + +#[test] +fn test_buffer_integer_diff_type_same_size_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let value = unsafe { get_field_integer::(&root_table, &i16_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some(32767)); +} + +#[test] +fn test_buffer_integer_diff_size_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let value = unsafe { get_field_integer::(&root_table, &i16_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("Short")) + ); +} + +#[test] +fn test_buffer_float_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_field_float::(&root_table, &f32_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some(3.14)); +} + +#[test] +fn test_buffer_float_diff_type_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_field_float::(&root_table, &f32_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_string_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let value = unsafe { get_field_string(&root_table, &string_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some("MyMonster")); +} + +#[test] +fn test_buffer_string_diff_type_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_field_string(&root_table, &f32_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("String"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_struct_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + + let res = unsafe { get_field_struct(&root_table, &struct_field) }; + + assert!(res.is_ok()); + let optional_value = res.unwrap(); + assert!(optional_value.is_some()); + assert_eq!(optional_value.unwrap().buf(), &buffer); + assert!(optional_value.unwrap().loc() > root_table.loc()); +} + +#[test] +fn test_buffer_struct_diff_type_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { get_field_struct(&root_table, &f32_field) }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("Obj"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_vector_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let vector_field = get_schema_field(&schema, "inventory"); + + let value = unsafe { get_field_vector::(&root_table, &vector_field) }; + + assert!(value.is_ok()); + let optional_vector = value.unwrap(); + assert!(optional_vector.is_some()); + let vector = optional_vector.unwrap(); + assert_eq!(vector.len(), 5); + assert_eq!(vector.get(0), 0); + assert_eq!(vector.get(1), 1); + assert_eq!(vector.get(2), 2); + assert_eq!(vector.get(3), 3); + assert_eq!(vector.get(4), 4); +} + +#[test] +fn test_buffer_vector_diff_type_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_field_vector::(&root_table, &f32_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("u8"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_table_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let table_field = get_schema_field(&schema, "testempty"); + + let value = unsafe { get_field_table(&root_table, &table_field) }; + + assert!(value.is_ok()); + let optional_nested_table = value.unwrap(); + assert!(optional_nested_table.is_some()); + let nested_table = optional_nested_table.unwrap(); + let nested_table_fields = &root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(table_field.type_().index() as usize) + .fields(); + let nested_table_field = nested_table_fields + .lookup_by_key("id", |field: &Field<'_>, key| { + field.key_compare_with_value(key) + }) + .unwrap(); + let nested_table_id = unsafe { get_field_string(&nested_table, &nested_table_field) }; + assert!(nested_table_id.is_ok()); + assert_eq!(nested_table_id.unwrap(), Some("Fred")); +} + +#[test] +fn test_buffer_table_diff_type_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_field_table(&root_table, &f32_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("Obj"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_nested_struct_same_type_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let nested_struct_field = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let res = unsafe { get_field_struct_in_struct(&struct_value, &nested_struct_field) }; + + assert!(res.is_ok()); + let value = res.unwrap(); + assert_eq!(value.buf(), &buffer); + assert!(value.loc() > struct_value.loc()); +} + +#[test] +fn test_buffer_nested_struct_diff_type_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let nested_float_field = struct_schema + .fields() + .lookup_by_key("x", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let res = unsafe { get_field_struct_in_struct(&struct_value, &nested_float_field) }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("Obj"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_i16_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let value = unsafe { get_any_field_integer(&root_table, &i16_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 32767); +} + +#[test] +fn test_buffer_f32_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_any_field_integer(&root_table, &f32_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 3); +} + +#[test] +fn test_buffer_inf_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let inf_field = get_schema_field(&schema, "inf_default"); + + let value = unsafe { get_any_field_integer(&root_table, &inf_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 0); +} + +#[test] +fn test_buffer_bool_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let bool_field = get_schema_field(&schema, "testbool"); + + let value = unsafe { get_any_field_integer(&root_table, &bool_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 0); +} + +#[test] +fn test_buffer_nan_as_integer_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let nan_field = get_schema_field(&schema, "nan_default"); + + let value = unsafe { get_any_field_integer(&root_table, &nan_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_string_as_integer_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let value = unsafe { get_any_field_integer(&root_table, &string_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("String")) + ); +} + +#[test] +fn test_buffer_i16_as_float_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let value = unsafe { get_any_field_float(&root_table, &i16_field) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 32767f64); +} + +#[test] +fn test_buffer_f32_as_float_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let value = unsafe { get_any_field_float(&root_table, &f32_field) }; + + assert!(value.is_ok()); + assert_approx_eq!(value.unwrap(), 3.14); +} + +#[test] +fn test_buffer_string_as_float_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let value = unsafe { get_any_field_float(&root_table, &string_field) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("String")) + ); +} + +#[test] +fn test_buffer_i16_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let value = unsafe { + get_any_field_string( + &root_table, + &i16_field, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert_eq!(value, String::from("32767")); +} + +#[test] +fn test_buffer_f32_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let mut value = unsafe { + get_any_field_string( + &root_table, + &f32_field, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + value.truncate(4); + assert_eq!(value, String::from("3.14")); +} + +#[test] +fn test_buffer_string_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let value = unsafe { + get_any_field_string( + &root_table, + &string_field, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert_eq!(value, "MyMonster"); +} + +#[test] +fn test_buffer_i16_in_struct_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let nested_struct_field = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + let nested_struct_value = + unsafe { get_field_struct_in_struct(&struct_value, &nested_struct_field).unwrap() }; + let nested_struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(nested_struct_field.type_().index() as usize); + let i16_in_struct = nested_struct_schema + .fields() + .lookup_by_key("a", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_integer_in_struct(&nested_struct_value, &i16_in_struct) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 5); +} + +#[test] +fn test_buffer_f32_in_struct_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let f32_in_struct = struct_schema + .fields() + .lookup_by_key("x", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_integer_in_struct(&struct_value, &f32_in_struct) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 1); +} + +#[test] +fn test_buffer_enum_in_struct_as_integer_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let enum_in_struct = struct_schema + .fields() + .lookup_by_key("test2", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_integer_in_struct(&struct_value, &enum_in_struct) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 2); +} + +#[test] +fn test_buffer_struct_in_struct_as_integer_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let struct_in_struct = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_integer_in_struct(&struct_value, &struct_in_struct) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("Obj")) + ); +} + +#[test] +fn test_buffer_i16_in_struct_as_float_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let nested_struct_field = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + let nested_struct_value = + unsafe { get_field_struct_in_struct(&struct_value, &nested_struct_field).unwrap() }; + let nested_struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(nested_struct_field.type_().index() as usize); + let i16_in_struct = nested_struct_schema + .fields() + .lookup_by_key("a", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_float_in_struct(&nested_struct_value, &i16_in_struct) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 5f64); +} + +#[test] +fn test_buffer_f32_in_struct_as_float_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let f32_in_struct = struct_schema + .fields() + .lookup_by_key("x", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_float_in_struct(&struct_value, &f32_in_struct) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 1f64); +} + +#[test] +fn test_buffer_enum_in_struct_as_float_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let enum_in_struct = struct_schema + .fields() + .lookup_by_key("test2", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_float_in_struct(&struct_value, &enum_in_struct) }; + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 2f64); +} + +#[test] +fn test_buffer_struct_in_struct_as_float_fails() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let struct_in_struct = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { get_any_field_float_in_struct(&struct_value, &struct_in_struct) }; + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("Obj")) + ); +} + +#[test] +fn test_buffer_i16_in_struct_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let nested_struct_field = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + let nested_struct_value = + unsafe { get_field_struct_in_struct(&struct_value, &nested_struct_field).unwrap() }; + let nested_struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(nested_struct_field.type_().index() as usize); + let i16_in_struct = nested_struct_schema + .fields() + .lookup_by_key("a", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { + get_any_field_string_in_struct( + &nested_struct_value, + &i16_in_struct, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert_eq!(value, String::from("5")); +} + +#[test] +fn test_buffer_f32_in_struct_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let f32_in_struct = struct_schema + .fields() + .lookup_by_key("x", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { + get_any_field_string_in_struct( + &struct_value, + &f32_in_struct, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert_eq!(value, String::from("1")); +} + +#[test] +fn test_buffer_enum_in_struct_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let enum_in_struct = struct_schema + .fields() + .lookup_by_key("test2", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { + get_any_field_string_in_struct( + &struct_value, + &enum_in_struct, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert_eq!(value, String::from("2")); +} + +#[test] +fn test_buffer_struct_in_struct_as_string_succeeds() { + let buffer = create_test_buffer(); + let root_table = unsafe { get_any_root(&buffer) }; + let schema = load_file_as_buffer("../monster_test.bfbs"); + let struct_field = get_schema_field(&schema, "pos"); + let struct_value = unsafe { + get_field_struct(&root_table, &struct_field) + .unwrap() + .unwrap() + }; + let struct_schema = root_as_schema(schema.as_slice()) + .unwrap() + .objects() + .get(struct_field.type_().index() as usize); + let struct_in_struct = struct_schema + .fields() + .lookup_by_key("test3", |field, key| field.key_compare_with_value(key)) + .unwrap(); + + let value = unsafe { + get_any_field_string_in_struct( + &struct_value, + &struct_in_struct, + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert_eq!(value, String::from("MyGame.Example.Test { a: 5, b: 6, }")); +} + +#[test] +fn test_buffer_set_valid_int_to_i16_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let res = unsafe { set_any_field_integer(&mut buffer, table_loc, &i16_field, 111) }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_integer::(&updated_table, &i16_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some(111)); +} + +#[test] +fn test_buffer_set_integer_to_f32_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_any_field_integer(&mut buffer, table_loc, &f32_field, 111) }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_float::(&updated_table, &f32_field) }; + assert!(updated_value.is_ok()); + assert_approx_eq!(updated_value.unwrap().unwrap(), 111f32); +} + +#[test] +fn test_buffer_set_overflow_to_i16_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let res = unsafe { set_any_field_integer(&mut buffer, table_loc, &i16_field, 32768) }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("Short")) + ); +} + +#[test] +fn test_buffer_set_integer_to_string_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { set_any_field_integer(&mut buffer, table_loc, &string_field, 1) }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_integer_to_unset_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let unset_field = get_schema_field(&schema, "testf3"); + + let res = unsafe { set_any_field_integer(&mut buffer, table_loc, &unset_field, 1) }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_valid_float_to_f32_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_any_field_float(&mut buffer, table_loc, &f32_field, 111.11) }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_float::(&updated_table, &f32_field) }; + assert!(updated_value.is_ok()); + assert_approx_eq!(updated_value.unwrap().unwrap(), 111.11); +} + +#[test] +fn test_buffer_set_float_to_i16_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let res = unsafe { set_any_field_float(&mut buffer, table_loc, &i16_field, 111.11) }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_integer::(&updated_table, &i16_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some(111)); +} + +#[test] +fn test_buffer_set_overflow_to_f32_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_any_field_float(&mut buffer, table_loc, &f32_field, f64::MAX) }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_set_float_to_string_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { set_any_field_float(&mut buffer, table_loc, &string_field, 1.1) }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_float_to_unset_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let unset_field = get_schema_field(&schema, "testf3"); + + let res = unsafe { set_any_field_float(&mut buffer, table_loc, &unset_field, 1.1) }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_float_str_to_f32_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_any_field_string(&mut buffer, table_loc, &f32_field, "111.11") }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_float::(&updated_table, &f32_field) }; + assert!(updated_value.is_ok()); + assert_approx_eq!(updated_value.unwrap().unwrap(), 111.11); +} + +#[test] +fn test_buffer_set_int_str_to_i16_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let res = unsafe { set_any_field_string(&mut buffer, table_loc, &i16_field, "111") }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_integer::(&updated_table, &i16_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some(111)); +} + +#[test] +fn test_buffer_set_non_num_str_to_f32_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_any_field_string(&mut buffer, table_loc, &f32_field, "any") }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err().to_string(), "invalid float literal"); +} + +#[test] +fn test_buffer_set_int_str_to_string_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { set_any_field_string(&mut buffer, table_loc, &string_field, "1") }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_int_str_to_unset_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let unset_field = get_schema_field(&schema, "testf3"); + + let res = unsafe { set_any_field_string(&mut buffer, table_loc, &unset_field, "1") }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_i16_to_i16_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let res = unsafe { set_field::(&mut buffer, table_loc, &i16_field, 111) }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_integer::(&updated_table, &i16_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some(111)); +} + +#[test] +fn test_buffer_set_i32_to_i16_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let i16_field = get_schema_field(&schema, "hp"); + + let res = unsafe { set_field::(&mut buffer, table_loc, &i16_field, 111) }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i32"), String::from("Short")) + ); +} + +#[test] +fn test_buffer_set_f32_to_f32_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_field::(&mut buffer, table_loc, &f32_field, 111.11) }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_float::(&updated_table, &f32_field) }; + assert!(updated_value.is_ok()); + assert_approx_eq!(updated_value.unwrap().unwrap(), 111.11); +} + +#[test] +fn test_buffer_set_f64_to_f32_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { set_field::(&mut buffer, table_loc, &f32_field, 111.11) }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("Float")) + ); +} + +#[test] +fn test_buffer_set_f32_to_f32_unset_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let unset_field = get_schema_field(&schema, "testf3"); + + let res = unsafe { set_field::(&mut buffer, table_loc, &unset_field, 111.11) }; + + assert!(res.is_err()); + assert_eq!(res.unwrap_err(), FlatbufferError::SetValueNotSupported); +} + +#[test] +fn test_buffer_set_string_same_str_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { + set_string( + &mut buffer, + table_loc, + &string_field, + "MyMonster", + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_string(&updated_table, &string_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some("MyMonster")); +} + +#[test] +fn test_buffer_set_string_same_size_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { + set_string( + &mut buffer, + table_loc, + &string_field, + "YoMonster", + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_string(&updated_table, &string_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some("YoMonster")); +} + +#[test] +fn test_buffer_set_string_bigger_size_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { + set_string( + &mut buffer, + table_loc, + &string_field, + "AStringWithSlightlyBiggerSize", + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_string(&updated_table, &string_field) }; + assert!(updated_value.is_ok()); + assert_eq!( + updated_value.unwrap(), + Some("AStringWithSlightlyBiggerSize") + ); +} + +#[test] +fn test_buffer_set_string_smaller_size_succeeds() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let string_field = get_schema_field(&schema, "name"); + + let res = unsafe { + set_string( + &mut buffer, + table_loc, + &string_field, + "s", + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert!(res.is_ok()); + let updated_table = unsafe { get_any_root(&buffer) }; + let updated_value = unsafe { get_field_string(&updated_table, &string_field) }; + assert!(updated_value.is_ok()); + assert_eq!(updated_value.unwrap(), Some("s")); +} + +#[test] +fn test_buffer_set_string_diff_type_fails() { + let mut buffer = create_test_buffer(); + let table_loc = unsafe { get_any_root(&buffer) }.loc(); + let schema = load_file_as_buffer("../monster_test.bfbs"); + let f32_field = get_schema_field(&schema, "testf"); + + let res = unsafe { + set_string( + &mut buffer, + table_loc, + &f32_field, + "any", + &root_as_schema(schema.as_slice()).unwrap(), + ) + }; + + assert!(res.is_err()); + assert_eq!( + res.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("String"), String::from("Float")) + ); +} + +#[test] +fn test_create_safe_buffer_default_options_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + + let safe_buffer = SafeBuffer::new(&buffer, &schema); + + assert!(safe_buffer.is_ok()); +} + +#[test] +fn test_create_safe_buffer_limit_max_depth_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let verify_options = VerifierOptions { + max_depth: 1, + ..Default::default() + }; + + let safe_buffer = SafeBuffer::new_with_options(&buffer, &schema, &verify_options); + + assert!(safe_buffer.is_err()); + assert!(format!("{:#?}", safe_buffer.err().unwrap()).contains("DepthLimitReached")); +} + +#[test] +fn test_create_safe_buffer_limit_max_table_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let verify_options = VerifierOptions { + max_tables: 1, + ..Default::default() + }; + + let safe_buffer = SafeBuffer::new_with_options(&buffer, &schema, &verify_options); + + assert!(safe_buffer.is_err()); + assert!(format!("{:#?}", safe_buffer.err().unwrap()).contains("TooManyTables")); +} + +#[test] +fn test_create_safe_buffer_limit_max_size_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let verify_options = VerifierOptions { + max_apparent_size: 1 << 6, + ..Default::default() + }; + + let safe_buffer = SafeBuffer::new_with_options(&buffer, &schema, &verify_options); + + assert!(safe_buffer.is_err()); + assert!(format!("{:#?}", safe_buffer.err().unwrap()).contains("ApparentSizeTooLarge")); +} + +#[test] +fn test_safe_buffer_integer_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_integer::("hp"); + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some(32767)); +} + +#[test] +fn test_safe_buffer_integer_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_integer::("nonexistent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_integer_diff_size_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_integer::("hp"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("Short")) + ); +} + +#[test] +fn test_safe_buffer_float_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_float::("testf"); + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some(3.14)); +} + +#[test] +fn test_safe_buffer_float_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_float::("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_float_diff_type_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_float::("testf"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("Float")) + ); +} + +#[test] +fn test_safe_buffer_string_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_string("name"); + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), Some("MyMonster")); +} + +#[test] +fn test_safe_buffer_string_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_string("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_string_diff_type_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_string("testf"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("String"), String::from("Float")) + ); +} + +#[test] +fn test_safe_buffer_struct_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_struct("pos"); + + assert!(value.is_ok()); + let optional_value = value.unwrap(); + assert!(optional_value.is_some()); + let safe_struct = optional_value.unwrap(); + assert!(safe_struct.get_field_struct("test3").is_ok()); +} + +#[test] +fn test_safe_buffer_struct_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_struct("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_struct_diff_type_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_struct("testf"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("Obj"), String::from("Float")) + ); +} + +#[test] +fn test_safe_buffer_vector_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_vector::("inventory"); + + assert!(value.is_ok()); + let optional_vector = value.unwrap(); + assert!(optional_vector.is_some()); + let vector = optional_vector.unwrap(); + assert_eq!(vector.len(), 5); + assert_eq!(vector.get(0), 0); + assert_eq!(vector.get(1), 1); + assert_eq!(vector.get(2), 2); + assert_eq!(vector.get(3), 3); + assert_eq!(vector.get(4), 4); +} + +#[test] +fn test_safe_buffer_vector_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_vector::("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_vector_diff_type_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_vector::("testf"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("u8"), String::from("Float")) + ); +} + +#[test] +fn test_safe_buffer_table_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_table("testempty"); + + assert!(value.is_ok()); + let optional_nested_table = value.unwrap(); + assert!(optional_nested_table.is_some()); + let nested_table = optional_nested_table.unwrap(); + let nested_field_value = nested_table.get_field_string("id"); + + assert!(nested_field_value.is_ok()); + assert_eq!(nested_field_value.unwrap(), Some("Fred")); +} + +#[test] +fn test_safe_buffer_table_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_table("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_table_diff_type_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_field_table("testf"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("Obj"), String::from("Float")) + ); +} + +#[test] +fn test_safe_buffer_i16_as_integer_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_integer("hp"); + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 32767); +} + +#[test] +fn test_safe_buffer_i16_as_integer_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_integer("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_string_as_integer_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_integer("name"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("String")) + ); +} + +#[test] +fn test_safe_buffer_i16_as_float_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_float("hp"); + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), 32767f64); +} + +#[test] +fn test_safe_buffer_i16_as_float_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_float("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_string_as_float_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_float("name"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("String")) + ); +} + +#[test] +fn test_safe_buffer_string_as_string_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_string("name"); + + assert!(value.is_ok()); + assert_eq!(value.unwrap(), "MyMonster"); +} + +#[test] +fn test_safe_buffer_i16_as_string_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + + let value = root_table.get_any_field_string("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_nested_struct_same_type_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let nested_struct_value = struct_value.get_field_struct("test3"); + + assert!(nested_struct_value.is_ok()); + let value = nested_struct_value.unwrap(); + assert!(value.get_any_field_integer("a").is_ok()); +} + +#[test] +fn test_safe_buffer_nested_struct_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let value = struct_value.get_field_struct("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_nested_struct_diff_type_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let nested_struct_value = struct_value.get_field_struct("x"); + + assert!(nested_struct_value.is_err()); + assert_eq!( + nested_struct_value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("Obj"), String::from("Float")) + ); +} + +#[test] +fn test_safe_buffer_enum_in_struct_as_integer_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let nested_enum_value = struct_value.get_any_field_integer("test2"); + + assert!(nested_enum_value.is_ok()); + assert_eq!(nested_enum_value.unwrap(), 2); +} + +#[test] +fn test_safe_buffer_enum_in_struct_as_integer_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let value = struct_value.get_any_field_integer("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_struct_in_struct_as_integer_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let nested_struct_value = struct_value.get_any_field_integer("test3"); + + assert!(nested_struct_value.is_err()); + assert_eq!( + nested_struct_value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("i64"), String::from("Obj")) + ); +} + +#[test] +fn test_safe_buffer_i16_in_struct_as_float_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + let nested_struct_value = struct_value.get_field_struct("test3").unwrap(); + + let nested_i16_value = nested_struct_value.get_any_field_float("a"); + + assert!(nested_i16_value.is_ok()); + assert_eq!(nested_i16_value.unwrap(), 5f64); +} + +#[test] +fn test_safe_buffer_child_in_struct_as_float_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let value = struct_value.get_any_field_float("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +#[test] +fn test_safe_buffer_struct_in_struct_as_float_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let value = struct_value.get_any_field_float("test3"); + + assert!(value.is_err()); + assert_eq!( + value.unwrap_err(), + FlatbufferError::FieldTypeMismatch(String::from("f64"), String::from("Obj")) + ); +} + +#[test] +fn test_safe_buffer_f32_in_struct_as_string_succeeds() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let nested_f32_value = struct_value.get_any_field_string("x"); + + assert!(nested_f32_value.is_ok()); + assert_eq!(nested_f32_value.unwrap(), String::from("1")); +} + +#[test] +fn test_safe_buffer_child_in_struct_as_string_invalid_field_fails() { + let buffer = create_test_buffer(); + let schema_buffer = load_file_as_buffer("../monster_test.bfbs"); + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let safe_buffer = SafeBuffer::new(&buffer, &schema).unwrap(); + let root_table = safe_buffer.get_root(); + let struct_value = root_table.get_field_struct("pos").unwrap().unwrap(); + + let value = struct_value.get_any_field_string("non_existent"); + + assert!(value.is_err()); + assert_eq!(value.unwrap_err(), FlatbufferError::FieldNotFound); +} + +fn load_file_as_buffer(path: &str) -> Vec { + std::fs::read(path).unwrap() +} + +fn get_schema_field<'a>(schema_buffer: &'a Vec, field_name: &'a str) -> Field<'a> { + let schema = root_as_schema(schema_buffer.as_slice()).unwrap(); + let root_table = schema.root_table().unwrap(); + let fields = root_table.fields(); + fields + .lookup_by_key(field_name, |field, key| field.key_compare_with_value(key)) + .unwrap() +} + +fn create_test_buffer() -> Vec { + let mut builder = FlatBufferBuilder::new(); + let mon = { + let s0 = builder.create_string("test1"); + let s1 = builder.create_string("test2"); + let fred_name = builder.create_string("Fred"); + + // can't inline creation of this Vec3 because we refer to it by reference, so it must live + // long enough to be used by MonsterArgs. + let pos = my_game::example::Vec3::new( + 1.0, + 2.0, + 3.0, + 3.0, + my_game::example::Color::Green, + &my_game::example::Test::new(5i16, 6i8), + ); + + let args = my_game::example::MonsterArgs { + hp: 32767, + testf: 3.14, + mana: 150, + name: Some(builder.create_string("MyMonster")), + pos: Some(&pos), + test_type: my_game::example::Any::Monster, + testempty: Some(my_game::example::Stat::create( + &mut builder, + &my_game::example::StatArgs { + id: Some(fred_name), + ..Default::default() + }, + )), + test: Some( + my_game::example::Monster::create( + &mut builder, + &my_game::example::MonsterArgs { + name: Some(fred_name), + ..Default::default() + }, + ) + .as_union_value(), + ), + inventory: Some(builder.create_vector(&[0u8, 1, 2, 3, 4])), + test4: Some(builder.create_vector(&[ + my_game::example::Test::new(10, 20), + my_game::example::Test::new(30, 40), + ])), + testarrayofstring: Some(builder.create_vector(&[s0, s1])), + ..Default::default() + }; + my_game::example::Monster::create(&mut builder, &args) + }; + my_game::example::finish_monster_buffer(&mut builder, mon); + let (flatbuf, start_loc) = builder.mut_finished_buffer(); + flatbuf[start_loc..].to_vec() +} diff --git a/third_party/flatbuffers/tests/rust_serialize_test/Cargo.toml b/third_party/flatbuffers/tests/rust_serialize_test/Cargo.toml new file mode 100644 index 00000000000..ff47c123e02 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_serialize_test/Cargo.toml @@ -0,0 +1,12 @@ +[package] +name = "rust_serialize_test" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +flatbuffers = { path = "../../rust/flatbuffers", features=["serialize"] } +serde = "1.0" +serde_json = "1.0" + diff --git a/third_party/flatbuffers/tests/rust_serialize_test/src/main.rs b/third_party/flatbuffers/tests/rust_serialize_test/src/main.rs new file mode 100644 index 00000000000..e6bdce6fb11 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_serialize_test/src/main.rs @@ -0,0 +1,89 @@ +#[allow(dead_code, unused_imports)] +#[path = "../../monster_test_serialize/mod.rs"] +mod monster_test_serialize_generated; +pub use monster_test_serialize_generated::my_game; + +fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) { + let mon = { + let s0 = builder.create_string("test1"); + let s1 = builder.create_string("test2"); + let fred_name = builder.create_string("Fred"); + + // can't inline creation of this Vec3 because we refer to it by reference, so it must live + // long enough to be used by MonsterArgs. + let pos = my_game::example::Vec3::new( + 1.0, + 2.0, + 3.0, + 3.0, + my_game::example::Color::Green, + &my_game::example::Test::new(5i16, 6i8), + ); + + let args = my_game::example::MonsterArgs { + hp: 80, + mana: 150, + name: Some(builder.create_string("MyMonster")), + pos: Some(&pos), + test_type: my_game::example::Any::Monster, + test: Some( + my_game::example::Monster::create( + builder, + &my_game::example::MonsterArgs { + name: Some(fred_name), + ..Default::default() + }, + ) + .as_union_value(), + ), + inventory: Some(builder.create_vector(&[0u8, 1, 2, 3, 4])), + test4: Some(builder.create_vector(&[ + my_game::example::Test::new(10, 20), + my_game::example::Test::new(30, 40), + ])), + testarrayofstring: Some(builder.create_vector(&[s0, s1])), + ..Default::default() + }; + my_game::example::Monster::create(builder, &args) + }; + my_game::example::finish_monster_buffer(builder, mon); +} + +fn main() { + // This test is built into its own crate because it has a different set of + // dependencies as the normal Rust tests; it requires that the `flatbuffer` + // dependency have the "serialize" feature enabled. As this feature may + // cause extra code gen and dependencies for those who do not need it, it + // is disabled by default. + let mut builder = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(&mut builder); + + let data = builder.finished_data(); + let obj = my_game::example::root_as_monster(&data[..]).unwrap(); + let value = serde_json::to_value(&obj).unwrap(); + let o = value.as_object().unwrap(); + + let pos = o.get("pos").unwrap().as_object().unwrap(); + assert_eq!(pos.get("x").unwrap().as_f64().unwrap(), 1.0); + assert_eq!(pos.get("y").unwrap().as_f64().unwrap(), 2.0); + assert_eq!(pos.get("z").unwrap().as_f64().unwrap(), 3.0); + + let mana = o.get("mana").unwrap(); + assert_eq!(mana.as_i64().unwrap(), 150); + + let hp = o.get("hp").unwrap(); + assert_eq!(hp.as_i64().unwrap(), 80); + + let name = o.get("name").unwrap(); + assert_eq!(name.as_str().unwrap(), "MyMonster"); + + let test_type = o.get("test_type").unwrap(); + assert_eq!(test_type.as_str().unwrap(), "Monster"); + + let testarrayofstring = o.get("testarrayofstring").unwrap().as_array().unwrap(); + let t0 = testarrayofstring[0].as_str().unwrap(); + assert_eq!(t0, "test1"); + + let t1 = testarrayofstring[1].as_str().unwrap(); + assert_eq!(t1, "test2"); +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/Cargo.toml b/third_party/flatbuffers/tests/rust_usage_test/Cargo.toml new file mode 100644 index 00000000000..5b7152b9c59 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/Cargo.toml @@ -0,0 +1,58 @@ +[package] +name = "rust_usage_test" +version = "0.1.0" +authors = ["Robert Winslow ", + "Casper Neo ", + "FlatBuffers Maintainers"] +edition = "2018" + +[dependencies] +flatbuffers = { path = "../../rust/flatbuffers", default-features = false } +flexbuffers = { path = "../../rust/flexbuffers" } +serde_derive = "1.0" +serde = "1.0" +serde_bytes = "0.11" +libc_alloc = { version = "1.0.3", optional = true } + +[features] +default = ["flatbuffers/default"] +no_std = ["libc_alloc"] + +[[bin]] +name = "monster_example" +path = "bin/monster_example.rs" + +[[bin]] +name = "flatbuffers_alloc_check" +path = "bin/flatbuffers_alloc_check.rs" + +[[bin]] +name = "flexbuffers_alloc_check" +path = "bin/flexbuffers_alloc_check.rs" + +[[bin]] +name = "sample_flexbuffers" +path = "../../samples/sample_flexbuffers.rs" + +[[bin]] +name = "sample_flexbuffers_serde" +path = "../../samples/sample_flexbuffers_serde.rs" + +[[bin]] +name = "sample_flatbuffers" +path = "../../samples/sample_binary.rs" + +[dev-dependencies] +quickcheck = "0.6" +# TODO(rw): look into moving to criterion.rs +serde = "1.0" +bencher = "0.1.5" +static_assertions = "1.0.0" +rand = "*" +quickcheck_derive = "*" +array-init = "2.0" + +[[bench]] +# setup for bencher +name = "benchmarks" +harness = false diff --git a/third_party/flatbuffers/tests/rust_usage_test/benches/benchmarks.rs b/third_party/flatbuffers/tests/rust_usage_test/benches/benchmarks.rs new file mode 100644 index 00000000000..51fae757251 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/benches/benchmarks.rs @@ -0,0 +1,33 @@ +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#[macro_use] +extern crate bencher; +extern crate flatbuffers; +extern crate flexbuffers; + +mod flatbuffers_benchmarks; +mod flexbuffers_benchmarks; + +#[allow(dead_code, unused_imports)] +#[path = "../../monster_test/mod.rs"] +mod monster_test_generated; +pub use monster_test_generated::my_game; + +benchmark_main!( + flatbuffers_benchmarks::benches, + flexbuffers_benchmarks::benches +); diff --git a/third_party/flatbuffers/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs b/third_party/flatbuffers/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs new file mode 100644 index 00000000000..3ab3b56aa4a --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/benches/flatbuffers_benchmarks.rs @@ -0,0 +1,269 @@ +/* + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +use bencher::{benchmark_group, Bencher}; +use flatbuffers; + +#[allow(dead_code, unused_imports)] +#[path = "../../monster_test/mod.rs"] +mod monster_test_generated; +pub use monster_test_generated::my_game; + +fn traverse_canonical_buffer(bench: &mut Bencher) { + let owned_data = { + let mut builder = &mut flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(&mut builder, true); + builder.finished_data().to_vec() + }; + let data = &owned_data[..]; + let n = data.len() as u64; + bench.iter(|| { + traverse_serialized_example_with_generated_code(data); + }); + bench.bytes = n; +} + +fn create_canonical_buffer_then_reset(bench: &mut Bencher) { + let mut builder = &mut flatbuffers::FlatBufferBuilder::new(); + // warmup + create_serialized_example_with_generated_code(&mut builder, true); + let n = builder.finished_data().len() as u64; + builder.reset(); + + bench.iter(|| { + let _ = create_serialized_example_with_generated_code(&mut builder, true); + builder.reset(); + }); + + bench.bytes = n; +} + +#[inline(always)] +fn create_serialized_example_with_generated_code( + builder: &mut flatbuffers::FlatBufferBuilder, + finish: bool, +) -> usize { + let s0 = builder.create_string("test1"); + let s1 = builder.create_string("test2"); + let t0_name = builder.create_string("Barney"); + let t1_name = builder.create_string("Fred"); + let t2_name = builder.create_string("Wilma"); + let t0 = my_game::example::Monster::create( + builder, + &my_game::example::MonsterArgs { + hp: 1000, + name: Some(t0_name), + ..Default::default() + }, + ); + let t1 = my_game::example::Monster::create( + builder, + &my_game::example::MonsterArgs { + name: Some(t1_name), + ..Default::default() + }, + ); + let t2 = my_game::example::Monster::create( + builder, + &my_game::example::MonsterArgs { + name: Some(t2_name), + ..Default::default() + }, + ); + let mon = { + let name = builder.create_string("MyMonster"); + let fred_name = builder.create_string("Fred"); + let inventory = builder.create_vector(&[0u8, 1, 2, 3, 4]); + let test4 = builder.create_vector(&[ + my_game::example::Test::new(10, 20), + my_game::example::Test::new(30, 40), + ]); + let pos = my_game::example::Vec3::new( + 1.0, + 2.0, + 3.0, + 3.0, + my_game::example::Color::Green, + &my_game::example::Test::new(5i16, 6i8), + ); + let args = my_game::example::MonsterArgs { + hp: 80, + mana: 150, + name: Some(name), + pos: Some(&pos), + test_type: my_game::example::Any::Monster, + test: Some( + my_game::example::Monster::create( + builder, + &my_game::example::MonsterArgs { + name: Some(fred_name), + ..Default::default() + }, + ) + .as_union_value(), + ), + inventory: Some(inventory), + test4: Some(test4), + testarrayofstring: Some(builder.create_vector(&[s0, s1])), + testarrayoftables: Some(builder.create_vector(&[t0, t1, t2])), + ..Default::default() + }; + my_game::example::Monster::create(builder, &args) + }; + if finish { + my_game::example::finish_monster_buffer(builder, mon); + } + + builder.finished_data().len() + + // make it do some work + // if builder.finished_data().len() == 0 { panic!("bad benchmark"); } +} + +#[inline(always)] +fn blackbox(t: T) -> T { + // encapsulate this in case we need to turn it into a noop + bencher::black_box(t) +} + +#[inline(always)] +fn traverse_serialized_example_with_generated_code(bytes: &[u8]) { + let m = unsafe { my_game::example::root_as_monster_unchecked(bytes) }; + blackbox(m.hp()); + blackbox(m.mana()); + blackbox(m.name()); + let pos = m.pos().unwrap(); + blackbox(pos.x()); + blackbox(pos.y()); + blackbox(pos.z()); + blackbox(pos.test1()); + blackbox(pos.test2()); + let pos_test3 = pos.test3(); + blackbox(pos_test3.a()); + blackbox(pos_test3.b()); + blackbox(m.test_type()); + let table2 = m.test().unwrap(); + let monster2 = unsafe { my_game::example::Monster::init_from_table(table2) }; + blackbox(monster2.name()); + blackbox(m.inventory()); + blackbox(m.test4()); + let testarrayoftables = m.testarrayoftables().unwrap(); + blackbox(testarrayoftables.get(0).hp()); + blackbox(testarrayoftables.get(0).name()); + blackbox(testarrayoftables.get(1).name()); + blackbox(testarrayoftables.get(2).name()); + let testarrayofstring = m.testarrayofstring().unwrap(); + blackbox(testarrayofstring.get(0)); + blackbox(testarrayofstring.get(1)); +} + +fn create_string_10(bench: &mut Bencher) { + let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20); + let mut i = 0; + bench.iter(|| { + builder.create_string("foobarbaz"); // zero-terminated -> 10 bytes + i += 1; + if i == 10000 { + builder.reset(); + i = 0; + } + }); + + bench.bytes = 10; +} + +fn create_string_100(bench: &mut Bencher) { + let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20); + let s_owned = (0..99).map(|_| "x").collect::(); + let s: &str = &s_owned; + + let mut i = 0; + bench.iter(|| { + builder.create_string(s); // zero-terminated -> 100 bytes + i += 1; + if i == 1000 { + builder.reset(); + i = 0; + } + }); + + bench.bytes = s.len() as u64; +} + +fn create_byte_vector_100_naive(bench: &mut Bencher) { + let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20); + let v_owned = (0u8..100).map(|i| i).collect::>(); + let v: &[u8] = &v_owned; + + let mut i = 0; + bench.iter(|| { + builder.create_vector(v); // zero-terminated -> 100 bytes + i += 1; + if i == 10000 { + builder.reset(); + i = 0; + } + }); + + bench.bytes = v.len() as u64; +} + +fn create_byte_vector_100_optimal(bench: &mut Bencher) { + let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20); + let v_owned = (0u8..100).map(|i| i).collect::>(); + let v: &[u8] = &v_owned; + + let mut i = 0; + bench.iter(|| { + builder.create_vector(v); + i += 1; + if i == 10000 { + builder.reset(); + i = 0; + } + }); + + bench.bytes = v.len() as u64; +} + +fn create_many_tables(bench: &mut Bencher) { + let builder = &mut flatbuffers::FlatBufferBuilder::with_capacity(1 << 20); + // We test vtable overhead by making many unique tables of up to 16 fields of u8s. + bench.iter(|| { + for i in 0..(1u16 << 10) { + let t = builder.start_table(); + for j in 0..15 { + if i & (1 << j) == 1 { + builder.push_slot_always(i * 2, 42u8); + } + } + builder.end_table(t); + } + builder.reset(); + }); + bench.bytes = 1 << 15; +} + +benchmark_group!( + benches, + create_byte_vector_100_naive, + create_byte_vector_100_optimal, + traverse_canonical_buffer, + create_canonical_buffer_then_reset, + create_string_10, + create_string_100, + create_many_tables, +); diff --git a/third_party/flatbuffers/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs b/third_party/flatbuffers/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs new file mode 100644 index 00000000000..26842910b72 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/benches/flexbuffers_benchmarks.rs @@ -0,0 +1,295 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use bencher::{benchmark_group, benchmark_main, Bencher}; +use flexbuffers::*; + +fn push_vec_u64_to_map(b: &mut Bencher) { + let va = vec![u64::max_value() - 10; 512]; + let vb = vec![u64::max_value() - 20; 512]; + let vc = vec![u64::max_value() - 30; 512]; + let mut n = 0; + + b.iter(|| { + let mut fxb = Builder::default(); + let mut m = fxb.start_map(); + let mut ma = m.start_vector("a"); + for &a in va.iter() { + ma.push(a); + } + ma.end_vector(); + let mut mb = m.start_vector("b"); + for &b in vb.iter() { + mb.push(b); + } + mb.end_vector(); + let mut mc = m.start_vector("c"); + for &c in vc.iter() { + mc.push(c); + } + mc.end_vector(); + m.end_map(); + n = fxb.view().len(); + }); + b.bytes = n as u64; +} +fn push_vec_u64_to_map_reused(b: &mut Bencher) { + let va = vec![u64::max_value() - 10; 512]; + let vb = vec![u64::max_value() - 20; 512]; + let vc = vec![u64::max_value() - 30; 512]; + let mut fxb = Builder::default(); + let mut n = 0; + let mut go = || { + let mut m = fxb.start_map(); + let mut ma = m.start_vector("a"); + for &a in va.iter() { + ma.push(a); + } + ma.end_vector(); + let mut mb = m.start_vector("b"); + for &b in vb.iter() { + mb.push(b); + } + mb.end_vector(); + let mut mc = m.start_vector("c"); + for &c in vc.iter() { + mc.push(c); + } + mc.end_vector(); + m.end_map(); + n = fxb.view().len(); + }; + go(); // warm up allocations. + b.iter(go); + b.bytes = n as u64; +} +fn push_vec_u64_to_map_direct(b: &mut Bencher) { + let va = vec![u64::max_value() - 10; 512]; + let vb = vec![u64::max_value() - 20; 512]; + let vc = vec![u64::max_value() - 30; 512]; + let mut n = 0; + + b.iter(|| { + let mut fxb = Builder::default(); + let mut m = fxb.start_map(); + m.push("a", &va); + m.push("b", &vb); + m.push("c", &vc); + m.end_map(); + n = fxb.view().len(); + }); + b.bytes = n as u64; +} +fn push_vec_u64_to_map_direct_reused(b: &mut Bencher) { + let va = vec![u64::max_value() - 10; 512]; + let vb = vec![u64::max_value() - 20; 512]; + let vc = vec![u64::max_value() - 30; 512]; + let mut n = 0; + let mut fxb = Builder::default(); + let mut go = || { + let mut m = fxb.start_map(); + m.push("a", &va); + m.push("b", &vb); + m.push("c", &vc); + m.end_map(); + n = fxb.view().len(); + }; + go(); // warm up allocations. + b.iter(go); + b.bytes = n as u64; +} + +fn push_vec_without_indirect(b: &mut Bencher) { + let mut builder = Builder::default(); + let mut n = 0; + let mut go = || { + let mut b = builder.start_vector(); + for i in 0..1024u16 { + b.push(i); + } + b.push(i64::max_value()); + b.end_vector(); + n = builder.view().len(); + }; + go(); // warm up allocations. + b.iter(go); + b.bytes = n as u64; +} +// This isn't actually faster than the alternative but it is a lot smaller. +// Based on the above benchmarks a lot of time is stuck in the `values` stack. +fn push_vec_with_indirect(b: &mut Bencher) { + let mut builder = Builder::default(); + let mut n = 0; + let mut go = || { + let mut b = builder.start_vector(); + for i in 0..1024u16 { + b.push(i); + } + b.push(IndirectInt(i64::max_value())); + b.end_vector(); + n = builder.view().len(); + }; + go(); // warm up allocations. + b.iter(go); + b.bytes = n as u64; +} + +fn example_map<'a>(m: &mut MapBuilder<'a>) { + m.push("some_ints", &[256; 5]); + m.push("some_uints", &[256u16; 5]); + m.push("some_floats", &[256f32; 5]); + m.push("some_strings", "muahahahahaha"); +} +fn hundred_maps(b: &mut Bencher) { + let mut builder = Builder::default(); + let mut n = 0; + let mut go = || { + let mut v = builder.start_vector(); + for _ in 0..100 { + example_map(&mut v.start_map()); + } + v.end_vector(); + n = builder.view().len(); + }; + go(); // Warm up allocations. + b.iter(go); + b.bytes = n as u64; +} +fn hundred_maps_pooled(b: &mut Bencher) { + let mut builder = Builder::default(); + let mut n = 0; + let mut go = || { + let mut v = builder.start_vector(); + for _ in 0..100 { + example_map(&mut v.start_map()); + } + v.end_vector(); + n = builder.view().len(); + }; + go(); // Warm up allocations. + b.iter(go); + b.bytes = n as u64; +} +fn make_monster(mut monster: MapBuilder) { + monster.push("type", "great orc"); + monster.push("age", 100u8); + monster.push("name", "Mr. Orc"); + monster.push("coins", &[1, 25, 50, 100, 250]); + monster.push("color", &[255u8, 0, 0, 0]); + { + let mut weapons = monster.start_vector("weapons"); + { + let mut hammer = weapons.start_map(); + hammer.push("name", "hammer"); + hammer.push("damage type", "crush"); + hammer.push("damage", 20); + } + { + let mut axe = weapons.start_map(); + axe.push("name", "Great Axe"); + axe.push("damage type", "slash"); + axe.push("damage", 30); + } + } + { + let mut sounds = monster.start_vector("sounds"); + sounds.push("grr"); + sounds.push("rawr"); + sounds.push("muahaha"); + } +} +fn serialize_monsters(b: &mut Bencher) { + let mut builder = Builder::default(); + let mut n = 0; + let mut go = || { + let mut monsters = builder.start_vector(); + for _ in 0..100 { + make_monster(monsters.start_map()) + } + monsters.end_vector(); + n = builder.view().len(); + }; + go(); // Warm up allocations. + b.iter(go); + b.bytes = n as u64; +} +fn validate_monster(r: MapReader<&[u8]>) { + assert_eq!(r.idx("type").as_str(), "great orc"); + assert_eq!(r.idx("age").as_u8(), 100); + assert_eq!(r.idx("name").as_str(), "Mr. Orc"); + assert!(r + .idx("coins") + .as_vector() + .iter() + .map(|c| c.as_i16()) + .eq([1, 25, 50, 100, 250].iter().cloned())); + assert!(r + .idx("color") + .as_vector() + .iter() + .map(|c| c.as_u8()) + .eq([255, 0, 0, 0].iter().cloned())); + + let weapons = r.idx("weapons").as_vector(); + assert_eq!(weapons.len(), 2); + + let hammer = weapons.idx(0).as_map(); + assert_eq!(hammer.idx("name").as_str(), "hammer"); + assert_eq!(hammer.idx("damage type").as_str(), "crush"); + assert_eq!(hammer.idx("damage").as_u64(), 20); + + let axe = weapons.idx(1).as_map(); + assert_eq!(axe.idx("name").as_str(), "Great Axe"); + assert_eq!(axe.idx("damage type").as_str(), "slash"); + assert_eq!(axe.idx("damage").as_u64(), 30); + + assert!(r + .idx("sounds") + .as_vector() + .iter() + .map(|s| s.as_str()) + .eq(["grr", "rawr", "muahaha"].iter().cloned())); +} +fn read_monsters(b: &mut Bencher) { + let mut builder = Builder::default(); + let mut monsters = builder.start_vector(); + for _ in 0..100 { + make_monster(monsters.start_map()); + } + monsters.end_vector(); + b.bytes = builder.view().len() as u64; + let go = || { + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + assert_eq!(r.len(), 100); + for i in 0..100 { + validate_monster(r.idx(i).as_map()); + } + }; + b.iter(go); +} + +benchmark_group!( + benches, + push_vec_u64_to_map, + push_vec_u64_to_map_reused, + push_vec_u64_to_map_direct, + push_vec_u64_to_map_direct_reused, + push_vec_without_indirect, + push_vec_with_indirect, + hundred_maps, + hundred_maps_pooled, + serialize_monsters, + read_monsters, +); +benchmark_main!(benches); diff --git a/third_party/flatbuffers/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs b/third_party/flatbuffers/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs new file mode 100644 index 00000000000..8a77c0e0e5b --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/bin/flatbuffers_alloc_check.rs @@ -0,0 +1,188 @@ +// define a passthrough allocator that tracks alloc calls. +// (note that we can't drop this in to the usual test suite, because it's a big +// global variable). +use std::alloc::{GlobalAlloc, Layout, System}; + + +static mut N_ALLOCS: usize = 0; + +struct TrackingAllocator; + +impl TrackingAllocator { + fn n_allocs(&self) -> usize { + unsafe { N_ALLOCS } + } +} + +unsafe impl GlobalAlloc for TrackingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + N_ALLOCS += 1; + System.alloc(layout) + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + System.dealloc(ptr, layout) + } +} + +// use the tracking allocator: +#[global_allocator] +static A: TrackingAllocator = TrackingAllocator; + +// import the flatbuffers generated code: +extern crate flatbuffers; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../include_test1/mod.rs"] +pub mod include_test1_generated; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../include_test2/mod.rs"] +pub mod include_test2_generated; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../monster_test/mod.rs"] +mod monster_test_generated; + +pub use monster_test_generated::my_game; + +// verbatim from the test suite: +fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) { + let mon = { + let strings = [ + builder.create_string("these"), + builder.create_string("unused"), + builder.create_string("strings"), + builder.create_string("check"), + builder.create_string("the"), + builder.create_string("create_vector_of_strings"), + builder.create_string("function") + ]; + let _ = builder.create_vector(&strings); + + let s0 = builder.create_string("test1"); + let s1 = builder.create_string("test2"); + let fred_name = builder.create_string("Fred"); + + // can't inline creation of this Vec3 because we refer to it by reference, so it must live + // long enough to be used by MonsterArgs. + let pos = my_game::example::Vec3::new( + 1.0, + 2.0, + 3.0, + 3.0, + my_game::example::Color::Green, + &my_game::example::Test::new(5i16, 6i8), + ); + + let args = my_game::example::MonsterArgs { + hp: 80, + mana: 150, + name: Some(builder.create_string("MyMonster")), + pos: Some(&pos), + test_type: my_game::example::Any::Monster, + test: Some( + my_game::example::Monster::create( + builder, + &my_game::example::MonsterArgs { + name: Some(fred_name), + ..Default::default() + }, + ) + .as_union_value(), + ), + inventory: Some(builder.create_vector(&[0u8, 1, 2, 3, 4])), + test4: Some(builder.create_vector(&[ + my_game::example::Test::new(10, 20), + my_game::example::Test::new(30, 40), + ])), + testarrayofstring: Some(builder.create_vector(&[s0, s1])), + ..Default::default() + }; + my_game::example::Monster::create(builder, &args) + }; + my_game::example::finish_monster_buffer(builder, mon); +} + +#[cfg(not(miri))] // slow. +fn main() { + // test the allocation tracking: + { + let before = A.n_allocs(); + let _x: Vec = vec![0u8; 1]; + let after = A.n_allocs(); + assert_eq!(before + 1, after); + } + + let builder = &mut flatbuffers::FlatBufferBuilder::new(); + { + // warm up the builder (it can make small allocs internally, such as for storing vtables): + create_serialized_example_with_generated_code(builder); + } + + // reset the builder, clearing its heap-allocated memory: + builder.reset(); + + { + let before = A.n_allocs(); + create_serialized_example_with_generated_code(builder); + let after = A.n_allocs(); + assert_eq!(before, after, "KO: Heap allocs occurred in Rust write path"); + } + + let buf = builder.finished_data(); + + // use the allocation tracking on the read path: + { + let before = A.n_allocs(); + + // do many reads, forcing them to execute by using assert_eq: + { + let m = unsafe { my_game::example::root_as_monster_unchecked(buf) }; + assert_eq!(80, m.hp()); + assert_eq!(150, m.mana()); + assert_eq!("MyMonster", m.name()); + + let pos = m.pos().unwrap(); + // We know the bits should be exactly equal here but compilers may + // optimize floats in subtle ways so we're playing it safe and using + // epsilon comparison + assert!((pos.x() - 1.0f32).abs() < std::f32::EPSILON); + assert!((pos.y() - 2.0f32).abs() < std::f32::EPSILON); + assert!((pos.z() - 3.0f32).abs() < std::f32::EPSILON); + assert!((pos.test1() - 3.0f64).abs() < std::f64::EPSILON); + assert_eq!(pos.test2(), my_game::example::Color::Green); + let pos_test3 = pos.test3(); + assert_eq!(pos_test3.a(), 5i16); + assert_eq!(pos_test3.b(), 6i8); + assert_eq!(m.test_type(), my_game::example::Any::Monster); + let table2 = m.test().unwrap(); + let m2 = unsafe { my_game::example::Monster::init_from_table(table2) }; + + assert_eq!(m2.name(), "Fred"); + + let inv = m.inventory().unwrap(); + assert_eq!(inv.len(), 5); + assert_eq!(inv.iter().sum::(), 10u8); + + let test4 = m.test4().unwrap(); + assert_eq!(test4.len(), 2); + assert_eq!( + i32::from(test4.get(0).a()) + + i32::from(test4.get(1).a()) + + i32::from(test4.get(0).b()) + + i32::from(test4.get(1).b()), + 100 + ); + + let testarrayofstring = m.testarrayofstring().unwrap(); + assert_eq!(testarrayofstring.len(), 2); + assert_eq!(testarrayofstring.get(0), "test1"); + assert_eq!(testarrayofstring.get(1), "test2"); + } + + // assert that no allocs occurred: + let after = A.n_allocs(); + assert_eq!(before, after, "KO: Heap allocs occurred in Rust read path"); + } + println!("Rust: Heap alloc checks completed successfully"); +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs b/third_party/flatbuffers/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs new file mode 100644 index 00000000000..a921af7fba7 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/bin/flexbuffers_alloc_check.rs @@ -0,0 +1,144 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +extern crate flexbuffers; + +use flexbuffers::*; +use std::alloc::{GlobalAlloc, Layout, System}; + +/// We take over the Rust allocator to count allocations. This is super not thread safe. +static mut NUM_ALLOCS: usize = 0; +fn current_allocs() -> usize { + unsafe { NUM_ALLOCS } +} +struct TrackingAllocator; +unsafe impl GlobalAlloc for TrackingAllocator { + unsafe fn alloc(&self, layout: Layout) -> *mut u8 { + NUM_ALLOCS += 1; + System.alloc(layout) + } + unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) { + System.dealloc(ptr, layout) + } +} +#[global_allocator] +static T: TrackingAllocator = TrackingAllocator; + +/// Make some example data +fn make_monster(mut monster: MapBuilder) { + monster.push("type", "great orc"); + monster.push("age", 100u8); + monster.push("name", "Mr. Orc"); + monster.push("coins", &[1, 25, 50, 100, 250]); + monster.push("color", &[255u8, 0, 0, 0]); + { + let mut weapons = monster.start_vector("weapons"); + { + let mut hammer = weapons.start_map(); + hammer.push("name", "hammer"); + hammer.push("damage type", "crush"); + hammer.push("damage", 20); + } + { + let mut axe = weapons.start_map(); + axe.push("name", "Great Axe"); + axe.push("damage type", "slash"); + axe.push("damage", 30); + } + } + { + let mut sounds = monster.start_vector("sounds"); + sounds.push("grr"); + sounds.push("rawr"); + sounds.push("muahaha"); + } + // TODO(cneo): Directly pushing string slices has alloc. +} + +// Read back the data from make_monster. +fn validate_monster(flexbuffer: &[u8]) { + let r = Reader::get_root(flexbuffer).unwrap().as_map(); + + assert!(!r.is_empty()); + assert!(r.index_key("not_a_field").is_none()); + + assert_eq!(r.len(), 7); + assert_eq!(r.idx("type").as_str(), "great orc"); + assert_eq!(r.idx("age").as_u8(), 100); + assert_eq!(r.idx("name").as_str(), "Mr. Orc"); + + let coins = r.idx("coins").as_vector(); + for (i, &c) in [1, 25, 50, 100, 250].iter().enumerate() { + assert_eq!(coins.idx(i).as_u16(), c); + } + let color = r.idx("color").as_vector(); + for (i, &c) in [255, 0, 0, 0].iter().enumerate() { + assert_eq!(color.idx(i).as_i32(), c); + } + let weapons = r.idx("weapons").as_vector(); + assert_eq!(weapons.len(), 2); + + let hammer = weapons.idx(0).as_map(); + assert_eq!(hammer.idx("name").as_str(), "hammer"); + assert_eq!(hammer.idx("damage type").as_str(), "crush"); + assert_eq!(hammer.idx("damage").as_u64(), 20); + + let axe = weapons.idx(1).as_map(); + assert_eq!(axe.idx("name").as_str(), "Great Axe"); + assert_eq!(axe.idx("damage type").as_str(), "slash"); + assert_eq!(axe.idx("damage").as_u64(), 30); + + let sounds = r.idx("sounds").as_vector(); + for (i, &s) in ["grr", "rawr", "muahaha"].iter().enumerate() { + assert_eq!(sounds.idx(i).as_str(), s); + } +} + +// This is in a separate binary than tests because taking over the global allocator is not +// hermetic and not thread safe. +#[cfg(not(miri))] // slow. +fn main() { + let start_up = current_allocs(); + + // Let's build a flexbuffer from a new (cold) flexbuffer builder. + let mut builder = Builder::default(); + make_monster(builder.start_map()); + let after_warmup = current_allocs(); + + // The builder makes some allocations while warming up. + assert!(after_warmup > start_up); + assert!(after_warmup < start_up + 20); + + // A warm builder should make no allocations. + make_monster(builder.start_map()); + assert_eq!(after_warmup, current_allocs()); + + // Nor should a reader. + validate_monster(builder.view()); + assert_eq!(after_warmup, current_allocs()); + + // Do it again just for kicks. + make_monster(builder.start_map()); + validate_monster(builder.view()); + assert_eq!(after_warmup, current_allocs()); + + let final_allocs = current_allocs(); // dbg! does allocate. + dbg!(start_up, after_warmup, final_allocs); +} + +#[test] +#[cfg(not(miri))] // slow. +fn no_extra_allocations() { + main() +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/bin/monster_example.rs b/third_party/flatbuffers/tests/rust_usage_test/bin/monster_example.rs new file mode 100644 index 00000000000..f50003f8762 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/bin/monster_example.rs @@ -0,0 +1,29 @@ +#![allow(clippy::derivable_impls, clippy::all)] +extern crate flatbuffers; + + +#[allow(dead_code, unused_imports)] +#[path = "../../include_test1/mod.rs"] +pub mod include_test1_generated; + +#[allow(dead_code, unused_imports)] +#[path = "../../include_test2/mod.rs"] +pub mod include_test2_generated; + +#[allow(dead_code, unused_imports, clippy::approx_constant)] +#[path = "../../monster_test/mod.rs"] +mod monster_test_generated; +pub use monster_test_generated::my_game; + +use std::io::Read; + +fn main() { + let mut f = std::fs::File::open("../monsterdata_test.mon").unwrap(); + let mut buf = Vec::new(); + f.read_to_end(&mut buf).expect("file reading failed"); + + let monster = my_game::example::root_as_monster(&buf[..]).unwrap(); + println!("{}", monster.hp()); // `80` + println!("{}", monster.mana()); // default value of `150` + println!("{:?}", monster.name()); // Some("MyMonster") +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/outdir/.gitignore b/third_party/flatbuffers/tests/rust_usage_test/outdir/.gitignore new file mode 100644 index 00000000000..c83f90a2b01 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/outdir/.gitignore @@ -0,0 +1 @@ +src/generated diff --git a/third_party/flatbuffers/tests/rust_usage_test/outdir/Cargo.toml b/third_party/flatbuffers/tests/rust_usage_test/outdir/Cargo.toml new file mode 100644 index 00000000000..659638f1dcb --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/outdir/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "outdir" +version = "0.1.0" +authors = ["Casper Neo "] +edition = "2018" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +flatbuffers = { path = "../../../rust/flatbuffers" } +serde = "1.0" diff --git a/third_party/flatbuffers/tests/rust_usage_test/outdir/build.rs b/third_party/flatbuffers/tests/rust_usage_test/outdir/build.rs new file mode 100644 index 00000000000..efd036b0637 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/outdir/build.rs @@ -0,0 +1,57 @@ +fn main() { + use std::process::Command; + let project_root = std::env::current_dir() + .unwrap() + .parent() // flatbuffers/tests/rust_usage test + .unwrap() + .parent() // flatbuffers/tests + .unwrap() + .parent() // flatbuffers/ + .unwrap() + .to_path_buf(); + let sample_schema = { + let mut s = project_root.to_path_buf(); + s.push("samples"); + s.push("monster.fbs"); + s + }; + + let flatc = { + let mut f = project_root.to_path_buf(); + f.push("flatc"); + f + }; + + let out_dir = { + let mut d = std::path::Path::new(&std::env::var("OUT_DIR").unwrap()).to_path_buf(); + d.push("flatbuffers"); + d + }; + + Command::new(&flatc) + .arg("-o") + .arg(&out_dir) + .arg("--rust") + .arg("--rust-module-root-file") + .arg(&sample_schema) + .output() + .expect("Failed to generate file"); + + assert!(out_dir.exists()); + + let generated = std::path::Path::new("src/generated"); + #[cfg(target_os = "windows")] + { + if generated.exists() { + std::fs::remove_dir(generated).unwrap(); + } + std::os::windows::fs::symlink_dir(out_dir, generated).unwrap(); + } + #[cfg(not(target_os = "windows"))] + { + if generated.exists() { + std::fs::remove_file(generated).unwrap(); + } + std::os::unix::fs::symlink(out_dir, generated).unwrap(); + } +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/outdir/src/main.rs b/third_party/flatbuffers/tests/rust_usage_test/outdir/src/main.rs new file mode 100644 index 00000000000..734e1375d78 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/outdir/src/main.rs @@ -0,0 +1,29 @@ +// In this example, a build.rs file generates the code and then copies it into generated/ +extern crate flatbuffers; +#[allow(unused_imports, dead_code)] +mod generated; +use generated::my_game::sample::{Monster, MonsterArgs}; + +fn main() { + let mut fbb = flatbuffers::FlatBufferBuilder::new(); + let name = Some(fbb.create_string("bob")); + let m = Monster::create( + &mut fbb, + &MonsterArgs { + hp: 1, + mana: 2, + name, + ..Default::default() + }, + ); + fbb.finish(m, None); + let mon = flatbuffers::root::(fbb.finished_data()).unwrap(); + assert_eq!(mon.hp(), 1); + assert_eq!(mon.mana(), 2); + assert_eq!(mon.name().unwrap(), "bob"); +} + +#[test] +fn test_main() { + main() +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/arrays_test.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/arrays_test.rs new file mode 100644 index 00000000000..1b4cc64cb0e --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/arrays_test.rs @@ -0,0 +1,340 @@ +#![no_std] + +#[cfg(not(feature = "no_std"))] +extern crate std; + +extern crate alloc; + +extern crate array_init; + +#[allow(dead_code, unused_imports)] +#[path = "../../arrays_test/mod.rs"] +mod arrays_test_generated; + +use alloc::format; +use core::fmt::Debug; + +use crate::arrays_test_generated::my_game::example::*; + +extern crate quickcheck; + +use array_init::array_init; +use core::mem::size_of; +use quickcheck::{Arbitrary, Gen}; + +fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) { + let nested_struct1 = NestedStruct::new( + &[-1, 2], + TestEnum::A, + &[TestEnum::C, TestEnum::B], + &[0x1122334455667788, -0x1122334455667788], + ); + let nested_struct2 = NestedStruct::new( + &[3, -4], + TestEnum::B, + &[TestEnum::B, TestEnum::A], + &[-0x1122334455667788, 0x1122334455667788], + ); + let array_struct = ArrayStruct::new( + 12.34, + &[1, 2, 3, 4, 5, 6, 7, 8, 9, 0xA, 0xB, 0xC, 0xD, 0xE, 0xF], + -127, + &[nested_struct1, nested_struct2], + 1, + &[-0x8000000000000000, 0x7FFFFFFFFFFFFFFF], + ); + // Test five makes sense when specified. + let ss = ArrayTable::create( + builder, + &ArrayTableArgs { + a: Some(&array_struct), + }, + ); + finish_array_table_buffer(builder, ss); +} + +fn serialized_example_is_accessible_and_correct( + bytes: &[u8], + identifier_required: bool, + size_prefixed: bool, +) { + if identifier_required { + let correct = if size_prefixed { + array_table_size_prefixed_buffer_has_identifier(bytes) + } else { + array_table_buffer_has_identifier(bytes) + }; + + assert_eq!(correct, true); + } + + let array_table = if size_prefixed { + size_prefixed_root_as_array_table(bytes).unwrap() + } else { + root_as_array_table(bytes).unwrap() + }; + + let array_struct = array_table.a().unwrap(); + assert_eq!(array_struct.a(), 12.34); + assert_eq!(array_struct.b().len(), 0xF); + assert_eq!(array_struct.b().iter().sum::(), 120); + assert_eq!(array_struct.c(), -127); + + assert_eq!(array_struct.d().len(), 2); + let nested_struct1 = array_struct.d().get(0); + assert_eq!(nested_struct1.a().len(), 2); + assert_eq!(nested_struct1.a().iter().sum::(), 1); + assert_eq!(nested_struct1.b(), TestEnum::A); + assert_eq!(nested_struct1.c().len(), 2); + assert_eq!(nested_struct1.c().get(0), TestEnum::C); + assert_eq!(nested_struct1.c().get(1), TestEnum::B); + assert_eq!(nested_struct1.d().len(), 2); + assert_eq!( + [nested_struct1.d().get(0), nested_struct1.d().get(1)], + [0x1122334455667788, -0x1122334455667788] + ); + let nested_struct2 = array_struct.d().get(1); + assert_eq!(nested_struct2.a().len(), 2); + assert_eq!(nested_struct2.a().iter().sum::(), -1); + assert_eq!(nested_struct2.b(), TestEnum::B); + assert_eq!(nested_struct2.c().len(), 2); + assert_eq!(nested_struct2.c().get(0), TestEnum::B); + assert_eq!(nested_struct2.c().get(1), TestEnum::A); + assert_eq!(nested_struct2.d().len(), 2); + let arr: [i64; 2] = nested_struct2.d().into(); + assert_eq!( + arr, + [-0x1122334455667788, 0x1122334455667788] + ); + + assert_eq!(array_struct.e(), 1); + assert_eq!(array_struct.f().len(), 2); + assert_eq!(array_struct.f().get(0), -0x8000000000000000); + assert_eq!(array_struct.f().get(1), 0x7FFFFFFFFFFFFFFF); +} + +#[test] +fn generated_code_creates_correct_example() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(&mut b); + let buf = b.finished_data(); + serialized_example_is_accessible_and_correct(&buf[..], true, false); +} + +#[test] +fn struct_netsted_struct_is_32_bytes() { + assert_eq!(32, ::core::mem::size_of::()); +} + +#[test] +fn struct_array_struct_is_160_bytes() { + assert_eq!(160, ::core::mem::size_of::()); +} + +#[test] +fn test_object_api_reads_correctly() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(&mut b); + + let array_table = root_as_array_table(b.finished_data()).unwrap().unpack(); + + let array_struct = array_table.a.unwrap(); + assert_eq!(array_struct.a, 12.34); + assert_eq!(array_struct.b.len(), 0xF); + assert_eq!(array_struct.b.iter().sum::(), 120); + assert_eq!(array_struct.c, -127); + + assert_eq!(array_struct.d.len(), 2); + let nested_struct1 = &array_struct.d[0]; + assert_eq!(nested_struct1.a.len(), 2); + assert_eq!(nested_struct1.a.iter().sum::(), 1); + assert_eq!(nested_struct1.b, TestEnum::A); + assert_eq!(nested_struct1.c.len(), 2); + assert_eq!(nested_struct1.c[0], TestEnum::C); + assert_eq!(nested_struct1.c[1], TestEnum::B); + assert_eq!(nested_struct1.d.len(), 2); + assert_eq!(nested_struct1.d, [0x1122334455667788, -0x1122334455667788]); + let nested_struct2 = &array_struct.d[1]; + assert_eq!(nested_struct2.a.len(), 2); + assert_eq!(nested_struct2.a.iter().sum::(), -1); + assert_eq!(nested_struct2.b, TestEnum::B); + assert_eq!(nested_struct2.c.len(), 2); + assert_eq!(nested_struct2.c[0], TestEnum::B); + assert_eq!(nested_struct2.c[1], TestEnum::A); + assert_eq!(nested_struct2.d.len(), 2); + assert_eq!(nested_struct2.d, [-0x1122334455667788, 0x1122334455667788]); + + assert_eq!(array_struct.e, 1); + assert_eq!(array_struct.f.len(), 2); + assert_eq!(array_struct.f[0], -0x8000000000000000); + assert_eq!(array_struct.f[1], 0x7FFFFFFFFFFFFFFF); +} + +#[test] +fn object_api_defaults() { + use arrays_test_generated::my_game::example::*; + + assert_eq!( + NestedStructT::default(), + NestedStructT { + a: [0, 0], + b: TestEnum::default(), + c: [TestEnum::default(), TestEnum::default()], + d: [0, 0], + } + ); + + assert_eq!( + ArrayStructT::default(), + ArrayStructT { + a: 0.0, + b: [0; 0xF], + c: 0, + d: [NestedStructT::default(), NestedStructT::default()], + e: 0, + f: [0, 0], + } + ); +} + +#[test] +fn generated_code_debug_prints_correctly() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(b); + let buf = b.finished_data(); + let array_table = root_as_array_table(buf).unwrap(); + assert_eq!( + format!("{:.5?}", &array_table), + "ArrayTable { a: Some(ArrayStruct { a: 12.34000, \ + b: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15], \ + c: -127, d: [NestedStruct { a: [-1, 2], b: A, c: [C, B], \ + d: [1234605616436508552, -1234605616436508552] }, \ + NestedStruct { a: [3, -4], b: B, c: [B, A], d: [-1234605616436508552, 1234605616436508552] }], \ + e: 1, f: [-9223372036854775808, 9223372036854775807] }) }" + ); +} + +#[test] +#[should_panic] +fn assert_on_too_small_array_buf() { + let a = [0u8; 19]; + unsafe { flatbuffers::Array::::new(&a) }; +} + +#[test] +#[should_panic] +fn assert_on_too_big_array_buf() { + let a = [0u8; 21]; + unsafe { flatbuffers::Array::::new(&a) }; +} + +#[test] +#[cfg(target_endian = "little")] +fn verify_struct_array_alignment() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(&mut b); + let buf = b.finished_data(); + let array_table = root_as_array_table(buf).unwrap(); + let array_struct = array_table.a().unwrap(); + let struct_start_ptr = array_struct.0.as_ptr() as usize; + let b_start_ptr = array_struct.b().as_ptr() as usize; + let d_start_ptr = array_struct.d().as_ptr() as usize; + // The T type of b + let b_aln = ::core::mem::align_of::(); + assert_eq!((b_start_ptr - struct_start_ptr) % b_aln, 0); + assert_eq!((d_start_ptr - b_start_ptr) % b_aln, 0); + assert_eq!((d_start_ptr - struct_start_ptr) % 8, 0); +} + +#[derive(Clone, Debug)] +struct FakeArray([T; N]); + +impl Arbitrary for FakeArray { + fn arbitrary(g: &mut G) -> FakeArray { + let x: [T; N] = array_init(|_| { + loop { + let generated_scalar = T::arbitrary(g); + // Verify that generated scalar is not Nan, which is not equals to itself, + // therefore we can't use it to validate input == output + if generated_scalar == generated_scalar { return generated_scalar; } + } + }); + FakeArray { 0: x } + } +} + +#[cfg(test)] +mod array_fuzz { + #[cfg(not(miri))] // slow. + extern crate quickcheck; + extern crate flatbuffers; + + use self::flatbuffers::{Follow, Push}; + use super::*; + + const MAX_TESTS: u64 = 20; + const ARRAY_SIZE: usize = 29; + + // This uses a macro because lifetimes for the trait-bounded function get too + // complicated. + macro_rules! impl_prop { + ($test_name:ident, $fn_name:ident, $ty:ident) => ( + fn $fn_name(xs: FakeArray<$ty, ARRAY_SIZE>) { + let mut test_buf = [0 as u8; 1024]; + let arr: flatbuffers::Array<$ty, ARRAY_SIZE> = unsafe { + flatbuffers::emplace_scalar_array(&mut test_buf, 0, &xs.0); + flatbuffers::Array::follow(&test_buf, 0) + }; + let got: [$ty; ARRAY_SIZE] = arr.into(); + assert_eq!(got, xs.0); + } + #[test] + fn $test_name() { + quickcheck::QuickCheck::new().max_tests(MAX_TESTS).quickcheck($fn_name as fn(FakeArray<$ty, ARRAY_SIZE>)); + } + ) + } + + impl_prop!(test_bool, prop_bool, bool); + impl_prop!(test_u8, prop_u8, u8); + impl_prop!(test_i8, prop_i8, i8); + impl_prop!(test_u16, prop_u16, u16); + impl_prop!(test_u32, prop_u32, u32); + impl_prop!(test_u64, prop_u64, u64); + impl_prop!(test_i16, prop_i16, i16); + impl_prop!(test_i32, prop_i32, i32); + impl_prop!(test_i64, prop_i64, i64); + impl_prop!(test_f32, prop_f32, f32); + impl_prop!(test_f64, prop_f64, f64); + + const NESTED_STRUCT_SIZE: usize = size_of::(); + + #[derive(Clone, Debug, PartialEq)] + struct NestedStructWrapper(NestedStruct); + + impl Arbitrary for NestedStructWrapper { + fn arbitrary(g: &mut G) -> NestedStructWrapper { + let mut x = NestedStruct::default(); + x.0 = FakeArray::::arbitrary(g).0; + NestedStructWrapper { 0: x } + } + } + + fn prop_struct(xs: FakeArray) { + let mut test_buf = [0 as u8; 1024]; + let native_struct_array: [&NestedStruct; ARRAY_SIZE] = array_init::from_iter(xs.0.iter().map(|x| &x.0)).unwrap(); + for i in 0..ARRAY_SIZE { + let offset = i * NESTED_STRUCT_SIZE; + unsafe { native_struct_array[i].push(&mut test_buf[offset..offset + NESTED_STRUCT_SIZE], 0) }; + } + let arr: flatbuffers::Array = unsafe { flatbuffers::Array::follow(&test_buf, 0) }; + let got: [&NestedStruct; ARRAY_SIZE] = arr.into(); + assert_eq!(got, native_struct_array); + } + + #[test] + #[cfg(not(miri))] // slow. + fn test_struct() { + quickcheck::QuickCheck::new().max_tests(MAX_TESTS).quickcheck(prop_struct as fn(FakeArray)); + } +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs new file mode 100644 index 00000000000..84fd21be299 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/binary_format.rs @@ -0,0 +1,535 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use flexbuffers::*; +use serde::Serialize; + +#[test] +fn store_13() { + let buf = singleton(13i32); + assert_eq!(&buf, &[13, 4, 1]); +} +#[test] +fn store_2pow20() { + let buf = singleton(1_048_576i32); + assert_eq!( + &buf, + &[ + 0, + 0, + 16, + 0, // 2^20 in LE bytes. + 1 << 2 | 2, // Int 32bit + 4 // Root width 32 bit + ] + ); +} + +#[test] +fn heterogenous_vector_of_string_because_width() { + // Each string is 32 characters. They are 256 bytes altogether. + // This forces the vector to be W16 because of the large offsets. + let test_data = [ + "0aaabbbbccccddddeeeeffffgggghhh", + "1aaabbbbccccddddeeeeffffgggghhh", + "2aaabbbbccccddddeeeeffffgggghhh", + "3aaabbbbccccddddeeeeffffgggghhh", + "4aaabbbbccccddddeeeeffffgggghhh", + "5aaabbbbccccddddeeeeffffgggghhh", + "6aaabbbbccccddddeeeeffffgggghhh", + "7aaabbbbccccddddeeeeffffgggghhh", + ]; + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + for &s in test_data.iter() { + v.push(s); + } + v.end_vector(); + let mut expected = vec![]; + for &s in test_data.iter() { + expected.push(s.len() as u8); + expected.extend(s.bytes()); + expected.push(b'\0'); + } + expected.extend(8u16.to_le_bytes().iter()); // Length. + for i in 0..test_data.len() as u16 { + let offset = 32 * (8 - i) + 9 + i; + expected.extend(offset.to_le_bytes().iter()); + } + for _ in 0..test_data.len() { + expected.push(5 << 2 | 0); // String, W8. + } + expected.push(24); // Offset to Vector. + expected.push(10 << 2 | 1); // Vector, W16. + expected.push(1); // Root width W8. + assert_eq!(fxb.view(), expected.as_slice()); +} + +#[test] +fn store_vec_uint_16() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(256u16); + v.push(257u16); + v.push(258u16); + v.push(259u16); + v.push(0u8); // This still becomes u16. + v.end_vector(); + assert_eq!( + fxb.view(), + &[ + 5, + 0, + 0, + 1, + 1, + 1, + 2, + 1, + 3, + 1, + 0, + 0, // Data + 10, // Vector offset. + 12 << 2 | 1, // (VectorUInt, W16 - referring to data). + 1, // Root width W8 - referring to vector. + ] + ); +} + +#[cfg(not(miri))] // slow. +quickcheck! { + fn qc_f32(x: f32) -> bool { + let fxb = singleton(x); + let mut expected = x.to_le_bytes().to_vec(); + expected.push(3 << 2 | 2); // Float W32. + expected.push(4); // Root width W32. + fxb == expected + } +} + +#[test] +fn singleton_vector_uint_4_16bit() { + let buf = singleton(&[4u16, 16, 64, 256]); + assert_eq!( + &buf, + &[ + 4, + 0, + 16, + 0, + 64, + 0, + 0, + 1, // Data + 8, // Vector offset. + 23 << 2 | 1, // (VectorUInt, W16 - referring to data). + 1, // Root width W8 - referring to vector. + ] + ); +} +#[test] +fn store_u64() { + let buf = singleton(u64::max_value() - 10); + assert_eq!( + &buf, + &[ + 245, + 255, + 255, + 255, + 255, + 255, + 255, + 255, // max value - 10. + 2 << 2 | 3, // (UInt, W64) + 8, // Root width W64. + ] + ); +} +#[test] +fn vector_uint4() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(2u8); + v.push(3u8); + v.push(5u8); + v.push(7u8); + v.end_vector(); + assert_eq!( + &fxb.view(), + &[ + 2, + 3, + 5, + 7, // data + 4, // Root (offset) + 23 << 2 | 0, // Root type VectorUInt4, BitWidth::W8 + 1, // Root bitwidth W8 + ] + ); +} +#[test] +fn nested_vector() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(0u8); + { + let mut nested = v.start_vector(); + nested.push(1u8); + nested.push(2u8); + nested.push(3u8); + } + v.push(-42i8); + v.end_vector(); + assert_eq!( + fxb.view(), + &[ + 1, + 2, + 3, // Nested vector + 3, + 0, + 5, + 214, // Root Vector: size, v[0], v[1] (offset), v[2] as u8 + 2 << 2 | 0, // v[0]: (UInt, W8) + 20 << 2 | 0, // v[1]: (VectorUInt3, W8) + 1 << 2 | 0, // v[2]: (Int, W8) + 6, // Root points to Root vector + 10 << 2 | 0, // Root type and width (Vector, W8) + 1, // Root bytes + ] + ) +} + +#[test] +fn nested_vector_push_direct() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(0u8); + v.push(&[1u8, 2, 3]); + v.push(-42i8); + v.end_vector(); + assert_eq!( + fxb.view(), + &[ + 1, + 2, + 3, // Nested VectorUInt3 + 3, + 0, + 5, + 214, // Root Vector: size, v[0], v[1] (offset), v[2] as u8 + 2 << 2 | 0, // v[0]: (UInt, W8) + 20 << 2 | 0, // v[1]: (VectorUInt3, W8) + 1 << 2 | 0, // v[2]: (Int, W8) + 6, // Root points to Root vector + 10 << 2 | 0, // Root type and width (Vector, W8) + 1, // Root bytes + ] + ) +} +#[test] +fn store_map_index_into_it() { + let mut fxb = Builder::default(); + { + let mut m = fxb.start_map(); + m.push("foo", 17u8); + m.push("bar", 33u16); + m.push("baz", 41u32); + } + assert_eq!( + fxb.view(), + &[ + b'f', + b'o', + b'o', + b'\0', + b'b', + b'a', + b'r', + b'\0', + b'b', + b'a', + b'z', + b'\0', + 3, + 9, + 6, + 15, // Keys vector (note "bar" < "baz" < "foo"). + 3, + 1, + 3, // map prefix + 33, + 41, + 17, // values + 8, + 8, + 8, // types (UInt, W8) ~ (2 << 2 | 0) + 6, // Offset to map (root) + 9 << 2 | 0, // Root type (map) + 1, // Root bytes + ] + ); +} +#[test] +fn utf8_snowman() { + let buf = singleton("snowman ☃︎"); + assert_eq!( + &buf, + &[ + 14, // Byte length (besides extra null terminator). + b's', + b'n', + b'o', + b'w', + b'm', + b'a', + b'n', + b' ', + 226, + 152, + 131, // snowman bytes + 239, + 184, + 142, // UTF Variation selector 15 + 0, // extra null terminator. + 15, // Offset to string start. + 5 << 2, // String, W8 + 1, // Root bytes + ] + ); + let r = Reader::get_root(buf.as_ref()).unwrap(); + assert_eq!(r.get_str(), Ok("snowman ☃︎")); +} +#[test] +fn indirect_numbers() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(IndirectUInt(u64::max_value())); + v.push(IndirectInt(i64::min_value())); + // TODO(cneo): Something about Float EPSILON and casting leads to a different binary format. + v.push(IndirectFloat(core::f64::consts::PI)); + v.push(0u32); // This is stored in 8 bits instead of 64 because of indirection. + v.end_vector(); + assert_eq!( + fxb.view(), + vec![ + 255, + 255, + 255, + 255, + 255, + 255, + 255, + 255, // u64 max + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 128, // i64 min value + 24, + 45, + 68, + 84, + 251, + 33, + 9, + 64, // f64 PI. + 4, // Vector length + 25, + 18, + 11, + 0, // offsets to the indirect numbers and zero. + 7 << 2 | 3, // IndirectUInt 64 bit + 6 << 2 | 3, // IndirectInt 64 bit + 8 << 2 | 3, // IndirectFloat 64 bit + 2 << 2 | 0, // (inline) UInt 8 bit + 8, // Offset to Root. + 10 << 2 | 0, // Vector 8 bit + 1, // 1 byte root + ] + .as_slice() + ) +} +#[test] +fn indirect_2p5x_smaller() { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for i in 0..512 { + v.push(i); + } + v.push(i64::max_value()); + v.end_vector(); + let len_without_indirect = builder.view().len() as f32; + + let mut v = builder.start_vector(); + for i in 0..512 { + v.push(i); + } + v.push(IndirectInt(i64::max_value())); + v.end_vector(); + let len_with_indirect = builder.view().len() as f32; + assert!(len_with_indirect * 2.5 < len_without_indirect); +} +#[test] +fn key_pool() { + let mut builder = Builder::default(); + let mut vector = builder.start_vector(); + for _ in 0..2 { + let mut m = vector.start_map(); + m.push("a", 42u8); + m.push("b", 42u8); + m.push("c", 42u8); + } + vector.end_vector(); + + assert_eq!( + builder.view(), + vec![ + b'a', + b'\0', + b'b', + b'\0', + b'c', + b'\0', + 3, + 7, + 6, + 5, // Key vector 0 + 3, + 1, + 3, + 42, + 42, + 42, + 2 << 2, + 2 << 2, + 2 << 2, // Map 0. + 3, + 20, + 19, + 18, // Key vector 1 (shares keys with key vector 0). + 3, + 1, + 3, + 42, + 42, + 42, + 2 << 2, + 2 << 2, + 2 << 2, // Map 1. + 2, + 20, + 8, + 9 << 2, + 9 << 2, // Vector containing the maps. + 4, + 10 << 2, + 1, // Root. + ] + .as_slice() + ); +} + +#[test] +fn serialize_unit() { + #[derive(Serialize)] + struct Foo; + let mut s = FlexbufferSerializer::new(); + Foo.serialize(&mut s).unwrap(); + assert_eq!(s.view(), &[0, 0, 1]); +} + +#[test] +fn serialize_i8() { + let mut s = FlexbufferSerializer::new(); + 13i8.serialize(&mut s).unwrap(); + assert_eq!(s.view(), &[13, 4, 1]); +} +#[test] +fn serialize_tuple_struct_i8() { + #[derive(Serialize)] + struct Foo(i32); + let mut s = FlexbufferSerializer::new(); + Foo(13).serialize(&mut s).unwrap(); + assert_eq!(s.view(), &[13, 4, 1]); +} +#[test] +fn serialize_tuple_tuple_struct_i8_is_inlined() { + #[derive(Serialize)] + struct Foo(i32); + #[derive(Serialize)] + struct Bar(Foo); + let mut s = FlexbufferSerializer::new(); + Bar(Foo(13)).serialize(&mut s).unwrap(); + assert_eq!(s.view(), &[13, 4, 1]); +} +#[test] +fn align_8byte() { + let mut b = Builder::default(); + let mut v = b.start_vector(); + v.push(IndirectUInt(42)); + v.push(&[u64::max_value(); 2]); + v.end_vector(); + assert_eq!( + b.view()[..16], + [ + 42, 0, 0, 0, 0, 0, 0, 0, // padding + 255, 255, 255, 255, 255, 255, 255, 255, // the first u64 max value. + ] + ); +} +#[test] +fn align_4byte() { + let mut b = Builder::default(); + let mut v = b.start_vector(); + v.push(IndirectUInt(42)); + v.push(&[u32::max_value(); 2]); + v.end_vector(); + assert_eq!( + b.view()[..8], + [ + 42, 0, 0, 0, // padding + 255, 255, 255, 255, // the first u32 max value. + ] + ); +} +#[test] +fn align_2byte() { + let mut b = Builder::default(); + let mut v = b.start_vector(); + v.push(IndirectUInt(42)); + v.push(&[u16::max_value(); 2]); + v.end_vector(); + assert_eq!( + b.view()[..4], + [ + 42, 0, // padding + 255, 255, // the first u16 max value. + ] + ); +} +#[test] +fn align_1byte() { + let mut b = Builder::default(); + let mut v = b.start_vector(); + v.push(IndirectUInt(42)); + v.push(&[u8::max_value(); 2]); + v.end_vector(); + assert_eq!(b.view()[..2], [42, 255]); // No padding. +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs new file mode 100644 index 00000000000..705948f69e6 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/interop.rs @@ -0,0 +1,50 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use flexbuffers::*; + +#[test] +fn read_golden_flexbuffer() { + let s = + std::fs::read("../gold_flexbuffer_example.bin").expect("Unable to read golden flexbuffer."); + let r = Reader::get_root(s.as_ref()).unwrap(); + let m = r.as_map(); + + let vec = m.idx("vec").as_vector(); + assert_eq!(vec.idx(0).as_i8(), -100); + assert_eq!(vec.idx(1).as_str(), "Fred"); + assert_eq!(vec.idx(2).as_f32(), 4.0); + assert_eq!(vec.idx(3).as_blob(), Blob([77].as_ref())); + assert_eq!(vec.idx(4).flexbuffer_type(), FlexBufferType::Bool); + assert_eq!(vec.idx(4).as_bool(), false); + assert_eq!(vec.idx(5).as_f64(), 4.0); + + let bar = m.idx("bar").as_vector(); + for (i, &x) in [1, 2, 3].iter().enumerate() { + assert_eq!(bar.idx(i).as_i8(), x); + } + let bar3 = m.idx("bar3").as_vector(); + for (i, &x) in [1, 2, 3].iter().enumerate() { + assert_eq!(bar3.idx(i).as_i8(), x); + } + let bools = m.idx("bools").as_vector(); + for (i, &b) in [true, false, true, false].iter().enumerate() { + assert_eq!(bools.idx(i).as_bool(), b) + } + + assert_eq!(m.idx("bool").as_bool(), true); + assert_eq!(m.idx("foo").as_f64(), 100.0); + let mymap = m.idx("mymap").as_map(); + assert_eq!(mymap.idx("foo").as_str(), "Fred"); +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs new file mode 100644 index 00000000000..ee52aca3062 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/mod.rs @@ -0,0 +1,21 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +mod binary_format; +#[cfg(not(feature = "no_std"))] // uses file I/O +mod interop; +mod other_api; +#[cfg(not(miri))] // slow. +mod qc_serious; +mod rwyw; diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs new file mode 100644 index 00000000000..9875c2282e5 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/other_api.rs @@ -0,0 +1,211 @@ +// Copyright 2020 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use alloc::vec::Vec; + +use flexbuffers::*; +#[cfg(not(miri))] // slow. +use quickcheck::QuickCheck; + +#[test] +#[cfg(not(miri))] // slow. +fn qc_reader_no_crash() { + fn no_crash(xs: Vec) -> bool { + let r = Reader::get_root(xs.as_ref()); + r.is_err() || r.is_ok() + } + QuickCheck::new() + .min_tests_passed(10_000_000) + .quicktest(no_crash as fn(Vec) -> bool) + .unwrap(); + + no_crash(vec![0, 10 << 2 | 2, 0]); +} +#[test] +fn as_num() { + let mut fxb = Builder::default(); + let mut m = fxb.start_map(); + m.push("a", &[-1i8, -2, -3, -4]); + m.push("b", 250i64); + m.push("c", 5000u16); + m.end_map(); + + let r = Reader::get_root(fxb.view()).unwrap(); + assert_eq!(r.as_i8(), 3); // length. + assert_eq!(r.as_i16(), 3); + assert_eq!(r.as_i32(), 3); + assert_eq!(r.as_i64(), 3); + assert_eq!(r.as_u8(), 3); + assert_eq!(r.as_u16(), 3); + assert_eq!(r.as_u32(), 3); + assert_eq!(r.as_u64(), 3); + assert_eq!(r.as_f32(), 3.0); + assert_eq!(r.as_f64(), 3.0); + + let m = r.as_map(); + let a = m.index("a").unwrap(); + assert_eq!(a.as_f32(), 4.0); // length. + assert_eq!(a.as_f64(), 4.0); // length. + assert_eq!(a.as_vector().idx(0).as_i8(), -1); + assert_eq!(a.as_vector().idx(1).as_i16(), -2); + assert_eq!(a.as_vector().idx(2).as_i32(), -3); + assert_eq!(a.as_vector().idx(3).as_i64(), -4); + + let b = m.index("b").unwrap(); + assert_eq!(b.as_u8(), 250); + assert_eq!(b.as_u16(), 250); + assert_eq!(b.as_u32(), 250); + assert_eq!(b.as_u64(), 250); + assert_eq!(b.as_i8(), 0); // overflow + assert_eq!(b.as_i16(), 250); + assert_eq!(b.as_i32(), 250); + assert_eq!(b.as_i64(), 250); + + let c = m.index("c").unwrap(); + assert_eq!(c.as_i64(), 5000); + assert_eq!(c.as_u64(), 5000); + assert_eq!(c.as_f32(), 5000.0); + assert_eq!(c.as_u8(), 0); // overflow + assert_eq!(c.as_u16(), 5000); + assert_eq!(c.as_u32(), 5000); + assert_eq!(c.as_u64(), 5000); + assert_eq!(c.as_i8(), 0); // overflow + assert_eq!(c.as_i16(), 5000); + assert_eq!(c.as_i32(), 5000); + assert_eq!(c.as_i64(), 5000); +} +#[test] +fn string_as_num() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push("3.1415"); + v.push("9.001e3"); + v.push("42"); + v.end_vector(); + let r = Reader::get_root(fxb.view()).unwrap(); + + let v0 = r.as_vector().idx(0); + assert_eq!(v0.as_f64(), 3.1415); + assert_eq!(v0.as_f32(), 3.1415); + assert_eq!(v0.as_u8(), 0); + assert_eq!(v0.as_u16(), 0); + assert_eq!(v0.as_u32(), 0); + assert_eq!(v0.as_u64(), 0); + assert_eq!(v0.as_i8(), 0); + assert_eq!(v0.as_i16(), 0); + assert_eq!(v0.as_i32(), 0); + assert_eq!(v0.as_i64(), 0); + + let v1 = r.as_vector().idx(1); + assert_eq!(v1.as_f64(), 9001.0); + assert_eq!(v1.as_f32(), 9001.0); + assert_eq!(v1.as_u8(), 0); + assert_eq!(v1.as_u16(), 0); + assert_eq!(v1.as_u32(), 0); + assert_eq!(v1.as_u64(), 0); + assert_eq!(v1.as_i8(), 0); + assert_eq!(v1.as_i16(), 0); + assert_eq!(v1.as_i32(), 0); + assert_eq!(v1.as_i64(), 0); + assert_eq!(v1.as_i32(), 0); + + let v2 = r.as_vector().idx(2); + assert_eq!(v2.as_f64(), 42.0); + assert_eq!(v2.as_f32(), 42.0); + assert_eq!(v2.as_u8(), 42); + assert_eq!(v2.as_u16(), 42); + assert_eq!(v2.as_u32(), 42); + assert_eq!(v2.as_u64(), 42); + assert_eq!(v2.as_i8(), 42); + assert_eq!(v2.as_i16(), 42); + assert_eq!(v2.as_i32(), 42); + assert_eq!(v2.as_i64(), 42); + assert_eq!(v2.as_i32(), 42); +} +#[test] +fn null_reader() { + let n = Reader::<&[u8]>::default(); + assert_eq!(n.as_i8(), 0); + assert_eq!(n.as_i16(), 0); + assert_eq!(n.as_i32(), 0); + assert_eq!(n.as_i64(), 0); + assert_eq!(n.as_u8(), 0); + assert_eq!(n.as_u16(), 0); + assert_eq!(n.as_u32(), 0); + assert_eq!(n.as_u64(), 0); + assert_eq!(n.as_f32(), 0.0); + assert_eq!(n.as_f64(), 0.0); + assert!(n.get_i64().is_err()); + assert!(n.get_u64().is_err()); + assert!(n.get_f64().is_err()); + assert!(n.as_vector().is_empty()); + assert!(n.as_map().is_empty()); + assert_eq!(n.as_vector().idx(1).flexbuffer_type(), FlexBufferType::Null); + assert_eq!(n.as_map().idx("1").flexbuffer_type(), FlexBufferType::Null); +} +#[test] +fn get_root_deref_oob() { + let s = &[ + 4, // Deref out of bounds + (FlexBufferType::Vector as u8) << 2 | BitWidth::W8 as u8, + 1, + ]; + assert!(Reader::get_root(s.as_ref()).is_err()); +} +#[test] +fn get_root_deref_u64() { + let s = &[ + 0, + 0, + (FlexBufferType::IndirectUInt as u8) << 2 | BitWidth::W64 as u8, + 1, + ]; + // The risk of crashing is reading 8 bytes from index 0. + assert_eq!(Reader::get_root(s.as_ref()).unwrap().as_u64(), 0); +} + +/// Verifies that the clone operation is shallow / zero copy. +#[test] +fn clone_is_shallow() { + let mut fxb = Builder::default(); + let mut m = fxb.start_map(); + m.push("a", &[-1i8, -2, -3, -4]); + m.push("b", 250i64); + m.push("c", 5000u16); + m.end_map(); + + let r = Reader::get_root(fxb.view()).unwrap(); + + let r2 = r.clone(); + + assert_eq!(r.buffer().as_ptr(), r2.buffer().as_ptr()); +} + +#[test] +#[should_panic] +fn build_map_panic_on_repeated_key() { + let mut b = Builder::default(); + let mut m = b.start_map(); + m.push("foo", 5u8); + m.push("foo", 6u8); + m.end_map(); +} +#[test] +#[should_panic] +fn build_map_panic_on_internal_null() { + let mut b = Builder::default(); + let mut m = b.start_map(); + m.push("foo\0", 5u8); + m.end_map(); +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs new file mode 100644 index 00000000000..b2e04ecfda5 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/qc_serious.rs @@ -0,0 +1,148 @@ +use alloc::collections::BTreeMap; +use alloc::string::String; +use alloc::vec::Vec; + +use super::rwyw::NonNullString; +use flexbuffers::*; +use quickcheck::{Arbitrary, Gen}; + +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] +enum Enum { + Unit, + U8(u8), + U16(u16), + U32(u32), + U64(u64), + Us(u8, u16, u32, u64), + I8(i8), + I16(i16), + I32(i32), + I64(i64), + Is(i8, i16, i32, i64), + F32(f32), + F64(f64), + Fs(f32, f64), + String(String), + Strings(String, String), + Everything(u8, u16, u32, u64, i8, i16, i32, i64, f32, f64, String), + Arrays { + a: Array3, + b: Array4, + c: Array2, + }, + Blobs(#[serde(with = "serde_bytes")] Vec), +} + +// There is some upstream bug in deriving Arbitrary for Enum so we manually implement it here. +impl Arbitrary for Enum { + fn arbitrary(g: &mut G) -> Self { + match g.gen_range(0, 18) { + 0 => Enum::Unit, + 1 => Enum::U8(::arbitrary(g)), + 2 => Enum::U16(::arbitrary(g)), + 3 => Enum::U32(::arbitrary(g)), + 4 => Enum::U64(::arbitrary(g)), + 5 => { + let (a, b, c, d) = <(u8, u16, u32, u64)>::arbitrary(g); + Enum::Us(a, b, c, d) + } + 6 => Enum::I8(::arbitrary(g)), + 7 => Enum::I16(::arbitrary(g)), + 8 => Enum::I32(::arbitrary(g)), + 9 => Enum::I64(::arbitrary(g)), + 10 => { + let (a, b, c, d) = <(i8, i16, i32, i64)>::arbitrary(g); + Enum::Is(a, b, c, d) + } + 11 => Enum::F32(::arbitrary(g)), + 12 => Enum::F64(::arbitrary(g)), + 13 => { + let (a, b) = <(f32, f64)>::arbitrary(g); + Enum::Fs(a, b) + } + 14 => Enum::String(String::arbitrary(g)), + 15 => { + let (a, b) = <(String, String)>::arbitrary(g); + Enum::Strings(a, b) + } + 16 => Enum::Everything( + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ::arbitrary(g), + ), + 17 => { + let a = Array3::arbitrary(g); + let b = Array4::arbitrary(g); + let c = Array2::arbitrary(g); + Enum::Arrays { a, b, c } + } + _ => unreachable!(), + } + } +} + +#[derive(Debug, Clone, Arbitrary, PartialEq, Serialize, Deserialize)] +struct Unit; + +#[derive(Debug, Clone, Arbitrary, PartialEq, Serialize, Deserialize)] +struct NewType(bool); + +#[derive(Debug, Clone, Arbitrary, PartialEq, Serialize, Deserialize)] +struct Tuple(bool, u8, i16, f32, String); + +#[derive(Debug, Clone, Arbitrary, PartialEq, Serialize, Deserialize)] +struct Struct { + a: Vec, + b: BTreeMap, + c: Tuple, + d: (Unit, Unit), + e: Array4, +} + +#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Serialize, Deserialize)] +struct Array2([A; 2]); +#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Serialize, Deserialize)] +struct Array3([A; 3]); +#[derive(Debug, Clone, PartialOrd, Ord, PartialEq, Eq, Serialize, Deserialize)] +struct Array4([A; 4]); + +impl Arbitrary for Array2 { + fn arbitrary(g: &mut G) -> Self { + Array2([A::arbitrary(g), A::arbitrary(g)]) + } +} +impl Arbitrary for Array3 { + fn arbitrary(g: &mut G) -> Self { + Array3([A::arbitrary(g), A::arbitrary(g), A::arbitrary(g)]) + } +} +impl Arbitrary for Array4 { + fn arbitrary(g: &mut G) -> Self { + Array4([ + A::arbitrary(g), + A::arbitrary(g), + A::arbitrary(g), + A::arbitrary(g), + ]) + } +} + +quickcheck! { + fn qc_serious(original: Struct) -> bool { + let struct_buf = flexbuffers::to_vec(&original).unwrap(); + let root = Reader::get_root(&*struct_buf).unwrap(); + let reader_buf = flexbuffers::to_vec(&root).unwrap(); + let deserialized: Struct = flexbuffers::from_slice(&struct_buf).unwrap(); + let reserialized: Struct = flexbuffers::from_slice(&reader_buf).unwrap(); + + original == deserialized && original == reserialized + } +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs new file mode 100644 index 00000000000..478d33aef3b --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/flexbuffers_tests/rwyw.rs @@ -0,0 +1,517 @@ +// Copyright 2019 Google LLC +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// https://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +use alloc::string::{String, ToString}; +use alloc::vec::Vec; + +// Read what you wrote. +use flexbuffers::*; +#[cfg(not(miri))] // slow. +use quickcheck; +use serde::{Deserialize, Serialize}; + +// TODO(cneo): Upstream this to the quickcheck crate. Also, write a macro to derive Arbitrary. +#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Debug, Serialize, Deserialize)] +pub struct NonNullString(String); +impl quickcheck::Arbitrary for NonNullString { + fn arbitrary(g: &mut G) -> Self { + let size = core::cmp::min(1, usize::arbitrary(g)); + NonNullString( + (0..) + .map(|_| ::arbitrary(g)) + .filter(|&b| b != '\0') + .take(size) + .collect(), + ) + } +} + +#[cfg(not(miri))] // slow. +quickcheck! { + fn qc_vec_bool(xs: Vec) -> bool { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for &x in &xs { + v.push(x); + } + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + xs.iter().enumerate().all(|(i, &x)| r.index(i).unwrap().get_bool().unwrap() == x) + } + fn qc_vec_uint(xs: Vec) -> bool { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for &x in &xs { + v.push(x); + } + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + xs.iter().enumerate().all(|(i, &x)| r.idx(i).as_u64() == x) + } + fn qc_vec_int(xs: Vec) -> bool { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for &x in &xs { + v.push(x); + } + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + xs.iter().enumerate().all(|(i, &x)| r.idx(i).as_i64() == x) + } + fn qc_vec_float(xs: Vec) -> bool { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for &x in &xs { + v.push(x); + } + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + xs.iter().enumerate().all(|(i, &x)| (r.idx(i).as_f64() - x).abs() < core::f64::EPSILON) + } + fn qc_vec_string(xs: Vec) -> bool { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for x in &xs { + v.push(x as &str); + } + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + xs.iter().enumerate().all(|(i, x)| (r.idx(i).as_str() == x)) + } + #[cfg(not(feature = "no_std"))] + fn qc_map_int(xs: std::collections::BTreeMap) -> bool { + let mut builder = Builder::default(); + let mut m = builder.start_map(); + for (k, &v) in &xs { + m.push(&k.0, v); + } + m.end_map(); + let r = Reader::get_root(builder.view()).unwrap().as_map(); + xs.iter().enumerate().all(|(i, (k, &v))| { + r.idx(i).as_i64() == v && r.idx(k.0.as_str()).as_i64() == v + }) + } + #[cfg(not(feature = "no_std"))] + fn qc_map_string(xs: std::collections::BTreeMap) -> bool { + let mut builder = Builder::default(); + let mut m = builder.start_map(); + for (k, v) in &xs { + m.push(&k.0, v as &str); + } + m.end_map(); + let r = Reader::get_root(builder.view()).unwrap().as_map(); + xs.iter().enumerate().all(|(i, (k, v))| { + r.idx(i).as_str() == v && r.idx(k.0.as_str()).as_str() == v + }) + } + fn qc_blob(xs: Vec>) -> bool { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + for x in &xs { + v.push(Blob(x.as_ref())); + } + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + xs.iter().enumerate().all( + |(i, x)| r.idx(i).get_blob().unwrap().0.iter().eq(x.iter()) + ) + } + fn qc_serde_ints( + u8s: Vec, + u16s: Vec, + u32s: Vec, + u64s: Vec, + i8s: Vec, + i16s: Vec, + i32s: Vec, + i64s: Vec + ) -> bool { + #[derive(Serialize, Deserialize, PartialEq)] + struct Foo { + u8s: Vec, + u16s: Vec, + u32s: Vec, + u64s: Vec, + i8s: Vec, + i16s: Vec, + i32s: Vec, + i64s: Vec, + } + let mut ser = FlexbufferSerializer::new(); + let foo1 = Foo { u8s, u16s, u32s, u64s, i8s, i16s, i32s, i64s }; + foo1.serialize(&mut ser).unwrap(); + let r = Reader::get_root(ser.view()).unwrap(); + let foo2 = Foo::deserialize(r).unwrap(); + foo1 == foo2 + } + fn qc_serde_others( + bools: Vec, + strings: Vec, + f32s: Vec, + f64s: Vec + ) -> bool { + #[derive(Serialize, Deserialize, PartialEq)] + struct Foo { + bools: Vec, + strings: Vec, + f32s: Vec, + f64s: Vec, + } + let mut ser = FlexbufferSerializer::new(); + let foo1 = Foo { bools, strings, f32s, f64s }; + foo1.serialize(&mut ser).unwrap(); + let r = Reader::get_root(ser.view()).unwrap(); + let foo2 = Foo::deserialize(r).unwrap(); + foo1 == foo2 + } + fn qc_serde_others2( + bools: Vec, + strings: Vec, + f32s: Vec, + f64s: Vec + ) -> bool { + #[derive(Serialize, Deserialize, PartialEq)] + struct Foo (Vec, Vec, Vec, Vec); + let mut ser = FlexbufferSerializer::new(); + let foo1 = Foo(bools, strings, f32s, f64s); + foo1.serialize(&mut ser).unwrap(); + let r = Reader::get_root(ser.view()).unwrap(); + let foo2 = Foo::deserialize(r).unwrap(); + foo1 == foo2 + } + +} + +#[test] +fn empty_vectors() { + #[derive(PartialEq, Serialize, Deserialize, Default, Debug)] + struct Foo(Vec, Vec); + let foo1 = Foo::default(); + let mut s = FlexbufferSerializer::new(); + foo1.serialize(&mut s).unwrap(); + let r = Reader::get_root(s.view()).unwrap(); + let foo2 = Foo::deserialize(r).unwrap(); + assert_eq!(foo1, foo2); +} + +#[test] +fn string() { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + v.push("foo"); + v.push("barrr"); + v.push("bazzzzzz"); + v.end_vector(); + let r = Reader::get_root(builder.view()).unwrap().as_vector(); + assert_eq!(r.idx(0).as_str(), "foo"); + assert_eq!(r.idx(1).as_str(), "barrr"); + assert_eq!(r.idx(2).as_str(), "bazzzzzz"); +} + +#[test] +fn store_13() { + let finished = singleton::(13); + let r = Reader::get_root(finished.as_ref()).unwrap(); + assert_eq!(r.as_i32(), 13); +} +#[test] +fn singleton_vector_uint_4_16bit() { + let mut builder = Builder::default(); + let mut v = builder.start_vector(); + v.push(2u8); + v.push(3u8); + v.push(5u8); + v.end_vector(); + let buf1 = builder.view(); + let buf2 = singleton(&[2u8, 3, 5]); + assert_eq!(buf1, buf2.as_slice()); + + let r = Reader::get_root(buf1).unwrap().as_vector(); + assert_eq!(r.idx(0).get_u64(), Ok(2)); + assert_eq!(r.idx(1).get_u64(), Ok(3)); + assert_eq!(r.idx(2).get_u64(), Ok(5)); + assert_eq!(r.index(3).unwrap_err(), ReaderError::IndexOutOfBounds); +} +#[test] +fn vector_uint4() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(2u8); + v.push(3u8); + v.push(5u8); + v.push(7u8); + v.end_vector(); + let r = Reader::get_root(fxb.view()).unwrap(); + let v = r.as_vector(); + assert_eq!(v.idx(0).get_u64(), Ok(2)); + assert_eq!(v.idx(1).get_u64(), Ok(3)); + assert_eq!(v.idx(2).get_u64(), Ok(5)); + assert_eq!(v.idx(3).get_u64(), Ok(7)); + assert!(v.index(4).is_err()); + #[allow(deprecated)] + #[cfg(target_endian = "little")] + { + assert_eq!(r.get_slice::().unwrap(), [2, 3, 5, 7]); + } +} +#[test] +fn store_and_read_blob() { + let mut fxb = Builder::default(); + let mut v = fxb.start_vector(); + v.push(Blob([1, 2, 3, 4].as_ref())); + v.push(Blob([5, 6, 7].as_ref())); + v.end_vector(); + + let r = Reader::get_root(fxb.view()).unwrap().as_vector(); + assert_eq!(r.idx(0).get_blob(), Ok(Blob([1, 2, 3, 4].as_ref()))); + assert_eq!(r.idx(1).get_blob(), Ok(Blob([5, 6, 7].as_ref()))); +} +#[test] +fn map_64bit() { + let mut fxb = Builder::default(); + let mut m = fxb.start_map(); + m.push("a", 257u16); + m.push("b", u64::max_value() - 3); + m.end_map(); + + let r = Reader::get_root(fxb.view()).unwrap().as_map(); + assert_eq!(r.idx("a").as_u16(), 257); + assert_eq!(r.idx("b").as_u64(), u64::max_value() - 3); +} +#[test] +fn index_map() { + let mut fxb = Builder::default(); + let mut m = fxb.start_map(); + m.push("foo", 17u8); + m.push("bar", 33u16); + m.push("baz", 41u32); + m.end_map(); + + let r = Reader::get_root(fxb.view()).unwrap().as_map(); + assert_eq!(r.idx(0).get_u64(), Ok(33)); + assert_eq!(r.idx(1).get_u64(), Ok(41)); + assert_eq!(r.idx(2).as_u8(), 17); + assert_eq!(r.index(3).unwrap_err(), ReaderError::IndexOutOfBounds); + + assert_eq!(r.idx("bar").as_u64(), 33); + assert_eq!(r.idx("baz").as_u32(), 41); + assert_eq!(r.idx("foo").as_u16(), 17); + assert_eq!(r.index("???").unwrap_err(), ReaderError::KeyNotFound); +} + +#[test] +fn map_strings() { + let mut fxb = Builder::default(); + { + let mut m = fxb.start_map(); + let mut a = m.start_vector("a"); + for &s in ["b", "c", "d", "e"].iter() { + a.push(s); + } + a.end_vector(); + let mut f = m.start_vector("f"); + for &s in ["gh", "ij"].iter() { + f.push(s); + } + } + let r = Reader::get_root(fxb.view()).unwrap().as_map(); + let a = r.idx("a").as_vector(); + + assert_eq!(a.idx(0).as_str(), "b"); + assert_eq!(a.idx(1).as_str(), "c"); + assert_eq!(a.idx(2).as_str(), "d"); + assert_eq!(a.idx(3).as_str(), "e"); + + let f = r.idx("f").as_vector(); + assert_eq!(f.idx(0).as_str(), "gh"); + assert_eq!(f.idx(1).as_str(), "ij"); + + // Defaults to empty string for index errors. + assert_eq!(r.idx("a").as_vector().idx(4).as_str(), ""); + assert_eq!(r.idx("b").as_vector().idx(2).as_str(), ""); + assert_eq!(r.idx("c").as_str(), ""); +} + +#[test] +fn store_u64() { + let finished = singleton(u64::max_value() - 10); + let r = Reader::get_root(finished.as_ref()).unwrap(); + assert_eq!(r.get_u64(), Ok(u64::max_value() - 10)); +} +#[test] +fn store_indirects() { + let mut b = Builder::default(); + let mut v = b.start_vector(); + v.push(IndirectInt(-42)); + v.push(IndirectUInt(9000)); + v.push(IndirectFloat(3.14)); + v.end_vector(); + let r = Reader::get_root(b.view()).unwrap().as_vector(); + assert_eq!(r.idx(0).get_i64().unwrap(), -42); + assert_eq!(r.idx(1).get_u64().unwrap(), 9000); + assert_eq!(r.idx(2).get_f64().unwrap(), 3.14); +} + +#[derive(Serialize, Deserialize, Debug, PartialEq)] +struct Foo { + a: i8, + b: f64, + c: Vec, + d: String, +} + +#[cfg(not(miri))] // slow. +quickcheck! { + fn serde_foo(a: i8, + b: f64, + c: Vec, + d: String) -> bool { + let mut s = FlexbufferSerializer::new(); + let data = Foo { a, b, c, d }; + data.serialize(&mut s).unwrap(); + + let read = Foo::deserialize(Reader::get_root(s.view()).unwrap()).unwrap(); + data == read + } +} + +#[test] +fn serde_serious() { + #[derive(Debug, PartialEq, Serialize, Deserialize)] + enum MyEnum { + Unit, + NewType([i32; 3]), + Tuple(f32, f64), + Struct { a: u8, b: u16, c: u32 }, + } + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct MyNewType; + + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct MyStruct { + a: u8, + b: u16, + c: u32, + d: u64, + } + + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct MyUnitStruct(Vec); + + #[derive(Debug, PartialEq, Serialize, Deserialize)] + struct MyTupleStruct(MyNewType, MyUnitStruct, MyStruct, Vec); + + let data = MyTupleStruct( + MyNewType, + MyUnitStruct(vec!["Hello".to_string(), "World".to_string()]), + MyStruct { + a: 2, + b: 4, + c: 8, + d: 16, + }, + vec![ + MyEnum::Unit, + MyEnum::NewType([-1, 0, 1]), + MyEnum::Unit, + MyEnum::Tuple(3.14, 2.71), + MyEnum::Struct { + a: 32, + b: 64, + c: 128, + }, + ], + ); + + let mut s = FlexbufferSerializer::new(); + data.serialize(&mut s).unwrap(); + + let reader = Reader::get_root(s.view()).unwrap(); + let read = MyTupleStruct::deserialize(reader).unwrap(); + assert_eq!(data, read); +} +#[test] +fn serialize_serde_with_bytes_as_blob() { + #[derive(Serialize, Deserialize)] + struct Foo(#[serde(with = "serde_bytes")] Vec); + let mut s = FlexbufferSerializer::new(); + Foo(vec![5, 6, 7, 8]).serialize(&mut s).unwrap(); + let reader = Reader::get_root(s.view()).unwrap(); + assert_eq!(reader.flexbuffer_type(), FlexBufferType::Blob); + assert_eq!(reader.as_blob(), Blob([5, 6, 7, 8].as_ref())); +} +#[test] +fn iter() { + let mut fxb = Builder::default(); + { + let mut m = fxb.start_map(); + m.push("a", "42"); + m.push("b", 250i64); + m.push("c", 5000u16); + } + let r = Reader::get_root(fxb.view()).unwrap(); + + let v: Vec = r.as_vector().iter().map(|x| x.as_u32()).collect(); + assert_eq!(&v, &[42, 250, 5000]); +} + +#[test] +fn deserialize_newtype_i8() { + #[derive(Deserialize)] + struct Foo(u8); + let data = [13, 4, 1]; + let r = Reader::get_root(data.as_ref()).unwrap(); + let foo = Foo::deserialize(r).unwrap(); + assert_eq!(foo.0, 13); +} +#[test] +fn deserialize_newtype_str() { + #[derive(Deserialize)] + struct Foo<'a>(&'a str); + let data = [5, b'h', b'e', b'l', b'l', b'o', b'\0', 6, 5 << 2, 1]; + let r = Reader::get_root(data.as_ref()).unwrap(); + let foo = Foo::deserialize(r).unwrap(); + assert_eq!(foo.0, "hello"); +} +#[test] +#[rustfmt::skip] +fn deserialize_tuple_struct_to_vec_uint4() { + #[derive(Deserialize)] + struct Foo(u8, u16, u32, u64); + let data = [ + 4, 0, 16, 0, 64, 0, 0, 1, // Data + 8, // Vector offset. + 23 << 2 | 1, // (VectorUInt4, W16 - referring to data). + 1, // Root width W8 - referring to vector. + ]; + let r = Reader::get_root(data.as_ref()).unwrap(); + let foo = Foo::deserialize(r).unwrap(); + assert_eq!(foo.0, 4); + assert_eq!(foo.1, 16); + assert_eq!(foo.2, 64); + assert_eq!(foo.3, 256); + + let data = [ + 1, 2, 3, 4, // The vector. + 4, // Root data (offset). + 23 << 2, // Root type: VectorUInt4, W8. + 1, // Root width: W8. + ]; + let r = Reader::get_root(data.as_ref()).unwrap(); + let foo = Foo::deserialize(r).unwrap(); + assert_eq!(foo.0, 1); + assert_eq!(foo.1, 2); + assert_eq!(foo.2, 3); + assert_eq!(foo.3, 4); +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/integration_test.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/integration_test.rs new file mode 100644 index 00000000000..d3dc731ceeb --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/integration_test.rs @@ -0,0 +1,3235 @@ +/* + * + * Copyright 2018 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#![no_std] + +#[cfg(not(feature = "no_std"))] +extern crate std; +#[cfg(not(feature = "no_std"))] +use alloc::vec::Vec; + +#[macro_use] +extern crate alloc; + +use alloc::string::String; + +#[cfg(feature = "no_std")] +#[global_allocator] +static ALLOCATOR: libc_alloc::LibcAlloc = libc_alloc::LibcAlloc; + +#[macro_use] +#[cfg(not(miri))] // slow. +extern crate quickcheck; +extern crate flatbuffers; +extern crate flexbuffers; +extern crate rand; +extern crate serde; +#[macro_use] +extern crate serde_derive; +#[cfg(not(miri))] // slow. +#[macro_use] +extern crate quickcheck_derive; + +mod flexbuffers_tests; +mod more_defaults_test; +mod optional_scalars_test; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../include_test1/mod.rs"] +pub mod include_test1_generated; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../include_test2/mod.rs"] +pub mod include_test2_generated; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../namespace_test/mod.rs"] +pub mod namespace_test_generated; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../monster_test/mod.rs"] +mod monster_test_generated; +pub use monster_test_generated::my_game; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../optional_scalars/mod.rs"] +mod optional_scalars_generated; + +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../arrays_test/mod.rs"] +mod arrays_test_generated; + +// We use incorrect casing to test keywords. +#[allow(dead_code, unused_imports, non_camel_case_types, non_snake_case)] +#[path = "../../keyword_test/mod.rs"] +mod keyword_test_generated; + +// Test rust namer, should not cause compiling issues +#[allow(dead_code, unused_imports, clippy::all)] +#[path = "../../rust_namer_test/mod.rs"] +mod rust_namer_test; + +#[rustfmt::skip] // TODO: Use standard rust formatting and remove dead code. +#[allow(dead_code)] +mod flatbuffers_tests { +use super::*; + +// Include simple random number generator to ensure results will be the +// same across platforms. +// http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator +struct LCG(u64); +impl LCG { + fn new() -> Self { + LCG { 0: 48271 } + } + fn next(&mut self) -> u64 { + let old = self.0; + self.0 = (self.0 * 279470273u64) % 4294967291u64; + old + } + fn reset(&mut self) { + self.0 = 48271 + } +} + +// test helper macro to return an error if two expressions are not equal +macro_rules! check_eq { + ($field_call:expr, $want:expr) => ( + if $field_call == $want { + Ok(()) + } else { + Err(stringify!($field_call)) + } + ) +} + +#[test] +fn macro_check_eq() { + assert!(check_eq!(1, 1).is_ok()); + assert!(check_eq!(1, 2).is_err()); +} + +// test helper macro to return an error if two expressions are equal +macro_rules! check_is_some { + ($field_call:expr) => ( + if $field_call.is_some() { + Ok(()) + } else { + Err(stringify!($field_call)) + } + ) +} + +#[test] +fn macro_check_is_some() { + let some: Option = Some(0); + let none: Option = None; + assert!(check_is_some!(some).is_ok()); + assert!(check_is_some!(none).is_err()); +} + +#[test] +fn object_api_defaults() { + use my_game::example::*; + assert_eq!( + Vec3T::default(), Vec3T { + x: 0.0, + y: 0.0, + z: 0.0, + test1: 0.0, + test2: Color::empty(), + test3: TestT { + a: 0, + b: 0 + } + }); + let mut default_without_nan = MonsterT::default(); + default_without_nan.nan_default = 0.0; + assert_eq!( + default_without_nan, + MonsterT { + pos: None, + hp: 100, + mana: 150, + name: String::new(), // required string => default is empty string. + color: Color::Blue, + inventory: None, + testarrayoftables: None, + testarrayofstring: None, + testarrayofstring2: None, + testarrayofbools: None, + testarrayofsortedstruct: None, + enemy: None, + test: AnyT::NONE, + test4: None, + test5: None, + testnestedflatbuffer: None, + testempty: None, + testbool: false, + testhashs32_fnv1: 0, + testhashu32_fnv1: 0, + testhashs64_fnv1: 0, + testhashu64_fnv1: 0, + testhashs32_fnv1a: 0, + testhashu32_fnv1a: 0, + testhashs64_fnv1a: 0, + testhashu64_fnv1a: 0, + testf: 3.14159, + testf2: 3.0, + testf3: 0.0, + flex: None, + vector_of_longs: None, + vector_of_doubles: None, + parent_namespace_test: None, + vector_of_referrables: None, + single_weak_reference: 0, + vector_of_weak_references: None, + vector_of_strong_referrables: None, + co_owning_reference: 0, + vector_of_co_owning_references: None, + non_owning_reference: 0, + vector_of_non_owning_references: None, + any_unique: AnyUniqueAliasesT::NONE, + any_ambiguous: AnyAmbiguousAliasesT::NONE, + vector_of_enums: None, + signed_enum: Race::None, + testrequirednestedflatbuffer: None, // despite the name, it is not required. + scalar_key_sorted_tables: None, + native_inline: None, + long_enum_non_enum_default: Default::default(), + long_enum_normal_default: LongEnum::LongOne, + nan_default: 0.0, + inf_default: f32::INFINITY, + positive_inf_default: f32::INFINITY, + infinity_default: f32::INFINITY, + positive_infinity_default: f32::INFINITY, + negative_inf_default: f32::NEG_INFINITY, + negative_infinity_default: f32::NEG_INFINITY, + double_inf_default: f64::INFINITY, + } + ); +} + +fn create_serialized_example_with_generated_code(builder: &mut flatbuffers::FlatBufferBuilder) { + let mon = { + let s0 = builder.create_string("test1"); + let s1 = builder.create_string("test2"); + let fred_name = builder.create_string("Fred"); + + // can't inline creation of this Vec3 because we refer to it by reference, so it must live + // long enough to be used by MonsterArgs. + let pos = my_game::example::Vec3::new(1.0, 2.0, 3.0, 3.0, my_game::example::Color::Green, &my_game::example::Test::new(5i16, 6i8)); + + let args = my_game::example::MonsterArgs{ + hp: 80, + mana: 150, + name: Some(builder.create_string("MyMonster")), + pos: Some(&pos), + test_type: my_game::example::Any::Monster, + test: Some(my_game::example::Monster::create(builder, &my_game::example::MonsterArgs{ + name: Some(fred_name), + ..Default::default() + }).as_union_value()), + inventory: Some(builder.create_vector(&[0u8, 1, 2, 3, 4])), + test4: Some(builder.create_vector(&[my_game::example::Test::new(10, 20), + my_game::example::Test::new(30, 40)])), + testarrayofstring: Some(builder.create_vector(&[s0, s1])), + ..Default::default() + }; + my_game::example::Monster::create(builder, &args) + }; + my_game::example::finish_monster_buffer(builder, mon); +} + +fn create_serialized_example_with_library_code(builder: &mut flatbuffers::FlatBufferBuilder) { + let nested_union_mon = { + let name = builder.create_string("Fred"); + let table_start = builder.start_table(); + builder.push_slot_always(my_game::example::Monster::VT_NAME, name); + builder.end_table(table_start) + }; + let pos = my_game::example::Vec3::new(1.0, 2.0, 3.0, 3.0, my_game::example::Color::Green, &my_game::example::Test::new(5i16, 6i8)); + let inv = builder.create_vector(&[0u8, 1, 2, 3, 4]); + + let test4 = builder.create_vector(&[my_game::example::Test::new(10, 20), + my_game::example::Test::new(30, 40)][..]); + + let name = builder.create_string("MyMonster"); + + let test1 = builder.create_string("test1"); + let test2 = builder.create_string("test2"); + + let testarrayofstring = builder.create_vector(&[test1, test2]); + + // begin building + + let table_start = builder.start_table(); + builder.push_slot(my_game::example::Monster::VT_HP, 80i16, 100); + builder.push_slot_always(my_game::example::Monster::VT_NAME, name); + builder.push_slot_always(my_game::example::Monster::VT_POS, &pos); + builder.push_slot(my_game::example::Monster::VT_TEST_TYPE, my_game::example::Any::Monster, my_game::example::Any::NONE); + builder.push_slot_always(my_game::example::Monster::VT_TEST, nested_union_mon); + builder.push_slot_always(my_game::example::Monster::VT_INVENTORY, inv); + builder.push_slot_always(my_game::example::Monster::VT_TEST4, test4); + builder.push_slot_always(my_game::example::Monster::VT_TESTARRAYOFSTRING, testarrayofstring); + let root = builder.end_table(table_start); + builder.finish(root, Some(my_game::example::MONSTER_IDENTIFIER)); +} + +fn serialized_example_is_accessible_and_correct(bytes: &[u8], identifier_required: bool, size_prefixed: bool) -> Result<(), &'static str> { + + if identifier_required { + let correct = if size_prefixed { + my_game::example::monster_size_prefixed_buffer_has_identifier(bytes) + } else { + my_game::example::monster_buffer_has_identifier(bytes) + }; + check_eq!(correct, true)?; + } + + let m = if size_prefixed { + my_game::example::size_prefixed_root_as_monster(bytes).unwrap() + } else { + my_game::example::root_as_monster(bytes).unwrap() + }; + + check_eq!(m.hp(), 80)?; + check_eq!(m.mana(), 150)?; + check_eq!(m.name(), "MyMonster")?; + + let pos = m.pos().unwrap(); + check_eq!(pos.x(), 1.0f32)?; + check_eq!(pos.y(), 2.0f32)?; + check_eq!(pos.z(), 3.0f32)?; + check_eq!(pos.test1(), 3.0f64)?; + check_eq!(pos.test2(), my_game::example::Color::Green)?; + + let pos_test3 = pos.test3(); + check_eq!(pos_test3.a(), 5i16)?; + check_eq!(pos_test3.b(), 6i8)?; + + check_eq!(m.test_type(), my_game::example::Any::Monster)?; + check_is_some!(m.test())?; + let table2 = m.test().unwrap(); + let monster2 = unsafe { my_game::example::Monster::init_from_table(table2) }; + + check_eq!(monster2.name(), "Fred")?; + + check_is_some!(m.inventory())?; + let inv = m.inventory().unwrap(); + check_eq!(inv.len(), 5)?; + check_eq!(inv.iter().sum::(), 10u8)?; + check_eq!(inv.iter().rev().sum::(), 10u8)?; + + check_is_some!(m.test4())?; + let test4 = m.test4().unwrap(); + check_eq!(test4.len(), 2)?; + check_eq!(test4.get(0).a() as i32 + test4.get(0).b() as i32 + + test4.get(1).a() as i32 + test4.get(1).b() as i32, 100)?; + + check_is_some!(m.testarrayofstring())?; + let testarrayofstring = m.testarrayofstring().unwrap(); + check_eq!(testarrayofstring.len(), 2)?; + check_eq!(testarrayofstring.get(0), "test1")?; + check_eq!(testarrayofstring.get(1), "test2")?; + + Ok(()) +} + +#[test] +fn test_object_api_reads_correctly() -> Result<(), &'static str>{ + let mut fbb = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_library_code(&mut fbb); + + let m = my_game::example::root_as_monster(fbb.finished_data()).unwrap().unpack(); + + check_eq!(m.hp, 80)?; + check_eq!(m.mana, 150)?; + check_eq!(m.name, "MyMonster")?; + + let pos = m.pos.as_ref().unwrap(); + check_eq!(pos.x, 1.0f32)?; + check_eq!(pos.y, 2.0f32)?; + check_eq!(pos.z, 3.0f32)?; + check_eq!(pos.test1, 3.0f64)?; + check_eq!(pos.test2, my_game::example::Color::Green)?; + + let pos_test3 = &pos.test3; + check_eq!(pos_test3.a, 5i16)?; + check_eq!(pos_test3.b, 6i8)?; + + let monster2 = m.test.as_monster().unwrap(); + check_eq!(monster2.name, "Fred")?; + + let inv = m.inventory.as_ref().unwrap(); + check_eq!(inv.len(), 5)?; + check_eq!(inv.iter().sum::(), 10u8)?; + check_eq!(inv.iter().rev().sum::(), 10u8)?; + + let test4 = m.test4.as_ref().unwrap(); + check_eq!(test4.len(), 2)?; + check_eq!(test4[0].a as i32 + test4[0].b as i32 + + test4[1].a as i32 + test4[1].b as i32, 100)?; + + let testarrayofstring = m.testarrayofstring.as_ref().unwrap(); + check_eq!(testarrayofstring.len(), 2)?; + check_eq!(testarrayofstring[0], "test1")?; + check_eq!(testarrayofstring[1], "test2")?; + Ok(()) +} + + + +// Disabled due to Windows CI limitations. +// #[test] +// fn builder_initializes_with_maximum_buffer_size() { +// flatbuffers::FlatBufferBuilder::with_capacity(flatbuffers::FLATBUFFERS_MAX_BUFFER_SIZE); +// } + +#[should_panic] +#[test] +fn builder_abort_with_greater_than_maximum_buffer_size() { + flatbuffers::FlatBufferBuilder::with_capacity(flatbuffers::FLATBUFFERS_MAX_BUFFER_SIZE+1); +} + +#[test] +fn builder_collapses_into_vec() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(&mut b); + let (backing_buf, head) = b.collapse(); + serialized_example_is_accessible_and_correct(&backing_buf[head..], true, false).unwrap(); +} + +#[test] +#[cfg(not(miri))] // slow. +fn verifier_one_byte_errors_do_not_crash() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_library_code(&mut b); + let mut badbuf = b.finished_data().to_vec(); + // If the verifier says a buffer is okay then using it won't cause a crash. + // We use write_fmt since Debug visits all the fields - but there's no need to store anything. + struct ForgetfulWriter; + use core::fmt::Write; + impl Write for ForgetfulWriter { + fn write_str(&mut self, _: &str) -> Result<(), core::fmt::Error> { + Ok(()) + } + } + let mut w = ForgetfulWriter; + for d in 1..=255u8 { + for i in 0..badbuf.len() { + let orig = badbuf[i]; + badbuf[i] = badbuf[i].wrapping_add(d); + if let Ok(m) = flatbuffers::root::(&badbuf) { + w.write_fmt(format_args!("{:?}", m)).unwrap() + } + badbuf[i] = orig; + } + } +} +#[test] +#[cfg(not(miri))] // slow. +fn verifier_too_many_tables() { + use my_game::example::*; + let b = &mut flatbuffers::FlatBufferBuilder::new(); + let r = Referrable::create(b, &ReferrableArgs { id: 42 }); + let rs = b.create_vector(&vec![r; 500]); + let name = Some(b.create_string("foo")); + let m = Monster::create(b, &MonsterArgs { + vector_of_referrables: Some(rs), + name, // required field. + ..Default::default() + }); + b.finish(m, None); + + let data = b.finished_data(); + let mut opts = flatbuffers::VerifierOptions::default(); + + opts.max_tables = 500; + let res = flatbuffers::root_with_opts::(&opts, data); + assert_eq!(res.unwrap_err(), flatbuffers::InvalidFlatbuffer::TooManyTables); + + opts.max_tables += 2; + assert!(flatbuffers::root_with_opts::(&opts, data).is_ok()); +} +#[test] +#[cfg(not(miri))] // slow. +fn verifier_apparent_size_too_large() { + use my_game::example::*; + let b = &mut flatbuffers::FlatBufferBuilder::new(); + let name = Some(b.create_string("foo")); + // String amplification attack. + let s = b.create_string(&(core::iter::repeat("X").take(1000).collect::())); + let testarrayofstring = Some(b.create_vector(&vec![s; 1000])); + let m = Monster::create(b, &MonsterArgs { + testarrayofstring, + name, // required field. + ..Default::default() + }); + b.finish(m, None); + let data = b.finished_data(); + assert!(data.len() < 5200); // est 4000 for the vector + 1000 for the string + 200 overhead. + let mut opts = flatbuffers::VerifierOptions::default(); + opts.max_apparent_size = 1_000_000; + + let res = flatbuffers::root_with_opts::(&opts, data); + assert_eq!(res.unwrap_err(), flatbuffers::InvalidFlatbuffer::ApparentSizeTooLarge); + + opts.max_apparent_size += 20_000; + assert!(flatbuffers::root_with_opts::(&opts, data).is_ok()); +} +#[test] +fn verifier_in_too_deep() { + use my_game::example::*; + let b = &mut flatbuffers::FlatBufferBuilder::new(); + let name = Some(b.create_string("foo")); + let mut prev_monster = None; + for _ in 0..11 { + prev_monster = Some(Monster::create(b, &MonsterArgs { + enemy: prev_monster, + name, // required field. + ..Default::default() + })); + }; + b.finish(prev_monster.unwrap(), None); + let mut opts = flatbuffers::VerifierOptions::default(); + opts.max_depth = 10; + + let data = b.finished_data(); + let res = flatbuffers::root_with_opts::(&opts, data); + assert_eq!(res.unwrap_err(), flatbuffers::InvalidFlatbuffer::DepthLimitReached); + + opts.max_depth += 1; + assert!(flatbuffers::root_with_opts::(&opts, data).is_ok()); +} + +#[cfg(test)] +mod generated_constants { + extern crate flatbuffers; + use super::my_game; + + #[test] + fn monster_identifier() { + assert_eq!("MONS", my_game::example::MONSTER_IDENTIFIER); + } + + #[test] + fn monster_file_extension() { + assert_eq!("mon", my_game::example::MONSTER_EXTENSION); + } + + #[test] + fn enum_constants_are_public() { + assert_eq!(-1, my_game::example::Race::ENUM_MIN); + assert_eq!(2, my_game::example::Race::ENUM_MAX); + assert_eq!(my_game::example::Race::ENUM_VALUES, [ + my_game::example::Race::None, + my_game::example::Race::Human, + my_game::example::Race::Dwarf, + my_game::example::Race::Elf, + ]); + + assert_eq!(0, my_game::example::Any::ENUM_MIN); + assert_eq!(3, my_game::example::Any::ENUM_MAX); + assert_eq!(my_game::example::Any::ENUM_VALUES, [ + my_game::example::Any::NONE, + my_game::example::Any::Monster, + my_game::example::Any::TestSimpleTableWithEnum, + my_game::example::Any::MyGame_Example2_Monster, + ]); + + assert_eq!(0, my_game::example::AnyUniqueAliases::ENUM_MIN); + assert_eq!(3, my_game::example::AnyUniqueAliases::ENUM_MAX); + assert_eq!(my_game::example::AnyUniqueAliases::ENUM_VALUES, [ + my_game::example::AnyUniqueAliases::NONE, + my_game::example::AnyUniqueAliases::M, + my_game::example::AnyUniqueAliases::TS, + my_game::example::AnyUniqueAliases::M2, + ]); + + assert_eq!(0, my_game::example::AnyAmbiguousAliases::ENUM_MIN); + assert_eq!(3, my_game::example::AnyAmbiguousAliases::ENUM_MAX); + assert_eq!(my_game::example::AnyAmbiguousAliases::ENUM_VALUES, [ + my_game::example::AnyAmbiguousAliases::NONE, + my_game::example::AnyAmbiguousAliases::M1, + my_game::example::AnyAmbiguousAliases::M2, + my_game::example::AnyAmbiguousAliases::M3, + ]); + } +} + +#[cfg(not(feature = "no_std"))] +#[cfg(test)] +mod lifetime_correctness { + extern crate flatbuffers; + + use core::mem; + + use super::my_game; + use super::load_file; + + #[test] + fn table_get_field_from_static_buffer_1() { + let buf = load_file("../monsterdata_test.mon").expect("missing monsterdata_test.mon"); + // create 'static slice + let slice: &[u8] = &buf; + let slice: &'static [u8] = unsafe { mem::transmute(slice) }; + // make sure values retrieved from the 'static buffer are themselves 'static + let monster: my_game::example::Monster<'static> = my_game::example::root_as_monster(slice).unwrap(); + // this line should compile: + let name: Option<&'static str> = unsafe { monster._tab.get::>(my_game::example::Monster::VT_NAME, None) }; + assert_eq!(name, Some("MyMonster")); + } + + #[test] + fn table_get_field_from_static_buffer_2() { + static DATA: [u8; 4] = [0, 0, 0, 0]; // some binary data + let table: flatbuffers::Table<'static> = unsafe { flatbuffers::Table::new(&DATA, 0) }; + // this line should compile: + unsafe { table.get::<&'static str>(0, None) }; + } + + #[test] + fn table_object_self_lifetime_in_closure() { + // This test is designed to ensure that lifetimes for temporary intermediate tables aren't inflated beyond where the need to be. + let buf = load_file("../monsterdata_test.mon").expect("missing monsterdata_test.mon"); + let monster = my_game::example::root_as_monster(&buf).unwrap(); + let enemy: Option = monster.enemy(); + // This line won't compile if "self" is required to live for the lifetime of buf above as the borrow disappears at the end of the closure. + let enemy_of_my_enemy = enemy.map(|e| { + // enemy (the Option) is consumed, and the enum's value is taken as a temporary (e) at the start of the closure + let name = e.name(); + // ... the temporary dies here, so for this to compile name's lifetime must not be tied to the temporary + name + // If this test fails the error would be "`e` dropped here while still borrowed" + }); + assert_eq!(enemy_of_my_enemy, Some("Fred")); + } +} + +#[cfg(test)] +mod roundtrip_generated_code { + extern crate flatbuffers; + + use alloc::vec::Vec; + + use super::my_game; + + fn build_mon<'a, 'b>(builder: &'a mut flatbuffers::FlatBufferBuilder, args: &'b my_game::example::MonsterArgs) -> my_game::example::Monster<'a> { + let mon = my_game::example::Monster::create(builder, &args); + my_game::example::finish_monster_buffer(builder, mon); + my_game::example::root_as_monster(builder.finished_data()).unwrap() + } + + #[test] + fn scalar_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{hp: 123, name: Some(name), ..Default::default()}); + assert_eq!(m.hp(), 123); + } + #[test] + fn scalar_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.hp(), 100); + } + #[test] + fn string_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foobar"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.name(), "foobar"); + } + #[test] + fn struct_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + pos: Some(&my_game::example::Vec3::new(1.0, 2.0, 3.0, 4.0, + my_game::example::Color::Green, + &my_game::example::Test::new(98, 99))), + ..Default::default() + }); + assert_eq!(m.pos(), Some(&my_game::example::Vec3::new(1.0, 2.0, 3.0, 4.0, + my_game::example::Color::Green, + &my_game::example::Test::new(98, 99)))); + } + #[test] + fn struct_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.pos(), None); + } + #[test] + fn enum_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), color: my_game::example::Color::Red, ..Default::default()}); + assert_eq!(m.color(), my_game::example::Color::Red); + } + #[test] + fn enum_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.color(), my_game::example::Color::Blue); + } + #[test] + fn union_store() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + { + let name_inner = b.create_string("foo"); + let name_outer = b.create_string("bar"); + + let inner = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name_inner), + ..Default::default() + }); + let outer = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name_outer), + test_type: my_game::example::Any::Monster, + test: Some(inner.as_union_value()), + ..Default::default() + }); + my_game::example::finish_monster_buffer(b, outer); + } + + let mon = my_game::example::root_as_monster(b.finished_data()).unwrap(); + assert_eq!(mon.name(), "bar"); + assert_eq!(mon.test_type(), my_game::example::Any::Monster); + let name = unsafe { my_game::example::Monster::init_from_table(mon.test().unwrap()).name() }; + assert_eq!(name, "foo"); + assert_eq!(mon.test_as_monster().unwrap().name(), "foo"); + assert_eq!(mon.test_as_test_simple_table_with_enum(), None); + assert_eq!(mon.test_as_my_game_example_2_monster(), None); + } + #[test] + fn union_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.test_type(), my_game::example::Any::NONE); + assert_eq!(m.test(), None); + } + #[test] + fn table_full_namespace_store() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + { + let name_inner = b.create_string("foo"); + let name_outer = b.create_string("bar"); + + let inner = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name_inner), + ..Default::default() + }); + let outer = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name_outer), + enemy: Some(inner), + ..Default::default() + }); + my_game::example::finish_monster_buffer(b, outer); + } + + let mon = my_game::example::root_as_monster(b.finished_data()).unwrap(); + assert_eq!(mon.name(), "bar"); + assert_eq!(mon.enemy().unwrap().name(), "foo"); + } + #[test] + fn table_full_namespace_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.enemy(), None); + } + #[test] + fn table_store() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + { + let id_inner = b.create_string("foo"); + let name_outer = b.create_string("bar"); + + let inner = my_game::example::Stat::create(b, &my_game::example::StatArgs{ + id: Some(id_inner), + ..Default::default() + }); + let outer = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name_outer), + testempty: Some(inner), + ..Default::default() + }); + my_game::example::finish_monster_buffer(b, outer); + } + + let mon = my_game::example::root_as_monster(b.finished_data()).unwrap(); + assert_eq!(mon.name(), "bar"); + assert_eq!(mon.testempty().unwrap().id(), Some("foo")); + } + #[test] + fn table_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert_eq!(m.testempty(), None); + } + #[test] + fn nested_flatbuffer_store() { + let b0 = { + let mut b0 = flatbuffers::FlatBufferBuilder::new(); + let args = my_game::example::MonsterArgs{ + hp: 123, + name: Some(b0.create_string("foobar")), + ..Default::default() + }; + let mon = my_game::example::Monster::create(&mut b0, &args); + my_game::example::finish_monster_buffer(&mut b0, mon); + b0 + }; + + let b1 = { + let mut b1 = flatbuffers::FlatBufferBuilder::new(); + let args = my_game::example::MonsterArgs{ + testnestedflatbuffer: Some(b1.create_vector(b0.finished_data())), + name: Some(b1.create_string("foo")), + ..Default::default() + }; + let mon = my_game::example::Monster::create(&mut b1, &args); + my_game::example::finish_monster_buffer(&mut b1, mon); + b1 + }; + + let m = my_game::example::root_as_monster(b1.finished_data()).unwrap(); + + assert!(m.testnestedflatbuffer().is_some()); + assert_eq!(m.testnestedflatbuffer().unwrap().bytes(), b0.finished_data()); + + let m2_a = my_game::example::root_as_monster(m.testnestedflatbuffer().unwrap().bytes()).unwrap(); + assert_eq!(m2_a.hp(), 123); + assert_eq!(m2_a.name(), "foobar"); + + assert!(m.testnestedflatbuffer_nested_flatbuffer().is_some()); + let m2_b = m.testnestedflatbuffer_nested_flatbuffer().unwrap(); + + assert_eq!(m2_b.hp(), 123); + assert_eq!(m2_b.name(), "foobar"); + } + #[test] + fn nested_flatbuffer_default() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{name: Some(name), ..Default::default()}); + assert!(m.testnestedflatbuffer().is_none()); + } + #[test] + fn vector_of_string_store_helper_build() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let strings = &[b.create_string("foobar"), b.create_string("baz")]; + let v = b.create_vector(strings); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + testarrayofstring: Some(v), ..Default::default()}); + assert_eq!(m.testarrayofstring().unwrap().len(), 2); + assert_eq!(m.testarrayofstring().unwrap().get(0), "foobar"); + assert_eq!(m.testarrayofstring().unwrap().get(1), "baz"); + + let rust_vec_inst = m.testarrayofstring().unwrap(); + let rust_vec_iter_collect = rust_vec_inst.iter().collect::>(); + assert_eq!(rust_vec_iter_collect.len(), 2); + assert_eq!(rust_vec_iter_collect[0], "foobar"); + assert_eq!(rust_vec_iter_collect[1], "baz"); + + let rust_vec_iter_rev_collect = rust_vec_inst.iter().rev().collect::>(); + assert_eq!(rust_vec_iter_rev_collect.len(), 2); + assert_eq!(rust_vec_iter_rev_collect[1], "foobar"); + assert_eq!(rust_vec_iter_rev_collect[0], "baz"); + + } + #[test] + fn vector_of_string_store_manual_build() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let s0 = b.create_string("foobar"); + let s1 = b.create_string("baz"); + let v = b.create_vector(&[s0, s1]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + testarrayofstring: Some(v), ..Default::default()}); + assert_eq!(m.testarrayofstring().unwrap().len(), 2); + assert_eq!(m.testarrayofstring().unwrap().get(0), "foobar"); + assert_eq!(m.testarrayofstring().unwrap().get(1), "baz"); + + let rust_vec_inst = m.testarrayofstring().unwrap(); + let rust_vec_iter_collect = rust_vec_inst.iter().collect::>(); + assert_eq!(rust_vec_iter_collect.len(), 2); + assert_eq!(rust_vec_iter_collect[0], "foobar"); + assert_eq!(rust_vec_iter_collect[1], "baz"); + + let rust_vec_iter_rev_collect = rust_vec_inst.iter().rev().collect::>(); + assert_eq!(rust_vec_iter_rev_collect.len(), 2); + assert_eq!(rust_vec_iter_rev_collect[0], "baz"); + assert_eq!(rust_vec_iter_rev_collect[1], "foobar"); + } + #[test] + fn vector_of_ubyte_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let v = b.create_vector(&[123u8, 234u8][..]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + inventory: Some(v), ..Default::default() + }); + assert_eq!(m.inventory().unwrap().bytes(), &[123, 234]); + } + #[test] + fn vector_of_bool_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let v = b.create_vector(&[false, true, false, true][..]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + testarrayofbools: Some(v), ..Default::default()}); + + let rust_vec_inst = m.testarrayofbools().unwrap(); + let rust_vec_iter_collect = rust_vec_inst.iter().collect::>(); + assert_eq!(&rust_vec_iter_collect, &[false, true, false, true]); + + let rust_vec_iter_rev_collect = rust_vec_inst.iter().rev().collect::>(); + assert_eq!(&rust_vec_iter_rev_collect, &[true, false, true, false]); + } + #[test] + fn vector_of_f64_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let v = b.create_vector(&[3.14159265359f64][..]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + vector_of_doubles: Some(v), ..Default::default()}); + assert_eq!(m.vector_of_doubles().unwrap().len(), 1); + assert_eq!(m.vector_of_doubles().unwrap().get(0), 3.14159265359f64); + + let rust_vec_inst = m.vector_of_doubles().unwrap(); + let rust_vec_iter_collect = rust_vec_inst.iter().collect::>(); + assert_eq!(rust_vec_iter_collect.len(), 1); + assert_eq!(rust_vec_iter_collect[0], 3.14159265359f64); + + let rust_vec_iter_rev_collect = rust_vec_inst.iter().rev().collect::>(); + assert_eq!(rust_vec_iter_rev_collect.len(), 1); + assert_eq!(rust_vec_iter_rev_collect[0], 3.14159265359f64); + } + #[test] + fn vector_of_struct_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let v = b.create_vector(&[my_game::example::Test::new(127, -128), my_game::example::Test::new(3, 123)][..]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + test4: Some(v), ..Default::default()}); + + let rust_vec_inst = m.test4().unwrap(); + let rust_vec_iter_collect = rust_vec_inst.iter().collect::>(); + assert_eq!(rust_vec_iter_collect, &[&my_game::example::Test::new(127, -128), &my_game::example::Test::new(3, 123)][..]); + + let rust_vec_iter_rev_collect = rust_vec_inst.iter().rev().collect::>(); + assert_eq!(rust_vec_iter_rev_collect, &[&my_game::example::Test::new(3, 123), &my_game::example::Test::new(127, -128)][..]); + } + #[test] + fn vector_of_struct_store_with_type_inference() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let v = b.create_vector(&[my_game::example::Test::new(127, -128), + my_game::example::Test::new(3, 123), + my_game::example::Test::new(100, 101)]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + test4: Some(v), ..Default::default()}); + let vals: Vec<_> = m.test4().unwrap().iter().collect::>(); + assert_eq!(vals, vec![&my_game::example::Test::new(127, -128), &my_game::example::Test::new(3, 123), &my_game::example::Test::new(100, 101)]); + } + #[test] + fn vector_of_enums_store() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let v = b.create_vector::(&[my_game::example::Color::Red, my_game::example::Color::Green][..]); + let name = b.create_string("foo"); + let m = build_mon(&mut b, &my_game::example::MonsterArgs{ + name: Some(name), + vector_of_enums: Some(v), ..Default::default()}); + assert_eq!(m.vector_of_enums().unwrap().len(), 2); + assert_eq!(m.vector_of_enums().unwrap().get(0), my_game::example::Color::Red); + assert_eq!(m.vector_of_enums().unwrap().get(1), my_game::example::Color::Green); + } + #[test] + fn vector_of_table_store() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + let t0 = { + let name = b.create_string("foo"); + let args = my_game::example::MonsterArgs{hp: 55, name: Some(name), ..Default::default()}; + my_game::example::Monster::create(b, &args) + }; + let t1 = { + let name = b.create_string("bar"); + let args = my_game::example::MonsterArgs{name: Some(name), ..Default::default()}; + my_game::example::Monster::create(b, &args) + }; + let v = b.create_vector(&[t0, t1][..]); + let name = b.create_string("foo"); + let m = build_mon(b, &my_game::example::MonsterArgs{ + name: Some(name), + testarrayoftables: Some(v), ..Default::default()}); + assert_eq!(m.testarrayoftables().unwrap().len(), 2); + assert_eq!(m.testarrayoftables().unwrap().get(0).hp(), 55); + assert_eq!(m.testarrayoftables().unwrap().get(0).name(), "foo"); + assert_eq!(m.testarrayoftables().unwrap().get(1).hp(), 100); + assert_eq!(m.testarrayoftables().unwrap().get(1).name(), "bar"); + + let rust_vec_inst = m.testarrayoftables().unwrap(); + let rust_vec_iter_collect = rust_vec_inst.iter().collect::>(); + assert_eq!(rust_vec_iter_collect.len(), 2); + assert_eq!(rust_vec_iter_collect[0].hp(), 55); + assert_eq!(rust_vec_iter_collect[0].name(), "foo"); + assert_eq!(rust_vec_iter_collect[1].hp(), 100); + assert_eq!(rust_vec_iter_collect[1].name(), "bar"); + + let rust_vec_iter_rev_collect = rust_vec_inst.iter().rev().collect::>(); + assert_eq!(rust_vec_iter_rev_collect.len(), 2); + assert_eq!(rust_vec_iter_rev_collect[0].hp(), 100); + assert_eq!(rust_vec_iter_rev_collect[0].name(), "bar"); + assert_eq!(rust_vec_iter_rev_collect[1].hp(), 55); + assert_eq!(rust_vec_iter_rev_collect[1].name(), "foo"); + } +} + +#[cfg(test)] +mod generated_code_alignment_and_padding { + extern crate flatbuffers; + use super::my_game; + + #[test] + fn enum_color_is_1_byte() { + assert_eq!(1, ::core::mem::size_of::()); + } + + #[test] + fn union_any_is_1_byte() { + assert_eq!(1, ::core::mem::size_of::()); + } + + #[test] + fn union_any_is_aligned_to_1() { + assert_eq!(1, ::core::mem::align_of::()); + } + #[test] + fn struct_test_is_4_bytes() { + assert_eq!(4, ::core::mem::size_of::()); + } + #[test] + fn struct_vec3_is_32_bytes() { + assert_eq!(32, ::core::mem::size_of::()); + } + + #[test] + fn struct_vec3_is_written_with_correct_alignment_in_table() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + { + let name = b.create_string("foo"); + let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name), + pos: Some(&my_game::example::Vec3::new(1.0, 2.0, 3.0, 4.0, + my_game::example::Color::Green, + &my_game::example::Test::new(98, 99))), + ..Default::default()}); + my_game::example::finish_monster_buffer(b, mon); + } + let buf = b.finished_data(); + let mon = my_game::example::root_as_monster(buf).unwrap(); + let vec3 = mon.pos().unwrap(); + + let start_ptr = buf.as_ptr() as usize; + let vec3_ptr = vec3 as *const my_game::example::Vec3 as usize; + + assert!(vec3_ptr > start_ptr); + // Vec3 is aligned to 8 wrt the flatbuffer. + assert_eq!((vec3_ptr - start_ptr) % 8, 0); + } + + #[test] + fn struct_ability_is_8_bytes() { + assert_eq!(8, ::core::mem::size_of::()); + } + + #[test] + fn struct_ability_is_written_with_correct_alignment_in_table_vector() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + { + let name = b.create_string("foo"); + let v = b.create_vector(&[my_game::example::Ability::new(1, 2), + my_game::example::Ability::new(3, 4), + my_game::example::Ability::new(5, 6)]); + let mon = my_game::example::Monster::create(b, &my_game::example::MonsterArgs{ + name: Some(name), + testarrayofsortedstruct: Some(v), + ..Default::default()}); + my_game::example::finish_monster_buffer(b, mon); + } + let buf = b.finished_data(); + let mon = my_game::example::root_as_monster(buf).unwrap(); + let abilities = mon.testarrayofsortedstruct().unwrap(); + + let start_ptr = buf.as_ptr() as usize; + for a in abilities.iter() { + let a_ptr = a as *const my_game::example::Ability as usize; + assert!(a_ptr > start_ptr); + let aln = ::core::mem::align_of::(); + assert_eq!((a_ptr - start_ptr) % aln, 0); + } + for a in abilities.iter().rev() { + let a_ptr = a as *const my_game::example::Ability as usize; + assert!(a_ptr > start_ptr); + // Vec3 is aligned to 8 wrt the flatbuffer. + assert_eq!((a_ptr - start_ptr) % 8, 0); + } + } +} + +#[cfg(not(miri))] +quickcheck! { + fn struct_of_structs( + a_id: u32, + a_distance: u32, + b_a: i16, + b_b: i8, + c_id: u32, + c_distance: u32 + ) -> bool { + use my_game::example::*; + let mut sos = StructOfStructs::default(); + let mut a = Ability::default(); + a.set_id(a_id); + a.set_distance(a_distance); + let mut b = Test::default(); + b.set_a(b_a); + b.set_b(b_b); + let mut c = Ability::default(); + c.set_id(c_id); + c.set_distance(c_distance); + sos.set_a(&a); + sos.set_b(&b); + sos.set_c(&c); + + sos.a().id() == a_id && + sos.a().distance() == a_distance && + sos.b().a() == b_a && + sos.b().b() == b_b && + sos.c().id() == c_id && + sos.c().distance() == c_distance + } +} + +#[cfg(not(miri))] // slow. +#[cfg(test)] +mod roundtrip_vectors { + + #[cfg(test)] + mod scalar { + extern crate quickcheck; + extern crate flatbuffers; + + use alloc::vec::Vec; + + const N: u64 = 20; + + fn prop(xs: Vec) + where + T: for<'a> flatbuffers::Follow<'a, Inner = T> + + flatbuffers::EndianScalar + + flatbuffers::Push + + ::core::fmt::Debug, + { + use flatbuffers::Follow; + + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(xs.len()); + for i in (0..xs.len()).rev() { + b.push::(xs[i]); + } + let vecend = b.end_vector::(xs.len()); + b.finish_minimal(vecend); + + let buf = b.finished_data(); + + let got = unsafe { >>::follow(&buf[..], 0) }; + let mut result_vec: Vec = Vec::with_capacity(got.len()); + for i in 0..got.len() { + result_vec.push(got.get(i)); + } + assert_eq!(result_vec, xs); + + let rust_vec_iter = got.iter().collect::>(); + assert_eq!(rust_vec_iter, xs); + + let mut rust_vec_rev_iter = got.iter().rev().collect::>(); + rust_vec_rev_iter.reverse(); + assert_eq!(rust_vec_rev_iter, xs); + } + + #[test] + fn easy_u8() { + prop::(vec![]); + prop::(vec![1u8]); + prop::(vec![1u8, 2u8]); + prop::(vec![1u8, 2u8, 3u8]); + prop::(vec![1u8, 2u8, 3u8, 4u8]); + } + + #[test] + fn fuzz_bool() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_u8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_i8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_u16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_i16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_u32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_i32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_u64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_i64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_f32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + #[test] + fn fuzz_f64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(Vec<_>)); } + } + + #[cfg(test)] + mod string_manual_build { + #[cfg(not(miri))] // slow. + extern crate quickcheck; + extern crate flatbuffers; + + use alloc::string::String; + use alloc::vec::Vec; + + fn prop(xs: Vec) { + use flatbuffers::Follow; + + let mut b = flatbuffers::FlatBufferBuilder::new(); + let mut offsets = Vec::new(); + for s in xs.iter().rev() { + offsets.push(b.create_string(s.as_str())); + } + + b.start_vector::>(xs.len()); + for &i in offsets.iter() { + b.push(i); + } + let vecend = b.end_vector::>(xs.len()); + + b.finish_minimal(vecend); + + let buf = b.finished_data(); + let got = unsafe { >>>::follow(buf, 0) }; + + assert_eq!(got.len(), xs.len()); + for i in 0..xs.len() { + assert_eq!(got.get(i), &xs[i][..]); + } + } + + #[test] + fn fuzz() { + quickcheck::QuickCheck::new().max_tests(20).quickcheck(prop as fn(Vec<_>)); + } + } + + #[cfg(test)] + mod string_helper_build { + #[cfg(not(miri))] // slow. + extern crate quickcheck; + extern crate flatbuffers; + + use alloc::string::String; + use alloc::vec::Vec; + + fn prop(input: Vec) { + use flatbuffers::Follow; + + let mut b = flatbuffers::FlatBufferBuilder::new(); + let xs: Vec<_> = input.iter().map(|s: &String| b.create_string(s)).collect(); + let vecend = b.create_vector(&xs); + + b.finish_minimal(vecend); + + let buf = b.finished_data(); + let got = unsafe { >>>::follow(buf, 0) }; + + assert_eq!(got.len(), xs.len()); + for (idx, s) in input.iter().enumerate() { + assert_eq!(got.get(idx), s); + } + } + + #[test] + fn fuzz() { + quickcheck::QuickCheck::new().max_tests(100).quickcheck(prop as fn(Vec<_>)); + } + } + + #[cfg(test)] + mod ubyte { + #[cfg(not(miri))] // slow. + extern crate quickcheck; + extern crate flatbuffers; + + use alloc::vec::Vec; + + #[cfg(not(miri))] // slow. + #[test] + fn fuzz_manual_build() { + fn prop(vec: Vec) { + let xs = &vec[..]; + + let mut b1 = flatbuffers::FlatBufferBuilder::new(); + b1.start_vector::(xs.len()); + + for i in (0..xs.len()).rev() { + b1.push(xs[i]); + } + b1.end_vector::(xs.len()); + + let mut b2 = flatbuffers::FlatBufferBuilder::new(); + b2.create_vector(xs); + assert_eq!(b1.unfinished_data(), b2.unfinished_data()); + } + quickcheck::QuickCheck::new().max_tests(100).quickcheck(prop as fn(Vec<_>)); + } + } +} + +#[cfg(test)] +mod framing_format { + extern crate flatbuffers; + + use super::my_game; + + #[test] + fn test_size_prefixed_buffer() { + // Create size prefixed buffer. + let mut b = flatbuffers::FlatBufferBuilder::new(); + let args = &my_game::example::MonsterArgs{ + mana: 200, + hp: 300, + name: Some(b.create_string("bob")), + ..Default::default() + }; + let mon = my_game::example::Monster::create(&mut b, &args); + b.finish_size_prefixed(mon, None); + + // Access it. + let buf = b.finished_data(); + let m = flatbuffers::size_prefixed_root::(buf).unwrap(); + assert_eq!(m.mana(), 200); + assert_eq!(m.hp(), 300); + assert_eq!(m.name(), "bob"); + } +} + +#[cfg(not(feature = "no_std"))] +#[cfg(test)] +mod roundtrip_table { + use alloc::string::String; + use alloc::vec::Vec; + use std::collections::HashMap; + + extern crate flatbuffers; + #[cfg(not(miri))] // slow. + extern crate quickcheck; + + use super::LCG; + + #[test] + #[cfg(not(miri))] // slow. + fn table_of_mixed_scalars_fuzz() { + // Values we're testing against: chosen to ensure no bits get chopped + // off anywhere, and also be different from eachother. + let bool_val: bool = true; + let char_val: i8 = -127; // 0x81 + let uchar_val: u8 = 0xFF; + let short_val: i16 = -32222; // 0x8222; + let ushort_val: u16 = 0xFEEE; + let int_val: i32 = unsafe { ::core::mem::transmute(0x83333333u32) }; + let uint_val: u32 = 0xFDDDDDDD; + let long_val: i64 = unsafe { ::core::mem::transmute(0x8444444444444444u64) }; // TODO: byte literal? + let ulong_val: u64 = 0xFCCCCCCCCCCCCCCCu64; + let float_val: f32 = 3.14159; + let double_val: f64 = 3.14159265359; + + let test_value_types_max: isize = 11; + let max_fields_per_object: flatbuffers::VOffsetT = 100; + let num_fuzz_objects: isize = 1000; // The higher, the more thorough :) + + let mut builder = flatbuffers::FlatBufferBuilder::new(); + let mut lcg = LCG::new(); + + let mut objects: Vec = vec![0; num_fuzz_objects as usize]; + + // Generate num_fuzz_objects random objects each consisting of + // fields_per_object fields, each of a random type. + for i in 0..(num_fuzz_objects as usize) { + let fields_per_object = (lcg.next() % (max_fields_per_object as u64)) as flatbuffers::VOffsetT; + let start = builder.start_table(); + + for j in 0..fields_per_object { + let choice = lcg.next() % (test_value_types_max as u64); + + let f = flatbuffers::field_index_to_field_offset(j); + + match choice { + 0 => {builder.push_slot::(f, bool_val, false);} + 1 => {builder.push_slot::(f, char_val, 0);} + 2 => {builder.push_slot::(f, uchar_val, 0);} + 3 => {builder.push_slot::(f, short_val, 0);} + 4 => {builder.push_slot::(f, ushort_val, 0);} + 5 => {builder.push_slot::(f, int_val, 0);} + 6 => {builder.push_slot::(f, uint_val, 0);} + 7 => {builder.push_slot::(f, long_val, 0);} + 8 => {builder.push_slot::(f, ulong_val, 0);} + 9 => {builder.push_slot::(f, float_val, 0.0);} + 10 => {builder.push_slot::(f, double_val, 0.0);} + _ => { panic!("unknown choice: {}", choice); } + } + } + objects[i] = builder.end_table(start).value(); + } + + // Do some bookkeeping to generate stats on fuzzes: + let mut stats: HashMap = HashMap::new(); + let mut values_generated: u64 = 0; + + // Embrace PRNG determinism: + lcg.reset(); + + // Test that all objects we generated are readable and return the + // expected values. We generate random objects in the same order + // so this is deterministic: + for i in 0..(num_fuzz_objects as usize) { + let table = { + let buf = builder.unfinished_data(); + let loc = buf.len() as flatbuffers::UOffsetT - objects[i]; + unsafe { flatbuffers::Table::new(buf, loc as usize) } + }; + + let fields_per_object = (lcg.next() % (max_fields_per_object as u64)) as flatbuffers::VOffsetT; + for j in 0..fields_per_object { + let choice = lcg.next() % (test_value_types_max as u64); + + *stats.entry(choice).or_insert(0) += 1; + values_generated += 1; + + let f = flatbuffers::field_index_to_field_offset(j); + + unsafe { + match choice { + 0 => { assert_eq!(bool_val, table.get::(f, Some(false)).unwrap()); } + 1 => { assert_eq!(char_val, table.get::(f, Some(0)).unwrap()); } + 2 => { assert_eq!(uchar_val, table.get::(f, Some(0)).unwrap()); } + 3 => { assert_eq!(short_val, table.get::(f, Some(0)).unwrap()); } + 4 => { assert_eq!(ushort_val, table.get::(f, Some(0)).unwrap()); } + 5 => { assert_eq!(int_val, table.get::(f, Some(0)).unwrap()); } + 6 => { assert_eq!(uint_val, table.get::(f, Some(0)).unwrap()); } + 7 => { assert_eq!(long_val, table.get::(f, Some(0)).unwrap()); } + 8 => { assert_eq!(ulong_val, table.get::(f, Some(0)).unwrap()); } + 9 => { assert_eq!(float_val, table.get::(f, Some(0.0)).unwrap()); } + 10 => { assert_eq!(double_val, table.get::(f, Some(0.0)).unwrap()); } + _ => { panic!("unknown choice: {}", choice); } + } + } + } + } + + // Assert that we tested all the fuzz cases enough: + let min_tests_per_choice = 1000; + assert!(values_generated > 0); + assert!(min_tests_per_choice > 0); + for i in 0..test_value_types_max as u64 { + assert!(stats[&i] >= min_tests_per_choice, "inadequately-tested fuzz case: {}", i); + } + } + + #[test] + #[cfg(not(miri))] // slow. + fn table_of_byte_strings_fuzz() { + fn prop(vec: Vec>) { + use flatbuffers::field_index_to_field_offset as fi2fo; + use flatbuffers::Follow; + + let xs = &vec[..]; + + // build + let mut b = flatbuffers::FlatBufferBuilder::new(); + let str_offsets: Vec> = xs.iter().map(|s| b.create_byte_string(&s[..])).collect(); + let table_start = b.start_table(); + + for i in 0..xs.len() { + b.push_slot_always(fi2fo(i as flatbuffers::VOffsetT), str_offsets[i]); + } + let root = b.end_table(table_start); + b.finish_minimal(root); + + // use + let buf = b.finished_data(); + let tab = unsafe { >::follow(buf, 0) }; + + for i in 0..xs.len() { + let v = unsafe { tab.get::>>(fi2fo(i as flatbuffers::VOffsetT), None) }; + assert!(v.is_some()); + let v2 = v.unwrap(); + assert_eq!(v2.bytes(), &xs[i]); + } + } + prop(vec![vec![1,2,3]]); + + let n = 20; + quickcheck::QuickCheck::new().max_tests(n).quickcheck(prop as fn(Vec<_>)); + } + + #[test] + #[cfg(not(miri))] // slow. + fn fuzz_table_of_strings() { + fn prop(vec: Vec) { + use flatbuffers::field_index_to_field_offset as fi2fo; + use flatbuffers::Follow; + + let xs = &vec[..]; + + // build + let mut b = flatbuffers::FlatBufferBuilder::new(); + let str_offsets: Vec> = xs.iter().map(|s| b.create_string(&s[..])).collect(); + let table_start = b.start_table(); + + for i in 0..xs.len() { + b.push_slot_always(fi2fo(i as flatbuffers::VOffsetT), str_offsets[i]); + } + let root = b.end_table(table_start); + b.finish_minimal(root); + + // use + let buf = b.finished_data(); + let tab = unsafe { >::follow(buf, 0) }; + + for i in 0..xs.len() { + let v = unsafe { tab.get::>(fi2fo(i as flatbuffers::VOffsetT), None) }; + assert_eq!(v, Some(&xs[i][..])); + } + } + let n = 20; + quickcheck::QuickCheck::new().max_tests(n).quickcheck(prop as fn(Vec)); + } + + #[cfg(not(miri))] // slow. + mod table_of_vectors_of_scalars { + + use alloc::vec::Vec; + + extern crate flatbuffers; + #[cfg(not(miri))] // slow. + extern crate quickcheck; + + const N: u64 = 20; + + fn prop(vecs: Vec>) + where + T: for<'a> flatbuffers::Follow<'a, Inner = T> + + flatbuffers::EndianScalar + + flatbuffers::Push + + ::core::fmt::Debug, + { + use flatbuffers::field_index_to_field_offset as fi2fo; + use flatbuffers::Follow; + + // build + let mut b = flatbuffers::FlatBufferBuilder::new(); + let mut offs = vec![]; + for vec in &vecs { + b.start_vector::(vec.len()); + + let xs = &vec[..]; + for i in (0..xs.len()).rev() { + b.push::(xs[i]); + } + let vecend = b.end_vector::(xs.len()); + offs.push(vecend); + } + + let table_start = b.start_table(); + + for i in 0..vecs.len() { + b.push_slot_always(fi2fo(i as flatbuffers::VOffsetT), offs[i]); + } + let root = b.end_table(table_start); + b.finish_minimal(root); + + // use + let buf = b.finished_data(); + let tab = unsafe { >::follow(buf, 0) }; + + for i in 0..vecs.len() { + let got = unsafe { tab.get::>>(fi2fo(i as flatbuffers::VOffsetT), None) }; + assert!(got.is_some()); + let got2 = got.unwrap(); + let mut got3: Vec = Vec::with_capacity(got2.len()); + for i in 0..got2.len() { + got3.push(got2.get(i)); + } + assert_eq!(vecs[i], got3); + } + } + + #[test] + fn fuzz_bool() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + + #[test] + fn fuzz_u8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_u16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_u32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_u64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + + #[test] + fn fuzz_i8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_i16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_i32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_i64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + + #[test] + fn fuzz_f32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + #[test] + fn fuzz_f64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop as fn(Vec>)); } + } +} + +#[cfg(not(miri))] // slow. +#[cfg(test)] +mod roundtrip_scalars { + extern crate flatbuffers; + #[cfg(not(miri))] // slow. + extern crate quickcheck; + + const N: u64 = 1000; + + fn prop(x: T) { + let mut buf = vec![0u8; ::core::mem::size_of::()]; + let y = unsafe { + flatbuffers::emplace_scalar(&mut buf[..], x); + flatbuffers::read_scalar(&buf[..]) + }; + assert_eq!(x, y); + } + + #[test] + fn fuzz_bool() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + #[test] + fn fuzz_u8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + #[test] + fn fuzz_i8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + + #[test] + fn fuzz_u16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + #[test] + fn fuzz_i16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + + #[test] + fn fuzz_u32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + #[test] + fn fuzz_i32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + + #[test] + fn fuzz_u64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + #[test] + fn fuzz_i64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + + #[test] + fn fuzz_f32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } + #[test] + fn fuzz_f64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop:: as fn(_)); } +} + +#[cfg(test)] +#[cfg(not(miri))] // slow. +mod roundtrip_push_follow_scalars { + extern crate flatbuffers; + #[cfg(not(miri))] // slow. + extern crate quickcheck; + + use flatbuffers::Push; + + const N: u64 = 1000; + + // This uses a macro because lifetimes for a trait-bounded function get too + // complicated. + macro_rules! impl_prop { + ($fn_name:ident, $ty:ident) => ( + fn $fn_name(x: $ty) { + let mut buf = vec![0u8; ::core::mem::size_of::<$ty>()]; + unsafe { x.push(&mut buf[..], 0) }; + let fs: flatbuffers::FollowStart<$ty> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { fs.self_follow(&buf[..], 0) }, x); + } + ) + } + + impl_prop!(prop_bool, bool); + impl_prop!(prop_u8, u8); + impl_prop!(prop_i8, i8); + impl_prop!(prop_u16, u16); + impl_prop!(prop_i16, i16); + impl_prop!(prop_u32, u32); + impl_prop!(prop_i32, i32); + impl_prop!(prop_u64, u64); + impl_prop!(prop_i64, i64); + impl_prop!(prop_f32, f32); + impl_prop!(prop_f64, f64); + + #[test] + fn fuzz_bool() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_bool as fn(bool)); } + #[test] + fn fuzz_u8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_u8 as fn(u8)); } + #[test] + fn fuzz_i8() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_i8 as fn(i8)); } + #[test] + fn fuzz_u16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_u16 as fn(u16)); } + #[test] + fn fuzz_i16() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_i16 as fn(i16)); } + #[test] + fn fuzz_u32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_u32 as fn(u32)); } + #[test] + fn fuzz_i32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_i32 as fn(i32)); } + #[test] + fn fuzz_u64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_u64 as fn(u64)); } + #[test] + fn fuzz_i64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_i64 as fn(i64)); } + #[test] + fn fuzz_f32() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_f32 as fn(f32)); } + #[test] + fn fuzz_f64() { quickcheck::QuickCheck::new().max_tests(N).quickcheck(prop_f64 as fn(f64)); } +} + + +#[cfg(test)] +mod write_and_read_examples { + extern crate flatbuffers; + + use super::create_serialized_example_with_library_code; + use super::create_serialized_example_with_generated_code; + use super::serialized_example_is_accessible_and_correct; + + #[test] + fn generated_code_creates_correct_example() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(b); + let buf = b.finished_data(); + serialized_example_is_accessible_and_correct(&buf[..], true, false).unwrap(); + } + + #[test] + fn generated_code_debug_prints_correctly() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(b); + let buf = b.finished_data(); + serialized_example_is_accessible_and_correct(&buf, true, false).unwrap(); + let m = super::my_game::example::root_as_monster(buf).unwrap(); + assert_eq!( + format!("{:.5?}", &m), + "Monster { pos: Some(Vec3 { x: 1.00000, y: 2.00000, z: 3.00000, \ + test1: 3.00000, test2: Color(Green), test3: Test { a: 5, b: 6 } \ + }), mana: 150, hp: 80, name: \"MyMonster\", inventory: Some([0, 1, \ + 2, 3, 4]), color: Color(Blue), test_type: Monster, test: Monster { \ + pos: None, mana: 150, hp: 100, name: \"Fred\", inventory: None, \ + color: Color(Blue), test_type: NONE, test: None, test4: None, \ + testarrayofstring: None, testarrayoftables: None, enemy: None, \ + testnestedflatbuffer: None, testempty: None, testbool: false, \ + testhashs32_fnv1: 0, testhashu32_fnv1: 0, testhashs64_fnv1: 0, \ + testhashu64_fnv1: 0, testhashs32_fnv1a: 0, testhashu32_fnv1a: 0, \ + testhashs64_fnv1a: 0, testhashu64_fnv1a: 0, testarrayofbools: \ + None, testf: 3.14159, testf2: 3.00000, testf3: 0.00000, \ + testarrayofstring2: None, testarrayofsortedstruct: None, flex: \ + None, test5: None, vector_of_longs: None, vector_of_doubles: None, \ + parent_namespace_test: None, vector_of_referrables: None, \ + single_weak_reference: 0, vector_of_weak_references: None, \ + vector_of_strong_referrables: None, co_owning_reference: 0, \ + vector_of_co_owning_references: None, non_owning_reference: 0, \ + vector_of_non_owning_references: None, any_unique_type: NONE, \ + any_unique: None, any_ambiguous_type: NONE, any_ambiguous: None, \ + vector_of_enums: None, signed_enum: None, \ + testrequirednestedflatbuffer: None, scalar_key_sorted_tables: \ + None, native_inline: None, long_enum_non_enum_default: \ + LongEnum(0x0), long_enum_normal_default: LongEnum(LongOne), \ + nan_default: NaN, inf_default: inf, positive_inf_default: inf, \ + infinity_default: inf, positive_infinity_default: inf, \ + negative_inf_default: -inf, negative_infinity_default: -inf, \ + double_inf_default: inf }, test4: Some([Test { a: 10, b: 20 }, \ + Test { a: 30, b: 40 }]), testarrayofstring: Some([\"test1\", \ + \"test2\"]), testarrayoftables: None, enemy: None, \ + testnestedflatbuffer: None, testempty: None, testbool: false, \ + testhashs32_fnv1: 0, testhashu32_fnv1: 0, testhashs64_fnv1: 0, \ + testhashu64_fnv1: 0, testhashs32_fnv1a: 0, testhashu32_fnv1a: 0, \ + testhashs64_fnv1a: 0, testhashu64_fnv1a: 0, testarrayofbools: \ + None, testf: 3.14159, testf2: 3.00000, testf3: 0.00000, \ + testarrayofstring2: None, testarrayofsortedstruct: None, flex: \ + None, test5: None, vector_of_longs: None, vector_of_doubles: None, \ + parent_namespace_test: None, vector_of_referrables: None, \ + single_weak_reference: 0, vector_of_weak_references: None, \ + vector_of_strong_referrables: None, co_owning_reference: 0, \ + vector_of_co_owning_references: None, non_owning_reference: 0, \ + vector_of_non_owning_references: None, any_unique_type: NONE, \ + any_unique: None, any_ambiguous_type: NONE, any_ambiguous: None, \ + vector_of_enums: None, signed_enum: None, \ + testrequirednestedflatbuffer: None, scalar_key_sorted_tables: \ + None, native_inline: None, long_enum_non_enum_default: \ + LongEnum(0x0), long_enum_normal_default: LongEnum(LongOne), \ + nan_default: NaN, inf_default: inf, positive_inf_default: inf, \ + infinity_default: inf, positive_infinity_default: inf, \ + negative_inf_default: -inf, negative_infinity_default: -inf, \ + double_inf_default: inf }" + ); + } + + #[test] + #[cfg(not(miri))] // slow. + fn generated_code_creates_correct_example_repeatedly_with_reset() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + for _ in 0..100 { + create_serialized_example_with_generated_code(b); + { + let buf = b.finished_data(); + serialized_example_is_accessible_and_correct(&buf[..], true, false).unwrap(); + } + b.reset(); + } + } + + #[test] + fn library_code_creates_correct_example() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_library_code(b); + let buf = b.finished_data(); + serialized_example_is_accessible_and_correct(&buf[..], true, false).unwrap(); + } + + #[test] + #[cfg(not(miri))] // slow. + fn library_code_creates_correct_example_repeatedly_with_reset() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + for _ in 0..100 { + create_serialized_example_with_library_code(b); + { + let buf = b.finished_data(); + serialized_example_is_accessible_and_correct(&buf[..], true, false).unwrap(); + } + b.reset(); + } + } +} + +#[cfg(not(feature = "no_std"))] +#[cfg(test)] +mod read_examples_from_other_language_ports { + extern crate flatbuffers; + + use std::println; + + use super::load_file; + use super::serialized_example_is_accessible_and_correct; + + #[test] + fn gold_cpp_example_data_is_accessible_and_correct() { + let buf = load_file("../monsterdata_test.mon").expect("missing monsterdata_test.mon"); + serialized_example_is_accessible_and_correct(&buf[..], true, false).unwrap(); + } + #[test] + fn java_wire_example_data_is_accessible_and_correct() { + let buf = load_file("../monsterdata_java_wire.mon"); + if buf.is_err() { + println!("skipping java wire test because it is not present"); + return; + } + let buf = buf.unwrap(); + serialized_example_is_accessible_and_correct(&buf[..], true, false).unwrap(); + } + #[test] + fn java_wire_size_prefixed_example_data_is_accessible_and_correct() { + let buf = load_file("../monsterdata_java_wire_sp.mon"); + if buf.is_err() { + println!("skipping java wire test because it is not present"); + return; + } + let buf = buf.unwrap(); + serialized_example_is_accessible_and_correct(&buf[..], true, true).unwrap(); + } +} + +#[cfg(test)] +mod generated_code_asserts { + extern crate flatbuffers; + + use super::my_game; + + #[test] + #[should_panic] + fn monster_builder_fails_when_name_is_missing() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + my_game::example::Monster::create(b, &my_game::example::MonsterArgs{..Default::default()}); + } +} + +#[cfg(test)] +mod generated_key_comparisons { + extern crate flatbuffers; + + use super::my_game; + + #[test] + fn struct_ability_key_compare_less_than() { + let a = my_game::example::Ability::new(1, 2); + let b = my_game::example::Ability::new(2, 1); + let c = my_game::example::Ability::new(3, 3); + + assert_eq!(a.key_compare_less_than(&a), false); + assert_eq!(b.key_compare_less_than(&b), false); + assert_eq!(c.key_compare_less_than(&c), false); + + assert_eq!(a.key_compare_less_than(&b), true); + assert_eq!(a.key_compare_less_than(&c), true); + + assert_eq!(b.key_compare_less_than(&a), false); + assert_eq!(b.key_compare_less_than(&c), true); + + assert_eq!(c.key_compare_less_than(&a), false); + assert_eq!(c.key_compare_less_than(&b), false); + } + + #[test] + fn struct_key_compare_with_value() { + let a = my_game::example::Ability::new(1, 2); + + assert_eq!(a.key_compare_with_value(0), ::core::cmp::Ordering::Greater); + assert_eq!(a.key_compare_with_value(1), ::core::cmp::Ordering::Equal); + assert_eq!(a.key_compare_with_value(2), ::core::cmp::Ordering::Less); + } + + #[test] + fn struct_key_compare_less_than() { + let a = my_game::example::Ability::new(1, 2); + let b = my_game::example::Ability::new(2, 1); + let c = my_game::example::Ability::new(3, 3); + + assert_eq!(a.key_compare_less_than(&a), false); + assert_eq!(b.key_compare_less_than(&b), false); + assert_eq!(c.key_compare_less_than(&c), false); + + assert_eq!(a.key_compare_less_than(&b), true); + assert_eq!(a.key_compare_less_than(&c), true); + + assert_eq!(b.key_compare_less_than(&a), false); + assert_eq!(b.key_compare_less_than(&c), true); + + assert_eq!(c.key_compare_less_than(&a), false); + assert_eq!(c.key_compare_less_than(&b), false); + } + + #[test] + fn table_key_compare_with_value() { + // setup + let builder = &mut flatbuffers::FlatBufferBuilder::new(); + super::create_serialized_example_with_library_code(builder); + let buf = builder.finished_data(); + let a = my_game::example::root_as_monster(buf).unwrap(); + + // preconditions + assert_eq!(a.name(), "MyMonster"); + + assert_eq!(a.key_compare_with_value("AAA"), ::core::cmp::Ordering::Greater); + assert_eq!(a.key_compare_with_value("MyMonster"), ::core::cmp::Ordering::Equal); + assert_eq!(a.key_compare_with_value("ZZZ"), ::core::cmp::Ordering::Less); + } + + #[test] + fn table_key_compare_less_than() { + // setup + let builder = &mut flatbuffers::FlatBufferBuilder::new(); + super::create_serialized_example_with_library_code(builder); + let buf = builder.finished_data(); + let a = my_game::example::root_as_monster(buf).unwrap(); + let b = a.test_as_monster().unwrap(); + + // preconditions + assert_eq!(a.name(), "MyMonster"); + assert_eq!(b.name(), "Fred"); + + assert_eq!(a.key_compare_less_than(&a), false); + assert_eq!(a.key_compare_less_than(&b), false); + + assert_eq!(b.key_compare_less_than(&a), true); + assert_eq!(b.key_compare_less_than(&b), false); + } +} + +#[cfg(test)] +mod included_schema_generated_code { + + #[test] + #[allow(unused_imports)] + fn namespace_test_mod_is_importable() { + use super::namespace_test_generated::{ + namespace_a, + namespace_a::namespace_b, + namespace_c, + }; + + } +} + +#[cfg(test)] +mod builder_asserts { + extern crate flatbuffers; + + #[test] + #[should_panic] + fn end_table_should_panic_when_not_in_table() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.end_table(flatbuffers::WIPOffset::new(0)); + } + + #[test] + #[should_panic] + fn create_string_should_panic_when_in_table() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_table(); + b.create_string("foo"); + } + + #[test] + #[should_panic] + fn create_byte_string_should_panic_when_in_table() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_table(); + b.create_byte_string(b"foo"); + } + + #[test] + #[should_panic] + fn push_struct_slot_should_panic_when_not_in_table() { + #[derive(Copy, Clone, Debug, PartialEq)] + #[repr(C, packed)] + struct foo { } + impl<'b> flatbuffers::Push for &'b foo { + type Output = foo; + unsafe fn push<'a>(&'a self, _dst: &'a mut [u8], _written_len: usize) { } + } + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push_slot_always(0, &foo{}); + } + + #[test] + #[should_panic] + fn finished_bytes_should_panic_when_table_is_not_finished() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_table(); + b.finished_data(); + } + + #[test] + #[should_panic] + fn required_panics_when_field_not_set() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let start = b.start_table(); + let o = b.end_table(start); + b.required(o, 4 /* byte offset to first field */, "test field"); + } +} + +#[cfg(test)] +mod follow_impls { + extern crate flatbuffers; + use flatbuffers::Follow; + use flatbuffers::field_index_to_field_offset as fi2fo; + + use alloc::vec::Vec; + + // Define a test struct to use in a few tests. This replicates the work that the code generator + // would normally do when defining a FlatBuffer struct. For reference, compare the following + // `FooStruct` code with the code generated for the `Vec3` struct in + // `../../monster_test/mod.rs`. + use flatbuffers::EndianScalar; + #[derive(Copy, Clone, Debug, PartialEq)] + #[repr(C, packed)] + struct FooStruct { + a: i8, + b: u8, + c: i16, + } + impl FooStruct { + fn new(_a: i8, _b: u8, _c: i16) -> Self { + FooStruct { + a: _a.to_little_endian(), + b: _b.to_little_endian(), + c: _c.to_little_endian(), + } + } + } + impl<'a> flatbuffers::Follow<'a> for FooStruct { + type Inner = &'a FooStruct; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + <&'a FooStruct>::follow(buf, loc) + } + } + impl<'a> flatbuffers::Follow<'a> for &'a FooStruct { + type Inner = &'a FooStruct; + #[inline(always)] + unsafe fn follow(buf: &'a [u8], loc: usize) -> Self::Inner { + flatbuffers::follow_cast_ref::(buf, loc) + } + } + + #[test] + fn to_u8() { + let vec: Vec = vec![255, 3]; + let fs: flatbuffers::FollowStart = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { fs.self_follow(&vec[..], 1) }, 3); + } + + #[test] + fn to_u16() { + let vec: Vec = vec![255, 255, 3, 4]; + let fs: flatbuffers::FollowStart = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { fs.self_follow(&vec[..], 2) }, 1027); + } + + #[test] + fn to_f32() { + let vec: Vec = vec![255, 255, 255, 255, /* start of value */ 208, 15, 73, 64]; + let fs: flatbuffers::FollowStart = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { fs.self_follow(&vec[..], 4) }, 3.14159); + } + + #[test] + fn to_string() { + let vec: Vec = vec![255,255,255,255, 3, 0, 0, 0, 'f' as u8, 'o' as u8, 'o' as u8, 0]; + let off: flatbuffers::FollowStart<&str> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { off.self_follow(&vec[..], 4) }, "foo"); + } + + #[test] + fn to_byte_slice() { + let vec: Vec = vec![255, 255, 255, 255, 4, 0, 0, 0, 1, 2, 3, 4]; + let off: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { off.self_follow(&vec[..], 4).bytes() }, &[1, 2, 3, 4][..]); + } + + #[test] + fn to_vector_of_u16() { + let vec: Vec = vec![255, 255, 255, 255, 2, 0, 0, 0, 1, 2, 3, 4]; + let off: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { off.self_follow(&vec[..], 4).len() }, 2); + assert_eq!(unsafe { off.self_follow(&vec[..], 4).get(0) }, 513); + assert_eq!(unsafe { off.self_follow(&vec[..], 4).get(1) }, 1027); + } + + #[test] + fn to_struct() { + let vec: Vec = vec![255, 255, 255, 255, 1, 2, 3, 4]; + let off: flatbuffers::FollowStart<&FooStruct> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { *off.self_follow(&vec[..], 4) }, FooStruct::new(1, 2, 1027)); + } + + #[test] + fn to_vector_of_offset_to_string_elements() { + let buf: Vec = vec![/* vec len */ 1, 0, 0, 0, /* offset to string */ 4, 0, 0, 0, /* str length */ 3, 0, 0, 0, 'f' as u8, 'o' as u8, 'o' as u8, 0]; + let s: flatbuffers::FollowStart>> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe {s.self_follow(&buf[..], 0).len() }, 1); + assert_eq!(unsafe { s.self_follow(&buf[..], 0).get(0) }, "foo"); + } + + #[test] + fn to_vector_of_struct_elements() { + let buf: Vec = vec![1, 0, 0, 0, /* struct data */ 1, 2, 3, 4]; + let fs: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + assert_eq!(unsafe { fs.self_follow(&buf[..], 0).len() }, 1); + assert_eq!(unsafe { fs.self_follow(&buf[..], 0).get(0) }, &FooStruct::new(1, 2, 1027)); + } + + #[test] + fn to_root_to_empty_table() { + let buf: Vec = vec![ + 12, 0, 0, 0, // offset to root table + // enter vtable + 4, 0, // vtable len + 0, 0, // inline size + 255, 255, 255, 255, // canary + // enter table + 8, 0, 0, 0, // vtable location + ]; + unsafe { + let fs: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + assert_eq!(fs.self_follow(&buf[..], 0), flatbuffers::Table::new(&buf[..], 12)); + } + } + + #[test] + fn to_root_table_get_slot_scalar_u8() { + let buf: Vec = vec![ + 14, 0, 0, 0, // offset to root table + // enter vtable + 6, 0, // vtable len + 2, 0, // inline size + 5, 0, // value loc + 255, 255, 255, 255, // canary + // enter table + 10, 0, 0, 0, // vtable location + 0, 99 // value (with padding) + ]; + unsafe { + let fs: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + let tab = fs.self_follow(&buf[..], 0); + assert_eq!(tab.get::(fi2fo(0), Some(123)), Some(99)); + } + } + + #[test] + fn to_root_to_table_get_slot_scalar_u8_default_via_vtable_len() { + let buf: Vec = vec![ + 12, 0, 0, 0, // offset to root table + // enter vtable + 4, 0, // vtable len + 2, 0, // inline size + 255, 255, 255, 255, // canary + // enter table + 8, 0, 0, 0, // vtable location + ]; + unsafe { + let fs: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + let tab = fs.self_follow(&buf[..], 0); + assert_eq!(tab.get::(fi2fo(0), Some(123)), Some(123)); + } + } + + #[test] + fn to_root_to_table_get_slot_scalar_u8_default_via_vtable_zero() { + let buf: Vec = vec![ + 14, 0, 0, 0, // offset to root table + // enter vtable + 6, 0, // vtable len + 2, 0, // inline size + 0, 0, // zero means use the default value + 255, 255, 255, 255, // canary + // enter table + 10, 0, 0, 0, // vtable location + ]; + unsafe { + let fs: flatbuffers::FollowStart> = flatbuffers::FollowStart::new(); + let tab = fs.self_follow(&buf[..], 0); + assert_eq!(tab.get::(fi2fo(0), Some(123)), Some(123)); + } + } + + #[test] + fn to_root_to_table_get_slot_string_multiple_types() { + let buf: Vec = vec![ + 14, 0, 0, 0, // offset to root table + // enter vtable + 6, 0, // vtable len + 2, 0, // inline size + 4, 0, // value loc + 255, 255, 255, 255, // canary + // enter table + 10, 0, 0, 0, // vtable location + 8, 0, 0, 0, // offset to string + // leave table + 255, 255, 255, 255, // canary + // enter string + 3, 0, 0, 0, 109, 111, 111, 0 // string length and contents + ]; + unsafe { + let tab = >::follow(&buf[..], 0); + assert_eq!(tab.get::>(fi2fo(0), None), Some("moo")); + let byte_vec = tab.get::>>(fi2fo(0), None).unwrap().bytes(); + assert_eq!(byte_vec, &vec![109, 111, 111][..]); + let v = tab.get::>>(fi2fo(0), None).unwrap(); + assert_eq!(v.len(), 3); + assert_eq!(v.get(0), 109); + assert_eq!(v.get(1), 111); + assert_eq!(v.get(2), 111); + } + } + + #[test] + fn to_root_to_table_get_slot_string_multiple_types_default_via_vtable_len() { + let buf: Vec = vec![ + 12, 0, 0, 0, // offset to root table + // enter vtable + 4, 0, // vtable len + 4, 0, // table inline len + 255, 255, 255, 255, // canary + // enter table + 8, 0, 0, 0, // vtable location + ]; + + unsafe { + let tab = >::follow(&buf[..], 0); + assert_eq!(tab.get::>(fi2fo(0), Some("abc")), Some("abc")); + #[cfg(target_endian = "little")] + { + assert_eq!(tab.get::>(fi2fo(0), Some(&vec![70, 71, 72][..])), Some(&vec![70, 71, 72][..])); + } + + let default_vec_buf: Vec = vec![3, 0, 0, 0, 70, 71, 72, 0]; + let default_vec = flatbuffers::Vector::new(&default_vec_buf[..], 0); + let v = tab.get::>>(fi2fo(0), Some(default_vec)).unwrap(); + assert_eq!(v.len(), 3); + assert_eq!(v.get(0), 70); + assert_eq!(v.get(1), 71); + assert_eq!(v.get(2), 72); + } + } + + #[test] + fn to_root_to_table_get_slot_string_multiple_types_default_via_vtable_zero() { + let buf: Vec = vec![ + 14, 0, 0, 0, // offset to root table + // enter vtable + 6, 0, // vtable len + 2, 0, // inline size + 0, 0, // value loc + 255, 255, 255, 255, // canary + // enter table + 10, 0, 0, 0, // vtable location + ]; + unsafe { + let tab = >::follow(&buf[..], 0); + assert_eq!(tab.get::>(fi2fo(0), Some("abc")), Some("abc")); + #[cfg(target_endian = "little")] + { + assert_eq!(tab.get::>(fi2fo(0), Some(&vec![70, 71, 72][..])), Some(&vec![70, 71, 72][..])); + } + + let default_vec_buf: Vec = vec![3, 0, 0, 0, 70, 71, 72, 0]; + let default_vec = flatbuffers::Vector::new(&default_vec_buf[..], 0); + let v = tab.get::>>(fi2fo(0), Some(default_vec)).unwrap(); + assert_eq!(v.len(), 3); + assert_eq!(v.get(0), 70); + assert_eq!(v.get(1), 71); + assert_eq!(v.get(2), 72); + } + } +} + +#[cfg(test)] +mod push_impls { + extern crate flatbuffers; + + use super::my_game; + + fn check<'a>(b: &'a flatbuffers::FlatBufferBuilder, want: &'a [u8]) { + let got = b.unfinished_data(); + assert_eq!(want, got); + } + + #[test] + fn push_u8() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(123u8); + check(&b, &[123]); + } + + #[test] + fn push_u64() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(0x12345678); + check(&b, &[0x78, 0x56, 0x34, 0x12]); + } + + #[test] + fn push_f64() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(3.14159265359f64); + check(&b, &[234, 46, 68, 84, 251, 33, 9, 64]); + } + + #[test] + fn push_generated_struct() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(my_game::example::Test::new(10, 20)); + check(&b, &[10, 0, 20, 0]); + } + + #[test] + fn push_u8_vector_with_offset_with_alignment() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.create_vector(&[1u8, 2, 3, 4, 5, 6, 7, 8, 9][..]); + b.push(off); + check(&b, &[/* loc */ 4, 0, 0, 0, /* len */ 9, 0, 0, 0, /* val */ 1, 2, 3, 4, 5, 6, 7, 8, 9, /* padding */ 0, 0, 0]); + } + + #[test] + fn push_u8_u16_alignment() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(1u8); + b.push(2u16); + check(&b, &[2, 0, 0, 1]); + } + + #[test] + fn push_u8_u32_alignment() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(1u8); + b.push(2u32); + check(&b, &[2, 0, 0, 0, 0, 0, 0, 1]); + } + + #[test] + fn push_u8_u64_alignment() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(1u8); + b.push(2u64); + check(&b, &[2, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 0, + 0, 0, 0, 1]); + } + + #[test] + fn push_u8_generated_struct_alignment() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(1u8); + b.push(my_game::example::Test::new(10, 20)); + check(&b, &[10, 0, 20, 0, 0, 1]); + } +} + +#[cfg(test)] +mod vtable_deduplication { + extern crate flatbuffers; + use flatbuffers::field_index_to_field_offset as fi2fo; + + fn check<'a>(b: &'a flatbuffers::FlatBufferBuilder, want: &'a [u8]) { + let got = b.unfinished_data(); + assert_eq!(want, got); + } + + #[test] + fn one_empty_table() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let start0 = b.start_table(); + b.end_table(start0); + check(&b, &[ + 4, 0, // vtable size in bytes + 4, 0, // object inline data in bytes + + 4, 0, 0, 0, // backwards offset to vtable + ]); + } + + #[test] + fn two_empty_tables_are_deduplicated() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let start0 = b.start_table(); + b.end_table(start0); + let start1 = b.start_table(); + b.end_table(start1); + check(&b, &[ + 252, 255, 255, 255, // forwards offset to vtable + + 4, 0, // vtable size in bytes + 4, 0, // object inline data in bytes + + 4, 0, 0, 0, // backwards offset to vtable + ]); + } + + #[test] + fn two_tables_with_two_conveniently_sized_inline_elements_are_deduplicated() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let start0 = b.start_table(); + b.push_slot::(fi2fo(0), 100, 0); + b.push_slot::(fi2fo(1), 101, 0); + b.end_table(start0); + let start1 = b.start_table(); + b.push_slot::(fi2fo(0), 200, 0); + b.push_slot::(fi2fo(1), 201, 0); + b.end_table(start1); + check(&b, &[ + 240, 255, 255, 255, // forwards offset to vtable + + 201, 0, 0, 0, // value #1 + 200, 0, 0, 0, 0, 0, 0, 0, // value #0 + + 8, 0, // vtable size in bytes + 16, 0, // object inline data in bytes + 8, 0, // offset in object for value #0 + 4, 0, // offset in object for value #1 + + 8, 0, 0, 0, // backwards offset to vtable + 101, 0, 0, 0, // value #1 + 100, 0, 0, 0, 0, 0, 0, 0 // value #0 + ]); + } + + #[cfg(not(miri))] // slow. + #[test] + fn many_identical_tables_use_few_vtables() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + for _ in 0..1000 { + let start = b.start_table(); + b.push_slot::(fi2fo(0), 100, 0); + b.push_slot::(fi2fo(1), 101, 0); + b.end_table(start); + } + assert!(b.num_written_vtables() <= 10); + } +} + +#[cfg(test)] +mod byte_layouts { + extern crate flatbuffers; + use flatbuffers::field_index_to_field_offset as fi2fo; + + fn check<'a>(b: &'a flatbuffers::FlatBufferBuilder, want: &'a [u8]) { + let got = b.unfinished_data(); + assert_eq!(want, got); + } + + #[test] + fn layout_01_basic_numbers() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(true); + check(&b, &[1]); + b.push(-127i8); + check(&b, &[129, 1]); + b.push(255u8); + check(&b, &[255, 129, 1]); + b.push(-32222i16); + check(&b, &[0x22, 0x82, 0, 255, 129, 1]); // first pad + b.push(0xFEEEu16); + check(&b, &[0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]); // no pad this time + b.push(-53687092i32); + check(&b, &[204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]); + b.push(0x98765432u32); + check(&b, &[0x32, 0x54, 0x76, 0x98, 204, 204, 204, 252, 0xEE, 0xFE, 0x22, 0x82, 0, 255, 129, 1]); + } + + #[test] + fn layout_01b_bigger_numbers() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.push(0x1122334455667788u64); + check(&b, &[0x88, 0x77, 0x66, 0x55, 0x44, 0x33, 0x22, 0x11]); + } + + #[test] + fn layout_02_1xbyte_vector() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + check(&b, &[]); + b.start_vector::(1); + check(&b, &[0, 0, 0]); // align to 4bytes + b.push(1u8); + check(&b, &[1, 0, 0, 0]); + b.end_vector::(1); + check(&b, &[1, 0, 0, 0, 1, 0, 0, 0]); // padding + } + + #[test] + fn layout_03_2xbyte_vector() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(2); + check(&b, &[0, 0]); // align to 4bytes + b.push(1u8); + check(&b, &[1, 0, 0]); + b.push(2u8); + check(&b, &[2, 1, 0, 0]); + b.end_vector::(2); + check(&b, &[2, 0, 0, 0, 2, 1, 0, 0]); // padding + } + + #[test] + fn layout_03b_11xbyte_vector_matches_builder_size() { + let mut b = flatbuffers::FlatBufferBuilder::with_capacity(12); + b.start_vector::(8); + + let mut gold = vec![0u8; 0]; + check(&b, &gold[..]); + + for i in 1u8..=8 { + b.push(i); + gold.insert(0, i); + check(&b, &gold[..]); + } + b.end_vector::(8); + let want = vec![8u8, 0, 0, 0, 8, 7, 6, 5, 4, 3, 2, 1]; + check(&b, &want[..]); + } + #[test] + fn layout_04_1xuint16_vector() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(1); + check(&b, &[0, 0]); // align to 4bytes + b.push(1u16); + check(&b, &[1, 0, 0, 0]); + b.end_vector::(1); + check(&b, &[1, 0, 0, 0, 1, 0, 0, 0]); // padding + } + + #[test] + fn layout_05_2xuint16_vector() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let _off = b.start_vector::(2); + check(&b, &[]); // align to 4bytes + b.push(0xABCDu16); + check(&b, &[0xCD, 0xAB]); + b.push(0xDCBAu16); + check(&b, &[0xBA, 0xDC, 0xCD, 0xAB]); + b.end_vector::(2); + check(&b, &[2, 0, 0, 0, 0xBA, 0xDC, 0xCD, 0xAB]); + } + + #[test] + fn layout_06_create_string() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off0 = b.create_string("foo"); + assert_eq!(8, off0.value()); + check(&b, b"\x03\x00\x00\x00foo\x00"); // 0-terminated, no pad + let off1 = b.create_string("moop"); + assert_eq!(20, off1.value()); + check(&b, b"\x04\x00\x00\x00moop\x00\x00\x00\x00\ + \x03\x00\x00\x00foo\x00"); // 0-terminated, 3-byte pad + } + + #[test] + fn layout_06b_create_string_unicode() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + // These characters are chinese from blog.golang.org/strings + // We use escape codes here so that editors without unicode support + // aren't bothered: + let uni_str = "\u{65e5}\u{672c}\u{8a9e}"; + let off0 = b.create_string(uni_str); + assert_eq!(16, off0.value()); + check(&b, &[9, 0, 0, 0, 230, 151, 165, 230, 156, 172, 232, 170, 158, 0, // null-terminated, 2-byte pad + 0, 0]); + } + + #[test] + fn layout_06c_create_byte_string() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off0 = b.create_byte_string(b"foo"); + assert_eq!(8, off0.value()); + check(&b, b"\x03\x00\x00\x00foo\x00"); // 0-terminated, no pad + let off1 = b.create_byte_string(b"moop"); + assert_eq!(20, off1.value()); + check(&b, b"\x04\x00\x00\x00moop\x00\x00\x00\x00\ + \x03\x00\x00\x00foo\x00"); // 0-terminated, 3-byte pad + } + + #[test] + fn layout_07_empty_vtable() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off0 = b.start_table(); + check(&b, &[]); + b.end_table(off0); + check(&b, &[4, 0, // vtable length + 4, 0, // length of table including vtable offset + 4, 0, 0, 0]); // offset for start of vtable + } + + #[test] + fn layout_08_vtable_with_one_true_bool() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + check(&b, &[]); + let off0 = b.start_table(); + assert_eq!(0, off0.value()); + check(&b, &[]); + b.push_slot(fi2fo(0), true, false); + check(&b, &[1]); + let off1 = b.end_table(off0); + assert_eq!(8, off1.value()); + check(&b, &[ + 6, 0, // vtable bytes + 8, 0, // length of object including vtable offset + 7, 0, // start of bool value + 6, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, 0, // padded to 4 bytes + 1, // bool value + ]); + } + + #[test] + fn layout_09_vtable_with_one_default_bool() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + check(&b, &[]); + let off = b.start_table(); + check(&b, &[]); + b.push_slot(fi2fo(0), false, false); + b.end_table(off); + check(&b, &[ + 4, 0, // vtable bytes + 4, 0, // end of object from here + // entry 1 is zero and not stored. + 4, 0, 0, 0, // offset for start of vtable (int32) + ]); + } + + #[test] + fn layout_09b_vtable_with_one_default_bool_force_defaults() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + check(&b, &[]); + let off = b.start_table(); + check(&b, &[]); + b.force_defaults(true); + b.push_slot(fi2fo(0), false, false); + b.end_table(off); + check(&b, &[ + 6, 0, // vtable bytes + 8, 0, // length of object including vtable offset + 7, 0, // start of bool value + 6, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, 0, // padded to 4 bytes + 0, // bool value + ]); + } + + #[test] + fn layout_10_vtable_with_one_int16() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + check(&b, &[]); + let off = b.start_table(); + b.push_slot(fi2fo(0), 0x789Ai16, 0); + b.end_table(off); + check(&b, &[ + 6, 0, // vtable bytes + 8, 0, // end of object from here + 6, 0, // offset to value + 6, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, // padding to 4 bytes + 0x9A, 0x78, + ]); + } + + #[test] + fn layout_11_vtable_with_two_int16() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot(fi2fo(0), 0x3456i16, 0); + b.push_slot(fi2fo(1), 0x789Ai16, 0); + b.end_table(off); + check(&b, &[ + 8, 0, // vtable bytes + 8, 0, // end of object from here + 6, 0, // offset to value 0 + 4, 0, // offset to value 1 + 8, 0, 0, 0, // offset for start of vtable (int32) + 0x9A, 0x78, // value 1 + 0x56, 0x34, // value 0 + ]); + } + + #[test] + fn layout_12_vtable_with_int16_and_bool() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot(fi2fo(0), 0x3456i16, 0); + b.push_slot(fi2fo(1), true, false); + b.end_table(off); + check(&b, &[ + 8, 0, // vtable bytes + 8, 0, // end of object from here + 6, 0, // offset to value 0 + 5, 0, // offset to value 1 + 8, 0, 0, 0, // offset for start of vtable (int32) + 0, // padding + 1, // value 1 + 0x56, 0x34, // value 0 + ]); + } + + #[test] + fn layout_12b_vtable_with_empty_vector() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(0); + let vecend = b.end_vector::(0); + let off = b.start_table(); + b.push_slot_always(fi2fo(0), vecend); + b.end_table(off); + check(&b, &[ + 6, 0, // vtable bytes + 8, 0, + 4, 0, // offset to vector offset + 6, 0, 0, 0, // offset for start of vtable (int32) + 4, 0, 0, 0, + 0, 0, 0, 0, // length of vector (not in struct) + ]); + } + + #[test] + fn layout_12c_vtable_with_empty_vector_of_byte_and_some_scalars() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(0); + let vecend = b.end_vector::(0); + let off = b.start_table(); + b.push_slot::(fi2fo(0), 55i16, 0); + b.push_slot_always::>(fi2fo(1), vecend); + b.end_table(off); + check(&b, &[ + 8, 0, // vtable bytes + 12, 0, + 10, 0, // offset to value 0 + 4, 0, // offset to vector offset + 8, 0, 0, 0, // vtable loc + 8, 0, 0, 0, // value 1 + 0, 0, 55, 0, // value 0 + + 0, 0, 0, 0, // length of vector (not in struct) + ]); + } + #[test] + fn layout_13_vtable_with_1_int16_and_2_vector_of_i16() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(2); + b.push(0x1234i16); + b.push(0x5678i16); + let vecend = b.end_vector::(2); + let off = b.start_table(); + b.push_slot_always(fi2fo(1), vecend); + b.push_slot(fi2fo(0), 55i16, 0); + b.end_table(off); + check(&b, &[ + 8, 0, // vtable bytes + 12, 0, // length of object + 6, 0, // start of value 0 from end of vtable + 8, 0, // start of value 1 from end of buffer + 8, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, // padding + 55, 0, // value 0 + 4, 0, 0, 0, // vector position from here + 2, 0, 0, 0, // length of vector (uint32) + 0x78, 0x56, // vector value 1 + 0x34, 0x12, // vector value 0 + ]); + } + #[test] + fn layout_14_vtable_with_1_struct_of_int8_and_int16_and_int32() { + #[derive(Copy, Clone, Debug, Eq, PartialEq)] + #[repr(C, packed)] + struct foo { + a: i32, + _pad0: [u8; 2], + b: i16, + _pad1: [u8; 3], + c: i8, + _pad2: [u8; 4], + } + assert_eq!(::core::mem::size_of::(), 16); + impl<'b> flatbuffers::Push for &'b foo { + type Output = foo; + unsafe fn push<'a>(&'a self, dst: &'a mut [u8], _written_len: usize) { + let src = ::core::slice::from_raw_parts(*self as *const foo as *const u8, ::core::mem::size_of::()); + dst.copy_from_slice(src); + } + } + + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + let x = foo{a: 0x12345678i32.to_le(), _pad0: [0,0], b: 0x1234i16.to_le(), _pad1: [0, 0, 0], c: 0x12i8.to_le(), _pad2: [0, 0, 0, 0]}; + b.push_slot_always(fi2fo(0), &x); + b.end_table(off); + check(&b, &[ + 6, 0, // vtable bytes + 20, 0, // end of object from here + 4, 0, // start of struct from here + 6, 0, 0, 0, // offset for start of vtable (int32) + + 0x78, 0x56, 0x34, 0x12, // value a + 0, 0, // padding + 0x34, 0x12, // value b + 0, 0, 0, // padding + 0x12, // value c + 0, 0, 0, 0, // padding + ]); + } + #[test] + fn layout_15_vtable_with_1_vector_of_4_int8() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + b.start_vector::(4); + b.push(33i8); + b.push(44i8); + b.push(55i8); + b.push(66i8); + let vecend = b.end_vector::(4); + let off = b.start_table(); + b.push_slot_always(fi2fo(0), vecend); + b.end_table(off); + check(&b, &[ + 6, 0, // vtable bytes + 8, 0, + 4, 0, // offset of vector offset + 6, 0, 0, 0, // offset for start of vtable (int32) + 4, 0, 0, 0, // vector start offset + + 4, 0, 0, 0, // vector length + 66, // vector value 1,1 + 55, // vector value 1,0 + 44, // vector value 0,1 + 33, // vector value 0,0 + ]); + } + + #[test] + fn layout_16_table_with_some_elements() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot(fi2fo(0), 33i8, 0); + b.push_slot(fi2fo(1), 66i16, 0); + let off2 = b.end_table(off); + b.finish_minimal(off2); + + check(&b, &[ + 12, 0, 0, 0, // root of table: points to vtable offset + + 8, 0, // vtable bytes + 8, 0, // end of object from here + 7, 0, // start of value 0 + 4, 0, // start of value 1 + + 8, 0, 0, 0, // offset for start of vtable (int32) + + 66, 0, // value 1 + 0, // padding + 33, // value 0 + ]); + } + + #[test] + fn layout_17_one_unfinished_table_and_one_finished_table() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + { + let off = b.start_table(); + b.push_slot(fi2fo(0), 33i8, 0); + b.push_slot(fi2fo(1), 44i8, 0); + b.end_table(off); + } + + { + let off = b.start_table(); + b.push_slot(fi2fo(0), 55i8, 0); + b.push_slot(fi2fo(1), 66i8, 0); + b.push_slot(fi2fo(2), 77i8, 0); + let off2 = b.end_table(off); + b.finish_minimal(off2); + } + + check(&b, &[ + 16, 0, 0, 0, // root of table: points to object + 0, 0, // padding + + 10, 0, // vtable bytes + 8, 0, // size of object + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 5, 0, // start of value 2 + 10, 0, 0, 0, // offset for start of vtable (int32) + 0, // padding + 77, // value 2 + 66, // value 1 + 55, // value 0 + + //12, 0, 0, 0, // root of table: points to object + + 8, 0, // vtable bytes + 8, 0, // size of object + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 8, 0, 0, 0, // offset for start of vtable (int32) + 0, 0, // padding + 44, // value 1 + 33, // value 0 + ]); + } + + #[test] + fn layout_18_a_bunch_of_bools() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot(fi2fo(0), true, false); + b.push_slot(fi2fo(1), true, false); + b.push_slot(fi2fo(2), true, false); + b.push_slot(fi2fo(3), true, false); + b.push_slot(fi2fo(4), true, false); + b.push_slot(fi2fo(5), true, false); + b.push_slot(fi2fo(6), true, false); + b.push_slot(fi2fo(7), true, false); + let off2 = b.end_table(off); + b.finish_minimal(off2); + + check(&b, &[ + 24, 0, 0, 0, // root of table: points to vtable offset + + 20, 0, // vtable bytes + 12, 0, // size of object + 11, 0, // start of value 0 + 10, 0, // start of value 1 + 9, 0, // start of value 2 + 8, 0, // start of value 3 + 7, 0, // start of value 4 + 6, 0, // start of value 5 + 5, 0, // start of value 6 + 4, 0, // start of value 7 + 20, 0, 0, 0, // vtable offset + + 1, // value 7 + 1, // value 6 + 1, // value 5 + 1, // value 4 + 1, // value 3 + 1, // value 2 + 1, // value 1 + 1, // value 0 + ]); + } + + #[test] + fn layout_19_three_bools() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot(fi2fo(0), true, false); + b.push_slot(fi2fo(1), true, false); + b.push_slot(fi2fo(2), true, false); + let off2 = b.end_table(off); + b.finish_minimal(off2); + + check(&b, &[ + 16, 0, 0, 0, // root of table: points to vtable offset + + 0, 0, // padding + + 10, 0, // vtable bytes + 8, 0, // size of object + 7, 0, // start of value 0 + 6, 0, // start of value 1 + 5, 0, // start of value 2 + 10, 0, 0, 0, // vtable offset from here + + 0, // padding + 1, // value 2 + 1, // value 1 + 1, // value 0 + ]); + } + + #[test] + fn layout_20_some_floats() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot(fi2fo(0), 1.0f32, 0.0); + b.end_table(off); + + check(&b, &[ + 6, 0, // vtable bytes + 8, 0, // size of object + 4, 0, // start of value 0 + 6, 0, 0, 0, // vtable offset + + 0, 0, 128, 63, // value 0 + ]); + } + + #[test] + fn layout_21_vtable_defaults() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot::(fi2fo(0), 1, 1); + b.push_slot::(fi2fo(1), 3, 2); + b.push_slot::(fi2fo(2), 3, 3); + b.end_table(off); + check(&b, &[ + 8, 0, // vtable size in bytes + 8, 0, // object inline data in bytes + 0, 0, // entry 1/3: 0 => default + 7, 0, // entry 2/3: 7 => table start + 7 bytes + // entry 3/3: not present => default + 8, 0, 0, 0, + 0, 0, 0, + 3, + ]); + } + + #[test] + fn layout_22_root() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + // skipped: b.push_slot_scalar::(0, 1, 1); + b.push_slot::(fi2fo(1), 3, 2); + b.push_slot::(fi2fo(2), 3, 3); + let table_end = b.end_table(off); + b.finish_minimal(table_end); + check(&b, &[ + 12, 0, 0, 0, // root + + 8, 0, // vtable size in bytes + 8, 0, // object inline data in bytes + 0, 0, // entry 1/3: 0 => default + 6, 0, // entry 2/3: 6 => table start + 6 bytes + // entry 3/3: not present => default + 8, 0, 0, 0, // size of table data in bytes + 0, 0, // padding + 3, 0, // value 2/3 + ]); + } + #[test] + fn layout_23_varied_slots_and_root() { + let mut b = flatbuffers::FlatBufferBuilder::new(); + let off = b.start_table(); + b.push_slot::(fi2fo(0), 1, 0); + b.push_slot::(fi2fo(1), 2, 0); + b.push_slot::(fi2fo(2), 3.0, 0.0); + let table_end = b.end_table(off); + b.finish_minimal(table_end); + check(&b, &[ + 16, 0, 0, 0, // root + 0, 0, // padding + 10, 0, // vtable bytes + 12, 0, // object inline data size + 10, 0, // offset to value #1 (i16) + 9, 0, // offset to value #2 (u8) + 4, 0, // offset to value #3 (f32) + 10, 0, // offset to vtable + 0, 0, // padding + 0, 0, 64, 64, // value #3 => 3.0 (float32) + 0, 2, // value #1 => 2 (u8) + 1, 0, // value #0 => 1 (int16) + ]); + } +} + +#[cfg(test)] +mod copy_clone_traits { + + use alloc::vec::Vec; + + #[test] + fn follow_types_implement_copy_and_clone() { + static_assertions::assert_impl_all!(flatbuffers::WIPOffset: Copy, Clone); + static_assertions::assert_impl_all!(flatbuffers::WIPOffset>: Copy, Clone); + + static_assertions::assert_impl_all!(flatbuffers::ForwardsUOffset: Copy, Clone); + static_assertions::assert_impl_all!(flatbuffers::ForwardsUOffset>: Copy, Clone); + + static_assertions::assert_impl_all!(flatbuffers::Vector<'static, u32>: Copy, Clone); + static_assertions::assert_impl_all!(flatbuffers::Vector<'static, Vec>: Copy, Clone); + } +} + +#[cfg(test)] +mod fully_qualified_name { + #[test] + fn fully_qualified_name_generated() { + assert!(check_eq!(super::my_game::example::Monster::get_fully_qualified_name(), "MyGame.Example.Monster").is_ok()); + assert!(check_eq!(super::my_game::example_2::Monster::get_fully_qualified_name(), "MyGame.Example2.Monster").is_ok()); + + assert!(check_eq!(super::my_game::example::Vec3::get_fully_qualified_name(), "MyGame.Example.Vec3").is_ok()); + assert!(check_eq!(super::my_game::example::Ability::get_fully_qualified_name(), "MyGame.Example.Ability").is_ok()); + } +} + +// this is not technically a test, but we want to always keep this generated +// file up-to-date, and the simplest way to do that is to make sure that when +// tests are run, the file is generated. +#[cfg(not(feature = "no_std"))] +#[test] +fn write_example_wire_data_to_file() { + let b = &mut flatbuffers::FlatBufferBuilder::new(); + create_serialized_example_with_generated_code(b); + + use ::std::io::Write; + let mut f = std::fs::File::create("../monsterdata_rust_wire.mon").unwrap(); + f.write_all(b.finished_data()).unwrap(); +} + +#[cfg(not(feature = "no_std"))] +fn load_file(filename: &str) -> Result, std::io::Error> { + use std::io::Read; + let mut f = std::fs::File::open(filename)?; + let mut buf = Vec::new(); + f.read_to_end(&mut buf)?; + Ok(buf) +} + +#[test] +fn test_shared_strings() { + let mut builder = flatbuffers::FlatBufferBuilder::new(); + let offset1 = builder.create_shared_string("welcome to flatbuffers!!"); + let offset2 = builder.create_shared_string("welcome"); + let offset3 = builder.create_shared_string("welcome to flatbuffers!!"); + assert_ne!(offset2.value(), offset3.value()); + assert_eq!(offset1.value(), offset3.value()); + builder.reset(); + let offset4 = builder.create_shared_string("welcome"); + let offset5 = builder.create_shared_string("welcome to flatbuffers!!"); + assert_ne!(offset2.value(), offset4.value()); + assert_ne!(offset5.value(), offset1.value()); + builder.reset(); + + // Checks if the shared string function would always work with + // an object in between the writes + let name = builder.create_shared_string("foo"); + let enemy = my_game::example::Monster::create(&mut builder, &my_game::example::MonsterArgs { + name: Some(name), + ..Default::default() + }); + let secondary_name = builder.create_shared_string("foo"); + assert_eq!(name.value(), secondary_name.value()); + + // Builds a new monster object and embeds enemy into it so we can verify + // that shared strings are working. + let args = my_game::example::MonsterArgs { + name: Some(secondary_name), + enemy: Some(enemy), + testarrayofstring: Some(builder.create_vector(&[name, secondary_name])), + ..Default::default() + }; + // Building secondary monster + let main_monster = my_game::example::Monster::create(&mut builder, &args); + builder.finish(main_monster, None); + let monster = my_game::example::root_as_monster(builder.finished_data()).unwrap(); + + // Checks if the embedded object (Enemy) name is foo + assert_eq!(monster.enemy().unwrap().name(), "foo"); + let string_vector = monster.testarrayofstring().unwrap(); + // Check if the vector will have the same string + assert_eq!(string_vector.get(0), "foo"); + assert_eq!(string_vector.get(1), "foo"); +} + +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/more_defaults_test.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/more_defaults_test.rs new file mode 100644 index 00000000000..4d62a4a3f84 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/more_defaults_test.rs @@ -0,0 +1,35 @@ +extern crate alloc; + +use alloc::string::ToString; +use alloc::vec::Vec; + +#[allow(dead_code, unused_imports)] +#[path = "../../more_defaults/mod.rs"] +mod more_defaults_generated; +use self::more_defaults_generated::*; + +#[test] +fn object_defaults() { + assert_eq!( + MoreDefaultsT::default(), + MoreDefaultsT { + ints: Vec::new(), + floats: Vec::new(), + empty_string: "".to_string(), + some_string: "some".to_string(), + abcs: Vec::new(), + bools: Vec::new(), + }, + ) +} + +#[test] +fn nonpresent_values() { + let m = flatbuffers::root::(&[0; 4]).unwrap(); + assert_eq!(m.ints().len(), 0); + assert_eq!(m.floats().len(), 0); + assert_eq!(m.abcs().len(), 0); + assert_eq!(m.bools().len(), 0); + assert_eq!(m.empty_string(), ""); + assert_eq!(m.some_string(), "some"); +} diff --git a/third_party/flatbuffers/tests/rust_usage_test/tests/optional_scalars_test.rs b/third_party/flatbuffers/tests/rust_usage_test/tests/optional_scalars_test.rs new file mode 100644 index 00000000000..f8588c53813 --- /dev/null +++ b/third_party/flatbuffers/tests/rust_usage_test/tests/optional_scalars_test.rs @@ -0,0 +1,149 @@ +#[allow(dead_code, unused_imports)] +#[path = "../../optional_scalars/mod.rs"] +mod optional_scalars_generated; +use crate::optional_scalars_generated::optional_scalars::*; + +// There are 3 variants of scalars in tables - those specified with default=42, +// optional scalars, and those with nothing specified (implicitly default=0). +// This tests that you can read what you write. +macro_rules! make_test { + ( + $test_name: ident, + $just: ident, $default: ident, $maybe: ident, + $five: expr, $zero: expr, $fortytwo: expr + ) => { + #[test] + fn $test_name() { + let mut builder = flatbuffers::FlatBufferBuilder::new(); + // Test five makes sense when specified. + let ss = ScalarStuff::create( + &mut builder, + &ScalarStuffArgs { + $just: $five, + $default: $five, + $maybe: Some($five), + ..Default::default() + }, + ); + builder.finish(ss, None); + + let s = flatbuffers::root::(builder.finished_data()).unwrap(); + assert_eq!(s.$just(), $five); + assert_eq!(s.$default(), $five); + assert_eq!(s.$maybe(), Some($five)); + + // Test defaults are used when not specified. + let s = flatbuffers::root::(&[0; 8]).unwrap(); + assert_eq!(s.$just(), $zero); + assert_eq!(s.$default(), $fortytwo); + assert_eq!(s.$maybe(), None); + + // Same for object API + let s = flatbuffers::root::(builder.finished_data()).unwrap().unpack(); + assert_eq!(s.$just, $five); + assert_eq!(s.$default, $five); + assert_eq!(s.$maybe, Some($five)); + let s = flatbuffers::root::(&[0; 8]).unwrap().unpack(); + assert_eq!(s.$just, $zero); + assert_eq!(s.$default, $fortytwo); + assert_eq!(s.$maybe, None); + } + }; +} + +make_test!(optional_i8, just_i8, default_i8, maybe_i8, 5, 0, 42); +make_test!(optional_u8, just_u8, default_u8, maybe_u8, 5, 0, 42); +make_test!(optional_i16, just_i16, default_i16, maybe_i16, 5, 0, 42); +make_test!(optional_u16, just_u16, default_u16, maybe_u16, 5, 0, 42); +make_test!(optional_i32, just_i32, default_i32, maybe_i32, 5, 0, 42); +make_test!(optional_u32, just_u32, default_u32, maybe_u32, 5, 0, 42); +make_test!(optional_i64, just_i64, default_i64, maybe_i64, 5, 0, 42); +make_test!(optional_u64, just_u64, default_u64, maybe_u64, 5, 0, 42); +make_test!( + optional_f32, + just_f32, + default_f32, + maybe_f32, + 5.0, + 0.0, + 42.0 +); +make_test!( + optional_f64, + just_f64, + default_f64, + maybe_f64, + 5.0, + 0.0, + 42.0 +); +make_test!( + optional_bool, + just_bool, + default_bool, + maybe_bool, + true, + false, + true +); +make_test!( + optional_enum, + just_enum, + default_enum, + maybe_enum, + OptionalByte::Two, + OptionalByte::None, + OptionalByte::One +); + +#[test] +fn object_api_defaults() { + assert_eq!( + ScalarStuffT::default(), + ScalarStuffT { + just_i8: 0, + maybe_i8: None, + default_i8: 42, + just_u8: 0, + maybe_u8: None, + default_u8: 42, + + just_i16: 0, + maybe_i16: None, + default_i16: 42, + just_u16: 0, + maybe_u16: None, + default_u16: 42, + + just_i32: 0, + maybe_i32: None, + default_i32: 42, + just_u32: 0, + maybe_u32: None, + default_u32: 42, + + just_i64: 0, + maybe_i64: None, + default_i64: 42, + just_u64: 0, + maybe_u64: None, + default_u64: 42, + + just_f32: 0.0, + maybe_f32: None, + default_f32: 42.0, + just_f64: 0.0, + maybe_f64: None, + default_f64: 42.0, + + just_bool: false, + maybe_bool: None, + default_bool: true, + + just_enum: OptionalByte::None, + maybe_enum: None, + default_enum: OptionalByte::One, + + } + ); +} diff --git a/third_party/flatbuffers/tests/service_test.fbs b/third_party/flatbuffers/tests/service_test.fbs new file mode 100644 index 00000000000..6a28f9f9030 --- /dev/null +++ b/third_party/flatbuffers/tests/service_test.fbs @@ -0,0 +1,11 @@ +namespace example; + +table HelloRequest {} +table HelloResponse {} + +rpc_service HelloService { + Hello(HelloRequest):HelloResponse; + StreamClient(HelloRequest):HelloResponse (streaming: "client"); + StreamServer(HelloRequest):HelloResponse (streaming: "server"); + Stream(HelloRequest):HelloResponse (streaming: "bidi"); +} diff --git a/third_party/flatbuffers/tests/service_test_generated.py b/third_party/flatbuffers/tests/service_test_generated.py new file mode 100644 index 00000000000..1fa9b099a07 --- /dev/null +++ b/third_party/flatbuffers/tests/service_test_generated.py @@ -0,0 +1,58 @@ +# automatically generated by the FlatBuffers compiler, do not modify + +# namespace: example + +import flatbuffers +from typing import Any +class HelloRequest(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HelloRequest() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHelloRequest(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # HelloRequest + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + +def HelloRequestStart(builder: flatbuffers.Builder): + builder.StartObject(0) + +def HelloRequestEnd(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + + + +class HelloResponse(object): + __slots__ = ['_tab'] + + @classmethod + def GetRootAs(cls, buf, offset: int = 0): + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, offset) + x = HelloResponse() + x.Init(buf, n + offset) + return x + + @classmethod + def GetRootAsHelloResponse(cls, buf, offset=0): + """This method is deprecated. Please switch to GetRootAs.""" + return cls.GetRootAs(buf, offset) + # HelloResponse + def Init(self, buf: bytes, pos: int): + self._tab = flatbuffers.table.Table(buf, pos) + +def HelloResponseStart(builder: flatbuffers.Builder): + builder.StartObject(0) + +def HelloResponseEnd(builder: flatbuffers.Builder) -> int: + return builder.EndObject() + + + diff --git a/third_party/flatbuffers/tests/service_test_generated.pyi b/third_party/flatbuffers/tests/service_test_generated.pyi new file mode 100644 index 00000000000..2189a94c693 --- /dev/null +++ b/third_party/flatbuffers/tests/service_test_generated.pyi @@ -0,0 +1,26 @@ +from __future__ import annotations + +import flatbuffers + +import flatbuffers +import typing + +uoffset: typing.TypeAlias = flatbuffers.number_types.UOffsetTFlags.py_type + +class HelloRequest(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> HelloRequest: ... + @classmethod + def GetRootAsHelloRequest(cls, buf: bytes, offset: int) -> HelloRequest: ... + def Init(self, buf: bytes, pos: int) -> None: ... +def HelloRequestStart(builder: flatbuffers.Builder) -> None: ... +def HelloRequestEnd(builder: flatbuffers.Builder) -> uoffset: ... +class HelloResponse(object): + @classmethod + def GetRootAs(cls, buf: bytes, offset: int) -> HelloResponse: ... + @classmethod + def GetRootAsHelloResponse(cls, buf: bytes, offset: int) -> HelloResponse: ... + def Init(self, buf: bytes, pos: int) -> None: ... +def HelloResponseStart(builder: flatbuffers.Builder) -> None: ... +def HelloResponseEnd(builder: flatbuffers.Builder) -> uoffset: ... + diff --git a/third_party/flatbuffers/tests/service_test_grpc.fb.py b/third_party/flatbuffers/tests/service_test_grpc.fb.py new file mode 100644 index 00000000000..27284ea9486 --- /dev/null +++ b/third_party/flatbuffers/tests/service_test_grpc.fb.py @@ -0,0 +1,97 @@ +# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT! + +import flatbuffers +import grpc + +from service_test_generated import HelloRequest, HelloResponse + + +def _serialize_to_bytes(table): + buf = table._tab.Bytes + n = flatbuffers.encode.Get(flatbuffers.packer.uoffset, buf, 0) + if table._tab.Pos != n: + raise ValueError('must be a top-level table') + return bytes(buf) + + +class HelloServiceStub(object): + '''Interface exported by the server.''' + + def __init__(self, channel): + '''Constructor. + + Args: + channel: A grpc.Channel. + ''' + + self.Hello = channel.unary_unary( + method='/example.HelloService/Hello', + request_serializer=_serialize_to_bytes, + response_deserializer=HelloResponse.GetRootAs) + + self.StreamClient = channel.stream_unary( + method='/example.HelloService/StreamClient', + request_serializer=_serialize_to_bytes, + response_deserializer=HelloResponse.GetRootAs) + + self.StreamServer = channel.unary_stream( + method='/example.HelloService/StreamServer', + request_serializer=_serialize_to_bytes, + response_deserializer=HelloResponse.GetRootAs) + + self.Stream = channel.stream_stream( + method='/example.HelloService/Stream', + request_serializer=_serialize_to_bytes, + response_deserializer=HelloResponse.GetRootAs) + + +class HelloServiceServicer(object): + '''Interface exported by the server.''' + + def Hello(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def StreamClient(self, request_iterator, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def StreamServer(self, request, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + def Stream(self, request_iterator, context): + context.set_code(grpc.StatusCode.UNIMPLEMENTED) + context.set_details('Method not implemented!') + raise NotImplementedError('Method not implemented!') + + +def add_HelloServiceServicer_to_server(servicer, server): + rpc_method_handlers = { + 'Hello': grpc.unary_unary_rpc_method_handler( + servicer.Hello, + request_deserializer=HelloRequest.GetRootAs, + response_serializer=_serialize_to_bytes), + 'StreamClient': grpc.stream_unary_rpc_method_handler( + servicer.StreamClient, + request_deserializer=HelloRequest.GetRootAs, + response_serializer=_serialize_to_bytes), + 'StreamServer': grpc.unary_stream_rpc_method_handler( + servicer.StreamServer, + request_deserializer=HelloRequest.GetRootAs, + response_serializer=_serialize_to_bytes), + 'Stream': grpc.stream_stream_rpc_method_handler( + servicer.Stream, + request_deserializer=HelloRequest.GetRootAs, + response_serializer=_serialize_to_bytes), + } + + generic_handler = grpc.method_handlers_generic_handler( + 'example.HelloService', rpc_method_handlers) + + server.add_generic_rpc_handlers((generic_handler,)) + + diff --git a/third_party/flatbuffers/tests/service_test_grpc.fb.pyi b/third_party/flatbuffers/tests/service_test_grpc.fb.pyi new file mode 100644 index 00000000000..d0f38aa4f3c --- /dev/null +++ b/third_party/flatbuffers/tests/service_test_grpc.fb.pyi @@ -0,0 +1,27 @@ +# Generated by the gRPC FlatBuffers compiler. DO NOT EDIT! + +from __future__ import annotations + +import grpc +import typing + +from service_test_generated import HelloRequest, HelloResponse + + +class HelloServiceStub(object): + def __init__(self, channel: grpc.Channel) -> None: ... + def Hello(self, request: HelloRequest) -> HelloResponse: ... + def StreamClient(self, request_iterator: typing.Iterator[HelloRequest]) -> HelloResponse: ... + def StreamServer(self, request: HelloRequest) -> typing.Iterator[HelloResponse]: ... + def Stream(self, request_iterator: typing.Iterator[HelloRequest]) -> typing.Iterator[HelloResponse]: ... + + +class HelloServiceServicer(object): + def Hello(self, request: HelloRequest, context: grpc.ServicerContext) -> HelloResponse: ... + def StreamClient(self, request_iterator: typing.Iterator[HelloRequest], context: grpc.ServicerContext) -> HelloResponse: ... + def StreamServer(self, request: HelloRequest, context: grpc.ServicerContext) -> typing.Iterator[HelloResponse]: ... + def Stream(self, request_iterator: typing.Iterator[HelloRequest], context: grpc.ServicerContext) -> typing.Iterator[HelloResponse]: ... + + +def add_HelloServiceServicer_to_server(servicer: HelloServiceServicer, server: grpc.Server) -> None: ... + diff --git a/third_party/flatbuffers/tests/swift/Wasm.tests/.swift-version b/third_party/flatbuffers/tests/swift/Wasm.tests/.swift-version new file mode 100644 index 00000000000..a00b467039c --- /dev/null +++ b/third_party/flatbuffers/tests/swift/Wasm.tests/.swift-version @@ -0,0 +1 @@ +wasm-6.0.2-RELEASE \ No newline at end of file diff --git a/third_party/flatbuffers/Package@swift-5.5.swift b/third_party/flatbuffers/tests/swift/Wasm.tests/Package.swift similarity index 65% rename from third_party/flatbuffers/Package@swift-5.5.swift rename to third_party/flatbuffers/tests/swift/Wasm.tests/Package.swift index 13313560ee0..a7573d6c706 100644 --- a/third_party/flatbuffers/Package@swift-5.5.swift +++ b/third_party/flatbuffers/tests/swift/Wasm.tests/Package.swift @@ -1,4 +1,4 @@ -// swift-tools-version:5.5 +// swift-tools-version:5.9 /* * Copyright 2020 Google Inc. All rights reserved. * @@ -18,20 +18,19 @@ import PackageDescription let package = Package( - name: "FlatBuffers", + name: "FlatBuffers.Test.Swift.Wasm", platforms: [ - .iOS(.v11), .macOS(.v10_14), ], - products: [ - .library( - name: "FlatBuffers", - targets: ["FlatBuffers"]), + dependencies: [ + .package(path: "../../.."), + .package(url: "https://github.com/swiftwasm/carton", exact: "1.1.2"), ], targets: [ - .target( - name: "FlatBuffers", - dependencies: [], - path: "swift/Sources"), + .target(name: "Wasm"), + .testTarget( + name: "FlatBuffers.Test.Swift.WasmTests", + dependencies: [ + .product(name: "FlatBuffers", package: "flatbuffers"), + ]), ]) - diff --git a/third_party/flatbuffers/tests/swift/Wasm.tests/Sources/Wasm/Wasm.swift b/third_party/flatbuffers/tests/swift/Wasm.tests/Sources/Wasm/Wasm.swift new file mode 100644 index 00000000000..e77aa2fec3a --- /dev/null +++ b/third_party/flatbuffers/tests/swift/Wasm.tests/Sources/Wasm/Wasm.swift @@ -0,0 +1,17 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +public struct Wasm {} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/swift/Wasm.tests/Tests/FlatBuffers.Test.Swift.WasmTests/FlatBuffersMonsterWriterTests.swift b/third_party/flatbuffers/tests/swift/Wasm.tests/Tests/FlatBuffers.Test.Swift.WasmTests/FlatBuffersMonsterWriterTests.swift new file mode 100644 index 00000000000..d126b0f6a54 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/Wasm.tests/Tests/FlatBuffers.Test.Swift.WasmTests/FlatBuffersMonsterWriterTests.swift @@ -0,0 +1,365 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation +import XCTest +@testable import FlatBuffers + +typealias Test = MyGame_Example_Test +typealias Monster = MyGame_Example_Monster +typealias Vec3 = MyGame_Example_Vec3 +typealias Stat = MyGame_Example_Stat + +class FlatBuffersMonsterWriterTests: XCTestCase { + + func testData() { + // swiftformat:disable all + let data: [UInt8] = [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0] + // swiftformat:enable all + let _data = ByteBuffer(bytes: data) + readVerifiedMonster(fb: _data) + } + + func testCreateMonster() { + let bytes = createMonster(withPrefix: false) + // swiftformat:disable all + XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + var buffer = bytes.buffer + let monster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer) + readMonster(monster: monster) + mutateMonster(fb: bytes.buffer) + readMonster(monster: monster) + } + + func testCreateMonsterResizedBuffer() { + let bytes = createMonster(withPrefix: false) + // swiftformat:disable all + XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + readVerifiedMonster(fb: bytes.sizedBuffer) + } + + func testCreateMonsterPrefixed() { + let bytes = createMonster(withPrefix: true) + // swiftformat:disable all + XCTAssertEqual(bytes.sizedByteArray, [44, 1, 0, 0, 44, 0, 0, 0, 77, 79, 78, 83, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + + var buffer = bytes.buffer + readMonster(monster: getPrefixedSizeRoot(byteBuffer: &buffer)) + } + + func testCreateMonsterUsingCreateMonsterMethodWithNilPos() { + var fbb = FlatBufferBuilder(initialSize: 1) + let name = fbb.create(string: "Frodo") + let mStart = Monster.startMonster(&fbb) + Monster.add(name: name, &fbb) + let root = Monster.endMonster(&fbb, start: mStart) + fbb.finish(offset: root) + var buffer = fbb.sizedBuffer + let newMonster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer) + XCTAssertNil(newMonster.pos) + XCTAssertEqual(newMonster.name, "Frodo") + } + + func testCreateMonsterUsingCreateMonsterMethodWithPosX() { + var fbb = FlatBufferBuilder(initialSize: 1) + let name = fbb.create(string: "Barney") + let mStart = Monster.startMonster(&fbb) + Monster.add( + pos: MyGame_Example_Vec3( + x: 10, + y: 0, + z: 0, + test1: 0, + test2: .blue, + test3: .init()), + &fbb) + Monster.add(name: name, &fbb) + let root = Monster.endMonster(&fbb, start: mStart) + fbb.finish(offset: root) + + var buffer = fbb.sizedBuffer + let newMonster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer) + XCTAssertEqual(newMonster.pos!.x, 10) + XCTAssertEqual(newMonster.name, "Barney") + } + + func testArrayOfBools() { + let boolArray = [false, true, false, true, false, true, false] + var fbb = FlatBufferBuilder(initialSize: 1) + let name = fbb.create(string: "Frodo") + let bools = fbb.createVector(boolArray) + let root = Monster.createMonster( + &fbb, + nameOffset: name, + testarrayofboolsVectorOffset: bools) + fbb.finish(offset: root) + var buffer = fbb.sizedBuffer + let monster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer) + + let values = monster.testarrayofbools + + XCTAssertEqual(boolArray, values) + + for i in 0.. FlatBufferBuilder { + var fbb = FlatBufferBuilder(initialSize: 1) + let names = [ + fbb.create(string: "Frodo"), + fbb.create(string: "Barney"), + fbb.create(string: "Wilma"), + ] + var offsets: [Offset] = [] + let start1 = Monster.startMonster(&fbb) + Monster.add(name: names[0], &fbb) + offsets.append(Monster.endMonster(&fbb, start: start1)) + let start2 = Monster.startMonster(&fbb) + Monster.add(name: names[1], &fbb) + offsets.append(Monster.endMonster(&fbb, start: start2)) + let start3 = Monster.startMonster(&fbb) + Monster.add(name: names[2], &fbb) + offsets.append(Monster.endMonster(&fbb, start: start3)) + + let sortedArray = Monster.sortVectorOfMonster(offsets: offsets, &fbb) + + let str = fbb.create(string: "MyMonster") + let test1 = fbb.create(string: "test1") + let test2 = fbb.create(string: "test2") + let _inv: [Byte] = [0, 1, 2, 3, 4] + let inv = fbb.createVector(_inv) + + let fred = fbb.create(string: "Fred") + let mon1Start = Monster.startMonster(&fbb) + Monster.add(name: fred, &fbb) + let mon2 = Monster.endMonster(&fbb, start: mon1Start) + + let test4 = fbb.createVector(ofStructs: [ + MyGame_Example_Test(a: 30, b: 40), + MyGame_Example_Test(a: 10, b: 20), + ]) + + let stringTestVector = fbb.createVector(ofOffsets: [test1, test2]) + let mStart = Monster.startMonster(&fbb) + Monster.add( + pos: MyGame_Example_Vec3( + x: 1, + y: 2, + z: 3, + test1: 3, + test2: .green, + test3: .init(a: 5, b: 6)), + &fbb) + Monster.add(hp: 80, &fbb) + Monster.add(name: str, &fbb) + Monster.addVectorOf(inventory: inv, &fbb) + Monster.add(testType: .monster, &fbb) + Monster.add(test: mon2, &fbb) + Monster.addVectorOf(test4: test4, &fbb) + Monster.addVectorOf(testarrayofstring: stringTestVector, &fbb) + Monster.add(testbool: true, &fbb) + Monster.addVectorOf(testarrayoftables: sortedArray, &fbb) + let end = Monster.endMonster(&fbb, start: mStart) + Monster.finish(&fbb, end: end, prefix: prefix) + return fbb + } + + func mutateMonster(fb: ByteBuffer) { + var fb = fb + + let monster: Monster = getRoot(byteBuffer: &fb) + XCTAssertFalse(monster.mutate(mana: 10)) + XCTAssertEqual(monster.testarrayoftables(at: 0)?.name, "Barney") + XCTAssertEqual(monster.testarrayoftables(at: 1)?.name, "Frodo") + XCTAssertEqual(monster.testarrayoftables(at: 2)?.name, "Wilma") + + // Example of searching for a table by the key + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Frodo")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Barney")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Wilma")) + + XCTAssertEqual(monster.testType, .monster) + + XCTAssertTrue(monster.mutate(testbool: false)) + XCTAssertEqual(monster.testbool, false) + XCTAssertTrue(monster.mutate(testbool: true)) + + XCTAssertEqual(monster.mutate(inventory: 1, at: 0), true) + XCTAssertEqual(monster.mutate(inventory: 2, at: 1), true) + XCTAssertEqual(monster.mutate(inventory: 3, at: 2), true) + XCTAssertEqual(monster.mutate(inventory: 4, at: 3), true) + XCTAssertEqual(monster.mutate(inventory: 5, at: 4), true) + + for i in 0...size } + public var value: UInt8 { return self.rawValue } + case red = 1 + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + case green = 2 + /// \brief color Blue (1u << 3) + case blue = 8 + + public static var max: MyGame_Example_Color { return .blue } + public static var min: MyGame_Example_Color { return .red } +} + +extension MyGame_Example_Color: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .red: try container.encode("Red") + case .green: try container.encode("Green") + case .blue: try container.encode("Blue") + } + } +} + +public enum MyGame_Example_Race: Int8, Enum, Verifiable { + public typealias T = Int8 + public static var byteSize: Int { return MemoryLayout.size } + public var value: Int8 { return self.rawValue } + case none_ = -1 + case human = 0 + case dwarf = 1 + case elf = 2 + + public static var max: MyGame_Example_Race { return .elf } + public static var min: MyGame_Example_Race { return .none_ } +} + +extension MyGame_Example_Race: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("None") + case .human: try container.encode("Human") + case .dwarf: try container.encode("Dwarf") + case .elf: try container.encode("Elf") + } + } +} + +public enum MyGame_Example_LongEnum: UInt64, Enum, Verifiable { + public typealias T = UInt64 + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt64 { return self.rawValue } + case longone = 2 + case longtwo = 4 + case longbig = 1099511627776 + + public static var max: MyGame_Example_LongEnum { return .longbig } + public static var min: MyGame_Example_LongEnum { return .longone } +} + +extension MyGame_Example_LongEnum: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .longone: try container.encode("LongOne") + case .longtwo: try container.encode("LongTwo") + case .longbig: try container.encode("LongBig") + } + } +} + +public enum MyGame_Example_Any_: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case monster = 1 + case testsimpletablewithenum = 2 + case mygameExample2Monster = 3 + + public static var max: MyGame_Example_Any_ { return .mygameExample2Monster } + public static var min: MyGame_Example_Any_ { return .none_ } +} + +extension MyGame_Example_Any_: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .monster: try container.encode("Monster") + case .testsimpletablewithenum: try container.encode("TestSimpleTableWithEnum") + case .mygameExample2Monster: try container.encode("MyGame_Example2_Monster") + } + } +} + +public struct MyGame_Example_Any_Union { + public var type: MyGame_Example_Any_ + public var value: NativeObject? + public init(_ v: NativeObject?, type: MyGame_Example_Any_) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .monster: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .testsimpletablewithenum: + var __obj = value as? MyGame_Example_TestSimpleTableWithEnumT + return MyGame_Example_TestSimpleTableWithEnum.pack(&builder, obj: &__obj) + case .mygameExample2Monster: + var __obj = value as? MyGame_Example2_MonsterT + return MyGame_Example2_Monster.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public enum MyGame_Example_AnyUniqueAliases: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case m = 1 + case ts = 2 + case m2 = 3 + + public static var max: MyGame_Example_AnyUniqueAliases { return .m2 } + public static var min: MyGame_Example_AnyUniqueAliases { return .none_ } +} + +extension MyGame_Example_AnyUniqueAliases: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .m: try container.encode("M") + case .ts: try container.encode("TS") + case .m2: try container.encode("M2") + } + } +} + +public struct MyGame_Example_AnyUniqueAliasesUnion { + public var type: MyGame_Example_AnyUniqueAliases + public var value: NativeObject? + public init(_ v: NativeObject?, type: MyGame_Example_AnyUniqueAliases) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .m: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .ts: + var __obj = value as? MyGame_Example_TestSimpleTableWithEnumT + return MyGame_Example_TestSimpleTableWithEnum.pack(&builder, obj: &__obj) + case .m2: + var __obj = value as? MyGame_Example2_MonsterT + return MyGame_Example2_Monster.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public enum MyGame_Example_AnyAmbiguousAliases: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case m1 = 1 + case m2 = 2 + case m3 = 3 + + public static var max: MyGame_Example_AnyAmbiguousAliases { return .m3 } + public static var min: MyGame_Example_AnyAmbiguousAliases { return .none_ } +} + +extension MyGame_Example_AnyAmbiguousAliases: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .m1: try container.encode("M1") + case .m2: try container.encode("M2") + case .m3: try container.encode("M3") + } + } +} + +public struct MyGame_Example_AnyAmbiguousAliasesUnion { + public var type: MyGame_Example_AnyAmbiguousAliases + public var value: NativeObject? + public init(_ v: NativeObject?, type: MyGame_Example_AnyAmbiguousAliases) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .m1: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .m2: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .m3: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public struct MyGame_Example_Test: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: Int16 + private var _b: Int8 + private let padding0__: UInt8 = 0 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = _accessor.readBuffer(of: Int16.self, at: 0) + _b = _accessor.readBuffer(of: Int8.self, at: 2) + } + + public init(a: Int16, b: Int8) { + _a = a + _b = b + } + + public init() { + _a = 0 + _b = 0 + } + + public init(_ _t: inout MyGame_Example_Test_Mutable) { + _a = _t.a + _b = _t.b + } + + public var a: Int16 { _a } + public var b: Int8 { _b } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_Test.self) + } +} + +extension MyGame_Example_Test: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + case b = "b" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if a != 0 { + try container.encodeIfPresent(a, forKey: .a) + } + if b != 0 { + try container.encodeIfPresent(b, forKey: .b) + } + } +} + +public struct MyGame_Example_Test_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: Int16 { return _accessor.readBuffer(of: Int16.self, at: 0) } + @discardableResult public func mutate(a: Int16) -> Bool { return _accessor.mutate(a, index: 0) } + public var b: Int8 { return _accessor.readBuffer(of: Int8.self, at: 2) } + @discardableResult public func mutate(b: Int8) -> Bool { return _accessor.mutate(b, index: 2) } + + + public mutating func unpack() -> MyGame_Example_Test { + return MyGame_Example_Test(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Test?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Test) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _x: Float32 + private var _y: Float32 + private var _z: Float32 + private let padding0__: UInt32 = 0 + private var _test1: Double + private var _test2: UInt8 + private let padding1__: UInt8 = 0 + private var _test3: MyGame_Example_Test + private let padding2__: UInt16 = 0 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _x = _accessor.readBuffer(of: Float32.self, at: 0) + _y = _accessor.readBuffer(of: Float32.self, at: 4) + _z = _accessor.readBuffer(of: Float32.self, at: 8) + _test1 = _accessor.readBuffer(of: Double.self, at: 16) + _test2 = _accessor.readBuffer(of: UInt8.self, at: 24) + _test3 = MyGame_Example_Test(_accessor.bb, o: _accessor.position + 26) + } + + public init(x: Float32, y: Float32, z: Float32, test1: Double, test2: MyGame_Example_Color, test3: MyGame_Example_Test) { + _x = x + _y = y + _z = z + _test1 = test1 + _test2 = test2.value + _test3 = test3 + } + + public init() { + _x = 0.0 + _y = 0.0 + _z = 0.0 + _test1 = 0.0 + _test2 = 0 + _test3 = MyGame_Example_Test() + } + + public init(_ _t: inout MyGame_Example_Vec3_Mutable) { + _x = _t.x + _y = _t.y + _z = _t.z + _test1 = _t.test1 + _test2 = _t.test2.value + var _vtest3 = _t.test3 + _test3 = _vtest3.unpack() + } + + public var x: Float32 { _x } + public var y: Float32 { _y } + public var z: Float32 { _z } + public var test1: Double { _test1 } + public var test2: MyGame_Example_Color { MyGame_Example_Color(rawValue: _test2)! } + public var test3: MyGame_Example_Test { _test3 } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_Vec3.self) + } +} + +extension MyGame_Example_Vec3: Encodable { + + enum CodingKeys: String, CodingKey { + case x = "x" + case y = "y" + case z = "z" + case test1 = "test1" + case test2 = "test2" + case test3 = "test3" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if x != 0.0 { + try container.encodeIfPresent(x, forKey: .x) + } + if y != 0.0 { + try container.encodeIfPresent(y, forKey: .y) + } + if z != 0.0 { + try container.encodeIfPresent(z, forKey: .z) + } + if test1 != 0.0 { + try container.encodeIfPresent(test1, forKey: .test1) + } + if test2 != .red { + try container.encodeIfPresent(test2, forKey: .test2) + } + try container.encodeIfPresent(test3, forKey: .test3) + } +} + +public struct MyGame_Example_Vec3_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) } + @discardableResult public func mutate(x: Float32) -> Bool { return _accessor.mutate(x, index: 0) } + public var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) } + @discardableResult public func mutate(y: Float32) -> Bool { return _accessor.mutate(y, index: 4) } + public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) } + @discardableResult public func mutate(z: Float32) -> Bool { return _accessor.mutate(z, index: 8) } + public var test1: Double { return _accessor.readBuffer(of: Double.self, at: 16) } + @discardableResult public func mutate(test1: Double) -> Bool { return _accessor.mutate(test1, index: 16) } + public var test2: MyGame_Example_Color { return MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: 24)) ?? .red } + @discardableResult public func mutate(test2: MyGame_Example_Color) -> Bool { return _accessor.mutate(test2.rawValue, index: 24) } + public var test3: MyGame_Example_Test_Mutable { return MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.position + 26) } + + + public mutating func unpack() -> MyGame_Example_Vec3 { + return MyGame_Example_Vec3(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_Ability: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _id: UInt32 + private var _distance: UInt32 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _id = _accessor.readBuffer(of: UInt32.self, at: 0) + _distance = _accessor.readBuffer(of: UInt32.self, at: 4) + } + + public init(id: UInt32, distance: UInt32) { + _id = id + _distance = distance + } + + public init() { + _id = 0 + _distance = 0 + } + + public init(_ _t: inout MyGame_Example_Ability_Mutable) { + _id = _t.id + _distance = _t.distance + } + + public var id: UInt32 { _id } + public var distance: UInt32 { _distance } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_Ability.self) + } +} + +extension MyGame_Example_Ability: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + case distance = "distance" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if id != 0 { + try container.encodeIfPresent(id, forKey: .id) + } + if distance != 0 { + try container.encodeIfPresent(distance, forKey: .distance) + } + } +} + +public struct MyGame_Example_Ability_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var id: UInt32 { return _accessor.readBuffer(of: UInt32.self, at: 0) } + @discardableResult public func mutate(id: UInt32) -> Bool { return _accessor.mutate(id, index: 0) } + public var distance: UInt32 { return _accessor.readBuffer(of: UInt32.self, at: 4) } + @discardableResult public func mutate(distance: UInt32) -> Bool { return _accessor.mutate(distance, index: 4) } + + + public mutating func unpack() -> MyGame_Example_Ability { + return MyGame_Example_Ability(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Ability?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Ability) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_StructOfStructs: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: MyGame_Example_Ability + private var _b: MyGame_Example_Test + private var _c: MyGame_Example_Ability + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = MyGame_Example_Ability(_accessor.bb, o: _accessor.position + 0) + _b = MyGame_Example_Test(_accessor.bb, o: _accessor.position + 8) + _c = MyGame_Example_Ability(_accessor.bb, o: _accessor.position + 12) + } + + public init(a: MyGame_Example_Ability, b: MyGame_Example_Test, c: MyGame_Example_Ability) { + _a = a + _b = b + _c = c + } + + public init() { + _a = MyGame_Example_Ability() + _b = MyGame_Example_Test() + _c = MyGame_Example_Ability() + } + + public init(_ _t: inout MyGame_Example_StructOfStructs_Mutable) { + var _va = _t.a + _a = _va.unpack() + var _vb = _t.b + _b = _vb.unpack() + var _vc = _t.c + _c = _vc.unpack() + } + + public var a: MyGame_Example_Ability { _a } + public var b: MyGame_Example_Test { _b } + public var c: MyGame_Example_Ability { _c } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_StructOfStructs.self) + } +} + +extension MyGame_Example_StructOfStructs: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + case b = "b" + case c = "c" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(a, forKey: .a) + try container.encodeIfPresent(b, forKey: .b) + try container.encodeIfPresent(c, forKey: .c) + } +} + +public struct MyGame_Example_StructOfStructs_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: MyGame_Example_Ability_Mutable { return MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.position + 0) } + public var b: MyGame_Example_Test_Mutable { return MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.position + 8) } + public var c: MyGame_Example_Ability_Mutable { return MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.position + 12) } + + + public mutating func unpack() -> MyGame_Example_StructOfStructs { + return MyGame_Example_StructOfStructs(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructs?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructs) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_StructOfStructsOfStructs: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: MyGame_Example_StructOfStructs + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = MyGame_Example_StructOfStructs(_accessor.bb, o: _accessor.position + 0) + } + + public init(a: MyGame_Example_StructOfStructs) { + _a = a + } + + public init() { + _a = MyGame_Example_StructOfStructs() + } + + public init(_ _t: inout MyGame_Example_StructOfStructsOfStructs_Mutable) { + var _va = _t.a + _a = _va.unpack() + } + + public var a: MyGame_Example_StructOfStructs { _a } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_StructOfStructsOfStructs.self) + } +} + +extension MyGame_Example_StructOfStructsOfStructs: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(a, forKey: .a) + } +} + +public struct MyGame_Example_StructOfStructsOfStructs_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: MyGame_Example_StructOfStructs_Mutable { return MyGame_Example_StructOfStructs_Mutable(_accessor.bb, o: _accessor.position + 0) } + + + public mutating func unpack() -> MyGame_Example_StructOfStructsOfStructs { + return MyGame_Example_StructOfStructsOfStructs(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructsOfStructs?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructsOfStructs) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_InParentNamespace: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_InParentNamespace.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + public static func startInParentNamespace(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 0) } + public static func endInParentNamespace(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + + + public mutating func unpack() -> MyGame_InParentNamespaceT { + return MyGame_InParentNamespaceT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT) -> Offset { + let __root = MyGame_InParentNamespace.startInParentNamespace(&builder) + return MyGame_InParentNamespace.endInParentNamespace(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + _v.finish() + } +} + +extension MyGame_InParentNamespace: Encodable { + + public func encode(to encoder: Encoder) throws { + } +} + +public class MyGame_InParentNamespaceT: NativeObject { + + + public init(_ _t: inout MyGame_InParentNamespace) { + } + + public init() { + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) } + +} +public struct MyGame_Example2_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example2_Monster.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 0) } + public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + + + public mutating func unpack() -> MyGame_Example2_MonsterT { + return MyGame_Example2_MonsterT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT) -> Offset { + let __root = MyGame_Example2_Monster.startMonster(&builder) + return MyGame_Example2_Monster.endMonster(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + _v.finish() + } +} + +extension MyGame_Example2_Monster: Encodable { + + public func encode(to encoder: Encoder) throws { + } +} + +public class MyGame_Example2_MonsterT: NativeObject { + + + public init(_ _t: inout MyGame_Example2_Monster) { + } + + public init() { + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) } + +} +internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + internal var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + internal static var id: String { "MONS" } + internal static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_TestSimpleTableWithEnum.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case color = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + internal var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .green : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .green } + @discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } + internal static func startTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) } + internal static func endTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + internal static func createTestSimpleTableWithEnum( + _ fbb: inout FlatBufferBuilder, + color: MyGame_Example_Color = .green + ) -> Offset { + let __start = MyGame_Example_TestSimpleTableWithEnum.startTestSimpleTableWithEnum(&fbb) + MyGame_Example_TestSimpleTableWithEnum.add(color: color, &fbb) + return MyGame_Example_TestSimpleTableWithEnum.endTestSimpleTableWithEnum(&fbb, start: __start) + } + + + internal mutating func unpack() -> MyGame_Example_TestSimpleTableWithEnumT { + return MyGame_Example_TestSimpleTableWithEnumT(&self) + } + internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT) -> Offset { + let __root = MyGame_Example_TestSimpleTableWithEnum.startTestSimpleTableWithEnum(&builder) + MyGame_Example_TestSimpleTableWithEnum.add(color: obj.color, &builder) + return MyGame_Example_TestSimpleTableWithEnum.endTestSimpleTableWithEnum(&builder, start: __root) + } + + internal static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) + _v.finish() + } +} + +extension MyGame_Example_TestSimpleTableWithEnum: Encodable { + + enum CodingKeys: String, CodingKey { + case color = "color" + } + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if color != .green { + try container.encodeIfPresent(color, forKey: .color) + } + } +} + +internal class MyGame_Example_TestSimpleTableWithEnumT: NativeObject { + + internal var color: MyGame_Example_Color + + internal init(_ _t: inout MyGame_Example_TestSimpleTableWithEnum) { + color = _t.color + } + + internal init() { + color = .green + } + + internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) } + +} +public struct MyGame_Example_Stat: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_Stat.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case id = 4 + case val = 6 + case count = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var id: String? { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? nil : _accessor.string(at: o) } + public var idSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.id.v) } + public var val: Int64 { let o = _accessor.offset(VTOFFSET.val.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(val: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.val.v); return _accessor.mutate(val, index: o) } + public var count: UInt16 { let o = _accessor.offset(VTOFFSET.count.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.count.v); return _accessor.mutate(count, index: o) } + public static func startStat(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } + public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VTOFFSET.id.p) } + public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VTOFFSET.val.p) } + public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VTOFFSET.count.p) } + public static func endStat(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createStat( + _ fbb: inout FlatBufferBuilder, + idOffset id: Offset = Offset(), + val: Int64 = 0, + count: UInt16 = 0 + ) -> Offset { + let __start = MyGame_Example_Stat.startStat(&fbb) + MyGame_Example_Stat.add(id: id, &fbb) + MyGame_Example_Stat.add(val: val, &fbb) + MyGame_Example_Stat.add(count: count, &fbb) + return MyGame_Example_Stat.endStat(&fbb, start: __start) + } + public static func sortVectorOfStat(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 8, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 8, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: UInt16, fbb: ByteBuffer) -> MyGame_Example_Stat? { + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = fbb.read(def: UInt16.self, position: Int(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 8, fbb: fbb))) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return MyGame_Example_Stat(fbb, o: tableOffset) + } + } + return nil + } + + + public mutating func unpack() -> MyGame_Example_StatT { + return MyGame_Example_StatT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT) -> Offset { + let __id: Offset + if let s = obj.id { + __id = builder.create(string: s) + } else { + __id = Offset() + } + + let __root = MyGame_Example_Stat.startStat(&builder) + MyGame_Example_Stat.add(id: __id, &builder) + MyGame_Example_Stat.add(val: obj.val, &builder) + MyGame_Example_Stat.add(count: obj.count, &builder) + return MyGame_Example_Stat.endStat(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.val.p, fieldName: "val", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.count.p, fieldName: "count", required: false, type: UInt16.self) + _v.finish() + } +} + +extension MyGame_Example_Stat: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + case val = "val" + case count = "count" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + if val != 0 { + try container.encodeIfPresent(val, forKey: .val) + } + if count != 0 { + try container.encodeIfPresent(count, forKey: .count) + } + } +} + +public class MyGame_Example_StatT: NativeObject { + + public var id: String? + public var val: Int64 + public var count: UInt16 + + public init(_ _t: inout MyGame_Example_Stat) { + id = _t.id + val = _t.val + count = _t.count + } + + public init() { + val = 0 + count = 0 + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) } + +} +public struct MyGame_Example_Referrable: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_Referrable.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case id = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var id: UInt64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) } + public static func startReferrable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) } + public static func endReferrable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createReferrable( + _ fbb: inout FlatBufferBuilder, + id: UInt64 = 0 + ) -> Offset { + let __start = MyGame_Example_Referrable.startReferrable(&fbb) + MyGame_Example_Referrable.add(id: id, &fbb) + return MyGame_Example_Referrable.endReferrable(&fbb, start: __start) + } + public static func sortVectorOfReferrable(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 4, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 4, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: UInt64, fbb: ByteBuffer) -> MyGame_Example_Referrable? { + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = fbb.read(def: UInt64.self, position: Int(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 4, fbb: fbb))) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return MyGame_Example_Referrable(fbb, o: tableOffset) + } + } + return nil + } + + + public mutating func unpack() -> MyGame_Example_ReferrableT { + return MyGame_Example_ReferrableT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT) -> Offset { + let __root = MyGame_Example_Referrable.startReferrable(&builder) + MyGame_Example_Referrable.add(id: obj.id, &builder) + return MyGame_Example_Referrable.endReferrable(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: UInt64.self) + _v.finish() + } +} + +extension MyGame_Example_Referrable: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if id != 0 { + try container.encodeIfPresent(id, forKey: .id) + } + } +} + +public class MyGame_Example_ReferrableT: NativeObject { + + public var id: UInt64 + + public init(_ _t: inout MyGame_Example_Referrable) { + id = _t.id + } + + public init() { + id = 0 + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Referrable.self) } + +} +/// an example documentation comment: "monster object" +public struct MyGame_Example_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_Monster.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case pos = 4 + case mana = 6 + case hp = 8 + case name = 10 + case inventory = 14 + case color = 16 + case testType = 18 + case test = 20 + case test4 = 22 + case testarrayofstring = 24 + case testarrayoftables = 26 + case enemy = 28 + case testnestedflatbuffer = 30 + case testempty = 32 + case testbool = 34 + case testhashs32Fnv1 = 36 + case testhashu32Fnv1 = 38 + case testhashs64Fnv1 = 40 + case testhashu64Fnv1 = 42 + case testhashs32Fnv1a = 44 + case testhashu32Fnv1a = 46 + case testhashs64Fnv1a = 48 + case testhashu64Fnv1a = 50 + case testarrayofbools = 52 + case testf = 54 + case testf2 = 56 + case testf3 = 58 + case testarrayofstring2 = 60 + case testarrayofsortedstruct = 62 + case flex = 64 + case test5 = 66 + case vectorOfLongs = 68 + case vectorOfDoubles = 70 + case parentNamespaceTest = 72 + case vectorOfReferrables = 74 + case singleWeakReference = 76 + case vectorOfWeakReferences = 78 + case vectorOfStrongReferrables = 80 + case coOwningReference = 82 + case vectorOfCoOwningReferences = 84 + case nonOwningReference = 86 + case vectorOfNonOwningReferences = 88 + case anyUniqueType = 90 + case anyUnique = 92 + case anyAmbiguousType = 94 + case anyAmbiguous = 96 + case vectorOfEnums = 98 + case signedEnum = 100 + case testrequirednestedflatbuffer = 102 + case scalarKeySortedTables = 104 + case nativeInline = 106 + case longEnumNonEnumDefault = 108 + case longEnumNormalDefault = 110 + case nanDefault = 112 + case infDefault = 114 + case positiveInfDefault = 116 + case infinityDefault = 118 + case positiveInfinityDefault = 120 + case negativeInfDefault = 122 + case negativeInfinityDefault = 124 + case doubleInfDefault = 126 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) } + public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } + public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.mana.v); return _accessor.mutate(mana, index: o) } + public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.hp.v); return _accessor.mutate(hp, index: o) } + public var name: String! { let o = _accessor.offset(VTOFFSET.name.v); return _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) } + public var hasInventory: Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? false : true } + public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] } + public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) } + public var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } + @discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } + public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VTOFFSET.testType.v); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func test(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.test.v); return o == 0 ? nil : _accessor.union(o) } + public var hasTest4: Bool { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? false : true } + public var test4Count: Int32 { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func test4(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Test.self, offset: _accessor.vector(at: o) + index * 4) } + public func mutableTest4(at index: Int32) -> MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } + public var hasTestarrayofstring: Bool { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? false : true } + public var testarrayofstringCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofstring(at index: Int32) -> String? { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? nil : _accessor.directString(at: _accessor.vector(at: o) + index * 4) } + /// an example documentation comment: this will end up in the generated code + /// multiline too + public var hasTestarrayoftables: Bool { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? false : true } + public var testarrayoftablesCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayoftables(at index: Int32) -> MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func testarrayoftablesBy(key: String) -> MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : MyGame_Example_Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var enemy: MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.enemy.v); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var hasTestnestedflatbuffer: Bool { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return o == 0 ? false : true } + public var testnestedflatbufferCount: Int32 { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testnestedflatbuffer(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var testnestedflatbuffer: [UInt8] { return _accessor.getVector(at: VTOFFSET.testnestedflatbuffer.v) ?? [] } + public func mutate(testnestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return _accessor.directMutate(testnestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public var testempty: MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.testempty.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var testbool: Bool { let o = _accessor.offset(VTOFFSET.testbool.v); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } + @discardableResult public func mutate(testbool: Bool) -> Bool {let o = _accessor.offset(VTOFFSET.testbool.v); return _accessor.mutate(testbool, index: o) } + public var testhashs32Fnv1: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return _accessor.mutate(testhashs32Fnv1, index: o) } + public var testhashu32Fnv1: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return _accessor.mutate(testhashu32Fnv1, index: o) } + public var testhashs64Fnv1: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return _accessor.mutate(testhashs64Fnv1, index: o) } + public var testhashu64Fnv1: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return _accessor.mutate(testhashu64Fnv1, index: o) } + public var testhashs32Fnv1a: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1a: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return _accessor.mutate(testhashs32Fnv1a, index: o) } + public var testhashu32Fnv1a: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1a: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return _accessor.mutate(testhashu32Fnv1a, index: o) } + public var testhashs64Fnv1a: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1a: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return _accessor.mutate(testhashs64Fnv1a, index: o) } + public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return _accessor.mutate(testhashu64Fnv1a, index: o) } + public var hasTestarrayofbools: Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? false : true } + public var testarrayofboolsCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofbools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? true : _accessor.directRead(of: Bool.self, offset: _accessor.vector(at: o) + index * 1) } + public var testarrayofbools: [Bool] { return _accessor.getVector(at: VTOFFSET.testarrayofbools.v) ?? [] } + public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) } + public var testf: Float32 { let o = _accessor.offset(VTOFFSET.testf.v); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf.v); return _accessor.mutate(testf, index: o) } + public var testf2: Float32 { let o = _accessor.offset(VTOFFSET.testf2.v); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf2: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf2.v); return _accessor.mutate(testf2, index: o) } + public var testf3: Float32 { let o = _accessor.offset(VTOFFSET.testf3.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf3: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf3.v); return _accessor.mutate(testf3, index: o) } + public var hasTestarrayofstring2: Bool { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? false : true } + public var testarrayofstring2Count: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofstring2(at index: Int32) -> String? { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? nil : _accessor.directString(at: _accessor.vector(at: o) + index * 4) } + public var hasTestarrayofsortedstruct: Bool { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? false : true } + public var testarrayofsortedstructCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Ability.self, offset: _accessor.vector(at: o) + index * 8) } + public func mutableTestarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability_Mutable? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 8) } + public var hasFlex: Bool { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? false : true } + public var flexCount: Int32 { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func flex(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var flex: [UInt8] { return _accessor.getVector(at: VTOFFSET.flex.v) ?? [] } + public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.flex.v); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) } + public var hasTest5: Bool { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? false : true } + public var test5Count: Int32 { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func test5(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Test.self, offset: _accessor.vector(at: o) + index * 4) } + public func mutableTest5(at index: Int32) -> MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } + public var hasVectorOfLongs: Bool { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? false : true } + public var vectorOfLongsCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfLongs(at index: Int32) -> Int64 { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? 0 : _accessor.directRead(of: Int64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfLongs: [Int64] { return _accessor.getVector(at: VTOFFSET.vectorOfLongs.v) ?? [] } + public func mutate(vectorOfLongs: Int64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return _accessor.directMutate(vectorOfLongs, index: _accessor.vector(at: o) + index * 8) } + public var hasVectorOfDoubles: Bool { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return o == 0 ? false : true } + public var vectorOfDoublesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfDoubles(at index: Int32) -> Double { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return o == 0 ? 0 : _accessor.directRead(of: Double.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfDoubles: [Double] { return _accessor.getVector(at: VTOFFSET.vectorOfDoubles.v) ?? [] } + public func mutate(vectorOfDoubles: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return _accessor.directMutate(vectorOfDoubles, index: _accessor.vector(at: o) + index * 8) } + public var parentNamespaceTest: MyGame_InParentNamespace? { let o = _accessor.offset(VTOFFSET.parentNamespaceTest.v); return o == 0 ? nil : MyGame_InParentNamespace(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var hasVectorOfReferrables: Bool { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? false : true } + public var vectorOfReferrablesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfReferrables(at index: Int32) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func vectorOfReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var singleWeakReference: UInt64 { let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(singleWeakReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return _accessor.mutate(singleWeakReference, index: o) } + public var hasVectorOfWeakReferences: Bool { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return o == 0 ? false : true } + public var vectorOfWeakReferencesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfWeakReferences(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfWeakReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfWeakReferences.v) ?? [] } + public func mutate(vectorOfWeakReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return _accessor.directMutate(vectorOfWeakReferences, index: _accessor.vector(at: o) + index * 8) } + public var hasVectorOfStrongReferrables: Bool { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? false : true } + public var vectorOfStrongReferrablesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfStrongReferrables(at index: Int32) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func vectorOfStrongReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var coOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.coOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(coOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.coOwningReference.v); return _accessor.mutate(coOwningReference, index: o) } + public var hasVectorOfCoOwningReferences: Bool { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return o == 0 ? false : true } + public var vectorOfCoOwningReferencesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfCoOwningReferences(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfCoOwningReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfCoOwningReferences.v) ?? [] } + public func mutate(vectorOfCoOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return _accessor.directMutate(vectorOfCoOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public var nonOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(nonOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return _accessor.mutate(nonOwningReference, index: o) } + public var hasVectorOfNonOwningReferences: Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return o == 0 ? false : true } + public var vectorOfNonOwningReferencesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfNonOwningReferences(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfNonOwningReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfNonOwningReferences.v) ?? [] } + public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VTOFFSET.anyUniqueType.v); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyUnique(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyUnique.v); return o == 0 ? nil : _accessor.union(o) } + public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VTOFFSET.anyAmbiguousType.v); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyAmbiguous(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyAmbiguous.v); return o == 0 ? nil : _accessor.union(o) } + public var hasVectorOfEnums: Bool { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? false : true } + public var vectorOfEnumsCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfEnums(at index: Int32) -> MyGame_Example_Color? { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? MyGame_Example_Color.red : MyGame_Example_Color(rawValue: _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1)) } + public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VTOFFSET.signedEnum.v); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } + @discardableResult public func mutate(signedEnum: MyGame_Example_Race) -> Bool {let o = _accessor.offset(VTOFFSET.signedEnum.v); return _accessor.mutate(signedEnum.rawValue, index: o) } + public var hasTestrequirednestedflatbuffer: Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? false : true } + public var testrequirednestedflatbufferCount: Int32 { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testrequirednestedflatbuffer(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var testrequirednestedflatbuffer: [UInt8] { return _accessor.getVector(at: VTOFFSET.testrequirednestedflatbuffer.v) ?? [] } + public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public var hasScalarKeySortedTables: Bool { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? false : true } + public var scalarKeySortedTablesCount: Int32 { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func scalarKeySortedTables(at index: Int32) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) } + public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.position) } + public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) } + public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) } + public var nanDefault: Float32 { let o = _accessor.offset(VTOFFSET.nanDefault.v); return o == 0 ? .nan : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(nanDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.nanDefault.v); return _accessor.mutate(nanDefault, index: o) } + public var infDefault: Float32 { let o = _accessor.offset(VTOFFSET.infDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infDefault.v); return _accessor.mutate(infDefault, index: o) } + public var positiveInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return _accessor.mutate(positiveInfDefault, index: o) } + public var infinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.infinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infinityDefault.v); return _accessor.mutate(infinityDefault, index: o) } + public var positiveInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return _accessor.mutate(positiveInfinityDefault, index: o) } + public var negativeInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return _accessor.mutate(negativeInfDefault, index: o) } + public var negativeInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return _accessor.mutate(negativeInfinityDefault, index: o) } + public var doubleInfDefault: Double { let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(doubleInfDefault: Double) -> Bool {let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return _accessor.mutate(doubleInfDefault, index: o) } + public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 62) } + public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) } + public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) } + public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) } + public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) } + public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VTOFFSET.testType.p) } + public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VTOFFSET.test.p) } + public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VTOFFSET.test4.p) } + public static func startVectorOfTest4(_ size: Int, in builder: inout FlatBufferBuilder) { + builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) + } + public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VTOFFSET.testarrayofstring.p) } + public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) } + public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VTOFFSET.enemy.p) } + public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VTOFFSET.testnestedflatbuffer.p) } + public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VTOFFSET.testempty.p) } + public static func add(testbool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testbool, def: false, + at: VTOFFSET.testbool.p) } + public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VTOFFSET.testhashs32Fnv1.p) } + public static func add(testhashu32Fnv1: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1, def: 0, at: VTOFFSET.testhashu32Fnv1.p) } + public static func add(testhashs64Fnv1: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1, def: 0, at: VTOFFSET.testhashs64Fnv1.p) } + public static func add(testhashu64Fnv1: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1, def: 0, at: VTOFFSET.testhashu64Fnv1.p) } + public static func add(testhashs32Fnv1a: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1a, def: 0, at: VTOFFSET.testhashs32Fnv1a.p) } + public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VTOFFSET.testhashu32Fnv1a.p) } + public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VTOFFSET.testhashs64Fnv1a.p) } + public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VTOFFSET.testhashu64Fnv1a.p) } + public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VTOFFSET.testarrayofbools.p) } + public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VTOFFSET.testf.p) } + public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VTOFFSET.testf2.p) } + public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VTOFFSET.testf3.p) } + public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VTOFFSET.testarrayofstring2.p) } + public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VTOFFSET.testarrayofsortedstruct.p) } + public static func startVectorOfTestarrayofsortedstruct(_ size: Int, in builder: inout FlatBufferBuilder) { + builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) + } + public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VTOFFSET.flex.p) } + public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VTOFFSET.test5.p) } + public static func startVectorOfTest5(_ size: Int, in builder: inout FlatBufferBuilder) { + builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) + } + public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VTOFFSET.vectorOfLongs.p) } + public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VTOFFSET.vectorOfDoubles.p) } + public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VTOFFSET.parentNamespaceTest.p) } + public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VTOFFSET.vectorOfReferrables.p) } + public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VTOFFSET.singleWeakReference.p) } + public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VTOFFSET.vectorOfWeakReferences.p) } + public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VTOFFSET.vectorOfStrongReferrables.p) } + public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VTOFFSET.coOwningReference.p) } + public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VTOFFSET.vectorOfCoOwningReferences.p) } + public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VTOFFSET.nonOwningReference.p) } + public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VTOFFSET.vectorOfNonOwningReferences.p) } + public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VTOFFSET.anyUniqueType.p) } + public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VTOFFSET.anyUnique.p) } + public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VTOFFSET.anyAmbiguousType.p) } + public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VTOFFSET.anyAmbiguous.p) } + public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VTOFFSET.vectorOfEnums.p) } + public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VTOFFSET.signedEnum.p) } + public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VTOFFSET.testrequirednestedflatbuffer.p) } + public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VTOFFSET.scalarKeySortedTables.p) } + public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VTOFFSET.nativeInline.p) } + public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VTOFFSET.longEnumNonEnumDefault.p) } + public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VTOFFSET.longEnumNormalDefault.p) } + public static func add(nanDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nanDefault, def: .nan, at: VTOFFSET.nanDefault.p) } + public static func add(infDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infDefault, def: .infinity, at: VTOFFSET.infDefault.p) } + public static func add(positiveInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfDefault, def: .infinity, at: VTOFFSET.positiveInfDefault.p) } + public static func add(infinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infinityDefault, def: .infinity, at: VTOFFSET.infinityDefault.p) } + public static func add(positiveInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfinityDefault, def: .infinity, at: VTOFFSET.positiveInfinityDefault.p) } + public static func add(negativeInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfDefault, def: -.infinity, at: VTOFFSET.negativeInfDefault.p) } + public static func add(negativeInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfinityDefault, def: -.infinity, at: VTOFFSET.negativeInfinityDefault.p) } + public static func add(doubleInfDefault: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: doubleInfDefault, def: .infinity, at: VTOFFSET.doubleInfDefault.p) } + public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end } + public static func createMonster( + _ fbb: inout FlatBufferBuilder, + pos: MyGame_Example_Vec3? = nil, + mana: Int16 = 150, + hp: Int16 = 100, + nameOffset name: Offset, + inventoryVectorOffset inventory: Offset = Offset(), + color: MyGame_Example_Color = .blue, + testType: MyGame_Example_Any_ = .none_, + testOffset test: Offset = Offset(), + test4VectorOffset test4: Offset = Offset(), + testarrayofstringVectorOffset testarrayofstring: Offset = Offset(), + testarrayoftablesVectorOffset testarrayoftables: Offset = Offset(), + enemyOffset enemy: Offset = Offset(), + testnestedflatbufferVectorOffset testnestedflatbuffer: Offset = Offset(), + testemptyOffset testempty: Offset = Offset(), + testbool: Bool = false, + testhashs32Fnv1: Int32 = 0, + testhashu32Fnv1: UInt32 = 0, + testhashs64Fnv1: Int64 = 0, + testhashu64Fnv1: UInt64 = 0, + testhashs32Fnv1a: Int32 = 0, + testhashu32Fnv1a: UInt32 = 0, + testhashs64Fnv1a: Int64 = 0, + testhashu64Fnv1a: UInt64 = 0, + testarrayofboolsVectorOffset testarrayofbools: Offset = Offset(), + testf: Float32 = 3.14159, + testf2: Float32 = 3.0, + testf3: Float32 = 0.0, + testarrayofstring2VectorOffset testarrayofstring2: Offset = Offset(), + testarrayofsortedstructVectorOffset testarrayofsortedstruct: Offset = Offset(), + flexVectorOffset flex: Offset = Offset(), + test5VectorOffset test5: Offset = Offset(), + vectorOfLongsVectorOffset vectorOfLongs: Offset = Offset(), + vectorOfDoublesVectorOffset vectorOfDoubles: Offset = Offset(), + parentNamespaceTestOffset parentNamespaceTest: Offset = Offset(), + vectorOfReferrablesVectorOffset vectorOfReferrables: Offset = Offset(), + singleWeakReference: UInt64 = 0, + vectorOfWeakReferencesVectorOffset vectorOfWeakReferences: Offset = Offset(), + vectorOfStrongReferrablesVectorOffset vectorOfStrongReferrables: Offset = Offset(), + coOwningReference: UInt64 = 0, + vectorOfCoOwningReferencesVectorOffset vectorOfCoOwningReferences: Offset = Offset(), + nonOwningReference: UInt64 = 0, + vectorOfNonOwningReferencesVectorOffset vectorOfNonOwningReferences: Offset = Offset(), + anyUniqueType: MyGame_Example_AnyUniqueAliases = .none_, + anyUniqueOffset anyUnique: Offset = Offset(), + anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases = .none_, + anyAmbiguousOffset anyAmbiguous: Offset = Offset(), + vectorOfEnumsVectorOffset vectorOfEnums: Offset = Offset(), + signedEnum: MyGame_Example_Race = .none_, + testrequirednestedflatbufferVectorOffset testrequirednestedflatbuffer: Offset = Offset(), + scalarKeySortedTablesVectorOffset scalarKeySortedTables: Offset = Offset(), + nativeInline: MyGame_Example_Test? = nil, + longEnumNonEnumDefault: MyGame_Example_LongEnum = .longone, + longEnumNormalDefault: MyGame_Example_LongEnum = .longone, + nanDefault: Float32 = .nan, + infDefault: Float32 = .infinity, + positiveInfDefault: Float32 = .infinity, + infinityDefault: Float32 = .infinity, + positiveInfinityDefault: Float32 = .infinity, + negativeInfDefault: Float32 = -.infinity, + negativeInfinityDefault: Float32 = -.infinity, + doubleInfDefault: Double = .infinity + ) -> Offset { + let __start = MyGame_Example_Monster.startMonster(&fbb) + MyGame_Example_Monster.add(pos: pos, &fbb) + MyGame_Example_Monster.add(mana: mana, &fbb) + MyGame_Example_Monster.add(hp: hp, &fbb) + MyGame_Example_Monster.add(name: name, &fbb) + MyGame_Example_Monster.addVectorOf(inventory: inventory, &fbb) + MyGame_Example_Monster.add(color: color, &fbb) + MyGame_Example_Monster.add(testType: testType, &fbb) + MyGame_Example_Monster.add(test: test, &fbb) + MyGame_Example_Monster.addVectorOf(test4: test4, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofstring: testarrayofstring, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayoftables: testarrayoftables, &fbb) + MyGame_Example_Monster.add(enemy: enemy, &fbb) + MyGame_Example_Monster.addVectorOf(testnestedflatbuffer: testnestedflatbuffer, &fbb) + MyGame_Example_Monster.add(testempty: testempty, &fbb) + MyGame_Example_Monster.add(testbool: testbool, &fbb) + MyGame_Example_Monster.add(testhashs32Fnv1: testhashs32Fnv1, &fbb) + MyGame_Example_Monster.add(testhashu32Fnv1: testhashu32Fnv1, &fbb) + MyGame_Example_Monster.add(testhashs64Fnv1: testhashs64Fnv1, &fbb) + MyGame_Example_Monster.add(testhashu64Fnv1: testhashu64Fnv1, &fbb) + MyGame_Example_Monster.add(testhashs32Fnv1a: testhashs32Fnv1a, &fbb) + MyGame_Example_Monster.add(testhashu32Fnv1a: testhashu32Fnv1a, &fbb) + MyGame_Example_Monster.add(testhashs64Fnv1a: testhashs64Fnv1a, &fbb) + MyGame_Example_Monster.add(testhashu64Fnv1a: testhashu64Fnv1a, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofbools: testarrayofbools, &fbb) + MyGame_Example_Monster.add(testf: testf, &fbb) + MyGame_Example_Monster.add(testf2: testf2, &fbb) + MyGame_Example_Monster.add(testf3: testf3, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofstring2: testarrayofstring2, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofsortedstruct: testarrayofsortedstruct, &fbb) + MyGame_Example_Monster.addVectorOf(flex: flex, &fbb) + MyGame_Example_Monster.addVectorOf(test5: test5, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfLongs: vectorOfLongs, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfDoubles: vectorOfDoubles, &fbb) + MyGame_Example_Monster.add(parentNamespaceTest: parentNamespaceTest, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfReferrables: vectorOfReferrables, &fbb) + MyGame_Example_Monster.add(singleWeakReference: singleWeakReference, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfWeakReferences: vectorOfWeakReferences, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfStrongReferrables: vectorOfStrongReferrables, &fbb) + MyGame_Example_Monster.add(coOwningReference: coOwningReference, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfCoOwningReferences: vectorOfCoOwningReferences, &fbb) + MyGame_Example_Monster.add(nonOwningReference: nonOwningReference, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfNonOwningReferences: vectorOfNonOwningReferences, &fbb) + MyGame_Example_Monster.add(anyUniqueType: anyUniqueType, &fbb) + MyGame_Example_Monster.add(anyUnique: anyUnique, &fbb) + MyGame_Example_Monster.add(anyAmbiguousType: anyAmbiguousType, &fbb) + MyGame_Example_Monster.add(anyAmbiguous: anyAmbiguous, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfEnums: vectorOfEnums, &fbb) + MyGame_Example_Monster.add(signedEnum: signedEnum, &fbb) + MyGame_Example_Monster.addVectorOf(testrequirednestedflatbuffer: testrequirednestedflatbuffer, &fbb) + MyGame_Example_Monster.addVectorOf(scalarKeySortedTables: scalarKeySortedTables, &fbb) + MyGame_Example_Monster.add(nativeInline: nativeInline, &fbb) + MyGame_Example_Monster.add(longEnumNonEnumDefault: longEnumNonEnumDefault, &fbb) + MyGame_Example_Monster.add(longEnumNormalDefault: longEnumNormalDefault, &fbb) + MyGame_Example_Monster.add(nanDefault: nanDefault, &fbb) + MyGame_Example_Monster.add(infDefault: infDefault, &fbb) + MyGame_Example_Monster.add(positiveInfDefault: positiveInfDefault, &fbb) + MyGame_Example_Monster.add(infinityDefault: infinityDefault, &fbb) + MyGame_Example_Monster.add(positiveInfinityDefault: positiveInfinityDefault, &fbb) + MyGame_Example_Monster.add(negativeInfDefault: negativeInfDefault, &fbb) + MyGame_Example_Monster.add(negativeInfinityDefault: negativeInfinityDefault, &fbb) + MyGame_Example_Monster.add(doubleInfDefault: doubleInfDefault, &fbb) + return MyGame_Example_Monster.endMonster(&fbb, start: __start) + } + public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: String, fbb: ByteBuffer) -> MyGame_Example_Monster? { + let key = key.utf8.map { $0 } + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = Table.compare(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 10, fbb: fbb), key, fbb: fbb) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return MyGame_Example_Monster(fbb, o: tableOffset) + } + } + return nil + } + + + public mutating func unpack() -> MyGame_Example_MonsterT { + return MyGame_Example_MonsterT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT) -> Offset { + let __name = builder.create(string: obj.name) + let __inventory = builder.createVector(obj.inventory) + let __test = obj.test?.pack(builder: &builder) ?? Offset() + MyGame_Example_Monster.startVectorOfTest4(obj.test4.count, in: &builder) + for i in obj.test4 { + guard let _o = i else { continue } + builder.create(struct: _o) + } + let __test4 = builder.endVector(len: obj.test4.count) + let __testarrayofstring = builder.createVector(ofStrings: obj.testarrayofstring.compactMap({ $0 }) ) + var __testarrayoftables__: [Offset] = [] + for var i in obj.testarrayoftables { + __testarrayoftables__.append(MyGame_Example_Monster.pack(&builder, obj: &i)) + } + let __testarrayoftables = builder.createVector(ofOffsets: __testarrayoftables__) + let __enemy = MyGame_Example_Monster.pack(&builder, obj: &obj.enemy) + let __testnestedflatbuffer = builder.createVector(obj.testnestedflatbuffer) + let __testempty = MyGame_Example_Stat.pack(&builder, obj: &obj.testempty) + let __testarrayofbools = builder.createVector(obj.testarrayofbools) + let __testarrayofstring2 = builder.createVector(ofStrings: obj.testarrayofstring2.compactMap({ $0 }) ) + MyGame_Example_Monster.startVectorOfTestarrayofsortedstruct(obj.testarrayofsortedstruct.count, in: &builder) + for i in obj.testarrayofsortedstruct { + guard let _o = i else { continue } + builder.create(struct: _o) + } + let __testarrayofsortedstruct = builder.endVector(len: obj.testarrayofsortedstruct.count) + let __flex = builder.createVector(obj.flex) + MyGame_Example_Monster.startVectorOfTest5(obj.test5.count, in: &builder) + for i in obj.test5 { + guard let _o = i else { continue } + builder.create(struct: _o) + } + let __test5 = builder.endVector(len: obj.test5.count) + let __vectorOfLongs = builder.createVector(obj.vectorOfLongs) + let __vectorOfDoubles = builder.createVector(obj.vectorOfDoubles) + let __parentNamespaceTest = MyGame_InParentNamespace.pack(&builder, obj: &obj.parentNamespaceTest) + var __vectorOfReferrables__: [Offset] = [] + for var i in obj.vectorOfReferrables { + __vectorOfReferrables__.append(MyGame_Example_Referrable.pack(&builder, obj: &i)) + } + let __vectorOfReferrables = builder.createVector(ofOffsets: __vectorOfReferrables__) + let __vectorOfWeakReferences = builder.createVector(obj.vectorOfWeakReferences) + var __vectorOfStrongReferrables__: [Offset] = [] + for var i in obj.vectorOfStrongReferrables { + __vectorOfStrongReferrables__.append(MyGame_Example_Referrable.pack(&builder, obj: &i)) + } + let __vectorOfStrongReferrables = builder.createVector(ofOffsets: __vectorOfStrongReferrables__) + let __vectorOfCoOwningReferences = builder.createVector(obj.vectorOfCoOwningReferences) + let __vectorOfNonOwningReferences = builder.createVector(obj.vectorOfNonOwningReferences) + let __anyUnique = obj.anyUnique?.pack(builder: &builder) ?? Offset() + let __anyAmbiguous = obj.anyAmbiguous?.pack(builder: &builder) ?? Offset() + let __vectorOfEnums = builder.createVector(obj.vectorOfEnums) + let __testrequirednestedflatbuffer = builder.createVector(obj.testrequirednestedflatbuffer) + var __scalarKeySortedTables__: [Offset] = [] + for var i in obj.scalarKeySortedTables { + __scalarKeySortedTables__.append(MyGame_Example_Stat.pack(&builder, obj: &i)) + } + let __scalarKeySortedTables = builder.createVector(ofOffsets: __scalarKeySortedTables__) + let __root = MyGame_Example_Monster.startMonster(&builder) + MyGame_Example_Monster.add(pos: obj.pos, &builder) + MyGame_Example_Monster.add(mana: obj.mana, &builder) + MyGame_Example_Monster.add(hp: obj.hp, &builder) + MyGame_Example_Monster.add(name: __name, &builder) + MyGame_Example_Monster.addVectorOf(inventory: __inventory, &builder) + MyGame_Example_Monster.add(color: obj.color, &builder) + if let o = obj.test?.type { + MyGame_Example_Monster.add(testType: o, &builder) + MyGame_Example_Monster.add(test: __test, &builder) + } + + MyGame_Example_Monster.addVectorOf(test4: __test4, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofstring: __testarrayofstring, &builder) + MyGame_Example_Monster.addVectorOf(testarrayoftables: __testarrayoftables, &builder) + MyGame_Example_Monster.add(enemy: __enemy, &builder) + MyGame_Example_Monster.addVectorOf(testnestedflatbuffer: __testnestedflatbuffer, &builder) + MyGame_Example_Monster.add(testempty: __testempty, &builder) + MyGame_Example_Monster.add(testbool: obj.testbool, &builder) + MyGame_Example_Monster.add(testhashs32Fnv1: obj.testhashs32Fnv1, &builder) + MyGame_Example_Monster.add(testhashu32Fnv1: obj.testhashu32Fnv1, &builder) + MyGame_Example_Monster.add(testhashs64Fnv1: obj.testhashs64Fnv1, &builder) + MyGame_Example_Monster.add(testhashu64Fnv1: obj.testhashu64Fnv1, &builder) + MyGame_Example_Monster.add(testhashs32Fnv1a: obj.testhashs32Fnv1a, &builder) + MyGame_Example_Monster.add(testhashu32Fnv1a: obj.testhashu32Fnv1a, &builder) + MyGame_Example_Monster.add(testhashs64Fnv1a: obj.testhashs64Fnv1a, &builder) + MyGame_Example_Monster.add(testhashu64Fnv1a: obj.testhashu64Fnv1a, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofbools: __testarrayofbools, &builder) + MyGame_Example_Monster.add(testf: obj.testf, &builder) + MyGame_Example_Monster.add(testf2: obj.testf2, &builder) + MyGame_Example_Monster.add(testf3: obj.testf3, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofstring2: __testarrayofstring2, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofsortedstruct: __testarrayofsortedstruct, &builder) + MyGame_Example_Monster.addVectorOf(flex: __flex, &builder) + MyGame_Example_Monster.addVectorOf(test5: __test5, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfLongs: __vectorOfLongs, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfDoubles: __vectorOfDoubles, &builder) + MyGame_Example_Monster.add(parentNamespaceTest: __parentNamespaceTest, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfReferrables: __vectorOfReferrables, &builder) + MyGame_Example_Monster.add(singleWeakReference: obj.singleWeakReference, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfWeakReferences: __vectorOfWeakReferences, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfStrongReferrables: __vectorOfStrongReferrables, &builder) + MyGame_Example_Monster.add(coOwningReference: obj.coOwningReference, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfCoOwningReferences: __vectorOfCoOwningReferences, &builder) + MyGame_Example_Monster.add(nonOwningReference: obj.nonOwningReference, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfNonOwningReferences: __vectorOfNonOwningReferences, &builder) + if let o = obj.anyUnique?.type { + MyGame_Example_Monster.add(anyUniqueType: o, &builder) + MyGame_Example_Monster.add(anyUnique: __anyUnique, &builder) + } + + if let o = obj.anyAmbiguous?.type { + MyGame_Example_Monster.add(anyAmbiguousType: o, &builder) + MyGame_Example_Monster.add(anyAmbiguous: __anyAmbiguous, &builder) + } + + MyGame_Example_Monster.addVectorOf(vectorOfEnums: __vectorOfEnums, &builder) + MyGame_Example_Monster.add(signedEnum: obj.signedEnum, &builder) + MyGame_Example_Monster.addVectorOf(testrequirednestedflatbuffer: __testrequirednestedflatbuffer, &builder) + MyGame_Example_Monster.addVectorOf(scalarKeySortedTables: __scalarKeySortedTables, &builder) + MyGame_Example_Monster.add(nativeInline: obj.nativeInline, &builder) + MyGame_Example_Monster.add(longEnumNonEnumDefault: obj.longEnumNonEnumDefault, &builder) + MyGame_Example_Monster.add(longEnumNormalDefault: obj.longEnumNormalDefault, &builder) + MyGame_Example_Monster.add(nanDefault: obj.nanDefault, &builder) + MyGame_Example_Monster.add(infDefault: obj.infDefault, &builder) + MyGame_Example_Monster.add(positiveInfDefault: obj.positiveInfDefault, &builder) + MyGame_Example_Monster.add(infinityDefault: obj.infinityDefault, &builder) + MyGame_Example_Monster.add(positiveInfinityDefault: obj.positiveInfinityDefault, &builder) + MyGame_Example_Monster.add(negativeInfDefault: obj.negativeInfDefault, &builder) + MyGame_Example_Monster.add(negativeInfinityDefault: obj.negativeInfinityDefault, &builder) + MyGame_Example_Monster.add(doubleInfDefault: obj.doubleInfDefault, &builder) + return MyGame_Example_Monster.endMonster(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self) + try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) + try _v.visit(unionKey: VTOFFSET.testType.p, unionField: VTOFFSET.test.p, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .monster: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .testsimpletablewithenum: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_TestSimpleTableWithEnum.self) + case .mygameExample2Monster: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) + } + }) + try _v.visit(field: VTOFFSET.test4.p, fieldName: "test4", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testarrayofstring.p, fieldName: "testarrayofstring", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset, MyGame_Example_Monster>>.self) + try _v.visit(field: VTOFFSET.enemy.p, fieldName: "enemy", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testnestedflatbuffer.p, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testempty.p, fieldName: "testempty", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testbool.p, fieldName: "testbool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1.p, fieldName: "testhashs32Fnv1", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1.p, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1.p, fieldName: "testhashs64Fnv1", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1.p, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1a.p, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1a.p, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1a.p, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1a.p, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testarrayofbools.p, fieldName: "testarrayofbools", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testf.p, fieldName: "testf", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf2.p, fieldName: "testf2", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf3.p, fieldName: "testf3", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testarrayofstring2.p, fieldName: "testarrayofstring2", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayofsortedstruct.p, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.flex.p, fieldName: "flex", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.test5.p, fieldName: "test5", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfLongs.p, fieldName: "vectorOfLongs", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfDoubles.p, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.parentNamespaceTest.p, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.vectorOfReferrables.p, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.singleWeakReference.p, fieldName: "singleWeakReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfWeakReferences.p, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfStrongReferrables.p, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.coOwningReference.p, fieldName: "coOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfCoOwningReferences.p, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.nonOwningReference.p, fieldName: "nonOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfNonOwningReferences.p, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(unionKey: VTOFFSET.anyUniqueType.p, unionField: VTOFFSET.anyUnique.p, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .m: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .ts: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_TestSimpleTableWithEnum.self) + case .m2: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) + } + }) + try _v.visit(unionKey: VTOFFSET.anyAmbiguousType.p, unionField: VTOFFSET.anyAmbiguous.p, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .m1: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .m2: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .m3: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + } + }) + try _v.visit(field: VTOFFSET.vectorOfEnums.p, fieldName: "vectorOfEnums", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.signedEnum.p, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self) + try _v.visit(field: VTOFFSET.testrequirednestedflatbuffer.p, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.scalarKeySortedTables.p, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset, MyGame_Example_Stat>>.self) + try _v.visit(field: VTOFFSET.nativeInline.p, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self) + try _v.visit(field: VTOFFSET.longEnumNonEnumDefault.p, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.longEnumNormalDefault.p, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.nanDefault.p, fieldName: "nanDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infDefault.p, fieldName: "infDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfDefault.p, fieldName: "positiveInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infinityDefault.p, fieldName: "infinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfinityDefault.p, fieldName: "positiveInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfDefault.p, fieldName: "negativeInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfinityDefault.p, fieldName: "negativeInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.doubleInfDefault.p, fieldName: "doubleInfDefault", required: false, type: Double.self) + _v.finish() + } +} + +extension MyGame_Example_Monster: Encodable { + + enum CodingKeys: String, CodingKey { + case pos = "pos" + case mana = "mana" + case hp = "hp" + case name = "name" + case inventory = "inventory" + case color = "color" + case testType = "test_type" + case test = "test" + case test4 = "test4" + case testarrayofstring = "testarrayofstring" + case testarrayoftables = "testarrayoftables" + case enemy = "enemy" + case testnestedflatbuffer = "testnestedflatbuffer" + case testempty = "testempty" + case testbool = "testbool" + case testhashs32Fnv1 = "testhashs32_fnv1" + case testhashu32Fnv1 = "testhashu32_fnv1" + case testhashs64Fnv1 = "testhashs64_fnv1" + case testhashu64Fnv1 = "testhashu64_fnv1" + case testhashs32Fnv1a = "testhashs32_fnv1a" + case testhashu32Fnv1a = "testhashu32_fnv1a" + case testhashs64Fnv1a = "testhashs64_fnv1a" + case testhashu64Fnv1a = "testhashu64_fnv1a" + case testarrayofbools = "testarrayofbools" + case testf = "testf" + case testf2 = "testf2" + case testf3 = "testf3" + case testarrayofstring2 = "testarrayofstring2" + case testarrayofsortedstruct = "testarrayofsortedstruct" + case flex = "flex" + case test5 = "test5" + case vectorOfLongs = "vector_of_longs" + case vectorOfDoubles = "vector_of_doubles" + case parentNamespaceTest = "parent_namespace_test" + case vectorOfReferrables = "vector_of_referrables" + case singleWeakReference = "single_weak_reference" + case vectorOfWeakReferences = "vector_of_weak_references" + case vectorOfStrongReferrables = "vector_of_strong_referrables" + case coOwningReference = "co_owning_reference" + case vectorOfCoOwningReferences = "vector_of_co_owning_references" + case nonOwningReference = "non_owning_reference" + case vectorOfNonOwningReferences = "vector_of_non_owning_references" + case anyUniqueType = "any_unique_type" + case anyUnique = "any_unique" + case anyAmbiguousType = "any_ambiguous_type" + case anyAmbiguous = "any_ambiguous" + case vectorOfEnums = "vector_of_enums" + case signedEnum = "signed_enum" + case testrequirednestedflatbuffer = "testrequirednestedflatbuffer" + case scalarKeySortedTables = "scalar_key_sorted_tables" + case nativeInline = "native_inline" + case longEnumNonEnumDefault = "long_enum_non_enum_default" + case longEnumNormalDefault = "long_enum_normal_default" + case nanDefault = "nan_default" + case infDefault = "inf_default" + case positiveInfDefault = "positive_inf_default" + case infinityDefault = "infinity_default" + case positiveInfinityDefault = "positive_infinity_default" + case negativeInfDefault = "negative_inf_default" + case negativeInfinityDefault = "negative_infinity_default" + case doubleInfDefault = "double_inf_default" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(pos, forKey: .pos) + if mana != 150 { + try container.encodeIfPresent(mana, forKey: .mana) + } + if hp != 100 { + try container.encodeIfPresent(hp, forKey: .hp) + } + try container.encodeIfPresent(name, forKey: .name) + if inventoryCount > 0 { + try container.encodeIfPresent(inventory, forKey: .inventory) + } + if color != .blue { + try container.encodeIfPresent(color, forKey: .color) + } + if testType != .none_ { + try container.encodeIfPresent(testType, forKey: .testType) + } + switch testType { + case .monster: + let _v = test(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .test) + case .testsimpletablewithenum: + let _v = test(type: MyGame_Example_TestSimpleTableWithEnum.self) + try container.encodeIfPresent(_v, forKey: .test) + case .mygameExample2Monster: + let _v = test(type: MyGame_Example2_Monster.self) + try container.encodeIfPresent(_v, forKey: .test) + default: break; + } + if test4Count > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .test4) + for index in 0.. 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofstring) + for index in 0.. 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayoftables) + for index in 0.. 0 { + try container.encodeIfPresent(testnestedflatbuffer, forKey: .testnestedflatbuffer) + } + try container.encodeIfPresent(testempty, forKey: .testempty) + if testbool != false { + try container.encodeIfPresent(testbool, forKey: .testbool) + } + if testhashs32Fnv1 != 0 { + try container.encodeIfPresent(testhashs32Fnv1, forKey: .testhashs32Fnv1) + } + if testhashu32Fnv1 != 0 { + try container.encodeIfPresent(testhashu32Fnv1, forKey: .testhashu32Fnv1) + } + if testhashs64Fnv1 != 0 { + try container.encodeIfPresent(testhashs64Fnv1, forKey: .testhashs64Fnv1) + } + if testhashu64Fnv1 != 0 { + try container.encodeIfPresent(testhashu64Fnv1, forKey: .testhashu64Fnv1) + } + if testhashs32Fnv1a != 0 { + try container.encodeIfPresent(testhashs32Fnv1a, forKey: .testhashs32Fnv1a) + } + if testhashu32Fnv1a != 0 { + try container.encodeIfPresent(testhashu32Fnv1a, forKey: .testhashu32Fnv1a) + } + if testhashs64Fnv1a != 0 { + try container.encodeIfPresent(testhashs64Fnv1a, forKey: .testhashs64Fnv1a) + } + if testhashu64Fnv1a != 0 { + try container.encodeIfPresent(testhashu64Fnv1a, forKey: .testhashu64Fnv1a) + } + if testarrayofboolsCount > 0 { + try container.encodeIfPresent(testarrayofbools, forKey: .testarrayofbools) + } + if testf != 3.14159 { + try container.encodeIfPresent(testf, forKey: .testf) + } + if testf2 != 3.0 { + try container.encodeIfPresent(testf2, forKey: .testf2) + } + if testf3 != 0.0 { + try container.encodeIfPresent(testf3, forKey: .testf3) + } + if testarrayofstring2Count > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofstring2) + for index in 0.. 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofsortedstruct) + for index in 0.. 0 { + try container.encodeIfPresent(flex, forKey: .flex) + } + if test5Count > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .test5) + for index in 0.. 0 { + try container.encodeIfPresent(vectorOfLongs, forKey: .vectorOfLongs) + } + if vectorOfDoublesCount > 0 { + try container.encodeIfPresent(vectorOfDoubles, forKey: .vectorOfDoubles) + } + try container.encodeIfPresent(parentNamespaceTest, forKey: .parentNamespaceTest) + if vectorOfReferrablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfReferrables) + for index in 0.. 0 { + try container.encodeIfPresent(vectorOfWeakReferences, forKey: .vectorOfWeakReferences) + } + if vectorOfStrongReferrablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfStrongReferrables) + for index in 0.. 0 { + try container.encodeIfPresent(vectorOfCoOwningReferences, forKey: .vectorOfCoOwningReferences) + } + if nonOwningReference != 0 { + try container.encodeIfPresent(nonOwningReference, forKey: .nonOwningReference) + } + if vectorOfNonOwningReferencesCount > 0 { + try container.encodeIfPresent(vectorOfNonOwningReferences, forKey: .vectorOfNonOwningReferences) + } + if anyUniqueType != .none_ { + try container.encodeIfPresent(anyUniqueType, forKey: .anyUniqueType) + } + switch anyUniqueType { + case .m: + let _v = anyUnique(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyUnique) + case .ts: + let _v = anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self) + try container.encodeIfPresent(_v, forKey: .anyUnique) + case .m2: + let _v = anyUnique(type: MyGame_Example2_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyUnique) + default: break; + } + if anyAmbiguousType != .none_ { + try container.encodeIfPresent(anyAmbiguousType, forKey: .anyAmbiguousType) + } + switch anyAmbiguousType { + case .m1: + let _v = anyAmbiguous(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyAmbiguous) + case .m2: + let _v = anyAmbiguous(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyAmbiguous) + case .m3: + let _v = anyAmbiguous(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyAmbiguous) + default: break; + } + if vectorOfEnumsCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfEnums) + for index in 0.. 0 { + try container.encodeIfPresent(testrequirednestedflatbuffer, forKey: .testrequirednestedflatbuffer) + } + if scalarKeySortedTablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .scalarKeySortedTables) + for index in 0.. ByteBuffer { return serialize(type: MyGame_Example_Monster.self) } + +} +public struct MyGame_Example_TypeAliases: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_TypeAliases.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case i8 = 4 + case u8 = 6 + case i16 = 8 + case u16 = 10 + case i32 = 12 + case u32 = 14 + case i64 = 16 + case u64 = 18 + case f32 = 20 + case f64 = 22 + case v8 = 24 + case vf64 = 26 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var i8: Int8 { let o = _accessor.offset(VTOFFSET.i8.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } + @discardableResult public func mutate(i8: Int8) -> Bool {let o = _accessor.offset(VTOFFSET.i8.v); return _accessor.mutate(i8, index: o) } + public var u8: UInt8 { let o = _accessor.offset(VTOFFSET.u8.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } + @discardableResult public func mutate(u8: UInt8) -> Bool {let o = _accessor.offset(VTOFFSET.u8.v); return _accessor.mutate(u8, index: o) } + public var i16: Int16 { let o = _accessor.offset(VTOFFSET.i16.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(i16: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.i16.v); return _accessor.mutate(i16, index: o) } + public var u16: UInt16 { let o = _accessor.offset(VTOFFSET.u16.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(u16: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.u16.v); return _accessor.mutate(u16, index: o) } + public var i32: Int32 { let o = _accessor.offset(VTOFFSET.i32.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(i32: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.i32.v); return _accessor.mutate(i32, index: o) } + public var u32: UInt32 { let o = _accessor.offset(VTOFFSET.u32.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(u32: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.u32.v); return _accessor.mutate(u32, index: o) } + public var i64: Int64 { let o = _accessor.offset(VTOFFSET.i64.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(i64: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.i64.v); return _accessor.mutate(i64, index: o) } + public var u64: UInt64 { let o = _accessor.offset(VTOFFSET.u64.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(u64: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.u64.v); return _accessor.mutate(u64, index: o) } + public var f32: Float32 { let o = _accessor.offset(VTOFFSET.f32.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(f32: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.f32.v); return _accessor.mutate(f32, index: o) } + public var f64: Double { let o = _accessor.offset(VTOFFSET.f64.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(f64: Double) -> Bool {let o = _accessor.offset(VTOFFSET.f64.v); return _accessor.mutate(f64, index: o) } + public var hasV8: Bool { let o = _accessor.offset(VTOFFSET.v8.v); return o == 0 ? false : true } + public var v8Count: Int32 { let o = _accessor.offset(VTOFFSET.v8.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func v8(at index: Int32) -> Int8 { let o = _accessor.offset(VTOFFSET.v8.v); return o == 0 ? 0 : _accessor.directRead(of: Int8.self, offset: _accessor.vector(at: o) + index * 1) } + public var v8: [Int8] { return _accessor.getVector(at: VTOFFSET.v8.v) ?? [] } + public func mutate(v8: Int8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.v8.v); return _accessor.directMutate(v8, index: _accessor.vector(at: o) + index * 1) } + public var hasVf64: Bool { let o = _accessor.offset(VTOFFSET.vf64.v); return o == 0 ? false : true } + public var vf64Count: Int32 { let o = _accessor.offset(VTOFFSET.vf64.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vf64(at index: Int32) -> Double { let o = _accessor.offset(VTOFFSET.vf64.v); return o == 0 ? 0 : _accessor.directRead(of: Double.self, offset: _accessor.vector(at: o) + index * 8) } + public var vf64: [Double] { return _accessor.getVector(at: VTOFFSET.vf64.v) ?? [] } + public func mutate(vf64: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vf64.v); return _accessor.directMutate(vf64, index: _accessor.vector(at: o) + index * 8) } + public static func startTypeAliases(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 12) } + public static func add(i8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i8, def: 0, at: VTOFFSET.i8.p) } + public static func add(u8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u8, def: 0, at: VTOFFSET.u8.p) } + public static func add(i16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i16, def: 0, at: VTOFFSET.i16.p) } + public static func add(u16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u16, def: 0, at: VTOFFSET.u16.p) } + public static func add(i32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i32, def: 0, at: VTOFFSET.i32.p) } + public static func add(u32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u32, def: 0, at: VTOFFSET.u32.p) } + public static func add(i64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i64, def: 0, at: VTOFFSET.i64.p) } + public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VTOFFSET.u64.p) } + public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VTOFFSET.f32.p) } + public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VTOFFSET.f64.p) } + public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VTOFFSET.v8.p) } + public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VTOFFSET.vf64.p) } + public static func endTypeAliases(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createTypeAliases( + _ fbb: inout FlatBufferBuilder, + i8: Int8 = 0, + u8: UInt8 = 0, + i16: Int16 = 0, + u16: UInt16 = 0, + i32: Int32 = 0, + u32: UInt32 = 0, + i64: Int64 = 0, + u64: UInt64 = 0, + f32: Float32 = 0.0, + f64: Double = 0.0, + v8VectorOffset v8: Offset = Offset(), + vf64VectorOffset vf64: Offset = Offset() + ) -> Offset { + let __start = MyGame_Example_TypeAliases.startTypeAliases(&fbb) + MyGame_Example_TypeAliases.add(i8: i8, &fbb) + MyGame_Example_TypeAliases.add(u8: u8, &fbb) + MyGame_Example_TypeAliases.add(i16: i16, &fbb) + MyGame_Example_TypeAliases.add(u16: u16, &fbb) + MyGame_Example_TypeAliases.add(i32: i32, &fbb) + MyGame_Example_TypeAliases.add(u32: u32, &fbb) + MyGame_Example_TypeAliases.add(i64: i64, &fbb) + MyGame_Example_TypeAliases.add(u64: u64, &fbb) + MyGame_Example_TypeAliases.add(f32: f32, &fbb) + MyGame_Example_TypeAliases.add(f64: f64, &fbb) + MyGame_Example_TypeAliases.addVectorOf(v8: v8, &fbb) + MyGame_Example_TypeAliases.addVectorOf(vf64: vf64, &fbb) + return MyGame_Example_TypeAliases.endTypeAliases(&fbb, start: __start) + } + + + public mutating func unpack() -> MyGame_Example_TypeAliasesT { + return MyGame_Example_TypeAliasesT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT) -> Offset { + let __v8 = builder.createVector(obj.v8) + let __vf64 = builder.createVector(obj.vf64) + let __root = MyGame_Example_TypeAliases.startTypeAliases(&builder) + MyGame_Example_TypeAliases.add(i8: obj.i8, &builder) + MyGame_Example_TypeAliases.add(u8: obj.u8, &builder) + MyGame_Example_TypeAliases.add(i16: obj.i16, &builder) + MyGame_Example_TypeAliases.add(u16: obj.u16, &builder) + MyGame_Example_TypeAliases.add(i32: obj.i32, &builder) + MyGame_Example_TypeAliases.add(u32: obj.u32, &builder) + MyGame_Example_TypeAliases.add(i64: obj.i64, &builder) + MyGame_Example_TypeAliases.add(u64: obj.u64, &builder) + MyGame_Example_TypeAliases.add(f32: obj.f32, &builder) + MyGame_Example_TypeAliases.add(f64: obj.f64, &builder) + MyGame_Example_TypeAliases.addVectorOf(v8: __v8, &builder) + MyGame_Example_TypeAliases.addVectorOf(vf64: __vf64, &builder) + return MyGame_Example_TypeAliases.endTypeAliases(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.i8.p, fieldName: "i8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.u8.p, fieldName: "u8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.i16.p, fieldName: "i16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.u16.p, fieldName: "u16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.i32.p, fieldName: "i32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.u32.p, fieldName: "u32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.i64.p, fieldName: "i64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.u64.p, fieldName: "u64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.f32.p, fieldName: "f32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.f64.p, fieldName: "f64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.v8.p, fieldName: "v8", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vf64.p, fieldName: "vf64", required: false, type: ForwardOffset>.self) + _v.finish() + } +} + +extension MyGame_Example_TypeAliases: Encodable { + + enum CodingKeys: String, CodingKey { + case i8 = "i8" + case u8 = "u8" + case i16 = "i16" + case u16 = "u16" + case i32 = "i32" + case u32 = "u32" + case i64 = "i64" + case u64 = "u64" + case f32 = "f32" + case f64 = "f64" + case v8 = "v8" + case vf64 = "vf64" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if i8 != 0 { + try container.encodeIfPresent(i8, forKey: .i8) + } + if u8 != 0 { + try container.encodeIfPresent(u8, forKey: .u8) + } + if i16 != 0 { + try container.encodeIfPresent(i16, forKey: .i16) + } + if u16 != 0 { + try container.encodeIfPresent(u16, forKey: .u16) + } + if i32 != 0 { + try container.encodeIfPresent(i32, forKey: .i32) + } + if u32 != 0 { + try container.encodeIfPresent(u32, forKey: .u32) + } + if i64 != 0 { + try container.encodeIfPresent(i64, forKey: .i64) + } + if u64 != 0 { + try container.encodeIfPresent(u64, forKey: .u64) + } + if f32 != 0.0 { + try container.encodeIfPresent(f32, forKey: .f32) + } + if f64 != 0.0 { + try container.encodeIfPresent(f64, forKey: .f64) + } + if v8Count > 0 { + try container.encodeIfPresent(v8, forKey: .v8) + } + if vf64Count > 0 { + try container.encodeIfPresent(vf64, forKey: .vf64) + } + } +} + +public class MyGame_Example_TypeAliasesT: NativeObject { + + public var i8: Int8 + public var u8: UInt8 + public var i16: Int16 + public var u16: UInt16 + public var i32: Int32 + public var u32: UInt32 + public var i64: Int64 + public var u64: UInt64 + public var f32: Float32 + public var f64: Double + public var v8: [Int8] + public var vf64: [Double] + + public init(_ _t: inout MyGame_Example_TypeAliases) { + i8 = _t.i8 + u8 = _t.u8 + i16 = _t.i16 + u16 = _t.u16 + i32 = _t.i32 + u32 = _t.u32 + i64 = _t.i64 + u64 = _t.u64 + f32 = _t.f32 + f64 = _t.f64 + v8 = [] + for index in 0..<_t.v8Count { + v8.append(_t.v8(at: index)) + } + vf64 = [] + for index in 0..<_t.vf64Count { + vf64.append(_t.vf64(at: index)) + } + } + + public init() { + i8 = 0 + u8 = 0 + i16 = 0 + u16 = 0 + i32 = 0 + u32 = 0 + i64 = 0 + u64 = 0 + f32 = 0.0 + f64 = 0.0 + v8 = [] + vf64 = [] + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TypeAliases.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_import.fbs b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_import.fbs new file mode 100644 index 00000000000..0a43956c408 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_import.fbs @@ -0,0 +1,3 @@ +table Message { + internal_message: string; +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_import_generated.swift b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_import_generated.swift new file mode 100644 index 00000000000..18faaa6c825 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_import_generated.swift @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +@_implementationOnly import FlatBuffers + +internal struct Message: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + internal var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case internalMessage = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + internal var internalMessage: String? { let o = _accessor.offset(VTOFFSET.internalMessage.v); return o == 0 ? nil : _accessor.string(at: o) } + internal var internalMessageSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.internalMessage.v) } + internal static func startMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + internal static func add(internalMessage: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: internalMessage, at: VTOFFSET.internalMessage.p) } + internal static func endMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + internal static func createMessage( + _ fbb: inout FlatBufferBuilder, + internalMessageOffset internalMessage: Offset = Offset() + ) -> Offset { + let __start = Message.startMessage(&fbb) + Message.add(internalMessage: internalMessage, &fbb) + return Message.endMessage(&fbb, start: __start) + } + + + internal mutating func unpack() -> MessageT { + return MessageT(&self) + } + internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT) -> Offset { + let __internalMessage: Offset + if let s = obj.internalMessage { + __internalMessage = builder.create(string: s) + } else { + __internalMessage = Offset() + } + + let __root = Message.startMessage(&builder) + Message.add(internalMessage: __internalMessage, &builder) + return Message.endMessage(&builder, start: __root) + } + + internal static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.internalMessage.p, fieldName: "internalMessage", required: false, type: ForwardOffset.self) + _v.finish() + } +} + +extension Message: Encodable { + + enum CodingKeys: String, CodingKey { + case internalMessage = "internal_message" + } + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(internalMessage, forKey: .internalMessage) + } +} + +internal class MessageT: NativeObject { + + internal var internalMessage: String? + + internal init(_ _t: inout Message) { + internalMessage = _t.internalMessage + } + + internal init() { + } + + internal func serialize() -> ByteBuffer { return serialize(type: Message.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_no_include.fbs b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_no_include.fbs new file mode 100644 index 00000000000..2f954681c52 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_no_include.fbs @@ -0,0 +1,13 @@ +struct BytesCount { + x: int64; +} + +table InternalMessage { + str: string; +} + +table Message { + id: int64; + position: BytesCount (required); + pointer: InternalMessage (required); +} \ No newline at end of file diff --git a/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_no_include_generated.swift b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_no_include_generated.swift new file mode 100644 index 00000000000..8a2b545778f --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/CodeGenerationTests/test_no_include_generated.swift @@ -0,0 +1,261 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +public struct BytesCount: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _x: Int64 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _x = _accessor.readBuffer(of: Int64.self, at: 0) + } + + public init(x: Int64) { + _x = x + } + + public init() { + _x = 0 + } + + public init(_ _t: inout BytesCount_Mutable) { + _x = _t.x + } + + public var x: Int64 { _x } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: BytesCount.self) + } +} + +extension BytesCount: Encodable { + + enum CodingKeys: String, CodingKey { + case x = "x" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if x != 0 { + try container.encodeIfPresent(x, forKey: .x) + } + } +} + +public struct BytesCount_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var x: Int64 { return _accessor.readBuffer(of: Int64.self, at: 0) } + @discardableResult public func mutate(x: Int64) -> Bool { return _accessor.mutate(x, index: 0) } + + + public mutating func unpack() -> BytesCount { + return BytesCount(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BytesCount?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BytesCount) -> Offset { + return builder.create(struct: obj) + } +} + +public struct InternalMessage: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case str = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var str: String? { let o = _accessor.offset(VTOFFSET.str.v); return o == 0 ? nil : _accessor.string(at: o) } + public var strSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.str.v) } + public static func startInternalMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(str: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: str, at: VTOFFSET.str.p) } + public static func endInternalMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createInternalMessage( + _ fbb: inout FlatBufferBuilder, + strOffset str: Offset = Offset() + ) -> Offset { + let __start = InternalMessage.startInternalMessage(&fbb) + InternalMessage.add(str: str, &fbb) + return InternalMessage.endInternalMessage(&fbb, start: __start) + } + + + public mutating func unpack() -> InternalMessageT { + return InternalMessageT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout InternalMessageT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout InternalMessageT) -> Offset { + let __str: Offset + if let s = obj.str { + __str = builder.create(string: s) + } else { + __str = Offset() + } + + let __root = InternalMessage.startInternalMessage(&builder) + InternalMessage.add(str: __str, &builder) + return InternalMessage.endInternalMessage(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.str.p, fieldName: "str", required: false, type: ForwardOffset.self) + _v.finish() + } +} + +extension InternalMessage: Encodable { + + enum CodingKeys: String, CodingKey { + case str = "str" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(str, forKey: .str) + } +} + +public class InternalMessageT: NativeObject { + + public var str: String? + + public init(_ _t: inout InternalMessage) { + str = _t.str + } + + public init() { + } + + public func serialize() -> ByteBuffer { return serialize(type: InternalMessage.self) } + +} +public struct Message: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case id = 4 + case position = 6 + case pointer = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var id: Int64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(id: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) } + public var position: BytesCount! { let o = _accessor.offset(VTOFFSET.position.v); return _accessor.readBuffer(of: BytesCount.self, at: o) } + public var mutablePosition: BytesCount_Mutable! { let o = _accessor.offset(VTOFFSET.position.v); return BytesCount_Mutable(_accessor.bb, o: o + _accessor.position) } + public var pointer: InternalMessage! { let o = _accessor.offset(VTOFFSET.pointer.v); return InternalMessage(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public static func startMessage(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } + public static func add(id: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) } + public static func add(position: BytesCount?, _ fbb: inout FlatBufferBuilder) { guard let position = position else { return }; fbb.create(struct: position, position: VTOFFSET.position.p) } + public static func add(pointer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: pointer, at: VTOFFSET.pointer.p) } + public static func endMessage(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [6, 8]); return end } + public static func createMessage( + _ fbb: inout FlatBufferBuilder, + id: Int64 = 0, + position: BytesCount, + pointerOffset pointer: Offset + ) -> Offset { + let __start = Message.startMessage(&fbb) + Message.add(id: id, &fbb) + Message.add(position: position, &fbb) + Message.add(pointer: pointer, &fbb) + return Message.endMessage(&fbb, start: __start) + } + + + public mutating func unpack() -> MessageT { + return MessageT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MessageT) -> Offset { + let __pointer = InternalMessage.pack(&builder, obj: &obj.pointer) + let __root = Message.startMessage(&builder) + Message.add(id: obj.id, &builder) + Message.add(position: obj.position, &builder) + Message.add(pointer: __pointer, &builder) + return Message.endMessage(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.position.p, fieldName: "position", required: true, type: BytesCount.self) + try _v.visit(field: VTOFFSET.pointer.p, fieldName: "pointer", required: true, type: ForwardOffset.self) + _v.finish() + } +} + +extension Message: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + case position = "position" + case pointer = "pointer" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if id != 0 { + try container.encodeIfPresent(id, forKey: .id) + } + try container.encodeIfPresent(position, forKey: .position) + try container.encodeIfPresent(pointer, forKey: .pointer) + } +} + +public class MessageT: NativeObject { + + public var id: Int64 + public var position: BytesCount + public var pointer: InternalMessageT + + public init(_ _t: inout Message) { + id = _t.id + position = _t.position + var __pointer = _t.pointer + pointer = __pointer!.unpack() + } + + public init() { + id = 0 + position = BytesCount() + pointer = InternalMessageT() + } + + public func serialize() -> ByteBuffer { return serialize(type: Message.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Package.swift b/third_party/flatbuffers/tests/swift/tests/Package.swift new file mode 100644 index 00000000000..d66380e044c --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Package.swift @@ -0,0 +1,46 @@ +// swift-tools-version:5.9 +/* + * Copyright 2020 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import PackageDescription + +let package = Package( + name: "FlatBuffers.Test.Swift", + platforms: [ + .iOS(.v11), + .macOS(.v10_14), + ], + dependencies: [ + .package(path: "../../.."), + .package(url: "https://github.com/grpc/grpc-swift.git", from: "1.4.1"), + // Prevent the build system from pulling 2.29.1 to prevent Swift 5.8 build breaks. + // The patch update introduced code that uses "switch expression syntax" that wasn't valid until Swift 5.9 [1]. + // [1] https://github.com/swiftlang/swift-evolution/blob/main/proposals/0380-if-switch-expressions.md + .package(url: "https://github.com/apple/swift-nio-ssl.git", exact: "2.29.0"), + ], + targets: [ + .executableTarget( + name: "SwiftFlatBuffers", + dependencies: [ + .product(name: "FlatBuffers", package: "flatbuffers"), + ]), + .testTarget( + name: "FlatBuffers.Test.SwiftTests", + dependencies: [ + .product(name: "FlatBuffers", package: "flatbuffers"), + .product(name: "GRPC", package: "grpc-swift"), + ]), + ]) diff --git a/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer.fbs b/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer.fbs new file mode 100644 index 00000000000..e0356fa33a3 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer.fbs @@ -0,0 +1,32 @@ +enum Color:ubyte (bit_flags) { + Red = 0, // color Red = (1u << 0) + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + Green, + /// \brief color Blue (1u << 3) + Blue = 3, +} + +struct Test { a:short; b:byte; } + +struct Vec3 (force_align: 8) { + x:float; + y:float; + z:float; + test1:double; + test2:Color; + test3:Test; +} + +/// an example documentation comment: "monster object" +table Monster { + pos:Vec3 (id: 0); + hp:short = 100 (id: 2); + mana:short = 150 (id: 1); + name:string (id: 3, key); + color:Color = Blue (id: 6); + inventory:[ubyte] (id: 5); + testarrayoftables:[Monster] (id: 4); +} + +root_type Monster; diff --git a/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift b/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift new file mode 100644 index 00000000000..9f716183a90 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/fuzzer_generated.swift @@ -0,0 +1,336 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public enum Color: UInt8, Enum, Verifiable { + public typealias T = UInt8 + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case red = 1 + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + case green = 2 + /// \brief color Blue (1u << 3) + case blue = 8 + + public static var max: Color { return .blue } + public static var min: Color { return .red } +} + +extension Color: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .red: try container.encode("Red") + case .green: try container.encode("Green") + case .blue: try container.encode("Blue") + } + } +} + +public struct Test: NativeStruct, Verifiable, FlatbuffersInitializable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: Int16 + private var _b: Int8 + private let padding0__: UInt8 = 0 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = _accessor.readBuffer(of: Int16.self, at: 0) + _b = _accessor.readBuffer(of: Int8.self, at: 2) + } + + public init(a: Int16, b: Int8) { + _a = a + _b = b + } + + public init() { + _a = 0 + _b = 0 + } + + public var a: Int16 { _a } + public var b: Int8 { _b } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: Test.self) + } +} + +extension Test: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + case b = "b" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if a != 0 { + try container.encodeIfPresent(a, forKey: .a) + } + if b != 0 { + try container.encodeIfPresent(b, forKey: .b) + } + } +} + +public struct Test_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: Int16 { return _accessor.readBuffer(of: Int16.self, at: 0) } + public var b: Int8 { return _accessor.readBuffer(of: Int8.self, at: 2) } +} + +public struct Vec3: NativeStruct, Verifiable, FlatbuffersInitializable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _x: Float32 + private var _y: Float32 + private var _z: Float32 + private let padding0__: UInt32 = 0 + private var _test1: Double + private var _test2: UInt8 + private let padding1__: UInt8 = 0 + private var _test3: Test + private let padding2__: UInt16 = 0 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _x = _accessor.readBuffer(of: Float32.self, at: 0) + _y = _accessor.readBuffer(of: Float32.self, at: 4) + _z = _accessor.readBuffer(of: Float32.self, at: 8) + _test1 = _accessor.readBuffer(of: Double.self, at: 16) + _test2 = _accessor.readBuffer(of: UInt8.self, at: 24) + _test3 = Test(_accessor.bb, o: _accessor.position + 26) + } + + public init(x: Float32, y: Float32, z: Float32, test1: Double, test2: Color, test3: Test) { + _x = x + _y = y + _z = z + _test1 = test1 + _test2 = test2.value + _test3 = test3 + } + + public init() { + _x = 0.0 + _y = 0.0 + _z = 0.0 + _test1 = 0.0 + _test2 = 0 + _test3 = Test() + } + + public var x: Float32 { _x } + public var y: Float32 { _y } + public var z: Float32 { _z } + public var test1: Double { _test1 } + public var test2: Color { Color(rawValue: _test2)! } + public var test3: Test { _test3 } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: Vec3.self) + } +} + +extension Vec3: Encodable { + + enum CodingKeys: String, CodingKey { + case x = "x" + case y = "y" + case z = "z" + case test1 = "test1" + case test2 = "test2" + case test3 = "test3" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if x != 0.0 { + try container.encodeIfPresent(x, forKey: .x) + } + if y != 0.0 { + try container.encodeIfPresent(y, forKey: .y) + } + if z != 0.0 { + try container.encodeIfPresent(z, forKey: .z) + } + if test1 != 0.0 { + try container.encodeIfPresent(test1, forKey: .test1) + } + if test2 != .red { + try container.encodeIfPresent(test2, forKey: .test2) + } + try container.encodeIfPresent(test3, forKey: .test3) + } +} + +public struct Vec3_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) } + public var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) } + public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) } + public var test1: Double { return _accessor.readBuffer(of: Double.self, at: 16) } + public var test2: Color { return Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: 24)) ?? .red } + public var test3: Test_Mutable { return Test_Mutable(_accessor.bb, o: _accessor.position + 26) } +} + +/// an example documentation comment: "monster object" +public struct Monster: FlatBufferObject, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case pos = 4 + case mana = 6 + case hp = 8 + case name = 10 + case testarrayoftables = 12 + case inventory = 14 + case color = 16 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var pos: Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: Vec3.self, at: o) } + public var mutablePos: Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } + public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } + public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } + public var name: String! { let o = _accessor.offset(VTOFFSET.name.v); return _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) } + public var hasTestarrayoftables: Bool { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? false : true } + public var testarrayoftablesCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayoftables(at index: Int32) -> Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : Monster(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func testarrayoftablesBy(key: String) -> Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var hasInventory: Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? false : true } + public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] } + public var color: Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } + public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 7) } + public static func add(pos: Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) } + public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) } + public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) } + public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) } + public static func add(color: Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) } + public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end } + public static func createMonster( + _ fbb: inout FlatBufferBuilder, + pos: Vec3? = nil, + mana: Int16 = 150, + hp: Int16 = 100, + nameOffset name: Offset, + testarrayoftablesVectorOffset testarrayoftables: Offset = Offset(), + inventoryVectorOffset inventory: Offset = Offset(), + color: Color = .blue + ) -> Offset { + let __start = Monster.startMonster(&fbb) + Monster.add(pos: pos, &fbb) + Monster.add(mana: mana, &fbb) + Monster.add(hp: hp, &fbb) + Monster.add(name: name, &fbb) + Monster.addVectorOf(testarrayoftables: testarrayoftables, &fbb) + Monster.addVectorOf(inventory: inventory, &fbb) + Monster.add(color: color, &fbb) + return Monster.endMonster(&fbb, start: __start) + } + public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: String, fbb: ByteBuffer) -> Monster? { + let key = key.utf8.map { $0 } + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = Table.compare(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 10, fbb: fbb), key, fbb: fbb) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return Monster(fbb, o: tableOffset) + } + } + return nil + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: Vec3.self) + try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset, Monster>>.self) + try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: Color.self) + _v.finish() + } +} + +extension Monster: Encodable { + + enum CodingKeys: String, CodingKey { + case pos = "pos" + case mana = "mana" + case hp = "hp" + case name = "name" + case testarrayoftables = "testarrayoftables" + case inventory = "inventory" + case color = "color" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(pos, forKey: .pos) + if mana != 150 { + try container.encodeIfPresent(mana, forKey: .mana) + } + if hp != 100 { + try container.encodeIfPresent(hp, forKey: .hp) + } + try container.encodeIfPresent(name, forKey: .name) + if testarrayoftablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayoftables) + for index in 0.. 0 { + try container.encodeIfPresent(inventory, forKey: .inventory) + } + if color != .blue { + try container.encodeIfPresent(color, forKey: .color) + } + } +} + diff --git a/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/main.swift b/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/main.swift new file mode 100644 index 00000000000..146b6362ef9 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Sources/SwiftFlatBuffers/main.swift @@ -0,0 +1,29 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import FlatBuffers + +@_cdecl("LLVMFuzzerTestOneInput") +public func FuzzFlatbuffers(_ start: UnsafeRawPointer, _ count: Int) -> CInt { + let bytes = UnsafeRawBufferPointer(start: start, count: count) + do { + var buffer = ByteBuffer(contiguousBytes: bytes, count: count) + let _: Monster = try getCheckedRoot(byteBuffer: &buffer) + } catch { + } + + return 0 +} diff --git a/third_party/flatbuffers/tests/swift/tests/SwiftTest.sh b/third_party/flatbuffers/tests/swift/tests/SwiftTest.sh new file mode 100755 index 00000000000..37563d4756d --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/SwiftTest.sh @@ -0,0 +1,39 @@ +current_dir=`pwd` +cd .. +swift_dir=`pwd` +cd .. +test_dir=`pwd` +alias fbc='${test_dir}/../flatc' +shopt -s expand_aliases + +cd ${current_dir}/Tests/FlatBuffers.Test.SwiftTests +fbc --swift --gen-mutable --grpc --gen-json-emit --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs ${test_dir}/union_vector/union_vector.fbs +fbc --swift --gen-json-emit ${test_dir}/optional_scalars.fbs +fbc --swift --gen-json-emit --gen-object-api ${test_dir}/more_defaults.fbs +fbc --swift --gen-json-emit --gen-mutable --gen-object-api ${test_dir}/MutatingBool.fbs +fbc --swift --gen-json-emit ${test_dir}/vector_has_test.fbs +cd ${current_dir} + +# Goes into the code generation tests +cd CodeGenerationTests +fbc --swift --gen-mutable --grpc --gen-json-emit --gen-object-api --swift-implementation-only test_import.fbs +fbc --swift --gen-mutable --grpc --gen-json-emit --gen-object-api --no-includes test_no_include.fbs +cd .. + +cd ${current_dir}/Sources/SwiftFlatBuffers +# create better fuzzing test file +fbc --swift --gen-json-emit fuzzer.fbs +cd ${current_dir} + +cd ${swift_dir}/Wasm.tests/Tests/FlatBuffers.Test.Swift.WasmTests +fbc --swift --gen-mutable --gen-json-emit --gen-object-api -I ${test_dir}/include_test ${test_dir}/monster_test.fbs +cd ${current_dir} + +swift build --build-tests +swift test + +if [ $(uname -s) != Darwin ]; then + echo fuzzing + swift build -c debug -Xswiftc -sanitize=fuzzer,address -Xswiftc -parse-as-library + swift build -c release -Xswiftc -sanitize=fuzzer,address -Xswiftc -parse-as-library +fi diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift new file mode 100644 index 00000000000..ccd8200bca1 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersMonsterWriterTests.swift @@ -0,0 +1,504 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation +import XCTest +@testable import FlatBuffers + +typealias Test = MyGame_Example_Test +typealias Monster = MyGame_Example_Monster +typealias Vec3 = MyGame_Example_Vec3 +typealias Stat = MyGame_Example_Stat + +class FlatBuffersMonsterWriterTests: XCTestCase { + + func testData() { + // swiftformat:disable all + let data = Data([48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + let _data = ByteBuffer(data: data) + readVerifiedMonster(fb: _data) + } + + func testReadFromOtherLanguages() { + let url = URL(fileURLWithPath: path, isDirectory: true) + .appendingPathComponent("monsterdata_test") + .appendingPathExtension("mon") + let data = try! Data(contentsOf: url) + let _data = ByteBuffer(data: data) + readVerifiedMonster(fb: _data) + } + + func testCreateMonster() { + let bytes = createMonster(withPrefix: false) + // swiftformat:disable all + XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + var buffer = bytes.buffer + let monster: MyGame_Example_Monster = getRoot(byteBuffer: &buffer) + readMonster(monster: monster) + mutateMonster(fb: bytes.buffer) + readMonster(monster: monster) + } + + func testCreateMonsterResizedBuffer() { + let bytes = createMonster(withPrefix: false) + // swiftformat:disable all + XCTAssertEqual(bytes.sizedByteArray, [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + readVerifiedMonster(fb: bytes.sizedBuffer) + } + + func testCreateMonsterPrefixed() { + let bytes = createMonster(withPrefix: true) + // swiftformat:disable all + XCTAssertEqual(bytes.sizedByteArray, [44, 1, 0, 0, 44, 0, 0, 0, 77, 79, 78, 83, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + // swiftformat:enable all + + var buffer = bytes.buffer + readMonster(monster: getPrefixedSizeRoot(byteBuffer: &buffer)) + } + + func testCreateMonsterUsingCreateMonsterMethodWithNilPos() { + var fbb = FlatBufferBuilder(initialSize: 1) + let name = fbb.create(string: "Frodo") + let mStart = Monster.startMonster(&fbb) + Monster.add(name: name, &fbb) + let root = Monster.endMonster(&fbb, start: mStart) + fbb.finish(offset: root) + var buffer = fbb.sizedBuffer + let newMonster: Monster = getRoot(byteBuffer: &buffer) + XCTAssertNil(newMonster.pos) + XCTAssertEqual(newMonster.name, "Frodo") + } + + func testCreateMonsterUsingCreateMonsterMethodWithPosX() { + var fbb = FlatBufferBuilder(initialSize: 1) + let name = fbb.create(string: "Barney") + let mStart = Monster.startMonster(&fbb) + Monster.add( + pos: MyGame_Example_Vec3( + x: 10, + y: 0, + z: 0, + test1: 0, + test2: .blue, + test3: .init()), + &fbb) + Monster.add(name: name, &fbb) + let root = Monster.endMonster(&fbb, start: mStart) + fbb.finish(offset: root) + + var buffer = fbb.sizedBuffer + let newMonster: Monster = getRoot(byteBuffer: &buffer) + XCTAssertEqual(newMonster.pos!.x, 10) + XCTAssertEqual(newMonster.name, "Barney") + } + + func testReadMonsterFromUnsafePointerWithoutCopying() { + // swiftformat:disable all + var array: [UInt8] = [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0] + // swiftformat:enable all + let unpacked = array + .withUnsafeMutableBytes { memory -> MyGame_Example_MonsterT in + var bytes = ByteBuffer( + assumingMemoryBound: memory.baseAddress!, + capacity: memory.count) + var monster: Monster = getRoot(byteBuffer: &bytes) + readFlatbufferMonster(monster: &monster) + let unpacked = monster.unpack() + return unpacked + } + readObjectApi(monster: unpacked) + } + + func testArrayOfBools() { + let boolArray = [false, true, false, true, false, true, false] + var fbb = FlatBufferBuilder(initialSize: 1) + let name = fbb.create(string: "Frodo") + let bools = fbb.createVector(boolArray) + let root = Monster.createMonster( + &fbb, + nameOffset: name, + testarrayofboolsVectorOffset: bools) + fbb.finish(offset: root) + var buffer = fbb.sizedBuffer + let monster: Monster = getRoot(byteBuffer: &buffer) + let values = monster.testarrayofbools + + XCTAssertEqual(boolArray, values) + + for i in 0.. Bool = { + var buffer = fbb.sizedBuffer + var monster: Monster = getRoot(byteBuffer: &buffer) + self.readFlatbufferMonster(monster: &monster) + return true + } + XCTAssertEqual(testAligned(), true) + let testUnaligned: () -> Bool = { + var bytes: [UInt8] = [0x00] + bytes.append(contentsOf: fbb.sizedByteArray) + return bytes.withUnsafeMutableBytes { ptr in + guard var baseAddress = ptr.baseAddress else { + XCTFail("Base pointer is not defined") + return false + } + baseAddress = baseAddress.advanced(by: 1) + let unlignedPtr = UnsafeMutableRawPointer(baseAddress) + var bytes = ByteBuffer( + assumingMemoryBound: unlignedPtr, + capacity: ptr.count - 1, + allowReadingUnalignedBuffers: true) + var monster: Monster = getRoot(byteBuffer: &bytes) + self.readFlatbufferMonster(monster: &monster) + return true + } + } + XCTAssertEqual(testUnaligned(), true) + } + + func testCopyUnalignedToAlignedBuffers() { + // Aligned read + let fbb = createMonster(withPrefix: true) + let testUnaligned: () -> Bool = { + var bytes: [UInt8] = [0x00] + bytes.append(contentsOf: fbb.sizedByteArray) + return bytes.withUnsafeMutableBytes { ptr in + guard var baseAddress = ptr.baseAddress else { + XCTFail("Base pointer is not defined") + return false + } + baseAddress = baseAddress.advanced(by: 1) + let unlignedPtr = UnsafeMutableRawPointer(baseAddress) + let bytes = ByteBuffer( + assumingMemoryBound: unlignedPtr, + capacity: ptr.count - 1, + allowReadingUnalignedBuffers: false) + var newBuf = FlatBuffersUtils.removeSizePrefix(bb: bytes) + var monster: Monster = getRoot(byteBuffer: &newBuf) + self.readFlatbufferMonster(monster: &monster) + return true + } + } + XCTAssertEqual(testUnaligned(), true) + } + + func readMonster(monster: Monster) { + var monster = monster + readFlatbufferMonster(monster: &monster) + let unpacked: MyGame_Example_MonsterT? = monster.unpack() + readObjectApi(monster: unpacked!) + guard var buffer = unpacked?.serialize() + else { fatalError("Couldnt generate bytebuffer") } + var newMonster: Monster = getRoot(byteBuffer: &buffer) + readFlatbufferMonster(monster: &newMonster) + } + + func createMonster(withPrefix prefix: Bool) -> FlatBufferBuilder { + var fbb = FlatBufferBuilder(initialSize: 1) + let names = [ + fbb.create(string: "Frodo"), + fbb.create(string: "Barney"), + fbb.create(string: "Wilma"), + ] + var offsets: [Offset] = [] + let start1 = Monster.startMonster(&fbb) + Monster.add(name: names[0], &fbb) + offsets.append(Monster.endMonster(&fbb, start: start1)) + let start2 = Monster.startMonster(&fbb) + Monster.add(name: names[1], &fbb) + offsets.append(Monster.endMonster(&fbb, start: start2)) + let start3 = Monster.startMonster(&fbb) + Monster.add(name: names[2], &fbb) + offsets.append(Monster.endMonster(&fbb, start: start3)) + + let sortedArray = Monster.sortVectorOfMonster(offsets: offsets, &fbb) + + let str = fbb.create(string: "MyMonster") + let test1 = fbb.create(string: "test1") + let test2 = fbb.create(string: "test2") + let _inv: [Byte] = [0, 1, 2, 3, 4] + let inv = fbb.createVector(_inv) + + let fred = fbb.create(string: "Fred") + let mon1Start = Monster.startMonster(&fbb) + Monster.add(name: fred, &fbb) + let mon2 = Monster.endMonster(&fbb, start: mon1Start) + + let test4 = fbb.createVector(ofStructs: [ + MyGame_Example_Test(a: 30, b: 40), + MyGame_Example_Test(a: 10, b: 20), + ]) + + let stringTestVector = fbb.createVector(ofOffsets: [test1, test2]) + let mStart = Monster.startMonster(&fbb) + Monster.add( + pos: MyGame_Example_Vec3( + x: 1, + y: 2, + z: 3, + test1: 3, + test2: .green, + test3: .init(a: 5, b: 6)), + &fbb) + Monster.add(hp: 80, &fbb) + Monster.add(name: str, &fbb) + Monster.addVectorOf(inventory: inv, &fbb) + Monster.add(testType: .monster, &fbb) + Monster.add(test: mon2, &fbb) + Monster.addVectorOf(test4: test4, &fbb) + Monster.addVectorOf(testarrayofstring: stringTestVector, &fbb) + Monster.add(testbool: true, &fbb) + Monster.addVectorOf(testarrayoftables: sortedArray, &fbb) + let end = Monster.endMonster(&fbb, start: mStart) + Monster.finish(&fbb, end: end, prefix: prefix) + return fbb + } + + func mutateMonster(fb: ByteBuffer) { + var fb = fb + let monster: Monster = getRoot(byteBuffer: &fb) + XCTAssertFalse(monster.mutate(mana: 10)) + XCTAssertEqual(monster.testarrayoftables(at: 0)?.name, "Barney") + XCTAssertEqual(monster.testarrayoftables(at: 1)?.name, "Frodo") + XCTAssertEqual(monster.testarrayoftables(at: 2)?.name, "Wilma") + + // Example of searching for a table by the key + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Frodo")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Barney")) + XCTAssertNotNil(monster.testarrayoftablesBy(key: "Wilma")) + + XCTAssertEqual(monster.testType, .monster) + + XCTAssertEqual(monster.mutate(inventory: 1, at: 0), true) + XCTAssertEqual(monster.mutate(inventory: 2, at: 1), true) + XCTAssertEqual(monster.mutate(inventory: 3, at: 2), true) + XCTAssertEqual(monster.mutate(inventory: 4, at: 3), true) + XCTAssertEqual(monster.mutate(inventory: 5, at: 4), true) + + for i in 0.. FlatBufferBuilder { + var fbb = FlatBufferBuilder() + let msg = Swift_Tests_NanInfTable.createNanInfTable( + &fbb, + valueNan: .nan, + valueInf: .infinity, + valueNinf: -.infinity, + value: 100.0) + fbb.finish(offset: msg) + return fbb + } + + func testInfNanBinary() { + let fbb = createTestTable() + let data = fbb.sizedByteArray + + var buffer = ByteBuffer(bytes: data) + let table: Swift_Tests_NanInfTable = getRoot(byteBuffer: &buffer) + XCTAssert(table.defaultNan.isNaN) + XCTAssertEqual(table.defaultInf, .infinity) + XCTAssertEqual(table.defaultNinf, -.infinity) + XCTAssert(table.valueNan.isNaN) + XCTAssertEqual(table.valueInf, .infinity) + XCTAssertEqual(table.valueNinf, -.infinity) + XCTAssertEqual(table.value, 100.0) + } + + func testInfNanJSON() { + let fbb = createTestTable() + var bb = fbb.sizedBuffer + do { + struct Test: Decodable { + let valueInf: Double + let value: Int + let valueNan: Double + let valueNinf: Double + } + let reader: Swift_Tests_NanInfTable = try getCheckedRoot(byteBuffer: &bb) + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + encoder.nonConformingFloatEncodingStrategy = + .convertToString( + positiveInfinity: "inf", + negativeInfinity: "-inf", + nan: "nan") + let data = try encoder.encode(reader) + let decoder = JSONDecoder() + decoder.nonConformingFloatDecodingStrategy = .convertFromString( + positiveInfinity: "inf", + negativeInfinity: "-inf", + nan: "nan") + decoder.keyDecodingStrategy = .convertFromSnakeCase + let value = try decoder.decode(Test.self, from: data) + XCTAssertEqual(value.value, 100) + XCTAssertEqual(value.valueInf, .infinity) + XCTAssertEqual(value.valueNinf, -.infinity) + } catch { + XCTFail(error.localizedDescription) + } + } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift new file mode 100644 index 00000000000..3efdb20425f --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersStructsTests.swift @@ -0,0 +1,45 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import XCTest +@testable import FlatBuffers + +final class FlatBuffersStructsTests: XCTestCase { + + func testWritingAndMutatingBools() { + var fbb = FlatBufferBuilder() + let start = TestMutatingBool.startTestMutatingBool(&fbb) + TestMutatingBool.add(b: Property(property: false), &fbb) + let root = TestMutatingBool.endTestMutatingBool(&fbb, start: start) + fbb.finish(offset: root) + + var buffer = fbb.sizedBuffer + let testMutatingBool: TestMutatingBool = getRoot(byteBuffer: &buffer) + let property = testMutatingBool.mutableB + XCTAssertEqual(property?.property, false) + property?.mutate(property: false) + XCTAssertEqual(property?.property, false) + property?.mutate(property: true) + XCTAssertEqual(property?.property, true) + } + +} + +struct Vec: NativeStruct { + var x: Float32 + var y: Float32 + var z: Float32 +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift new file mode 100644 index 00000000000..13780d53dc4 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersTests.swift @@ -0,0 +1,205 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import XCTest +@testable import FlatBuffers + +final class FlatBuffersTests: XCTestCase { + + let country = "Norway" + + func testEndian() { XCTAssertEqual(isLitteEndian, true) } + + func testOffset() { + let o = Offset() + let b = Offset(offset: 1) + XCTAssertEqual(o.isEmpty, true) + XCTAssertEqual(b.isEmpty, false) + } + + func testCreateString() { + let helloWorld = "Hello, world!" + var b = FlatBufferBuilder(initialSize: 16) + XCTAssertEqual(b.create(string: country).o, 12) + XCTAssertEqual(b.create(string: helloWorld).o, 32) + b.clear() + XCTAssertEqual(b.create(string: helloWorld).o, 20) + XCTAssertEqual(b.create(string: country).o, 32) + b.clear() + XCTAssertEqual(b.create(string: String(repeating: "a", count: 257)).o, 264) + } + + func testStartTable() { + var b = FlatBufferBuilder(initialSize: 16) + XCTAssertNoThrow(b.startTable(with: 0)) + b.clear() + XCTAssertEqual(b.create(string: country).o, 12) + XCTAssertEqual(b.startTable(with: 0), 12) + } + + func testCreateFinish() { + var b = FlatBufferBuilder(initialSize: 16) + let countryOff = Country.createCountry( + builder: &b, + name: country, + log: 200, + lan: 100) + b.finish(offset: countryOff) + // swiftformat:disable all + let v: [UInt8] = [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 12, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0] + // swiftformat:enable all + XCTAssertEqual(b.sizedByteArray, v) + } + + func testCreateFinishWithPrefix() { + var b = FlatBufferBuilder(initialSize: 16) + let countryOff = Country.createCountry( + builder: &b, + name: country, + log: 200, + lan: 100) + b.finish(offset: countryOff, addPrefix: true) + // swiftformat:disable all + let v: [UInt8] = [44, 0, 0, 0, 16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 12, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0] + // swiftformat:enable all + XCTAssertEqual(b.sizedByteArray, v) + } + + func testReadCountry() { + // swiftformat:disable all + let v: [UInt8] = [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 12, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0] + // swiftformat:enable all + let buffer = ByteBuffer(bytes: v) + let c = Country.getRootAsCountry(buffer) + XCTAssertEqual(c.lan, 100) + XCTAssertEqual(c.log, 200) + XCTAssertEqual(c.nameVector, [78, 111, 114, 119, 97, 121]) + XCTAssertEqual(c.name, country) + } + + func testWriteNullableStrings() { + var b = FlatBufferBuilder() + XCTAssertTrue(b.create(string: nil).isEmpty) + XCTAssertTrue(b.createShared(string: nil).isEmpty) + } + + func testWriteOptionalValues() { + var b = FlatBufferBuilder() + let root = optional_scalars_ScalarStuff.createScalarStuff( + &b, + justI8: 80, + maybeI8: nil, + justU8: 100, + maybeU8: 10, + maybeBool: true, + justEnum: .one, + maybeEnum: nil) + b.finish(offset: root) + var buffer = b.sizedBuffer + let scalarTable: optional_scalars_ScalarStuff = getRoot(byteBuffer: &buffer) + XCTAssertEqual(scalarTable.justI8, 80) + XCTAssertNil(scalarTable.maybeI8) + XCTAssertEqual(scalarTable.maybeBool, true) + XCTAssertEqual(scalarTable.defaultI8, 42) + XCTAssertEqual(scalarTable.justU8, 100) + XCTAssertEqual(scalarTable.maybeU8, 10) + XCTAssertEqual(scalarTable.justEnum, .one) + XCTAssertNil(scalarTable.maybeEnum) + } +} + +class Country { + + static let offsets: (name: VOffset, lan: VOffset, lng: VOffset) = (4, 6, 8) + private var __t: Table + + private init(_ t: Table) { + __t = t + } + + var lan: Int32 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer( + of: Int32.self, + at: o) } + var log: Int32 { let o = __t.offset(8); return o == 0 ? 0 : __t.readBuffer( + of: Int32.self, + at: o) } + var nameVector: [UInt8]? { __t.getVector(at: 4) } + var name: String? { + let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) } + + @inlinable + static func getRootAsCountry(_ bb: ByteBuffer) -> Country { + Country(Table( + bb: bb, + position: Int32(bb.read(def: UOffset.self, position: 0)))) + } + + @inlinable + static func createCountry( + builder: inout FlatBufferBuilder, + name: String, + log: Int32, + lan: Int32) -> Offset + { + createCountry( + builder: &builder, + offset: builder.create(string: name), + log: log, + lan: lan) + } + + @inlinable + static func createCountry( + builder: inout FlatBufferBuilder, + offset: Offset, + log: Int32, + lan: Int32) -> Offset + { + let _start = builder.startTable(with: 3) + Country.add(builder: &builder, lng: log) + Country.add(builder: &builder, lan: lan) + Country.add(builder: &builder, name: offset) + return Country.end(builder: &builder, startOffset: _start) + } + + @inlinable + static func end( + builder: inout FlatBufferBuilder, + startOffset: UOffset) -> Offset + { + Offset(offset: builder.endTable(at: startOffset)) + } + + @inlinable + static func add(builder: inout FlatBufferBuilder, name: String) { + add(builder: &builder, name: builder.create(string: name)) + } + + @inlinable + static func add(builder: inout FlatBufferBuilder, name: Offset) { + builder.add(offset: name, at: Country.offsets.name) + } + + @inlinable + static func add(builder: inout FlatBufferBuilder, lan: Int32) { + builder.add(element: lan, def: 0, at: Country.offsets.lan) + } + + @inlinable + static func add(builder: inout FlatBufferBuilder, lng: Int32) { + builder.add(element: lng, def: 0, at: Country.offsets.lng) + } +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift new file mode 100644 index 00000000000..1f7edaf6872 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersUnionTests.swift @@ -0,0 +1,429 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import XCTest +@testable import FlatBuffers + +final class FlatBuffersUnionTests: XCTestCase { + + func testCreateMonstor() { + + var b = FlatBufferBuilder(initialSize: 20) + let dmg: Int16 = 5 + let str = "Axe" + let axe = b.create(string: str) + let weapon = Weapon.createWeapon(builder: &b, offset: axe, dmg: dmg) + let weapons = b.createVector(ofOffsets: [weapon]) + let root = LocalMonster.createMonster( + builder: &b, + offset: weapons, + equipment: .Weapon, + equippedOffset: weapon.o) + b.finish(offset: root) + let buffer = b.sizedByteArray + // swiftformat:disable all + XCTAssertEqual(buffer, [16, 0, 0, 0, 0, 0, 10, 0, 16, 0, 8, 0, 7, 0, 12, 0, 10, 0, 0, 0, 0, 0, 0, 1, 8, 0, 0, 0, 20, 0, 0, 0, 1, 0, 0, 0, 12, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 5, 0, 4, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0]) + // swiftformat:enable all + let monster = LocalMonster.getRootAsMonster(bb: ByteBuffer(bytes: buffer)) + XCTAssertEqual(monster.weapon(at: 0)?.dmg, dmg) + XCTAssertEqual(monster.weapon(at: 0)?.name, str) + XCTAssertEqual(monster.weapon(at: 0)?.nameVector, [65, 120, 101]) + let p: Weapon? = monster.equiped() + XCTAssertEqual(p?.dmg, dmg) + XCTAssertEqual(p?.name, str) + XCTAssertEqual(p?.nameVector, [65, 120, 101]) + } + + func testEndTableFinish() { + var builder = FlatBufferBuilder(initialSize: 20) + let sword = builder.create(string: "Sword") + let axe = builder.create(string: "Axe") + let weaponOne = Weapon.createWeapon( + builder: &builder, + offset: sword, + dmg: 3) + let weaponTwo = Weapon.createWeapon(builder: &builder, offset: axe, dmg: 5) + let name = builder.create(string: "Orc") + let inventory: [UInt8] = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] + let inv = builder.createVector(inventory, size: 10) + let weapons = builder.createVector(ofOffsets: [weaponOne, weaponTwo]) + let path = builder.createVector(ofStructs: [ + Vec(x: 4.0, y: 5.0, z: 6.0), + Vec(x: 1.0, y: 2.0, z: 3.0), + ]) + let orc = FinalMonster.createMonster( + builder: &builder, + position: Vec(x: 1, y: 2, z: 3), + hp: 300, + name: name, + inventory: inv, + color: .red, + weapons: weapons, + equipment: .Weapon, + equippedOffset: weaponTwo, + path: path) + builder.finish(offset: orc) + // swiftformat:disable all + XCTAssertEqual(builder.sizedByteArray, [32, 0, 0, 0, 0, 0, 26, 0, 48, 0, 36, 0, 0, 0, 34, 0, 28, 0, 0, 0, 24, 0, 23, 0, 16, 0, 15, 0, 8, 0, 4, 0, 26, 0, 0, 0, 44, 0, 0, 0, 104, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 0, 0, 0, 0, 64, 0, 0, 0, 76, 0, 0, 0, 0, 0, 44, 1, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 2, 0, 0, 0, 52, 0, 0, 0, 28, 0, 0, 0, 10, 0, 0, 0, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 0, 3, 0, 0, 0, 79, 114, 99, 0, 244, 255, 255, 255, 0, 0, 5, 0, 24, 0, 0, 0, 8, 0, 12, 0, 8, 0, 6, 0, 8, 0, 0, 0, 0, 0, 3, 0, 12, 0, 0, 0, 3, 0, 0, 0, 65, 120, 101, 0, 5, 0, 0, 0, 83, 119, 111, 114, 100, 0, 0, 0]) + // swiftformat:enable all + } + + func testEnumVector() { + let vectorOfEnums: [ColorsNameSpace.RGB] = [.blue, .green] + + var builder = FlatBufferBuilder(initialSize: 1) + let off = builder.createVector(vectorOfEnums) + let start = ColorsNameSpace.Monster.startMonster(&builder) + ColorsNameSpace.Monster.add(colors: off, &builder) + let end = ColorsNameSpace.Monster.endMonster(&builder, start: start) + builder.finish(offset: end) + // swiftformat:disable all + XCTAssertEqual(builder.sizedByteArray, [12, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 4, 0, 0, 0, 2, 0, 0, 0, 2, 0, 0, 0, 1, 0, 0, 0]) + // swiftformat:enable all + let monster = ColorsNameSpace.Monster.getRootAsMonster(bb: builder.buffer) + XCTAssertEqual(monster.colorsCount, 2) + XCTAssertEqual(monster.colors(at: 0), .blue) + XCTAssertEqual(monster.colors(at: 1), .green) + } + + func testUnionVector() { + var fb = FlatBufferBuilder() + + let swordDmg: Int32 = 8 + let attackStart = Attacker.startAttacker(&fb) + Attacker.add(swordAttackDamage: swordDmg, &fb) + let attack = Attacker.endAttacker(&fb, start: attackStart) + + let characterType: [Character] = [.belle, .mulan, .bookfan] + + let characters = [ + fb.create(struct: BookReader(booksRead: 7)), + attack, + fb.create(struct: BookReader(booksRead: 2)), + ] + let types = fb.createVector(characterType) + let characterVector = fb.createVector(ofOffsets: characters) + let end = Movie.createMovie( + &fb, + charactersTypeVectorOffset: types, + charactersVectorOffset: characterVector) + Movie.finish(&fb, end: end) + + var buffer = fb.buffer + var movie: Movie = getRoot(byteBuffer: &buffer) + XCTAssertEqual(movie.charactersTypeCount, Int32(characterType.count)) + XCTAssertEqual(movie.charactersCount, Int32(characters.count)) + + for i in 0...size } + var value: Int32 { rawValue } + case red = 0, green = 1, blue = 2 + } + + struct Monster: FlatBufferObject { + var __buffer: ByteBuffer! { _accessor.bb } + + private var _accessor: Table + static func getRootAsMonster(bb: ByteBuffer) -> Monster { Monster(Table( + bb: bb, + position: Int32(bb.read(def: UOffset.self, position: bb.reader)) + + Int32(bb.reader))) } + + init(_ t: Table) { _accessor = t } + init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + public var colorsCount: Int32 { + let o = _accessor.offset(4); return o == 0 ? 0 : _accessor + .vector(count: o) } + public func colors(at index: Int32) -> ColorsNameSpace + .RGB? + { let o = _accessor.offset(4); return o == 0 ? ColorsNameSpace + .RGB(rawValue: 0)! : ColorsNameSpace.RGB(rawValue: _accessor.directRead( + of: Int32.self, + offset: _accessor.vector(at: o) + index * 4)) } + static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb + .startTable(with: 1) } + static func add(colors: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add( + offset: colors, + at: 4) } + static func endMonster( + _ fbb: inout FlatBufferBuilder, + start: UOffset) + -> Offset + { let end = Offset(offset: fbb.endTable(at: start)); return end + } + } +} + + +enum Equipment: Byte { case none, Weapon } + +enum Color3: Int8 { case red = 0, green, blue } + +struct FinalMonster { + + @inlinable + static func createMonster( + builder: inout FlatBufferBuilder, + position: Vec, + hp: Int16, + name: Offset, + inventory: Offset, + color: Color3, + weapons: Offset, + equipment: Equipment = .none, + equippedOffset: Offset, + path: Offset) -> Offset + { + let start = builder.startTable(with: 11) + builder.create(struct: position, position: 4) + builder.add(element: hp, def: 100, at: 8) + builder.add(offset: name, at: 10) + builder.add(offset: inventory, at: 14) + builder.add(element: color.rawValue, def: Color3.green.rawValue, at: 16) + builder.add(offset: weapons, at: 18) + builder.add( + element: equipment.rawValue, + def: Equipment.none.rawValue, + at: 20) + builder.add(offset: equippedOffset, at: 22) + builder.add(offset: path, at: 24) + return Offset(offset: builder.endTable(at: start)) + } +} + +struct LocalMonster { + + private var __t: Table + + init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o) } + init(_ t: Table) { __t = t } + + func weapon(at index: Int32) -> Weapon? { let o = __t + .offset(4); return o == 0 ? nil : Weapon.assign( + __t.indirect(__t.vector(at: o) + (index * 4)), + __t.bb) } + + func equiped() -> T? { + let o = __t.offset(8); return o == 0 ? nil : __t.union(o) + } + + static func getRootAsMonster(bb: ByteBuffer) -> LocalMonster { + LocalMonster(Table( + bb: bb, + position: Int32(bb.read(def: UOffset.self, position: 0)))) + } + + @inlinable + static func createMonster( + builder: inout FlatBufferBuilder, + offset: Offset, + equipment: Equipment = .none, + equippedOffset: UOffset) -> Offset + { + let start = builder.startTable(with: 3) + builder.add(element: equippedOffset, def: 0, at: 8) + builder.add(offset: offset, at: 4) + builder.add( + element: equipment.rawValue, + def: Equipment.none.rawValue, + at: 6) + return Offset(offset: builder.endTable(at: start)) + } +} + +struct Weapon: FlatBufferObject { + + var __buffer: ByteBuffer! { __t.bb } + + static let offsets: (name: VOffset, dmg: VOffset) = (4, 6) + private var __t: Table + + init(_ t: Table) { __t = t } + init(_ fb: ByteBuffer, o: Int32) { __t = Table(bb: fb, position: o)} + + var dmg: Int16 { let o = __t.offset(6); return o == 0 ? 0 : __t.readBuffer( + of: Int16.self, + at: o) } + var nameVector: [UInt8]? { __t.getVector(at: 4) } + var name: String? { + let o = __t.offset(4); return o == 0 ? nil : __t.string(at: o) } + + static func assign(_ i: Int32, _ bb: ByteBuffer) -> Weapon { Weapon(Table( + bb: bb, + position: i)) } + + @inlinable + static func createWeapon( + builder: inout FlatBufferBuilder, + offset: Offset, + dmg: Int16) -> Offset + { + let _start = builder.startTable(with: 2) + Weapon.add(builder: &builder, name: offset) + Weapon.add(builder: &builder, dmg: dmg) + return Weapon.end(builder: &builder, startOffset: _start) + } + + @inlinable + static func end( + builder: inout FlatBufferBuilder, + startOffset: UOffset) -> Offset + { + Offset(offset: builder.endTable(at: startOffset)) + } + + @inlinable + static func add(builder: inout FlatBufferBuilder, name: Offset) { + builder.add(offset: name, at: Weapon.offsets.name) + } + + @inlinable + static func add(builder: inout FlatBufferBuilder, dmg: Int16) { + builder.add(element: dmg, def: 0, at: Weapon.offsets.dmg) + } +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift new file mode 100644 index 00000000000..f0dedfeb3f8 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatBuffersVectorsTests.swift @@ -0,0 +1,202 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import XCTest +@testable import FlatBuffers + +final class FlatBuffersVectors: XCTestCase { + + func testCreatingTwoCountries() { + let norway = "Norway" + let denmark = "Denmark" + var b = FlatBufferBuilder(initialSize: 20) + let noStr = b.create(string: norway) + let deStr = b.create(string: denmark) + let n = Country.createCountry( + builder: &b, + offset: noStr, + log: 888, + lan: 700) + let d = Country.createCountry( + builder: &b, + offset: deStr, + log: 200, + lan: 100) + let vector = [n, d] + let vectorOffset = b.createVector(ofOffsets: vector) + b.finish(offset: vectorOffset) + // swiftformat:disable all + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 2, 0, 0, 0, 48, 0, 0, 0, 16, 0, 0, 0, 0, 0, 10, 0, 18, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 40, 0, 0, 0, 100, 0, 0, 0, 200, 0, 0, 0, 0, 0, 10, 0, 16, 0, 4, 0, 8, 0, 12, 0, 10, 0, 0, 0, 24, 0, 0, 0, 188, 2, 0, 0, 120, 3, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]) + // swiftformat:enable all + } + + func testCreateIntArray() { + let numbers: [Int32] = [1, 2, 3, 4, 5] + var b = FlatBufferBuilder(initialSize: 20) + let o = b.createVector(numbers, size: numbers.count) + b.finish(offset: o) + // swiftformat:disable all + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 5, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0]) + // swiftformat:enable all + } + + func testCreateStructArray() { + struct Vec: NativeStruct { + let x, y, z: Float32 + } + let vector: [Vec] = [ + Vec(x: 1, y: 2, z: 3), + Vec(x: 4, y: 5, z: 6), + Vec(x: 7, y: 8, z: 9), + ] + var b = FlatBufferBuilder(initialSize: 100) + let o = b.createVector(ofStructs: vector) + b.finish(offset: o) + // swiftformat:disable all + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 3, 0, 0, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 128, 64, 0, 0, 160, 64, 0, 0, 192, 64, 0, 0, 224, 64, 0, 0, 0, 65, 0, 0, 16, 65]) + // swiftformat:enable all + } + + func testCreateEmptyIntArray() { + let numbers: [Int32] = [] + var b = FlatBufferBuilder(initialSize: 20) + let o = b.createVector(numbers, size: numbers.count) + b.finish(offset: o) + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 0, 0, 0, 0]) + } + + func testCreateVectorOfStrings() { + let strs = ["Denmark", "Norway"] + var b = FlatBufferBuilder(initialSize: 20) + let o = b.createVector(ofStrings: strs) + b.finish(offset: o) + // swiftformat:disable all + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 2, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0]) + // swiftformat:enable all + } + func testCreateSharedStringVector() { + let norway = "Norway" + let denmark = "Denmark" + var b = FlatBufferBuilder(initialSize: 20) + let noStr = b.createShared(string: norway) + let deStr = b.createShared(string: denmark) + let _noStr = b.createShared(string: norway) + let _deStr = b.createShared(string: denmark) + let v = [noStr, deStr, _noStr, _deStr] + let end = b.createVector(ofOffsets: v) + b.finish(offset: end) + // swiftformat:disable all + XCTAssertEqual(b.sizedByteArray, [4, 0, 0, 0, 4, 0, 0, 0, 28, 0, 0, 0, 12, 0, 0, 0, 20, 0, 0, 0, 4, 0, 0, 0, 7, 0, 0, 0, 68, 101, 110, 109, 97, 114, 107, 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0]) + // swiftformat:enable all + } + + func testReadInt32Array() { + let data: [Int32] = [1, 2, 3, 4, 5] + var b = FlatBufferBuilder(initialSize: 20) + let v = Numbers.createNumbersVector(b: &b, array: data) + let end = Numbers.createNumbers(b: &b, o: v) + b.finish(offset: end) + let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray)) + XCTAssertEqual(number.vArrayInt32, [1, 2, 3, 4, 5]) + } + + func testReadDoubleArray() { + let data: [Double] = [1, 2, 3, 4, 5] + var b = FlatBufferBuilder(initialSize: 20) + let v = Numbers.createNumbersVector(b: &b, array: data) + let end = Numbers.createNumbers(b: &b, o: v) + b.finish(offset: end) + let number = Numbers.getRootAsNumbers(ByteBuffer(bytes: b.sizedByteArray)) + XCTAssertEqual(number.vArrayDouble, [1, 2, 3, 4, 5]) + } + + func testHasForArray() { + var builder = FlatBufferBuilder(initialSize: 20) + let emptyVector = [UInt8]() + let emptyOffset = builder.createVector(emptyVector) + let nonEmptyVector = [1, 2, 3] + let nonEmptyVectorOffest = builder.createVector(nonEmptyVector) + let start = Swift_Tests_Vectors.startVectors(&builder) + Swift_Tests_Vectors.addVectorOf(empty: emptyOffset, &builder) + Swift_Tests_Vectors.addVectorOf(array: nonEmptyVectorOffest, &builder) + let finish = Swift_Tests_Vectors.endVectors(&builder, start: start) + builder.finish(offset: finish) + + var byteBuffer = ByteBuffer(bytes: builder.sizedByteArray) + let msg: Swift_Tests_Vectors = getRoot(byteBuffer: &byteBuffer) + XCTAssertEqual(msg.hasNone, false) + XCTAssertEqual(msg.hasEmpty, true) + XCTAssertEqual(msg.emptyCount, 0) + XCTAssertEqual(msg.hasArray, true) + XCTAssertEqual(msg.arrayCount, 3) + XCTAssertEqual(msg.array, [1, 2, 3]) + } +} + +struct Numbers { + + private var __t: Table + + private init(_ t: Table) { + __t = t + } + + @inlinable + static func getRootAsNumbers(_ bb: ByteBuffer) -> Numbers { + Numbers(Table( + bb: bb, + position: Int32(bb.read(def: UOffset.self, position: 0)))) + } + + var vArrayInt: [Int]? { __t.getVector(at: 4) } + var vArrayInt32: [Int32]? { __t.getVector(at: 4) } + var vArrayDouble: [Double]? { __t.getVector(at: 4) } + var vArrayFloat: [Float32]? { __t.getVector(at: 4) } + + static func createNumbersVector( + b: inout FlatBufferBuilder, + array: [Int]) -> Offset + { + b.createVector(array, size: array.count) + } + + static func createNumbersVector( + b: inout FlatBufferBuilder, + array: [Int32]) -> Offset + { + b.createVector(array, size: array.count) + } + + static func createNumbersVector( + b: inout FlatBufferBuilder, + array: [Double]) -> Offset + { + b.createVector(array, size: array.count) + } + + static func createNumbersVector( + b: inout FlatBufferBuilder, + array: [Float32]) -> Offset + { + b.createVector(array, size: array.count) + } + + static func createNumbers(b: inout FlatBufferBuilder, o: Offset) -> Offset { + let start = b.startTable(with: 1) + b.add(offset: o, at: 4) + return Offset(offset: b.endTable(at: start)) + } +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift new file mode 100644 index 00000000000..8898391e939 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersDoubleTests.swift @@ -0,0 +1,124 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import XCTest +@testable import FlatBuffers + +final class FlatBuffersDoubleTests: XCTestCase { + + let country = "Norway" + + func testCreateFinish() { + var b = FlatBufferBuilder(initialSize: 16) + let countryOff = CountryDouble.createCountry( + builder: &b, + name: country, + log: 200, + lan: 100) + b.finish(offset: countryOff) + // swiftformat:disable all + let v: [UInt8] = [ + 16, 0, 0, 0, 0, 0, 10, 0, 28, 0, 4, 0, 8, 0, 16, 0, 10, + 0, 0, 0, 24, 0, 0, 0, 0, 0, 0, 0, 0, 0, 89, 64, 0, 0, 0, + 0, 0, 0, 105, 64, 0, 0, 0, 0, 6, 0, 0, 0, 78, 111, 114, 119, + 97, 121, 0, 0 + ] + // swiftformat:enable all + XCTAssertEqual(b.sizedByteArray, v) + } + + func testCreateFinishWithPrefix() { + var b = FlatBufferBuilder(initialSize: 16) + let countryOff = CountryDouble.createCountry( + builder: &b, + name: country, + log: 200, + lan: 100) + b.finish(offset: countryOff, addPrefix: true) + // swiftformat:disable all + let v: [UInt8] = [ + 60, 0, 0, 0, 20, 0, 0, 0, 0, 0, 0, 0, 0, 0, 10, 0, 28 + , 0, 4, 0, 8, 0, 16, 0, 10, 0, 0, 0, 24, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 89, 64, 0, 0, 0, 0, 0, 0, 105, 64, 0, 0, 0, + 0, 6, 0, 0, 0, 78, 111, 114, 119, 97, 121, 0, 0 + ] + // swiftformat:enable all + XCTAssertEqual(b.sizedByteArray, v) + } +} + +class CountryDouble { + + static let offsets: (name: VOffset, lan: VOffset, lng: VOffset) = (4, 6, 8) + + private var table: Table + + private init(table t: Table) { table = t } + + static func getRootAsCountry(_ bb: ByteBuffer) -> CountryDouble { + let pos = bb.read(def: Int32.self, position: Int(bb.size)) + return CountryDouble(table: Table(bb: bb, position: Int32(pos))) + } + + static func createCountry( + builder: inout FlatBufferBuilder, + name: String, + log: Double, + lan: Double) -> Offset + { + createCountry( + builder: &builder, + offset: builder.create(string: name), + log: log, + lan: lan) + } + + static func createCountry( + builder: inout FlatBufferBuilder, + offset: Offset, + log: Double, + lan: Double) -> Offset + { + let _start = builder.startTable(with: 3) + CountryDouble.add(builder: &builder, lng: log) + CountryDouble.add(builder: &builder, lan: lan) + CountryDouble.add(builder: &builder, name: offset) + return CountryDouble.end(builder: &builder, startOffset: _start) + } + + static func end( + builder: inout FlatBufferBuilder, + startOffset: UOffset) -> Offset + { + Offset(offset: builder.endTable(at: startOffset)) + } + + static func add(builder: inout FlatBufferBuilder, name: String) { + add(builder: &builder, name: builder.create(string: name)) + } + + static func add(builder: inout FlatBufferBuilder, name: Offset) { + builder.add(offset: name, at: Country.offsets.name) + } + + static func add(builder: inout FlatBufferBuilder, lan: Double) { + builder.add(element: lan, def: 0, at: Country.offsets.lan) + } + + static func add(builder: inout FlatBufferBuilder, lng: Double) { + builder.add(element: lng, def: 0, at: Country.offsets.lng) + } +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersMoreDefaults.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersMoreDefaults.swift new file mode 100644 index 00000000000..66a106e3799 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersMoreDefaults.swift @@ -0,0 +1,86 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import Foundation +import XCTest +@testable import FlatBuffers + +class FlatBuffersMoreDefaults: XCTestCase { + + func testFlatbuffersObject() { + var fbb = FlatBufferBuilder() + let root = MoreDefaults.createMoreDefaults(&fbb) + fbb.finish(offset: root) + var byteBuffer = fbb.sizedBuffer + let defaults: MoreDefaults = getRoot(byteBuffer: &byteBuffer) + XCTAssertEqual(defaults.emptyString, "") + XCTAssertEqual(defaults.someString, "some") + XCTAssertEqual(defaults.ints, []) + XCTAssertEqual(defaults.floats, []) + XCTAssertEqual(defaults.bools, []) + XCTAssertEqual(defaults.intsCount, 0) + XCTAssertEqual(defaults.floatsCount, 0) + XCTAssertEqual(defaults.abcsCount, 0) + XCTAssertEqual(defaults.boolsCount, 0) + } + + func testFlatbuffersObjectAPI() { + var fbb = FlatBufferBuilder() + let defaults = MoreDefaultsT() + XCTAssertEqual(defaults.emptyString, "") + XCTAssertEqual(defaults.someString, "some") + XCTAssertEqual(defaults.ints, []) + XCTAssertEqual(defaults.floats, []) + XCTAssertEqual(defaults.abcs, []) + XCTAssertEqual(defaults.bools, []) + + var buffer = defaults.serialize(builder: &fbb, type: MoreDefaults.self) + let fDefaults: MoreDefaults = getRoot(byteBuffer: &buffer) + XCTAssertEqual(fDefaults.emptyString, "") + XCTAssertEqual(fDefaults.someString, "some") + XCTAssertEqual(fDefaults.ints, []) + XCTAssertEqual(fDefaults.floats, []) + XCTAssertEqual(fDefaults.intsCount, 0) + XCTAssertEqual(fDefaults.floatsCount, 0) + XCTAssertEqual(fDefaults.abcsCount, 0) + XCTAssertEqual(fDefaults.boolsCount, 0) + } + + func testEncoding() { + var fbb = FlatBufferBuilder() + let root = MoreDefaults.createMoreDefaults(&fbb) + fbb.finish(offset: root) + var sizedBuffer = fbb.sizedBuffer + do { + struct Test: Decodable { + var emptyString: String + var someString: String + } + let reader: MoreDefaults = try getCheckedRoot(byteBuffer: &sizedBuffer) + let encoder = JSONEncoder() + encoder.keyEncodingStrategy = .convertToSnakeCase + let data = try encoder.encode(reader) + let decoder = JSONDecoder() + decoder.keyDecodingStrategy = .convertFromSnakeCase + let value = try decoder.decode(Test.self, from: data) + XCTAssertEqual(value.someString, "some") + XCTAssertEqual(value.emptyString, "") + } catch { + XCTFail(error.localizedDescription) + } + } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersVerifierTests.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersVerifierTests.swift new file mode 100644 index 00000000000..53c40278762 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/FlatbuffersVerifierTests.swift @@ -0,0 +1,346 @@ +/* + * Copyright 2024 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import XCTest +@testable import FlatBuffers + +final class FlatbuffersVerifierTests: XCTestCase { + + lazy var validStorage: ByteBuffer.Storage = ByteBuffer.Storage( + count: Int(FlatBufferMaxSize) - 1, + alignment: 1) + lazy var errorStorage: ByteBuffer.Storage = ByteBuffer.Storage( + count: Int(FlatBufferMaxSize) + 1, + alignment: 1) + + var buffer: ByteBuffer! + + var validFlatbuffersObject: ByteBuffer! + var invalidFlatbuffersObject: ByteBuffer! + var invalidFlatbuffersObject2: ByteBuffer! + var invalidFlatbuffersObject3: ByteBuffer! + + override func setUp() { + // swiftformat:disable all + buffer = ByteBuffer(initialSize: 32) + add(buffer: &buffer, v: 4, p: 16) + add(buffer: &buffer, v: 4, p: 20) + + validFlatbuffersObject = ByteBuffer(bytes: [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + + invalidFlatbuffersObject = ByteBuffer(bytes: [0, 48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + + // Array failure within a the inventory array + invalidFlatbuffersObject2 = ByteBuffer(bytes: [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 0x00, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 111, 0, 0, 0]) + + // Array failure within a the strings array + invalidFlatbuffersObject3 = ByteBuffer(bytes: [48, 0, 0, 0, 77, 79, 78, 83, 0, 0, 0, 0, 36, 0, 72, 0, 40, 0, 0, 0, 38, 0, 32, 0, 0, 0, 28, 0, 0, 0, 27, 0, 20, 0, 16, 0, 12, 0, 4, 0, 0, 0, 0, 0, 0, 0, 11, 0, 36, 0, 0, 0, 164, 0, 0, 0, 0, 0, 0, 1, 60, 0, 0, 0, 68, 0, 0, 0, 76, 0, 0, 0, 0, 0, 0, 1, 88, 0, 0, 0, 120, 0, 0, 0, 0, 0, 80, 0, 0, 0, 128, 63, 0, 0, 0, 64, 0, 0, 64, 64, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 8, 64, 2, 0, 5, 0, 6, 0, 0, 0, 2, 0, 0, 0, 64, 0, 0, 0, 48, 0, 0, 0, 2, 0, 0, 0, 30, 0, 40, 0, 10, 0, 20, 0, 152, 255, 255, 255, 4, 0, 0, 0, 4, 0, 0, 0, 70, 114, 101, 100, 0, 0, 0, 0, 5, 0, 0, 0, 0, 1, 2, 3, 4, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 50, 0, 0, 0, 5, 0, 0, 0, 116, 101, 115, 116, 49, 0, 0, 0, 9, 0, 0, 0, 77, 121, 77, 111, 110, 115, 116, 101, 114, 0, 0, 0, 3, 0, 0, 0, 20, 0, 0, 0, 36, 0, 0, 0, 4, 0, 0, 0, 240, 255, 255, 255, 32, 0, 0, 0, 248, 255, 255, 255, 36, 0, 0, 0, 12, 0, 8, 0, 0, 0, 0, 0, 0, 0, 4, 0, 12, 0, 0, 0, 28, 0, 0, 0, 5, 0, 0, 0, 87, 105, 108, 109, 97, 0, 0, 0, 6, 0, 0, 0, 66, 97, 114, 110, 101, 121, 0, 0, 5, 0, 0, 0, 70, 114, 111, 100, 0x00, 111, 0, 0, 0]) + // swiftformat:enable all + } + + func testVeriferInitPassing() { + var buffer = ByteBuffer(initialSize: 0) + buffer._storage = validStorage + XCTAssertNoThrow(try Verifier(buffer: &buffer)) + } + + func testVeriferInitFailing() { + var buffer = ByteBuffer(initialSize: 0) + buffer._storage = errorStorage + XCTAssertThrowsError(try Verifier(buffer: &buffer)) + } + + func testFailingID() { + let dutData : [UInt8] = [1,2,3,4,5,6,7] + var buff = ByteBuffer(bytes: dutData) + do { + let _: Monster = try getCheckedRoot(byteBuffer: &buff, fileId: "ABCD") + XCTFail("This should always fail") + } catch { + XCTAssertEqual(error as? FlatbuffersErrors, .bufferDoesntContainID) + } + } + + func testVerifierCheckAlignment() { + let verifier = try! Verifier(buffer: &buffer) + do { + try verifier.isAligned(position: 20, type: Int.self) + } catch { + XCTAssertEqual( + error as? FlatbuffersErrors, + .missAlignedPointer(position: 20, type: "Int")) + } + XCTAssertNoThrow(try verifier.isAligned(position: 16, type: Int.self)) + + let newVerifer = try! Verifier(buffer: &buffer, checkAlignment: false) + XCTAssertNoThrow(try newVerifer.isAligned(position: 16, type: Int.self)) + } + + func testRangeInBuffer() { + var verifier = try! Verifier(buffer: &buffer) + let size = MemoryLayout.size + XCTAssertNoThrow(try verifier.rangeInBuffer(position: 24, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 26, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 26, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 30, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 32, size: size)) + XCTAssertThrowsError(try verifier.rangeInBuffer(position: 34, size: size)) + + verifier = try! Verifier( + buffer: &buffer, + options: .init(maxDepth: 0, maxTableCount: 0, maxApparentSize: 4)) + do { + try verifier.rangeInBuffer(position: 24, size: size) + } catch { + XCTAssertEqual( + error as! FlatbuffersErrors, + .apparentSizeTooLarge) + } + } + + func testPositionInBuffer() { + let verifier = try! Verifier(buffer: &buffer) + XCTAssertNoThrow(try verifier.inBuffer(position: 0, of: Int64.self)) + XCTAssertNoThrow(try verifier.inBuffer(position: 24, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: -9, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 25, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 26, of: Int32.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 26, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 30, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 32, of: Int64.self)) + XCTAssertThrowsError(try verifier.inBuffer(position: 34, of: Int64.self)) + } + + func testVisitTable() { + var verifier = try! Verifier(buffer: &validFlatbuffersObject) + XCTAssertNoThrow(try verifier.visitTable(at: 48)) + verifier.reset() + } + + func testTableVerifier() { + var verifier = try! Verifier(buffer: &validFlatbuffersObject) + + var tableVerifer = try! verifier.visitTable(at: 48) + XCTAssertEqual(verifier.depth, 1) + XCTAssertEqual(verifier.tableCount, 1) + + XCTAssertNoThrow(try tableVerifer.visit( + field: 4, + fieldName: "Vec", + required: false, + type: Vec3.self)) + XCTAssertNoThrow(try tableVerifer.visit( + field: 8, + fieldName: "hp", + required: false, + type: Int16.self)) + + XCTAssertNoThrow(try tableVerifer.visit( + field: 10, + fieldName: "name", + required: true, + type: ForwardOffset.self)) + + XCTAssertNoThrow(try tableVerifer.visit( + field: 14, + fieldName: "inventory", + required: false, + type: ForwardOffset>.self)) + + XCTAssertNoThrow(try tableVerifer.visit( + field: 22, + fieldName: "test4", + required: false, + type: ForwardOffset> + .self)) + + XCTAssertNoThrow(try tableVerifer.visit( + field: 24, + fieldName: "Vector of strings", + required: false, + type: ForwardOffset, String>>.self)) + + do { + try tableVerifer.visit( + field: 13, + fieldName: "notvalid", + required: false, + type: Int16.self) + } catch { + XCTAssertEqual( + error as! FlatbuffersErrors, + .missAlignedPointer(position: 25, type: "UInt16")) + } + + do { + try tableVerifer.visit( + unionKey: 18, + unionField: 20, + unionKeyName: "testType", + fieldName: "test", + required: false, + completion: { (verifier, key: MyGame_Example_Any_, pos) in + switch key { + case .none_: + break + case .monster: + try ForwardOffset.verify( + &verifier, + at: pos, + of: MyGame_Example_Monster.self) + + case .testsimpletablewithenum: + break + case .mygameExample2Monster: + break + } + }) + } catch { + XCTAssertEqual( + error as! FlatbuffersErrors, + .missAlignedPointer(position: 25, type: "UInt16")) + } + tableVerifer.finish() + XCTAssertEqual(verifier.depth, 0) + } + + func testVerifyUnionVectors() { + // swiftformat:disable all + var byteBuffer = ByteBuffer(bytes: [20, 0, 0, 0, 77, 79, 86, 73, 12, 0, 12, 0, 0, 0, 0, 0, 8, 0, 4, 0, 12, 0, 0, 0, 8, 0, 0, 0, 20, 0, 0, 0, 3, 0, 0, 0, 24, 0, 0, 0, 32, 0, 0, 0, 12, 0, 0, 0, 3, 0, 0, 0, 3, 1, 4, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0]) + // swiftformat:enable all + XCTAssertNoThrow(try getCheckedRoot(byteBuffer: &byteBuffer) as Movie) + } + + func testErrorWrongFileId() { + // swiftformat:disable all + var byteBuffer = ByteBuffer(bytes: [20, 0, 0, 0, 77, 79, 86, 73, 12, 0, 12, 0, 0, 0, 0, 0, 8, 0, 4, 0, 12, 0, 0, 0, 8, 0, 0, 0, 20, 0, 0, 0, 3, 0, 0, 0, 24, 0, 0, 0, 32, 0, 0, 0, 12, 0, 0, 0, 3, 0, 0, 0, 3, 1, 4, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0]) + // swiftformat:enable all + XCTAssertThrowsError(try getCheckedRoot( + byteBuffer: &byteBuffer, + fileId: "FLEX") as Movie) + } + + func testVerifyPrefixedBuffer() { + // swiftformat:disable all + var byteBuffer = ByteBuffer(bytes: [0, 0, 0, 1, 20, 0, 0, 0, 77, 79, 86, 73, 12, 0, 12, 0, 0, 0, 0, 0, 8, 0, 4, 0, 12, 0, 0, 0, 8, 0, 0, 0, 20, 0, 0, 0, 3, 0, 0, 0, 24, 0, 0, 0, 32, 0, 0, 0, 12, 0, 0, 0, 3, 0, 0, 0, 3, 1, 4, 0, 2, 0, 0, 0, 7, 0, 0, 0, 0, 0, 6, 0, 8, 0, 4, 0, 6, 0, 0, 0, 8, 0, 0, 0]) + // swiftformat:enable all + XCTAssertThrowsError( + try getCheckedPrefixedSizeRoot(byteBuffer: &byteBuffer) as Movie) + } + + func testFullVerifier() { + XCTAssertNoThrow( + try getCheckedRoot( + byteBuffer: &validFlatbuffersObject) as MyGame_Example_Monster) + } + + func testFullVerifierWithFileId() { + XCTAssertNoThrow( + try getCheckedRoot( + byteBuffer: &validFlatbuffersObject, + fileId: MyGame_Example_Monster.id) as MyGame_Example_Monster) + } + + func testInvalidBuffer() { + XCTAssertThrowsError( + try getCheckedRoot( + byteBuffer: &invalidFlatbuffersObject) as MyGame_Example_Monster) + } + + func testInvalidBuffer2() { + XCTAssertThrowsError( + try getCheckedRoot( + byteBuffer: &invalidFlatbuffersObject2) as MyGame_Example_Monster) + } + + func testInvalidBuffer3() { + XCTAssertThrowsError( + try getCheckedRoot( + byteBuffer: &invalidFlatbuffersObject3) as MyGame_Example_Monster) + } + + func testValidUnionBuffer() { + let string = "Awesome \\\\t\t\nstring!" + var fb = FlatBufferBuilder() + let stringOffset = fb.create(string: string) + let characterType: [Character] = [.bookfan, .other] + + let characters = [ + fb.create(struct: BookReader(booksRead: 7)), + stringOffset, + ] + let types = fb.createVector(characterType) + let characterVector = fb.createVector(ofOffsets: characters) + + let end = Movie.createMovie( + &fb, + mainCharacterType: .other, + mainCharacterOffset: Offset(offset: stringOffset.o), + charactersTypeVectorOffset: types, + charactersVectorOffset: characterVector) + Movie.finish(&fb, end: end) + var buf = fb.sizedBuffer + XCTAssertNoThrow(try getCheckedRoot(byteBuffer: &buf) as Movie) + } + + func testNestedTables() throws { + var builder = FlatBufferBuilder() + let name = builder.create(string: "Monster") + + let enemy = MyGame_Example_Monster.createMonster( + &builder, + nameOffset: name) + let currentName = builder.create(string: "Main name") + let monster = MyGame_Example_Monster.createMonster( + &builder, + nameOffset: currentName, + enemyOffset: enemy) + builder.finish(offset: monster) + + var sizedBuffer = builder.sizedBuffer + var verifier = try! Verifier(buffer: &sizedBuffer) + var tableVerifer = try! verifier.visitTable( + at: try getOffset(at: 0, within: verifier)) + XCTAssertEqual(verifier.depth, 1) + XCTAssertEqual(verifier.tableCount, 1) + + let position = try tableVerifer.dereference(28)! + + var nestedTable = try verifier.visitTable( + at: try getOffset(at: position, within: verifier)) + + XCTAssertEqual(verifier.depth, 2) + XCTAssertEqual(verifier.tableCount, 2) + nestedTable.finish() + XCTAssertEqual(verifier.depth, 1) + XCTAssertEqual(verifier.tableCount, 2) + tableVerifer.finish() + XCTAssertEqual(verifier.depth, 0) + XCTAssertEqual(verifier.tableCount, 2) + } + + func add(buffer: inout ByteBuffer, v: Int32, p: Int) { + buffer.write(value: v, index: p) + } + + private func getOffset( + at value: Int, + within verifier: Verifier) throws -> Int + { + let offset: UOffset = try verifier.getValue(at: value) + return Int(clamping: (Int(offset) &+ 0).magnitude) + } +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift new file mode 100644 index 00000000000..1fa367092f6 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/MutatingBool_generated.swift @@ -0,0 +1,151 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public struct Property: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _property: Bool + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _property = _accessor.readBuffer(of: Bool.self, at: 0) + } + + public init(property: Bool) { + _property = property + } + + public init() { + _property = false + } + + public init(_ _t: inout Property_Mutable) { + _property = _t.property + } + + public var property: Bool { _property } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: Property.self) + } +} + +extension Property: Encodable { + + enum CodingKeys: String, CodingKey { + case property = "property" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if property != false { + try container.encodeIfPresent(property, forKey: .property) + } + } +} + +public struct Property_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var property: Bool { return _accessor.readBuffer(of: Bool.self, at: 0) } + @discardableResult public func mutate(property: Bool) -> Bool { return _accessor.mutate(property, index: 0) } + + + public mutating func unpack() -> Property { + return Property(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Property?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Property) -> Offset { + return builder.create(struct: obj) + } +} + +public struct TestMutatingBool: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case b = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var b: Property? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : _accessor.readBuffer(of: Property.self, at: o) } + public var mutableB: Property_Mutable? { let o = _accessor.offset(VTOFFSET.b.v); return o == 0 ? nil : Property_Mutable(_accessor.bb, o: o + _accessor.position) } + public static func startTestMutatingBool(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(b: Property?, _ fbb: inout FlatBufferBuilder) { guard let b = b else { return }; fbb.create(struct: b, position: VTOFFSET.b.p) } + public static func endTestMutatingBool(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createTestMutatingBool( + _ fbb: inout FlatBufferBuilder, + b: Property? = nil + ) -> Offset { + let __start = TestMutatingBool.startTestMutatingBool(&fbb) + TestMutatingBool.add(b: b, &fbb) + return TestMutatingBool.endTestMutatingBool(&fbb, start: __start) + } + + + public mutating func unpack() -> TestMutatingBoolT { + return TestMutatingBoolT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout TestMutatingBoolT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout TestMutatingBoolT) -> Offset { + let __root = TestMutatingBool.startTestMutatingBool(&builder) + TestMutatingBool.add(b: obj.b, &builder) + return TestMutatingBool.endTestMutatingBool(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.b.p, fieldName: "b", required: false, type: Property.self) + _v.finish() + } +} + +extension TestMutatingBool: Encodable { + + enum CodingKeys: String, CodingKey { + case b = "b" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(b, forKey: .b) + } +} + +public class TestMutatingBoolT: NativeObject { + + public var b: Property? + + public init(_ _t: inout TestMutatingBool) { + b = _t.b + } + + public init() { + b = Property() + } + + public func serialize() -> ByteBuffer { return serialize(type: TestMutatingBool.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift new file mode 100644 index 00000000000..b5fd53596a8 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/monster_test.grpc.swift @@ -0,0 +1,208 @@ +// Generated GRPC code for FlatBuffers swift! +/// The following code is generated by the Flatbuffers library which might not be in sync with grpc-swift +/// in case of an issue please open github issue, though it would be maintained + +// swiftlint:disable all +// swiftformat:disable all + +import Foundation +import GRPC +import NIO +import NIOHTTP1 +import FlatBuffers + +public protocol GRPCFlatBufPayload: GRPCPayload, FlatBufferGRPCMessage {} +public extension GRPCFlatBufPayload { + init(serializedByteBuffer: inout NIO.ByteBuffer) throws { + self.init(byteBuffer: FlatBuffers.ByteBuffer(contiguousBytes: serializedByteBuffer.readableBytesView, count: serializedByteBuffer.readableBytes)) + } + func serialize(into buffer: inout NIO.ByteBuffer) throws { + let buf = UnsafeRawBufferPointer(start: self.rawPointer, count: Int(self.size)) + buffer.writeBytes(buf) + } +} +extension Message: GRPCFlatBufPayload {} + +/// Usage: instantiate MyGame_Example_MonsterStorageServiceClient, then call methods of this protocol to make API calls. +public protocol MyGame_Example_MonsterStorageClientProtocol: GRPCClient { + + var serviceName: String { get } + + var interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? { get } + + func Store( + _ request: Message + , callOptions: CallOptions? + ) -> UnaryCall, Message> + + func Retrieve( + _ request: Message + , callOptions: CallOptions?, + handler: @escaping (Message) -> Void + ) -> ServerStreamingCall, Message> + + func GetMaxHitPoint( + callOptions: CallOptions? + ) -> ClientStreamingCall, Message> + + func GetMinMaxHitPoints( + callOptions: CallOptions?, + handler: @escaping (Message ) -> Void + ) -> BidirectionalStreamingCall, Message> + +} + +extension MyGame_Example_MonsterStorageClientProtocol { + + public var serviceName: String { "MyGame.Example.MonsterStorage" } + + public func Store( + _ request: Message + , callOptions: CallOptions? = nil + ) -> UnaryCall, Message> { + return self.makeUnaryCall( + path: "/MyGame.Example.MonsterStorage/Store", + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeStoreInterceptors() ?? [] + ) + } + + public func Retrieve( + _ request: Message + , callOptions: CallOptions? = nil, + handler: @escaping (Message) -> Void + ) -> ServerStreamingCall, Message> { + return self.makeServerStreamingCall( + path: "/MyGame.Example.MonsterStorage/Retrieve", + request: request, + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeRetrieveInterceptors() ?? [], + handler: handler + ) + } + + public func GetMaxHitPoint( + callOptions: CallOptions? = nil + ) -> ClientStreamingCall, Message> { + return self.makeClientStreamingCall( + path: "/MyGame.Example.MonsterStorage/GetMaxHitPoint", + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeGetMaxHitPointInterceptors() ?? [] + ) + } + + public func GetMinMaxHitPoints( + callOptions: CallOptions? = nil, + handler: @escaping (Message ) -> Void + ) -> BidirectionalStreamingCall, Message> { + return self.makeBidirectionalStreamingCall( + path: "/MyGame.Example.MonsterStorage/GetMinMaxHitPoints", + callOptions: callOptions ?? self.defaultCallOptions, + interceptors: self.interceptors?.makeGetMinMaxHitPointsInterceptors() ?? [], + handler: handler + ) + } +} + +public protocol MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol { + /// - Returns: Interceptors to use when invoking 'Store'. + func makeStoreInterceptors() -> [ClientInterceptor, Message>] + + /// - Returns: Interceptors to use when invoking 'Retrieve'. + func makeRetrieveInterceptors() -> [ClientInterceptor, Message>] + + /// - Returns: Interceptors to use when invoking 'GetMaxHitPoint'. + func makeGetMaxHitPointInterceptors() -> [ClientInterceptor, Message>] + + /// - Returns: Interceptors to use when invoking 'GetMinMaxHitPoints'. + func makeGetMinMaxHitPointsInterceptors() -> [ClientInterceptor, Message>] + +} + +public final class MyGame_Example_MonsterStorageServiceClient: MyGame_Example_MonsterStorageClientProtocol { + public let channel: GRPCChannel + public var defaultCallOptions: CallOptions + public var interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? + + public init( + channel: GRPCChannel, + defaultCallOptions: CallOptions = CallOptions(), + interceptors: MyGame_Example_MonsterStorageClientInterceptorFactoryProtocol? = nil + ) { + self.channel = channel + self.defaultCallOptions = defaultCallOptions + self.interceptors = interceptors + } +} + +public protocol MyGame_Example_MonsterStorageProvider: CallHandlerProvider { + var interceptors: MyGame_Example_MonsterStorageServerInterceptorFactoryProtocol? { get } + func Store(request: Message, context: StatusOnlyCallContext) -> EventLoopFuture> + func Retrieve(request: Message, context: StreamingResponseCallContext>) -> EventLoopFuture + func GetMaxHitPoint(context: UnaryResponseCallContext>) -> EventLoopFuture<(StreamEvent>) -> Void> + func GetMinMaxHitPoints(context: StreamingResponseCallContext>) -> EventLoopFuture<(StreamEvent>) -> Void> +} + +public extension MyGame_Example_MonsterStorageProvider { + + var serviceName: Substring { return "MyGame.Example.MonsterStorage" } + + func handle(method name: Substring, context: CallHandlerContext) -> GRPCServerHandlerProtocol? { + switch name { + case "Store": + return UnaryServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeStoreInterceptors() ?? [], + userFunction: self.Store(request:context:)) + + case "Retrieve": + return ServerStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeRetrieveInterceptors() ?? [], + userFunction: self.Retrieve(request:context:)) + + case "GetMaxHitPoint": + return ClientStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeGetMaxHitPointInterceptors() ?? [], + observerFactory: self.GetMaxHitPoint(context:)) + + case "GetMinMaxHitPoints": + return BidirectionalStreamingServerHandler( + context: context, + requestDeserializer: GRPCPayloadDeserializer>(), + responseSerializer: GRPCPayloadSerializer>(), + interceptors: self.interceptors?.makeGetMinMaxHitPointsInterceptors() ?? [], + observerFactory: self.GetMinMaxHitPoints(context:)) + + default: return nil; + } + } + +} + +public protocol MyGame_Example_MonsterStorageServerInterceptorFactoryProtocol { + /// - Returns: Interceptors to use when handling 'Store'. + /// Defaults to calling `self.makeInterceptors()`. + func makeStoreInterceptors() -> [ServerInterceptor, Message>] + + /// - Returns: Interceptors to use when handling 'Retrieve'. + /// Defaults to calling `self.makeInterceptors()`. + func makeRetrieveInterceptors() -> [ServerInterceptor, Message>] + + /// - Returns: Interceptors to use when handling 'GetMaxHitPoint'. + /// Defaults to calling `self.makeInterceptors()`. + func makeGetMaxHitPointInterceptors() -> [ServerInterceptor, Message>] + + /// - Returns: Interceptors to use when handling 'GetMinMaxHitPoints'. + /// Defaults to calling `self.makeInterceptors()`. + func makeGetMinMaxHitPointsInterceptors() -> [ServerInterceptor, Message>] + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift new file mode 100644 index 00000000000..476854444b3 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/monster_test_generated.swift @@ -0,0 +1,2665 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +/// Composite components of Monster color. +public enum MyGame_Example_Color: UInt8, Enum, Verifiable { + public typealias T = UInt8 + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case red = 1 + /// \brief color Green + /// Green is bit_flag with value (1u << 1) + case green = 2 + /// \brief color Blue (1u << 3) + case blue = 8 + + public static var max: MyGame_Example_Color { return .blue } + public static var min: MyGame_Example_Color { return .red } +} + +extension MyGame_Example_Color: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .red: try container.encode("Red") + case .green: try container.encode("Green") + case .blue: try container.encode("Blue") + } + } +} + +public enum MyGame_Example_Race: Int8, Enum, Verifiable { + public typealias T = Int8 + public static var byteSize: Int { return MemoryLayout.size } + public var value: Int8 { return self.rawValue } + case none_ = -1 + case human = 0 + case dwarf = 1 + case elf = 2 + + public static var max: MyGame_Example_Race { return .elf } + public static var min: MyGame_Example_Race { return .none_ } +} + +extension MyGame_Example_Race: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("None") + case .human: try container.encode("Human") + case .dwarf: try container.encode("Dwarf") + case .elf: try container.encode("Elf") + } + } +} + +public enum MyGame_Example_LongEnum: UInt64, Enum, Verifiable { + public typealias T = UInt64 + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt64 { return self.rawValue } + case longone = 2 + case longtwo = 4 + case longbig = 1099511627776 + + public static var max: MyGame_Example_LongEnum { return .longbig } + public static var min: MyGame_Example_LongEnum { return .longone } +} + +extension MyGame_Example_LongEnum: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .longone: try container.encode("LongOne") + case .longtwo: try container.encode("LongTwo") + case .longbig: try container.encode("LongBig") + } + } +} + +public enum MyGame_Example_Any_: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case monster = 1 + case testsimpletablewithenum = 2 + case mygameExample2Monster = 3 + + public static var max: MyGame_Example_Any_ { return .mygameExample2Monster } + public static var min: MyGame_Example_Any_ { return .none_ } +} + +extension MyGame_Example_Any_: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .monster: try container.encode("Monster") + case .testsimpletablewithenum: try container.encode("TestSimpleTableWithEnum") + case .mygameExample2Monster: try container.encode("MyGame_Example2_Monster") + } + } +} + +public struct MyGame_Example_Any_Union { + public var type: MyGame_Example_Any_ + public var value: NativeObject? + public init(_ v: NativeObject?, type: MyGame_Example_Any_) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .monster: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .testsimpletablewithenum: + var __obj = value as? MyGame_Example_TestSimpleTableWithEnumT + return MyGame_Example_TestSimpleTableWithEnum.pack(&builder, obj: &__obj) + case .mygameExample2Monster: + var __obj = value as? MyGame_Example2_MonsterT + return MyGame_Example2_Monster.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public enum MyGame_Example_AnyUniqueAliases: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case m = 1 + case ts = 2 + case m2 = 3 + + public static var max: MyGame_Example_AnyUniqueAliases { return .m2 } + public static var min: MyGame_Example_AnyUniqueAliases { return .none_ } +} + +extension MyGame_Example_AnyUniqueAliases: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .m: try container.encode("M") + case .ts: try container.encode("TS") + case .m2: try container.encode("M2") + } + } +} + +public struct MyGame_Example_AnyUniqueAliasesUnion { + public var type: MyGame_Example_AnyUniqueAliases + public var value: NativeObject? + public init(_ v: NativeObject?, type: MyGame_Example_AnyUniqueAliases) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .m: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .ts: + var __obj = value as? MyGame_Example_TestSimpleTableWithEnumT + return MyGame_Example_TestSimpleTableWithEnum.pack(&builder, obj: &__obj) + case .m2: + var __obj = value as? MyGame_Example2_MonsterT + return MyGame_Example2_Monster.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public enum MyGame_Example_AnyAmbiguousAliases: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case m1 = 1 + case m2 = 2 + case m3 = 3 + + public static var max: MyGame_Example_AnyAmbiguousAliases { return .m3 } + public static var min: MyGame_Example_AnyAmbiguousAliases { return .none_ } +} + +extension MyGame_Example_AnyAmbiguousAliases: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .m1: try container.encode("M1") + case .m2: try container.encode("M2") + case .m3: try container.encode("M3") + } + } +} + +public struct MyGame_Example_AnyAmbiguousAliasesUnion { + public var type: MyGame_Example_AnyAmbiguousAliases + public var value: NativeObject? + public init(_ v: NativeObject?, type: MyGame_Example_AnyAmbiguousAliases) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .m1: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .m2: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + case .m3: + var __obj = value as? MyGame_Example_MonsterT + return MyGame_Example_Monster.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public struct MyGame_Example_Test: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: Int16 + private var _b: Int8 + private let padding0__: UInt8 = 0 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = _accessor.readBuffer(of: Int16.self, at: 0) + _b = _accessor.readBuffer(of: Int8.self, at: 2) + } + + public init(a: Int16, b: Int8) { + _a = a + _b = b + } + + public init() { + _a = 0 + _b = 0 + } + + public init(_ _t: inout MyGame_Example_Test_Mutable) { + _a = _t.a + _b = _t.b + } + + public var a: Int16 { _a } + public var b: Int8 { _b } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_Test.self) + } +} + +extension MyGame_Example_Test: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + case b = "b" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if a != 0 { + try container.encodeIfPresent(a, forKey: .a) + } + if b != 0 { + try container.encodeIfPresent(b, forKey: .b) + } + } +} + +public struct MyGame_Example_Test_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: Int16 { return _accessor.readBuffer(of: Int16.self, at: 0) } + @discardableResult public func mutate(a: Int16) -> Bool { return _accessor.mutate(a, index: 0) } + public var b: Int8 { return _accessor.readBuffer(of: Int8.self, at: 2) } + @discardableResult public func mutate(b: Int8) -> Bool { return _accessor.mutate(b, index: 2) } + + + public mutating func unpack() -> MyGame_Example_Test { + return MyGame_Example_Test(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Test?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Test) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_Vec3: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _x: Float32 + private var _y: Float32 + private var _z: Float32 + private let padding0__: UInt32 = 0 + private var _test1: Double + private var _test2: UInt8 + private let padding1__: UInt8 = 0 + private var _test3: MyGame_Example_Test + private let padding2__: UInt16 = 0 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _x = _accessor.readBuffer(of: Float32.self, at: 0) + _y = _accessor.readBuffer(of: Float32.self, at: 4) + _z = _accessor.readBuffer(of: Float32.self, at: 8) + _test1 = _accessor.readBuffer(of: Double.self, at: 16) + _test2 = _accessor.readBuffer(of: UInt8.self, at: 24) + _test3 = MyGame_Example_Test(_accessor.bb, o: _accessor.position + 26) + } + + public init(x: Float32, y: Float32, z: Float32, test1: Double, test2: MyGame_Example_Color, test3: MyGame_Example_Test) { + _x = x + _y = y + _z = z + _test1 = test1 + _test2 = test2.value + _test3 = test3 + } + + public init() { + _x = 0.0 + _y = 0.0 + _z = 0.0 + _test1 = 0.0 + _test2 = 0 + _test3 = MyGame_Example_Test() + } + + public init(_ _t: inout MyGame_Example_Vec3_Mutable) { + _x = _t.x + _y = _t.y + _z = _t.z + _test1 = _t.test1 + _test2 = _t.test2.value + var _vtest3 = _t.test3 + _test3 = _vtest3.unpack() + } + + public var x: Float32 { _x } + public var y: Float32 { _y } + public var z: Float32 { _z } + public var test1: Double { _test1 } + public var test2: MyGame_Example_Color { MyGame_Example_Color(rawValue: _test2)! } + public var test3: MyGame_Example_Test { _test3 } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_Vec3.self) + } +} + +extension MyGame_Example_Vec3: Encodable { + + enum CodingKeys: String, CodingKey { + case x = "x" + case y = "y" + case z = "z" + case test1 = "test1" + case test2 = "test2" + case test3 = "test3" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if x != 0.0 { + try container.encodeIfPresent(x, forKey: .x) + } + if y != 0.0 { + try container.encodeIfPresent(y, forKey: .y) + } + if z != 0.0 { + try container.encodeIfPresent(z, forKey: .z) + } + if test1 != 0.0 { + try container.encodeIfPresent(test1, forKey: .test1) + } + if test2 != .red { + try container.encodeIfPresent(test2, forKey: .test2) + } + try container.encodeIfPresent(test3, forKey: .test3) + } +} + +public struct MyGame_Example_Vec3_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var x: Float32 { return _accessor.readBuffer(of: Float32.self, at: 0) } + @discardableResult public func mutate(x: Float32) -> Bool { return _accessor.mutate(x, index: 0) } + public var y: Float32 { return _accessor.readBuffer(of: Float32.self, at: 4) } + @discardableResult public func mutate(y: Float32) -> Bool { return _accessor.mutate(y, index: 4) } + public var z: Float32 { return _accessor.readBuffer(of: Float32.self, at: 8) } + @discardableResult public func mutate(z: Float32) -> Bool { return _accessor.mutate(z, index: 8) } + public var test1: Double { return _accessor.readBuffer(of: Double.self, at: 16) } + @discardableResult public func mutate(test1: Double) -> Bool { return _accessor.mutate(test1, index: 16) } + public var test2: MyGame_Example_Color { return MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: 24)) ?? .red } + @discardableResult public func mutate(test2: MyGame_Example_Color) -> Bool { return _accessor.mutate(test2.rawValue, index: 24) } + public var test3: MyGame_Example_Test_Mutable { return MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.position + 26) } + + + public mutating func unpack() -> MyGame_Example_Vec3 { + return MyGame_Example_Vec3(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Vec3) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_Ability: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _id: UInt32 + private var _distance: UInt32 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _id = _accessor.readBuffer(of: UInt32.self, at: 0) + _distance = _accessor.readBuffer(of: UInt32.self, at: 4) + } + + public init(id: UInt32, distance: UInt32) { + _id = id + _distance = distance + } + + public init() { + _id = 0 + _distance = 0 + } + + public init(_ _t: inout MyGame_Example_Ability_Mutable) { + _id = _t.id + _distance = _t.distance + } + + public var id: UInt32 { _id } + public var distance: UInt32 { _distance } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_Ability.self) + } +} + +extension MyGame_Example_Ability: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + case distance = "distance" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if id != 0 { + try container.encodeIfPresent(id, forKey: .id) + } + if distance != 0 { + try container.encodeIfPresent(distance, forKey: .distance) + } + } +} + +public struct MyGame_Example_Ability_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var id: UInt32 { return _accessor.readBuffer(of: UInt32.self, at: 0) } + @discardableResult public func mutate(id: UInt32) -> Bool { return _accessor.mutate(id, index: 0) } + public var distance: UInt32 { return _accessor.readBuffer(of: UInt32.self, at: 4) } + @discardableResult public func mutate(distance: UInt32) -> Bool { return _accessor.mutate(distance, index: 4) } + + + public mutating func unpack() -> MyGame_Example_Ability { + return MyGame_Example_Ability(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Ability?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_Ability) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_StructOfStructs: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: MyGame_Example_Ability + private var _b: MyGame_Example_Test + private var _c: MyGame_Example_Ability + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = MyGame_Example_Ability(_accessor.bb, o: _accessor.position + 0) + _b = MyGame_Example_Test(_accessor.bb, o: _accessor.position + 8) + _c = MyGame_Example_Ability(_accessor.bb, o: _accessor.position + 12) + } + + public init(a: MyGame_Example_Ability, b: MyGame_Example_Test, c: MyGame_Example_Ability) { + _a = a + _b = b + _c = c + } + + public init() { + _a = MyGame_Example_Ability() + _b = MyGame_Example_Test() + _c = MyGame_Example_Ability() + } + + public init(_ _t: inout MyGame_Example_StructOfStructs_Mutable) { + var _va = _t.a + _a = _va.unpack() + var _vb = _t.b + _b = _vb.unpack() + var _vc = _t.c + _c = _vc.unpack() + } + + public var a: MyGame_Example_Ability { _a } + public var b: MyGame_Example_Test { _b } + public var c: MyGame_Example_Ability { _c } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_StructOfStructs.self) + } +} + +extension MyGame_Example_StructOfStructs: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + case b = "b" + case c = "c" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(a, forKey: .a) + try container.encodeIfPresent(b, forKey: .b) + try container.encodeIfPresent(c, forKey: .c) + } +} + +public struct MyGame_Example_StructOfStructs_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: MyGame_Example_Ability_Mutable { return MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.position + 0) } + public var b: MyGame_Example_Test_Mutable { return MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.position + 8) } + public var c: MyGame_Example_Ability_Mutable { return MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.position + 12) } + + + public mutating func unpack() -> MyGame_Example_StructOfStructs { + return MyGame_Example_StructOfStructs(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructs?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructs) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_Example_StructOfStructsOfStructs: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _a: MyGame_Example_StructOfStructs + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _a = MyGame_Example_StructOfStructs(_accessor.bb, o: _accessor.position + 0) + } + + public init(a: MyGame_Example_StructOfStructs) { + _a = a + } + + public init() { + _a = MyGame_Example_StructOfStructs() + } + + public init(_ _t: inout MyGame_Example_StructOfStructsOfStructs_Mutable) { + var _va = _t.a + _a = _va.unpack() + } + + public var a: MyGame_Example_StructOfStructs { _a } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: MyGame_Example_StructOfStructsOfStructs.self) + } +} + +extension MyGame_Example_StructOfStructsOfStructs: Encodable { + + enum CodingKeys: String, CodingKey { + case a = "a" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(a, forKey: .a) + } +} + +public struct MyGame_Example_StructOfStructsOfStructs_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var a: MyGame_Example_StructOfStructs_Mutable { return MyGame_Example_StructOfStructs_Mutable(_accessor.bb, o: _accessor.position + 0) } + + + public mutating func unpack() -> MyGame_Example_StructOfStructsOfStructs { + return MyGame_Example_StructOfStructsOfStructs(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructsOfStructs?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StructOfStructsOfStructs) -> Offset { + return builder.create(struct: obj) + } +} + +public struct MyGame_InParentNamespace: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_InParentNamespace.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + public static func startInParentNamespace(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 0) } + public static func endInParentNamespace(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + + + public mutating func unpack() -> MyGame_InParentNamespaceT { + return MyGame_InParentNamespaceT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_InParentNamespaceT) -> Offset { + let __root = MyGame_InParentNamespace.startInParentNamespace(&builder) + return MyGame_InParentNamespace.endInParentNamespace(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + _v.finish() + } +} + +extension MyGame_InParentNamespace: Encodable { + + public func encode(to encoder: Encoder) throws { + } +} + +public class MyGame_InParentNamespaceT: NativeObject { + + + public init(_ _t: inout MyGame_InParentNamespace) { + } + + public init() { + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_InParentNamespace.self) } + +} +public struct MyGame_Example2_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example2_Monster.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 0) } + public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + + + public mutating func unpack() -> MyGame_Example2_MonsterT { + return MyGame_Example2_MonsterT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example2_MonsterT) -> Offset { + let __root = MyGame_Example2_Monster.startMonster(&builder) + return MyGame_Example2_Monster.endMonster(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + _v.finish() + } +} + +extension MyGame_Example2_Monster: Encodable { + + public func encode(to encoder: Encoder) throws { + } +} + +public class MyGame_Example2_MonsterT: NativeObject { + + + public init(_ _t: inout MyGame_Example2_Monster) { + } + + public init() { + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example2_Monster.self) } + +} +internal struct MyGame_Example_TestSimpleTableWithEnum: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + internal var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + internal static var id: String { "MONS" } + internal static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_TestSimpleTableWithEnum.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + internal init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case color = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + internal var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .green : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .green } + @discardableResult internal func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } + internal static func startTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + internal static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 2, at: VTOFFSET.color.p) } + internal static func endTestSimpleTableWithEnum(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + internal static func createTestSimpleTableWithEnum( + _ fbb: inout FlatBufferBuilder, + color: MyGame_Example_Color = .green + ) -> Offset { + let __start = MyGame_Example_TestSimpleTableWithEnum.startTestSimpleTableWithEnum(&fbb) + MyGame_Example_TestSimpleTableWithEnum.add(color: color, &fbb) + return MyGame_Example_TestSimpleTableWithEnum.endTestSimpleTableWithEnum(&fbb, start: __start) + } + + + internal mutating func unpack() -> MyGame_Example_TestSimpleTableWithEnumT { + return MyGame_Example_TestSimpleTableWithEnumT(&self) + } + internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + internal static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TestSimpleTableWithEnumT) -> Offset { + let __root = MyGame_Example_TestSimpleTableWithEnum.startTestSimpleTableWithEnum(&builder) + MyGame_Example_TestSimpleTableWithEnum.add(color: obj.color, &builder) + return MyGame_Example_TestSimpleTableWithEnum.endTestSimpleTableWithEnum(&builder, start: __root) + } + + internal static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) + _v.finish() + } +} + +extension MyGame_Example_TestSimpleTableWithEnum: Encodable { + + enum CodingKeys: String, CodingKey { + case color = "color" + } + internal func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if color != .green { + try container.encodeIfPresent(color, forKey: .color) + } + } +} + +internal class MyGame_Example_TestSimpleTableWithEnumT: NativeObject { + + internal var color: MyGame_Example_Color + + internal init(_ _t: inout MyGame_Example_TestSimpleTableWithEnum) { + color = _t.color + } + + internal init() { + color = .green + } + + internal func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TestSimpleTableWithEnum.self) } + +} +public struct MyGame_Example_Stat: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_Stat.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case id = 4 + case val = 6 + case count = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var id: String? { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? nil : _accessor.string(at: o) } + public var idSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.id.v) } + public var val: Int64 { let o = _accessor.offset(VTOFFSET.val.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(val: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.val.v); return _accessor.mutate(val, index: o) } + public var count: UInt16 { let o = _accessor.offset(VTOFFSET.count.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(count: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.count.v); return _accessor.mutate(count, index: o) } + public static func startStat(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } + public static func add(id: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: id, at: VTOFFSET.id.p) } + public static func add(val: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: val, def: 0, at: VTOFFSET.val.p) } + public static func add(count: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: count, def: 0, at: VTOFFSET.count.p) } + public static func endStat(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createStat( + _ fbb: inout FlatBufferBuilder, + idOffset id: Offset = Offset(), + val: Int64 = 0, + count: UInt16 = 0 + ) -> Offset { + let __start = MyGame_Example_Stat.startStat(&fbb) + MyGame_Example_Stat.add(id: id, &fbb) + MyGame_Example_Stat.add(val: val, &fbb) + MyGame_Example_Stat.add(count: count, &fbb) + return MyGame_Example_Stat.endStat(&fbb, start: __start) + } + public static func sortVectorOfStat(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 8, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 8, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: UInt16, fbb: ByteBuffer) -> MyGame_Example_Stat? { + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = fbb.read(def: UInt16.self, position: Int(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 8, fbb: fbb))) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return MyGame_Example_Stat(fbb, o: tableOffset) + } + } + return nil + } + + + public mutating func unpack() -> MyGame_Example_StatT { + return MyGame_Example_StatT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_StatT) -> Offset { + let __id: Offset + if let s = obj.id { + __id = builder.create(string: s) + } else { + __id = Offset() + } + + let __root = MyGame_Example_Stat.startStat(&builder) + MyGame_Example_Stat.add(id: __id, &builder) + MyGame_Example_Stat.add(val: obj.val, &builder) + MyGame_Example_Stat.add(count: obj.count, &builder) + return MyGame_Example_Stat.endStat(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.val.p, fieldName: "val", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.count.p, fieldName: "count", required: false, type: UInt16.self) + _v.finish() + } +} + +extension MyGame_Example_Stat: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + case val = "val" + case count = "count" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(id, forKey: .id) + if val != 0 { + try container.encodeIfPresent(val, forKey: .val) + } + if count != 0 { + try container.encodeIfPresent(count, forKey: .count) + } + } +} + +public class MyGame_Example_StatT: NativeObject { + + public var id: String? + public var val: Int64 + public var count: UInt16 + + public init(_ _t: inout MyGame_Example_Stat) { + id = _t.id + val = _t.val + count = _t.count + } + + public init() { + val = 0 + count = 0 + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Stat.self) } + +} +public struct MyGame_Example_Referrable: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_Referrable.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case id = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var id: UInt64 { let o = _accessor.offset(VTOFFSET.id.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(id: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.id.v); return _accessor.mutate(id, index: o) } + public static func startReferrable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(id: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: id, def: 0, at: VTOFFSET.id.p) } + public static func endReferrable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createReferrable( + _ fbb: inout FlatBufferBuilder, + id: UInt64 = 0 + ) -> Offset { + let __start = MyGame_Example_Referrable.startReferrable(&fbb) + MyGame_Example_Referrable.add(id: id, &fbb) + return MyGame_Example_Referrable.endReferrable(&fbb, start: __start) + } + public static func sortVectorOfReferrable(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 4, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 4, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: UInt64, fbb: ByteBuffer) -> MyGame_Example_Referrable? { + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = fbb.read(def: UInt64.self, position: Int(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 4, fbb: fbb))) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return MyGame_Example_Referrable(fbb, o: tableOffset) + } + } + return nil + } + + + public mutating func unpack() -> MyGame_Example_ReferrableT { + return MyGame_Example_ReferrableT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_ReferrableT) -> Offset { + let __root = MyGame_Example_Referrable.startReferrable(&builder) + MyGame_Example_Referrable.add(id: obj.id, &builder) + return MyGame_Example_Referrable.endReferrable(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.id.p, fieldName: "id", required: false, type: UInt64.self) + _v.finish() + } +} + +extension MyGame_Example_Referrable: Encodable { + + enum CodingKeys: String, CodingKey { + case id = "id" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if id != 0 { + try container.encodeIfPresent(id, forKey: .id) + } + } +} + +public class MyGame_Example_ReferrableT: NativeObject { + + public var id: UInt64 + + public init(_ _t: inout MyGame_Example_Referrable) { + id = _t.id + } + + public init() { + id = 0 + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_Referrable.self) } + +} +/// an example documentation comment: "monster object" +public struct MyGame_Example_Monster: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_Monster.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case pos = 4 + case mana = 6 + case hp = 8 + case name = 10 + case inventory = 14 + case color = 16 + case testType = 18 + case test = 20 + case test4 = 22 + case testarrayofstring = 24 + case testarrayoftables = 26 + case enemy = 28 + case testnestedflatbuffer = 30 + case testempty = 32 + case testbool = 34 + case testhashs32Fnv1 = 36 + case testhashu32Fnv1 = 38 + case testhashs64Fnv1 = 40 + case testhashu64Fnv1 = 42 + case testhashs32Fnv1a = 44 + case testhashu32Fnv1a = 46 + case testhashs64Fnv1a = 48 + case testhashu64Fnv1a = 50 + case testarrayofbools = 52 + case testf = 54 + case testf2 = 56 + case testf3 = 58 + case testarrayofstring2 = 60 + case testarrayofsortedstruct = 62 + case flex = 64 + case test5 = 66 + case vectorOfLongs = 68 + case vectorOfDoubles = 70 + case parentNamespaceTest = 72 + case vectorOfReferrables = 74 + case singleWeakReference = 76 + case vectorOfWeakReferences = 78 + case vectorOfStrongReferrables = 80 + case coOwningReference = 82 + case vectorOfCoOwningReferences = 84 + case nonOwningReference = 86 + case vectorOfNonOwningReferences = 88 + case anyUniqueType = 90 + case anyUnique = 92 + case anyAmbiguousType = 94 + case anyAmbiguous = 96 + case vectorOfEnums = 98 + case signedEnum = 100 + case testrequirednestedflatbuffer = 102 + case scalarKeySortedTables = 104 + case nativeInline = 106 + case longEnumNonEnumDefault = 108 + case longEnumNormalDefault = 110 + case nanDefault = 112 + case infDefault = 114 + case positiveInfDefault = 116 + case infinityDefault = 118 + case positiveInfinityDefault = 120 + case negativeInfDefault = 122 + case negativeInfinityDefault = 124 + case doubleInfDefault = 126 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var pos: MyGame_Example_Vec3? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Vec3.self, at: o) } + public var mutablePos: MyGame_Example_Vec3_Mutable? { let o = _accessor.offset(VTOFFSET.pos.v); return o == 0 ? nil : MyGame_Example_Vec3_Mutable(_accessor.bb, o: o + _accessor.position) } + public var mana: Int16 { let o = _accessor.offset(VTOFFSET.mana.v); return o == 0 ? 150 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(mana: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.mana.v); return _accessor.mutate(mana, index: o) } + public var hp: Int16 { let o = _accessor.offset(VTOFFSET.hp.v); return o == 0 ? 100 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(hp: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.hp.v); return _accessor.mutate(hp, index: o) } + public var name: String! { let o = _accessor.offset(VTOFFSET.name.v); return _accessor.string(at: o) } + public var nameSegmentArray: [UInt8]! { return _accessor.getVector(at: VTOFFSET.name.v) } + public var hasInventory: Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? false : true } + public var inventoryCount: Int32 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func inventory(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.inventory.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var inventory: [UInt8] { return _accessor.getVector(at: VTOFFSET.inventory.v) ?? [] } + public func mutate(inventory: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.inventory.v); return _accessor.directMutate(inventory, index: _accessor.vector(at: o) + index * 1) } + public var color: MyGame_Example_Color { let o = _accessor.offset(VTOFFSET.color.v); return o == 0 ? .blue : MyGame_Example_Color(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .blue } + @discardableResult public func mutate(color: MyGame_Example_Color) -> Bool {let o = _accessor.offset(VTOFFSET.color.v); return _accessor.mutate(color.rawValue, index: o) } + public var testType: MyGame_Example_Any_ { let o = _accessor.offset(VTOFFSET.testType.v); return o == 0 ? .none_ : MyGame_Example_Any_(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func test(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.test.v); return o == 0 ? nil : _accessor.union(o) } + public var hasTest4: Bool { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? false : true } + public var test4Count: Int32 { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func test4(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Test.self, offset: _accessor.vector(at: o) + index * 4) } + public func mutableTest4(at index: Int32) -> MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.test4.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } + public var hasTestarrayofstring: Bool { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? false : true } + public var testarrayofstringCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofstring(at index: Int32) -> String? { let o = _accessor.offset(VTOFFSET.testarrayofstring.v); return o == 0 ? nil : _accessor.directString(at: _accessor.vector(at: o) + index * 4) } + /// an example documentation comment: this will end up in the generated code + /// multiline too + public var hasTestarrayoftables: Bool { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? false : true } + public var testarrayoftablesCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayoftables(at index: Int32) -> MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func testarrayoftablesBy(key: String) -> MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.testarrayoftables.v); return o == 0 ? nil : MyGame_Example_Monster.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var enemy: MyGame_Example_Monster? { let o = _accessor.offset(VTOFFSET.enemy.v); return o == 0 ? nil : MyGame_Example_Monster(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var hasTestnestedflatbuffer: Bool { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return o == 0 ? false : true } + public var testnestedflatbufferCount: Int32 { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testnestedflatbuffer(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var testnestedflatbuffer: [UInt8] { return _accessor.getVector(at: VTOFFSET.testnestedflatbuffer.v) ?? [] } + public func mutate(testnestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testnestedflatbuffer.v); return _accessor.directMutate(testnestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public var testempty: MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.testempty.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var testbool: Bool { let o = _accessor.offset(VTOFFSET.testbool.v); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } + @discardableResult public func mutate(testbool: Bool) -> Bool {let o = _accessor.offset(VTOFFSET.testbool.v); return _accessor.mutate(testbool, index: o) } + public var testhashs32Fnv1: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1.v); return _accessor.mutate(testhashs32Fnv1, index: o) } + public var testhashu32Fnv1: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1.v); return _accessor.mutate(testhashu32Fnv1, index: o) } + public var testhashs64Fnv1: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1.v); return _accessor.mutate(testhashs64Fnv1, index: o) } + public var testhashu64Fnv1: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1.v); return _accessor.mutate(testhashu64Fnv1, index: o) } + public var testhashs32Fnv1a: Int32 { let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(testhashs32Fnv1a: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs32Fnv1a.v); return _accessor.mutate(testhashs32Fnv1a, index: o) } + public var testhashu32Fnv1a: UInt32 { let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(testhashu32Fnv1a: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu32Fnv1a.v); return _accessor.mutate(testhashu32Fnv1a, index: o) } + public var testhashs64Fnv1a: Int64 { let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(testhashs64Fnv1a: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashs64Fnv1a.v); return _accessor.mutate(testhashs64Fnv1a, index: o) } + public var testhashu64Fnv1a: UInt64 { let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(testhashu64Fnv1a: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.testhashu64Fnv1a.v); return _accessor.mutate(testhashu64Fnv1a, index: o) } + public var hasTestarrayofbools: Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? false : true } + public var testarrayofboolsCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofbools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return o == 0 ? true : _accessor.directRead(of: Bool.self, offset: _accessor.vector(at: o) + index * 1) } + public var testarrayofbools: [Bool] { return _accessor.getVector(at: VTOFFSET.testarrayofbools.v) ?? [] } + public func mutate(testarrayofbools: Bool, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testarrayofbools.v); return _accessor.directMutate(testarrayofbools, index: _accessor.vector(at: o) + index * 1) } + public var testf: Float32 { let o = _accessor.offset(VTOFFSET.testf.v); return o == 0 ? 3.14159 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf.v); return _accessor.mutate(testf, index: o) } + public var testf2: Float32 { let o = _accessor.offset(VTOFFSET.testf2.v); return o == 0 ? 3.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf2: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf2.v); return _accessor.mutate(testf2, index: o) } + public var testf3: Float32 { let o = _accessor.offset(VTOFFSET.testf3.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(testf3: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.testf3.v); return _accessor.mutate(testf3, index: o) } + public var hasTestarrayofstring2: Bool { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? false : true } + public var testarrayofstring2Count: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofstring2(at index: Int32) -> String? { let o = _accessor.offset(VTOFFSET.testarrayofstring2.v); return o == 0 ? nil : _accessor.directString(at: _accessor.vector(at: o) + index * 4) } + public var hasTestarrayofsortedstruct: Bool { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? false : true } + public var testarrayofsortedstructCount: Int32 { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Ability.self, offset: _accessor.vector(at: o) + index * 8) } + public func mutableTestarrayofsortedstruct(at index: Int32) -> MyGame_Example_Ability_Mutable? { let o = _accessor.offset(VTOFFSET.testarrayofsortedstruct.v); return o == 0 ? nil : MyGame_Example_Ability_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 8) } + public var hasFlex: Bool { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? false : true } + public var flexCount: Int32 { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func flex(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.flex.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var flex: [UInt8] { return _accessor.getVector(at: VTOFFSET.flex.v) ?? [] } + public func mutate(flex: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.flex.v); return _accessor.directMutate(flex, index: _accessor.vector(at: o) + index * 1) } + public var hasTest5: Bool { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? false : true } + public var test5Count: Int32 { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func test5(at index: Int32) -> MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : _accessor.directRead(of: MyGame_Example_Test.self, offset: _accessor.vector(at: o) + index * 4) } + public func mutableTest5(at index: Int32) -> MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.test5.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: _accessor.vector(at: o) + index * 4) } + public var hasVectorOfLongs: Bool { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? false : true } + public var vectorOfLongsCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfLongs(at index: Int32) -> Int64 { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return o == 0 ? 0 : _accessor.directRead(of: Int64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfLongs: [Int64] { return _accessor.getVector(at: VTOFFSET.vectorOfLongs.v) ?? [] } + public func mutate(vectorOfLongs: Int64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfLongs.v); return _accessor.directMutate(vectorOfLongs, index: _accessor.vector(at: o) + index * 8) } + public var hasVectorOfDoubles: Bool { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return o == 0 ? false : true } + public var vectorOfDoublesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfDoubles(at index: Int32) -> Double { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return o == 0 ? 0 : _accessor.directRead(of: Double.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfDoubles: [Double] { return _accessor.getVector(at: VTOFFSET.vectorOfDoubles.v) ?? [] } + public func mutate(vectorOfDoubles: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfDoubles.v); return _accessor.directMutate(vectorOfDoubles, index: _accessor.vector(at: o) + index * 8) } + public var parentNamespaceTest: MyGame_InParentNamespace? { let o = _accessor.offset(VTOFFSET.parentNamespaceTest.v); return o == 0 ? nil : MyGame_InParentNamespace(_accessor.bb, o: _accessor.indirect(o + _accessor.position)) } + public var hasVectorOfReferrables: Bool { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? false : true } + public var vectorOfReferrablesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfReferrables(at index: Int32) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func vectorOfReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var singleWeakReference: UInt64 { let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(singleWeakReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.singleWeakReference.v); return _accessor.mutate(singleWeakReference, index: o) } + public var hasVectorOfWeakReferences: Bool { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return o == 0 ? false : true } + public var vectorOfWeakReferencesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfWeakReferences(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfWeakReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfWeakReferences.v) ?? [] } + public func mutate(vectorOfWeakReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfWeakReferences.v); return _accessor.directMutate(vectorOfWeakReferences, index: _accessor.vector(at: o) + index * 8) } + public var hasVectorOfStrongReferrables: Bool { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? false : true } + public var vectorOfStrongReferrablesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfStrongReferrables(at index: Int32) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func vectorOfStrongReferrablesBy(key: UInt64) -> MyGame_Example_Referrable? { let o = _accessor.offset(VTOFFSET.vectorOfStrongReferrables.v); return o == 0 ? nil : MyGame_Example_Referrable.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var coOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.coOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(coOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.coOwningReference.v); return _accessor.mutate(coOwningReference, index: o) } + public var hasVectorOfCoOwningReferences: Bool { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return o == 0 ? false : true } + public var vectorOfCoOwningReferencesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfCoOwningReferences(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfCoOwningReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfCoOwningReferences.v) ?? [] } + public func mutate(vectorOfCoOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfCoOwningReferences.v); return _accessor.directMutate(vectorOfCoOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public var nonOwningReference: UInt64 { let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(nonOwningReference: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.nonOwningReference.v); return _accessor.mutate(nonOwningReference, index: o) } + public var hasVectorOfNonOwningReferences: Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return o == 0 ? false : true } + public var vectorOfNonOwningReferencesCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfNonOwningReferences(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var vectorOfNonOwningReferences: [UInt64] { return _accessor.getVector(at: VTOFFSET.vectorOfNonOwningReferences.v) ?? [] } + public func mutate(vectorOfNonOwningReferences: UInt64, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vectorOfNonOwningReferences.v); return _accessor.directMutate(vectorOfNonOwningReferences, index: _accessor.vector(at: o) + index * 8) } + public var anyUniqueType: MyGame_Example_AnyUniqueAliases { let o = _accessor.offset(VTOFFSET.anyUniqueType.v); return o == 0 ? .none_ : MyGame_Example_AnyUniqueAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyUnique(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyUnique.v); return o == 0 ? nil : _accessor.union(o) } + public var anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases { let o = _accessor.offset(VTOFFSET.anyAmbiguousType.v); return o == 0 ? .none_ : MyGame_Example_AnyAmbiguousAliases(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func anyAmbiguous(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.anyAmbiguous.v); return o == 0 ? nil : _accessor.union(o) } + public var hasVectorOfEnums: Bool { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? false : true } + public var vectorOfEnumsCount: Int32 { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vectorOfEnums(at index: Int32) -> MyGame_Example_Color? { let o = _accessor.offset(VTOFFSET.vectorOfEnums.v); return o == 0 ? MyGame_Example_Color.red : MyGame_Example_Color(rawValue: _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1)) } + public var signedEnum: MyGame_Example_Race { let o = _accessor.offset(VTOFFSET.signedEnum.v); return o == 0 ? .none_ : MyGame_Example_Race(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } + @discardableResult public func mutate(signedEnum: MyGame_Example_Race) -> Bool {let o = _accessor.offset(VTOFFSET.signedEnum.v); return _accessor.mutate(signedEnum.rawValue, index: o) } + public var hasTestrequirednestedflatbuffer: Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? false : true } + public var testrequirednestedflatbufferCount: Int32 { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func testrequirednestedflatbuffer(at index: Int32) -> UInt8 { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return o == 0 ? 0 : _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1) } + public var testrequirednestedflatbuffer: [UInt8] { return _accessor.getVector(at: VTOFFSET.testrequirednestedflatbuffer.v) ?? [] } + public func mutate(testrequirednestedflatbuffer: UInt8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.testrequirednestedflatbuffer.v); return _accessor.directMutate(testrequirednestedflatbuffer, index: _accessor.vector(at: o) + index * 1) } + public var hasScalarKeySortedTables: Bool { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? false : true } + public var scalarKeySortedTablesCount: Int32 { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func scalarKeySortedTables(at index: Int32) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat(_accessor.bb, o: _accessor.indirect(_accessor.vector(at: o) + index * 4)) } + public func scalarKeySortedTablesBy(key: UInt16) -> MyGame_Example_Stat? { let o = _accessor.offset(VTOFFSET.scalarKeySortedTables.v); return o == 0 ? nil : MyGame_Example_Stat.lookupByKey(vector: _accessor.vector(at: o), key: key, fbb: _accessor.bb) } + public var nativeInline: MyGame_Example_Test? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : _accessor.readBuffer(of: MyGame_Example_Test.self, at: o) } + public var mutableNativeInline: MyGame_Example_Test_Mutable? { let o = _accessor.offset(VTOFFSET.nativeInline.v); return o == 0 ? nil : MyGame_Example_Test_Mutable(_accessor.bb, o: o + _accessor.position) } + public var longEnumNonEnumDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNonEnumDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNonEnumDefault.v); return _accessor.mutate(longEnumNonEnumDefault.rawValue, index: o) } + public var longEnumNormalDefault: MyGame_Example_LongEnum { let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return o == 0 ? .longone : MyGame_Example_LongEnum(rawValue: _accessor.readBuffer(of: UInt64.self, at: o)) ?? .longone } + @discardableResult public func mutate(longEnumNormalDefault: MyGame_Example_LongEnum) -> Bool {let o = _accessor.offset(VTOFFSET.longEnumNormalDefault.v); return _accessor.mutate(longEnumNormalDefault.rawValue, index: o) } + public var nanDefault: Float32 { let o = _accessor.offset(VTOFFSET.nanDefault.v); return o == 0 ? .nan : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(nanDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.nanDefault.v); return _accessor.mutate(nanDefault, index: o) } + public var infDefault: Float32 { let o = _accessor.offset(VTOFFSET.infDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infDefault.v); return _accessor.mutate(infDefault, index: o) } + public var positiveInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfDefault.v); return _accessor.mutate(positiveInfDefault, index: o) } + public var infinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.infinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(infinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.infinityDefault.v); return _accessor.mutate(infinityDefault, index: o) } + public var positiveInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(positiveInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.positiveInfinityDefault.v); return _accessor.mutate(positiveInfinityDefault, index: o) } + public var negativeInfDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfDefault.v); return _accessor.mutate(negativeInfDefault, index: o) } + public var negativeInfinityDefault: Float32 { let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(negativeInfinityDefault: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.negativeInfinityDefault.v); return _accessor.mutate(negativeInfinityDefault, index: o) } + public var doubleInfDefault: Double { let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(doubleInfDefault: Double) -> Bool {let o = _accessor.offset(VTOFFSET.doubleInfDefault.v); return _accessor.mutate(doubleInfDefault, index: o) } + public static func startMonster(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 62) } + public static func add(pos: MyGame_Example_Vec3?, _ fbb: inout FlatBufferBuilder) { guard let pos = pos else { return }; fbb.create(struct: pos, position: VTOFFSET.pos.p) } + public static func add(mana: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mana, def: 150, at: VTOFFSET.mana.p) } + public static func add(hp: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: hp, def: 100, at: VTOFFSET.hp.p) } + public static func add(name: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: name, at: VTOFFSET.name.p) } + public static func addVectorOf(inventory: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: inventory, at: VTOFFSET.inventory.p) } + public static func add(color: MyGame_Example_Color, _ fbb: inout FlatBufferBuilder) { fbb.add(element: color.rawValue, def: 8, at: VTOFFSET.color.p) } + public static func add(testType: MyGame_Example_Any_, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testType.rawValue, def: 0, at: VTOFFSET.testType.p) } + public static func add(test: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test, at: VTOFFSET.test.p) } + public static func addVectorOf(test4: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test4, at: VTOFFSET.test4.p) } + public static func startVectorOfTest4(_ size: Int, in builder: inout FlatBufferBuilder) { + builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) + } + public static func addVectorOf(testarrayofstring: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring, at: VTOFFSET.testarrayofstring.p) } + public static func addVectorOf(testarrayoftables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayoftables, at: VTOFFSET.testarrayoftables.p) } + public static func add(enemy: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: enemy, at: VTOFFSET.enemy.p) } + public static func addVectorOf(testnestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testnestedflatbuffer, at: VTOFFSET.testnestedflatbuffer.p) } + public static func add(testempty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testempty, at: VTOFFSET.testempty.p) } + public static func add(testbool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testbool, def: false, + at: VTOFFSET.testbool.p) } + public static func add(testhashs32Fnv1: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1, def: 0, at: VTOFFSET.testhashs32Fnv1.p) } + public static func add(testhashu32Fnv1: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1, def: 0, at: VTOFFSET.testhashu32Fnv1.p) } + public static func add(testhashs64Fnv1: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1, def: 0, at: VTOFFSET.testhashs64Fnv1.p) } + public static func add(testhashu64Fnv1: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1, def: 0, at: VTOFFSET.testhashu64Fnv1.p) } + public static func add(testhashs32Fnv1a: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs32Fnv1a, def: 0, at: VTOFFSET.testhashs32Fnv1a.p) } + public static func add(testhashu32Fnv1a: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu32Fnv1a, def: 0, at: VTOFFSET.testhashu32Fnv1a.p) } + public static func add(testhashs64Fnv1a: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashs64Fnv1a, def: 0, at: VTOFFSET.testhashs64Fnv1a.p) } + public static func add(testhashu64Fnv1a: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testhashu64Fnv1a, def: 0, at: VTOFFSET.testhashu64Fnv1a.p) } + public static func addVectorOf(testarrayofbools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofbools, at: VTOFFSET.testarrayofbools.p) } + public static func add(testf: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf, def: 3.14159, at: VTOFFSET.testf.p) } + public static func add(testf2: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf2, def: 3.0, at: VTOFFSET.testf2.p) } + public static func add(testf3: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: testf3, def: 0.0, at: VTOFFSET.testf3.p) } + public static func addVectorOf(testarrayofstring2: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofstring2, at: VTOFFSET.testarrayofstring2.p) } + public static func addVectorOf(testarrayofsortedstruct: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testarrayofsortedstruct, at: VTOFFSET.testarrayofsortedstruct.p) } + public static func startVectorOfTestarrayofsortedstruct(_ size: Int, in builder: inout FlatBufferBuilder) { + builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) + } + public static func addVectorOf(flex: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: flex, at: VTOFFSET.flex.p) } + public static func addVectorOf(test5: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: test5, at: VTOFFSET.test5.p) } + public static func startVectorOfTest5(_ size: Int, in builder: inout FlatBufferBuilder) { + builder.startVector(size * MemoryLayout.size, elementSize: MemoryLayout.alignment) + } + public static func addVectorOf(vectorOfLongs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfLongs, at: VTOFFSET.vectorOfLongs.p) } + public static func addVectorOf(vectorOfDoubles: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfDoubles, at: VTOFFSET.vectorOfDoubles.p) } + public static func add(parentNamespaceTest: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: parentNamespaceTest, at: VTOFFSET.parentNamespaceTest.p) } + public static func addVectorOf(vectorOfReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfReferrables, at: VTOFFSET.vectorOfReferrables.p) } + public static func add(singleWeakReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: singleWeakReference, def: 0, at: VTOFFSET.singleWeakReference.p) } + public static func addVectorOf(vectorOfWeakReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfWeakReferences, at: VTOFFSET.vectorOfWeakReferences.p) } + public static func addVectorOf(vectorOfStrongReferrables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfStrongReferrables, at: VTOFFSET.vectorOfStrongReferrables.p) } + public static func add(coOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: coOwningReference, def: 0, at: VTOFFSET.coOwningReference.p) } + public static func addVectorOf(vectorOfCoOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfCoOwningReferences, at: VTOFFSET.vectorOfCoOwningReferences.p) } + public static func add(nonOwningReference: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nonOwningReference, def: 0, at: VTOFFSET.nonOwningReference.p) } + public static func addVectorOf(vectorOfNonOwningReferences: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfNonOwningReferences, at: VTOFFSET.vectorOfNonOwningReferences.p) } + public static func add(anyUniqueType: MyGame_Example_AnyUniqueAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyUniqueType.rawValue, def: 0, at: VTOFFSET.anyUniqueType.p) } + public static func add(anyUnique: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyUnique, at: VTOFFSET.anyUnique.p) } + public static func add(anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases, _ fbb: inout FlatBufferBuilder) { fbb.add(element: anyAmbiguousType.rawValue, def: 0, at: VTOFFSET.anyAmbiguousType.p) } + public static func add(anyAmbiguous: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: anyAmbiguous, at: VTOFFSET.anyAmbiguous.p) } + public static func addVectorOf(vectorOfEnums: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vectorOfEnums, at: VTOFFSET.vectorOfEnums.p) } + public static func add(signedEnum: MyGame_Example_Race, _ fbb: inout FlatBufferBuilder) { fbb.add(element: signedEnum.rawValue, def: -1, at: VTOFFSET.signedEnum.p) } + public static func addVectorOf(testrequirednestedflatbuffer: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: testrequirednestedflatbuffer, at: VTOFFSET.testrequirednestedflatbuffer.p) } + public static func addVectorOf(scalarKeySortedTables: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: scalarKeySortedTables, at: VTOFFSET.scalarKeySortedTables.p) } + public static func add(nativeInline: MyGame_Example_Test?, _ fbb: inout FlatBufferBuilder) { guard let nativeInline = nativeInline else { return }; fbb.create(struct: nativeInline, position: VTOFFSET.nativeInline.p) } + public static func add(longEnumNonEnumDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNonEnumDefault.rawValue, def: 0, at: VTOFFSET.longEnumNonEnumDefault.p) } + public static func add(longEnumNormalDefault: MyGame_Example_LongEnum, _ fbb: inout FlatBufferBuilder) { fbb.add(element: longEnumNormalDefault.rawValue, def: 2, at: VTOFFSET.longEnumNormalDefault.p) } + public static func add(nanDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: nanDefault, def: .nan, at: VTOFFSET.nanDefault.p) } + public static func add(infDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infDefault, def: .infinity, at: VTOFFSET.infDefault.p) } + public static func add(positiveInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfDefault, def: .infinity, at: VTOFFSET.positiveInfDefault.p) } + public static func add(infinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: infinityDefault, def: .infinity, at: VTOFFSET.infinityDefault.p) } + public static func add(positiveInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: positiveInfinityDefault, def: .infinity, at: VTOFFSET.positiveInfinityDefault.p) } + public static func add(negativeInfDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfDefault, def: -.infinity, at: VTOFFSET.negativeInfDefault.p) } + public static func add(negativeInfinityDefault: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: negativeInfinityDefault, def: -.infinity, at: VTOFFSET.negativeInfinityDefault.p) } + public static func add(doubleInfDefault: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: doubleInfDefault, def: .infinity, at: VTOFFSET.doubleInfDefault.p) } + public static func endMonster(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); fbb.require(table: end, fields: [10]); return end } + public static func createMonster( + _ fbb: inout FlatBufferBuilder, + pos: MyGame_Example_Vec3? = nil, + mana: Int16 = 150, + hp: Int16 = 100, + nameOffset name: Offset, + inventoryVectorOffset inventory: Offset = Offset(), + color: MyGame_Example_Color = .blue, + testType: MyGame_Example_Any_ = .none_, + testOffset test: Offset = Offset(), + test4VectorOffset test4: Offset = Offset(), + testarrayofstringVectorOffset testarrayofstring: Offset = Offset(), + testarrayoftablesVectorOffset testarrayoftables: Offset = Offset(), + enemyOffset enemy: Offset = Offset(), + testnestedflatbufferVectorOffset testnestedflatbuffer: Offset = Offset(), + testemptyOffset testempty: Offset = Offset(), + testbool: Bool = false, + testhashs32Fnv1: Int32 = 0, + testhashu32Fnv1: UInt32 = 0, + testhashs64Fnv1: Int64 = 0, + testhashu64Fnv1: UInt64 = 0, + testhashs32Fnv1a: Int32 = 0, + testhashu32Fnv1a: UInt32 = 0, + testhashs64Fnv1a: Int64 = 0, + testhashu64Fnv1a: UInt64 = 0, + testarrayofboolsVectorOffset testarrayofbools: Offset = Offset(), + testf: Float32 = 3.14159, + testf2: Float32 = 3.0, + testf3: Float32 = 0.0, + testarrayofstring2VectorOffset testarrayofstring2: Offset = Offset(), + testarrayofsortedstructVectorOffset testarrayofsortedstruct: Offset = Offset(), + flexVectorOffset flex: Offset = Offset(), + test5VectorOffset test5: Offset = Offset(), + vectorOfLongsVectorOffset vectorOfLongs: Offset = Offset(), + vectorOfDoublesVectorOffset vectorOfDoubles: Offset = Offset(), + parentNamespaceTestOffset parentNamespaceTest: Offset = Offset(), + vectorOfReferrablesVectorOffset vectorOfReferrables: Offset = Offset(), + singleWeakReference: UInt64 = 0, + vectorOfWeakReferencesVectorOffset vectorOfWeakReferences: Offset = Offset(), + vectorOfStrongReferrablesVectorOffset vectorOfStrongReferrables: Offset = Offset(), + coOwningReference: UInt64 = 0, + vectorOfCoOwningReferencesVectorOffset vectorOfCoOwningReferences: Offset = Offset(), + nonOwningReference: UInt64 = 0, + vectorOfNonOwningReferencesVectorOffset vectorOfNonOwningReferences: Offset = Offset(), + anyUniqueType: MyGame_Example_AnyUniqueAliases = .none_, + anyUniqueOffset anyUnique: Offset = Offset(), + anyAmbiguousType: MyGame_Example_AnyAmbiguousAliases = .none_, + anyAmbiguousOffset anyAmbiguous: Offset = Offset(), + vectorOfEnumsVectorOffset vectorOfEnums: Offset = Offset(), + signedEnum: MyGame_Example_Race = .none_, + testrequirednestedflatbufferVectorOffset testrequirednestedflatbuffer: Offset = Offset(), + scalarKeySortedTablesVectorOffset scalarKeySortedTables: Offset = Offset(), + nativeInline: MyGame_Example_Test? = nil, + longEnumNonEnumDefault: MyGame_Example_LongEnum = .longone, + longEnumNormalDefault: MyGame_Example_LongEnum = .longone, + nanDefault: Float32 = .nan, + infDefault: Float32 = .infinity, + positiveInfDefault: Float32 = .infinity, + infinityDefault: Float32 = .infinity, + positiveInfinityDefault: Float32 = .infinity, + negativeInfDefault: Float32 = -.infinity, + negativeInfinityDefault: Float32 = -.infinity, + doubleInfDefault: Double = .infinity + ) -> Offset { + let __start = MyGame_Example_Monster.startMonster(&fbb) + MyGame_Example_Monster.add(pos: pos, &fbb) + MyGame_Example_Monster.add(mana: mana, &fbb) + MyGame_Example_Monster.add(hp: hp, &fbb) + MyGame_Example_Monster.add(name: name, &fbb) + MyGame_Example_Monster.addVectorOf(inventory: inventory, &fbb) + MyGame_Example_Monster.add(color: color, &fbb) + MyGame_Example_Monster.add(testType: testType, &fbb) + MyGame_Example_Monster.add(test: test, &fbb) + MyGame_Example_Monster.addVectorOf(test4: test4, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofstring: testarrayofstring, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayoftables: testarrayoftables, &fbb) + MyGame_Example_Monster.add(enemy: enemy, &fbb) + MyGame_Example_Monster.addVectorOf(testnestedflatbuffer: testnestedflatbuffer, &fbb) + MyGame_Example_Monster.add(testempty: testempty, &fbb) + MyGame_Example_Monster.add(testbool: testbool, &fbb) + MyGame_Example_Monster.add(testhashs32Fnv1: testhashs32Fnv1, &fbb) + MyGame_Example_Monster.add(testhashu32Fnv1: testhashu32Fnv1, &fbb) + MyGame_Example_Monster.add(testhashs64Fnv1: testhashs64Fnv1, &fbb) + MyGame_Example_Monster.add(testhashu64Fnv1: testhashu64Fnv1, &fbb) + MyGame_Example_Monster.add(testhashs32Fnv1a: testhashs32Fnv1a, &fbb) + MyGame_Example_Monster.add(testhashu32Fnv1a: testhashu32Fnv1a, &fbb) + MyGame_Example_Monster.add(testhashs64Fnv1a: testhashs64Fnv1a, &fbb) + MyGame_Example_Monster.add(testhashu64Fnv1a: testhashu64Fnv1a, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofbools: testarrayofbools, &fbb) + MyGame_Example_Monster.add(testf: testf, &fbb) + MyGame_Example_Monster.add(testf2: testf2, &fbb) + MyGame_Example_Monster.add(testf3: testf3, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofstring2: testarrayofstring2, &fbb) + MyGame_Example_Monster.addVectorOf(testarrayofsortedstruct: testarrayofsortedstruct, &fbb) + MyGame_Example_Monster.addVectorOf(flex: flex, &fbb) + MyGame_Example_Monster.addVectorOf(test5: test5, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfLongs: vectorOfLongs, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfDoubles: vectorOfDoubles, &fbb) + MyGame_Example_Monster.add(parentNamespaceTest: parentNamespaceTest, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfReferrables: vectorOfReferrables, &fbb) + MyGame_Example_Monster.add(singleWeakReference: singleWeakReference, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfWeakReferences: vectorOfWeakReferences, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfStrongReferrables: vectorOfStrongReferrables, &fbb) + MyGame_Example_Monster.add(coOwningReference: coOwningReference, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfCoOwningReferences: vectorOfCoOwningReferences, &fbb) + MyGame_Example_Monster.add(nonOwningReference: nonOwningReference, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfNonOwningReferences: vectorOfNonOwningReferences, &fbb) + MyGame_Example_Monster.add(anyUniqueType: anyUniqueType, &fbb) + MyGame_Example_Monster.add(anyUnique: anyUnique, &fbb) + MyGame_Example_Monster.add(anyAmbiguousType: anyAmbiguousType, &fbb) + MyGame_Example_Monster.add(anyAmbiguous: anyAmbiguous, &fbb) + MyGame_Example_Monster.addVectorOf(vectorOfEnums: vectorOfEnums, &fbb) + MyGame_Example_Monster.add(signedEnum: signedEnum, &fbb) + MyGame_Example_Monster.addVectorOf(testrequirednestedflatbuffer: testrequirednestedflatbuffer, &fbb) + MyGame_Example_Monster.addVectorOf(scalarKeySortedTables: scalarKeySortedTables, &fbb) + MyGame_Example_Monster.add(nativeInline: nativeInline, &fbb) + MyGame_Example_Monster.add(longEnumNonEnumDefault: longEnumNonEnumDefault, &fbb) + MyGame_Example_Monster.add(longEnumNormalDefault: longEnumNormalDefault, &fbb) + MyGame_Example_Monster.add(nanDefault: nanDefault, &fbb) + MyGame_Example_Monster.add(infDefault: infDefault, &fbb) + MyGame_Example_Monster.add(positiveInfDefault: positiveInfDefault, &fbb) + MyGame_Example_Monster.add(infinityDefault: infinityDefault, &fbb) + MyGame_Example_Monster.add(positiveInfinityDefault: positiveInfinityDefault, &fbb) + MyGame_Example_Monster.add(negativeInfDefault: negativeInfDefault, &fbb) + MyGame_Example_Monster.add(negativeInfinityDefault: negativeInfinityDefault, &fbb) + MyGame_Example_Monster.add(doubleInfDefault: doubleInfDefault, &fbb) + return MyGame_Example_Monster.endMonster(&fbb, start: __start) + } + public static func sortVectorOfMonster(offsets:[Offset], _ fbb: inout FlatBufferBuilder) -> Offset { + var off = offsets + off.sort { Table.compare(Table.offset(Int32($1.o), vOffset: 10, fbb: fbb.buffer), Table.offset(Int32($0.o), vOffset: 10, fbb: fbb.buffer), fbb: fbb.buffer) < 0 } + return fbb.createVector(ofOffsets: off) + } + fileprivate static func lookupByKey(vector: Int32, key: String, fbb: ByteBuffer) -> MyGame_Example_Monster? { + let key = key.utf8.map { $0 } + var span = fbb.read(def: Int32.self, position: Int(vector - 4)) + var start: Int32 = 0 + while span != 0 { + var middle = span / 2 + let tableOffset = Table.indirect(vector + 4 * (start + middle), fbb) + let comp = Table.compare(Table.offset(Int32(fbb.capacity) - tableOffset, vOffset: 10, fbb: fbb), key, fbb: fbb) + if comp > 0 { + span = middle + } else if comp < 0 { + middle += 1 + start += middle + span -= middle + } else { + return MyGame_Example_Monster(fbb, o: tableOffset) + } + } + return nil + } + + + public mutating func unpack() -> MyGame_Example_MonsterT { + return MyGame_Example_MonsterT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_MonsterT) -> Offset { + let __name = builder.create(string: obj.name) + let __inventory = builder.createVector(obj.inventory) + let __test = obj.test?.pack(builder: &builder) ?? Offset() + MyGame_Example_Monster.startVectorOfTest4(obj.test4.count, in: &builder) + for i in obj.test4 { + guard let _o = i else { continue } + builder.create(struct: _o) + } + let __test4 = builder.endVector(len: obj.test4.count) + let __testarrayofstring = builder.createVector(ofStrings: obj.testarrayofstring.compactMap({ $0 }) ) + var __testarrayoftables__: [Offset] = [] + for var i in obj.testarrayoftables { + __testarrayoftables__.append(MyGame_Example_Monster.pack(&builder, obj: &i)) + } + let __testarrayoftables = builder.createVector(ofOffsets: __testarrayoftables__) + let __enemy = MyGame_Example_Monster.pack(&builder, obj: &obj.enemy) + let __testnestedflatbuffer = builder.createVector(obj.testnestedflatbuffer) + let __testempty = MyGame_Example_Stat.pack(&builder, obj: &obj.testempty) + let __testarrayofbools = builder.createVector(obj.testarrayofbools) + let __testarrayofstring2 = builder.createVector(ofStrings: obj.testarrayofstring2.compactMap({ $0 }) ) + MyGame_Example_Monster.startVectorOfTestarrayofsortedstruct(obj.testarrayofsortedstruct.count, in: &builder) + for i in obj.testarrayofsortedstruct { + guard let _o = i else { continue } + builder.create(struct: _o) + } + let __testarrayofsortedstruct = builder.endVector(len: obj.testarrayofsortedstruct.count) + let __flex = builder.createVector(obj.flex) + MyGame_Example_Monster.startVectorOfTest5(obj.test5.count, in: &builder) + for i in obj.test5 { + guard let _o = i else { continue } + builder.create(struct: _o) + } + let __test5 = builder.endVector(len: obj.test5.count) + let __vectorOfLongs = builder.createVector(obj.vectorOfLongs) + let __vectorOfDoubles = builder.createVector(obj.vectorOfDoubles) + let __parentNamespaceTest = MyGame_InParentNamespace.pack(&builder, obj: &obj.parentNamespaceTest) + var __vectorOfReferrables__: [Offset] = [] + for var i in obj.vectorOfReferrables { + __vectorOfReferrables__.append(MyGame_Example_Referrable.pack(&builder, obj: &i)) + } + let __vectorOfReferrables = builder.createVector(ofOffsets: __vectorOfReferrables__) + let __vectorOfWeakReferences = builder.createVector(obj.vectorOfWeakReferences) + var __vectorOfStrongReferrables__: [Offset] = [] + for var i in obj.vectorOfStrongReferrables { + __vectorOfStrongReferrables__.append(MyGame_Example_Referrable.pack(&builder, obj: &i)) + } + let __vectorOfStrongReferrables = builder.createVector(ofOffsets: __vectorOfStrongReferrables__) + let __vectorOfCoOwningReferences = builder.createVector(obj.vectorOfCoOwningReferences) + let __vectorOfNonOwningReferences = builder.createVector(obj.vectorOfNonOwningReferences) + let __anyUnique = obj.anyUnique?.pack(builder: &builder) ?? Offset() + let __anyAmbiguous = obj.anyAmbiguous?.pack(builder: &builder) ?? Offset() + let __vectorOfEnums = builder.createVector(obj.vectorOfEnums) + let __testrequirednestedflatbuffer = builder.createVector(obj.testrequirednestedflatbuffer) + var __scalarKeySortedTables__: [Offset] = [] + for var i in obj.scalarKeySortedTables { + __scalarKeySortedTables__.append(MyGame_Example_Stat.pack(&builder, obj: &i)) + } + let __scalarKeySortedTables = builder.createVector(ofOffsets: __scalarKeySortedTables__) + let __root = MyGame_Example_Monster.startMonster(&builder) + MyGame_Example_Monster.add(pos: obj.pos, &builder) + MyGame_Example_Monster.add(mana: obj.mana, &builder) + MyGame_Example_Monster.add(hp: obj.hp, &builder) + MyGame_Example_Monster.add(name: __name, &builder) + MyGame_Example_Monster.addVectorOf(inventory: __inventory, &builder) + MyGame_Example_Monster.add(color: obj.color, &builder) + if let o = obj.test?.type { + MyGame_Example_Monster.add(testType: o, &builder) + MyGame_Example_Monster.add(test: __test, &builder) + } + + MyGame_Example_Monster.addVectorOf(test4: __test4, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofstring: __testarrayofstring, &builder) + MyGame_Example_Monster.addVectorOf(testarrayoftables: __testarrayoftables, &builder) + MyGame_Example_Monster.add(enemy: __enemy, &builder) + MyGame_Example_Monster.addVectorOf(testnestedflatbuffer: __testnestedflatbuffer, &builder) + MyGame_Example_Monster.add(testempty: __testempty, &builder) + MyGame_Example_Monster.add(testbool: obj.testbool, &builder) + MyGame_Example_Monster.add(testhashs32Fnv1: obj.testhashs32Fnv1, &builder) + MyGame_Example_Monster.add(testhashu32Fnv1: obj.testhashu32Fnv1, &builder) + MyGame_Example_Monster.add(testhashs64Fnv1: obj.testhashs64Fnv1, &builder) + MyGame_Example_Monster.add(testhashu64Fnv1: obj.testhashu64Fnv1, &builder) + MyGame_Example_Monster.add(testhashs32Fnv1a: obj.testhashs32Fnv1a, &builder) + MyGame_Example_Monster.add(testhashu32Fnv1a: obj.testhashu32Fnv1a, &builder) + MyGame_Example_Monster.add(testhashs64Fnv1a: obj.testhashs64Fnv1a, &builder) + MyGame_Example_Monster.add(testhashu64Fnv1a: obj.testhashu64Fnv1a, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofbools: __testarrayofbools, &builder) + MyGame_Example_Monster.add(testf: obj.testf, &builder) + MyGame_Example_Monster.add(testf2: obj.testf2, &builder) + MyGame_Example_Monster.add(testf3: obj.testf3, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofstring2: __testarrayofstring2, &builder) + MyGame_Example_Monster.addVectorOf(testarrayofsortedstruct: __testarrayofsortedstruct, &builder) + MyGame_Example_Monster.addVectorOf(flex: __flex, &builder) + MyGame_Example_Monster.addVectorOf(test5: __test5, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfLongs: __vectorOfLongs, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfDoubles: __vectorOfDoubles, &builder) + MyGame_Example_Monster.add(parentNamespaceTest: __parentNamespaceTest, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfReferrables: __vectorOfReferrables, &builder) + MyGame_Example_Monster.add(singleWeakReference: obj.singleWeakReference, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfWeakReferences: __vectorOfWeakReferences, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfStrongReferrables: __vectorOfStrongReferrables, &builder) + MyGame_Example_Monster.add(coOwningReference: obj.coOwningReference, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfCoOwningReferences: __vectorOfCoOwningReferences, &builder) + MyGame_Example_Monster.add(nonOwningReference: obj.nonOwningReference, &builder) + MyGame_Example_Monster.addVectorOf(vectorOfNonOwningReferences: __vectorOfNonOwningReferences, &builder) + if let o = obj.anyUnique?.type { + MyGame_Example_Monster.add(anyUniqueType: o, &builder) + MyGame_Example_Monster.add(anyUnique: __anyUnique, &builder) + } + + if let o = obj.anyAmbiguous?.type { + MyGame_Example_Monster.add(anyAmbiguousType: o, &builder) + MyGame_Example_Monster.add(anyAmbiguous: __anyAmbiguous, &builder) + } + + MyGame_Example_Monster.addVectorOf(vectorOfEnums: __vectorOfEnums, &builder) + MyGame_Example_Monster.add(signedEnum: obj.signedEnum, &builder) + MyGame_Example_Monster.addVectorOf(testrequirednestedflatbuffer: __testrequirednestedflatbuffer, &builder) + MyGame_Example_Monster.addVectorOf(scalarKeySortedTables: __scalarKeySortedTables, &builder) + MyGame_Example_Monster.add(nativeInline: obj.nativeInline, &builder) + MyGame_Example_Monster.add(longEnumNonEnumDefault: obj.longEnumNonEnumDefault, &builder) + MyGame_Example_Monster.add(longEnumNormalDefault: obj.longEnumNormalDefault, &builder) + MyGame_Example_Monster.add(nanDefault: obj.nanDefault, &builder) + MyGame_Example_Monster.add(infDefault: obj.infDefault, &builder) + MyGame_Example_Monster.add(positiveInfDefault: obj.positiveInfDefault, &builder) + MyGame_Example_Monster.add(infinityDefault: obj.infinityDefault, &builder) + MyGame_Example_Monster.add(positiveInfinityDefault: obj.positiveInfinityDefault, &builder) + MyGame_Example_Monster.add(negativeInfDefault: obj.negativeInfDefault, &builder) + MyGame_Example_Monster.add(negativeInfinityDefault: obj.negativeInfinityDefault, &builder) + MyGame_Example_Monster.add(doubleInfDefault: obj.doubleInfDefault, &builder) + return MyGame_Example_Monster.endMonster(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.pos.p, fieldName: "pos", required: false, type: MyGame_Example_Vec3.self) + try _v.visit(field: VTOFFSET.mana.p, fieldName: "mana", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.hp.p, fieldName: "hp", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.name.p, fieldName: "name", required: true, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.inventory.p, fieldName: "inventory", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.color.p, fieldName: "color", required: false, type: MyGame_Example_Color.self) + try _v.visit(unionKey: VTOFFSET.testType.p, unionField: VTOFFSET.test.p, unionKeyName: "testType", fieldName: "test", required: false, completion: { (verifier, key: MyGame_Example_Any_, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .monster: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .testsimpletablewithenum: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_TestSimpleTableWithEnum.self) + case .mygameExample2Monster: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) + } + }) + try _v.visit(field: VTOFFSET.test4.p, fieldName: "test4", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testarrayofstring.p, fieldName: "testarrayofstring", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayoftables.p, fieldName: "testarrayoftables", required: false, type: ForwardOffset, MyGame_Example_Monster>>.self) + try _v.visit(field: VTOFFSET.enemy.p, fieldName: "enemy", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testnestedflatbuffer.p, fieldName: "testnestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testempty.p, fieldName: "testempty", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.testbool.p, fieldName: "testbool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1.p, fieldName: "testhashs32Fnv1", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1.p, fieldName: "testhashu32Fnv1", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1.p, fieldName: "testhashs64Fnv1", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1.p, fieldName: "testhashu64Fnv1", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testhashs32Fnv1a.p, fieldName: "testhashs32Fnv1a", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.testhashu32Fnv1a.p, fieldName: "testhashu32Fnv1a", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.testhashs64Fnv1a.p, fieldName: "testhashs64Fnv1a", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.testhashu64Fnv1a.p, fieldName: "testhashu64Fnv1a", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.testarrayofbools.p, fieldName: "testarrayofbools", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.testf.p, fieldName: "testf", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf2.p, fieldName: "testf2", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testf3.p, fieldName: "testf3", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.testarrayofstring2.p, fieldName: "testarrayofstring2", required: false, type: ForwardOffset, String>>.self) + try _v.visit(field: VTOFFSET.testarrayofsortedstruct.p, fieldName: "testarrayofsortedstruct", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.flex.p, fieldName: "flex", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.test5.p, fieldName: "test5", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfLongs.p, fieldName: "vectorOfLongs", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfDoubles.p, fieldName: "vectorOfDoubles", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.parentNamespaceTest.p, fieldName: "parentNamespaceTest", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.vectorOfReferrables.p, fieldName: "vectorOfReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.singleWeakReference.p, fieldName: "singleWeakReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfWeakReferences.p, fieldName: "vectorOfWeakReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vectorOfStrongReferrables.p, fieldName: "vectorOfStrongReferrables", required: false, type: ForwardOffset, MyGame_Example_Referrable>>.self) + try _v.visit(field: VTOFFSET.coOwningReference.p, fieldName: "coOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfCoOwningReferences.p, fieldName: "vectorOfCoOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.nonOwningReference.p, fieldName: "nonOwningReference", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.vectorOfNonOwningReferences.p, fieldName: "vectorOfNonOwningReferences", required: false, type: ForwardOffset>.self) + try _v.visit(unionKey: VTOFFSET.anyUniqueType.p, unionField: VTOFFSET.anyUnique.p, unionKeyName: "anyUniqueType", fieldName: "anyUnique", required: false, completion: { (verifier, key: MyGame_Example_AnyUniqueAliases, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .m: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .ts: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_TestSimpleTableWithEnum.self) + case .m2: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example2_Monster.self) + } + }) + try _v.visit(unionKey: VTOFFSET.anyAmbiguousType.p, unionField: VTOFFSET.anyAmbiguous.p, unionKeyName: "anyAmbiguousType", fieldName: "anyAmbiguous", required: false, completion: { (verifier, key: MyGame_Example_AnyAmbiguousAliases, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .m1: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .m2: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + case .m3: + try ForwardOffset.verify(&verifier, at: pos, of: MyGame_Example_Monster.self) + } + }) + try _v.visit(field: VTOFFSET.vectorOfEnums.p, fieldName: "vectorOfEnums", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.signedEnum.p, fieldName: "signedEnum", required: false, type: MyGame_Example_Race.self) + try _v.visit(field: VTOFFSET.testrequirednestedflatbuffer.p, fieldName: "testrequirednestedflatbuffer", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.scalarKeySortedTables.p, fieldName: "scalarKeySortedTables", required: false, type: ForwardOffset, MyGame_Example_Stat>>.self) + try _v.visit(field: VTOFFSET.nativeInline.p, fieldName: "nativeInline", required: false, type: MyGame_Example_Test.self) + try _v.visit(field: VTOFFSET.longEnumNonEnumDefault.p, fieldName: "longEnumNonEnumDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.longEnumNormalDefault.p, fieldName: "longEnumNormalDefault", required: false, type: MyGame_Example_LongEnum.self) + try _v.visit(field: VTOFFSET.nanDefault.p, fieldName: "nanDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infDefault.p, fieldName: "infDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfDefault.p, fieldName: "positiveInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.infinityDefault.p, fieldName: "infinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.positiveInfinityDefault.p, fieldName: "positiveInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfDefault.p, fieldName: "negativeInfDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.negativeInfinityDefault.p, fieldName: "negativeInfinityDefault", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.doubleInfDefault.p, fieldName: "doubleInfDefault", required: false, type: Double.self) + _v.finish() + } +} + +extension MyGame_Example_Monster: Encodable { + + enum CodingKeys: String, CodingKey { + case pos = "pos" + case mana = "mana" + case hp = "hp" + case name = "name" + case inventory = "inventory" + case color = "color" + case testType = "test_type" + case test = "test" + case test4 = "test4" + case testarrayofstring = "testarrayofstring" + case testarrayoftables = "testarrayoftables" + case enemy = "enemy" + case testnestedflatbuffer = "testnestedflatbuffer" + case testempty = "testempty" + case testbool = "testbool" + case testhashs32Fnv1 = "testhashs32_fnv1" + case testhashu32Fnv1 = "testhashu32_fnv1" + case testhashs64Fnv1 = "testhashs64_fnv1" + case testhashu64Fnv1 = "testhashu64_fnv1" + case testhashs32Fnv1a = "testhashs32_fnv1a" + case testhashu32Fnv1a = "testhashu32_fnv1a" + case testhashs64Fnv1a = "testhashs64_fnv1a" + case testhashu64Fnv1a = "testhashu64_fnv1a" + case testarrayofbools = "testarrayofbools" + case testf = "testf" + case testf2 = "testf2" + case testf3 = "testf3" + case testarrayofstring2 = "testarrayofstring2" + case testarrayofsortedstruct = "testarrayofsortedstruct" + case flex = "flex" + case test5 = "test5" + case vectorOfLongs = "vector_of_longs" + case vectorOfDoubles = "vector_of_doubles" + case parentNamespaceTest = "parent_namespace_test" + case vectorOfReferrables = "vector_of_referrables" + case singleWeakReference = "single_weak_reference" + case vectorOfWeakReferences = "vector_of_weak_references" + case vectorOfStrongReferrables = "vector_of_strong_referrables" + case coOwningReference = "co_owning_reference" + case vectorOfCoOwningReferences = "vector_of_co_owning_references" + case nonOwningReference = "non_owning_reference" + case vectorOfNonOwningReferences = "vector_of_non_owning_references" + case anyUniqueType = "any_unique_type" + case anyUnique = "any_unique" + case anyAmbiguousType = "any_ambiguous_type" + case anyAmbiguous = "any_ambiguous" + case vectorOfEnums = "vector_of_enums" + case signedEnum = "signed_enum" + case testrequirednestedflatbuffer = "testrequirednestedflatbuffer" + case scalarKeySortedTables = "scalar_key_sorted_tables" + case nativeInline = "native_inline" + case longEnumNonEnumDefault = "long_enum_non_enum_default" + case longEnumNormalDefault = "long_enum_normal_default" + case nanDefault = "nan_default" + case infDefault = "inf_default" + case positiveInfDefault = "positive_inf_default" + case infinityDefault = "infinity_default" + case positiveInfinityDefault = "positive_infinity_default" + case negativeInfDefault = "negative_inf_default" + case negativeInfinityDefault = "negative_infinity_default" + case doubleInfDefault = "double_inf_default" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + try container.encodeIfPresent(pos, forKey: .pos) + if mana != 150 { + try container.encodeIfPresent(mana, forKey: .mana) + } + if hp != 100 { + try container.encodeIfPresent(hp, forKey: .hp) + } + try container.encodeIfPresent(name, forKey: .name) + if inventoryCount > 0 { + try container.encodeIfPresent(inventory, forKey: .inventory) + } + if color != .blue { + try container.encodeIfPresent(color, forKey: .color) + } + if testType != .none_ { + try container.encodeIfPresent(testType, forKey: .testType) + } + switch testType { + case .monster: + let _v = test(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .test) + case .testsimpletablewithenum: + let _v = test(type: MyGame_Example_TestSimpleTableWithEnum.self) + try container.encodeIfPresent(_v, forKey: .test) + case .mygameExample2Monster: + let _v = test(type: MyGame_Example2_Monster.self) + try container.encodeIfPresent(_v, forKey: .test) + default: break; + } + if test4Count > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .test4) + for index in 0.. 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofstring) + for index in 0.. 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayoftables) + for index in 0.. 0 { + try container.encodeIfPresent(testnestedflatbuffer, forKey: .testnestedflatbuffer) + } + try container.encodeIfPresent(testempty, forKey: .testempty) + if testbool != false { + try container.encodeIfPresent(testbool, forKey: .testbool) + } + if testhashs32Fnv1 != 0 { + try container.encodeIfPresent(testhashs32Fnv1, forKey: .testhashs32Fnv1) + } + if testhashu32Fnv1 != 0 { + try container.encodeIfPresent(testhashu32Fnv1, forKey: .testhashu32Fnv1) + } + if testhashs64Fnv1 != 0 { + try container.encodeIfPresent(testhashs64Fnv1, forKey: .testhashs64Fnv1) + } + if testhashu64Fnv1 != 0 { + try container.encodeIfPresent(testhashu64Fnv1, forKey: .testhashu64Fnv1) + } + if testhashs32Fnv1a != 0 { + try container.encodeIfPresent(testhashs32Fnv1a, forKey: .testhashs32Fnv1a) + } + if testhashu32Fnv1a != 0 { + try container.encodeIfPresent(testhashu32Fnv1a, forKey: .testhashu32Fnv1a) + } + if testhashs64Fnv1a != 0 { + try container.encodeIfPresent(testhashs64Fnv1a, forKey: .testhashs64Fnv1a) + } + if testhashu64Fnv1a != 0 { + try container.encodeIfPresent(testhashu64Fnv1a, forKey: .testhashu64Fnv1a) + } + if testarrayofboolsCount > 0 { + try container.encodeIfPresent(testarrayofbools, forKey: .testarrayofbools) + } + if testf != 3.14159 { + try container.encodeIfPresent(testf, forKey: .testf) + } + if testf2 != 3.0 { + try container.encodeIfPresent(testf2, forKey: .testf2) + } + if testf3 != 0.0 { + try container.encodeIfPresent(testf3, forKey: .testf3) + } + if testarrayofstring2Count > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofstring2) + for index in 0.. 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .testarrayofsortedstruct) + for index in 0.. 0 { + try container.encodeIfPresent(flex, forKey: .flex) + } + if test5Count > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .test5) + for index in 0.. 0 { + try container.encodeIfPresent(vectorOfLongs, forKey: .vectorOfLongs) + } + if vectorOfDoublesCount > 0 { + try container.encodeIfPresent(vectorOfDoubles, forKey: .vectorOfDoubles) + } + try container.encodeIfPresent(parentNamespaceTest, forKey: .parentNamespaceTest) + if vectorOfReferrablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfReferrables) + for index in 0.. 0 { + try container.encodeIfPresent(vectorOfWeakReferences, forKey: .vectorOfWeakReferences) + } + if vectorOfStrongReferrablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfStrongReferrables) + for index in 0.. 0 { + try container.encodeIfPresent(vectorOfCoOwningReferences, forKey: .vectorOfCoOwningReferences) + } + if nonOwningReference != 0 { + try container.encodeIfPresent(nonOwningReference, forKey: .nonOwningReference) + } + if vectorOfNonOwningReferencesCount > 0 { + try container.encodeIfPresent(vectorOfNonOwningReferences, forKey: .vectorOfNonOwningReferences) + } + if anyUniqueType != .none_ { + try container.encodeIfPresent(anyUniqueType, forKey: .anyUniqueType) + } + switch anyUniqueType { + case .m: + let _v = anyUnique(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyUnique) + case .ts: + let _v = anyUnique(type: MyGame_Example_TestSimpleTableWithEnum.self) + try container.encodeIfPresent(_v, forKey: .anyUnique) + case .m2: + let _v = anyUnique(type: MyGame_Example2_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyUnique) + default: break; + } + if anyAmbiguousType != .none_ { + try container.encodeIfPresent(anyAmbiguousType, forKey: .anyAmbiguousType) + } + switch anyAmbiguousType { + case .m1: + let _v = anyAmbiguous(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyAmbiguous) + case .m2: + let _v = anyAmbiguous(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyAmbiguous) + case .m3: + let _v = anyAmbiguous(type: MyGame_Example_Monster.self) + try container.encodeIfPresent(_v, forKey: .anyAmbiguous) + default: break; + } + if vectorOfEnumsCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .vectorOfEnums) + for index in 0.. 0 { + try container.encodeIfPresent(testrequirednestedflatbuffer, forKey: .testrequirednestedflatbuffer) + } + if scalarKeySortedTablesCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .scalarKeySortedTables) + for index in 0.. ByteBuffer { return serialize(type: MyGame_Example_Monster.self) } + +} +public struct MyGame_Example_TypeAliases: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MONS" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: MyGame_Example_TypeAliases.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case i8 = 4 + case u8 = 6 + case i16 = 8 + case u16 = 10 + case i32 = 12 + case u32 = 14 + case i64 = 16 + case u64 = 18 + case f32 = 20 + case f64 = 22 + case v8 = 24 + case vf64 = 26 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var i8: Int8 { let o = _accessor.offset(VTOFFSET.i8.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } + @discardableResult public func mutate(i8: Int8) -> Bool {let o = _accessor.offset(VTOFFSET.i8.v); return _accessor.mutate(i8, index: o) } + public var u8: UInt8 { let o = _accessor.offset(VTOFFSET.u8.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } + @discardableResult public func mutate(u8: UInt8) -> Bool {let o = _accessor.offset(VTOFFSET.u8.v); return _accessor.mutate(u8, index: o) } + public var i16: Int16 { let o = _accessor.offset(VTOFFSET.i16.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } + @discardableResult public func mutate(i16: Int16) -> Bool {let o = _accessor.offset(VTOFFSET.i16.v); return _accessor.mutate(i16, index: o) } + public var u16: UInt16 { let o = _accessor.offset(VTOFFSET.u16.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + @discardableResult public func mutate(u16: UInt16) -> Bool {let o = _accessor.offset(VTOFFSET.u16.v); return _accessor.mutate(u16, index: o) } + public var i32: Int32 { let o = _accessor.offset(VTOFFSET.i32.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(i32: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.i32.v); return _accessor.mutate(i32, index: o) } + public var u32: UInt32 { let o = _accessor.offset(VTOFFSET.u32.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + @discardableResult public func mutate(u32: UInt32) -> Bool {let o = _accessor.offset(VTOFFSET.u32.v); return _accessor.mutate(u32, index: o) } + public var i64: Int64 { let o = _accessor.offset(VTOFFSET.i64.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + @discardableResult public func mutate(i64: Int64) -> Bool {let o = _accessor.offset(VTOFFSET.i64.v); return _accessor.mutate(i64, index: o) } + public var u64: UInt64 { let o = _accessor.offset(VTOFFSET.u64.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + @discardableResult public func mutate(u64: UInt64) -> Bool {let o = _accessor.offset(VTOFFSET.u64.v); return _accessor.mutate(u64, index: o) } + public var f32: Float32 { let o = _accessor.offset(VTOFFSET.f32.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + @discardableResult public func mutate(f32: Float32) -> Bool {let o = _accessor.offset(VTOFFSET.f32.v); return _accessor.mutate(f32, index: o) } + public var f64: Double { let o = _accessor.offset(VTOFFSET.f64.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + @discardableResult public func mutate(f64: Double) -> Bool {let o = _accessor.offset(VTOFFSET.f64.v); return _accessor.mutate(f64, index: o) } + public var hasV8: Bool { let o = _accessor.offset(VTOFFSET.v8.v); return o == 0 ? false : true } + public var v8Count: Int32 { let o = _accessor.offset(VTOFFSET.v8.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func v8(at index: Int32) -> Int8 { let o = _accessor.offset(VTOFFSET.v8.v); return o == 0 ? 0 : _accessor.directRead(of: Int8.self, offset: _accessor.vector(at: o) + index * 1) } + public var v8: [Int8] { return _accessor.getVector(at: VTOFFSET.v8.v) ?? [] } + public func mutate(v8: Int8, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.v8.v); return _accessor.directMutate(v8, index: _accessor.vector(at: o) + index * 1) } + public var hasVf64: Bool { let o = _accessor.offset(VTOFFSET.vf64.v); return o == 0 ? false : true } + public var vf64Count: Int32 { let o = _accessor.offset(VTOFFSET.vf64.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func vf64(at index: Int32) -> Double { let o = _accessor.offset(VTOFFSET.vf64.v); return o == 0 ? 0 : _accessor.directRead(of: Double.self, offset: _accessor.vector(at: o) + index * 8) } + public var vf64: [Double] { return _accessor.getVector(at: VTOFFSET.vf64.v) ?? [] } + public func mutate(vf64: Double, at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.vf64.v); return _accessor.directMutate(vf64, index: _accessor.vector(at: o) + index * 8) } + public static func startTypeAliases(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 12) } + public static func add(i8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i8, def: 0, at: VTOFFSET.i8.p) } + public static func add(u8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u8, def: 0, at: VTOFFSET.u8.p) } + public static func add(i16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i16, def: 0, at: VTOFFSET.i16.p) } + public static func add(u16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u16, def: 0, at: VTOFFSET.u16.p) } + public static func add(i32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i32, def: 0, at: VTOFFSET.i32.p) } + public static func add(u32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u32, def: 0, at: VTOFFSET.u32.p) } + public static func add(i64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: i64, def: 0, at: VTOFFSET.i64.p) } + public static func add(u64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: u64, def: 0, at: VTOFFSET.u64.p) } + public static func add(f32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f32, def: 0.0, at: VTOFFSET.f32.p) } + public static func add(f64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: f64, def: 0.0, at: VTOFFSET.f64.p) } + public static func addVectorOf(v8: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: v8, at: VTOFFSET.v8.p) } + public static func addVectorOf(vf64: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: vf64, at: VTOFFSET.vf64.p) } + public static func endTypeAliases(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createTypeAliases( + _ fbb: inout FlatBufferBuilder, + i8: Int8 = 0, + u8: UInt8 = 0, + i16: Int16 = 0, + u16: UInt16 = 0, + i32: Int32 = 0, + u32: UInt32 = 0, + i64: Int64 = 0, + u64: UInt64 = 0, + f32: Float32 = 0.0, + f64: Double = 0.0, + v8VectorOffset v8: Offset = Offset(), + vf64VectorOffset vf64: Offset = Offset() + ) -> Offset { + let __start = MyGame_Example_TypeAliases.startTypeAliases(&fbb) + MyGame_Example_TypeAliases.add(i8: i8, &fbb) + MyGame_Example_TypeAliases.add(u8: u8, &fbb) + MyGame_Example_TypeAliases.add(i16: i16, &fbb) + MyGame_Example_TypeAliases.add(u16: u16, &fbb) + MyGame_Example_TypeAliases.add(i32: i32, &fbb) + MyGame_Example_TypeAliases.add(u32: u32, &fbb) + MyGame_Example_TypeAliases.add(i64: i64, &fbb) + MyGame_Example_TypeAliases.add(u64: u64, &fbb) + MyGame_Example_TypeAliases.add(f32: f32, &fbb) + MyGame_Example_TypeAliases.add(f64: f64, &fbb) + MyGame_Example_TypeAliases.addVectorOf(v8: v8, &fbb) + MyGame_Example_TypeAliases.addVectorOf(vf64: vf64, &fbb) + return MyGame_Example_TypeAliases.endTypeAliases(&fbb, start: __start) + } + + + public mutating func unpack() -> MyGame_Example_TypeAliasesT { + return MyGame_Example_TypeAliasesT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MyGame_Example_TypeAliasesT) -> Offset { + let __v8 = builder.createVector(obj.v8) + let __vf64 = builder.createVector(obj.vf64) + let __root = MyGame_Example_TypeAliases.startTypeAliases(&builder) + MyGame_Example_TypeAliases.add(i8: obj.i8, &builder) + MyGame_Example_TypeAliases.add(u8: obj.u8, &builder) + MyGame_Example_TypeAliases.add(i16: obj.i16, &builder) + MyGame_Example_TypeAliases.add(u16: obj.u16, &builder) + MyGame_Example_TypeAliases.add(i32: obj.i32, &builder) + MyGame_Example_TypeAliases.add(u32: obj.u32, &builder) + MyGame_Example_TypeAliases.add(i64: obj.i64, &builder) + MyGame_Example_TypeAliases.add(u64: obj.u64, &builder) + MyGame_Example_TypeAliases.add(f32: obj.f32, &builder) + MyGame_Example_TypeAliases.add(f64: obj.f64, &builder) + MyGame_Example_TypeAliases.addVectorOf(v8: __v8, &builder) + MyGame_Example_TypeAliases.addVectorOf(vf64: __vf64, &builder) + return MyGame_Example_TypeAliases.endTypeAliases(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.i8.p, fieldName: "i8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.u8.p, fieldName: "u8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.i16.p, fieldName: "i16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.u16.p, fieldName: "u16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.i32.p, fieldName: "i32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.u32.p, fieldName: "u32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.i64.p, fieldName: "i64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.u64.p, fieldName: "u64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.f32.p, fieldName: "f32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.f64.p, fieldName: "f64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.v8.p, fieldName: "v8", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.vf64.p, fieldName: "vf64", required: false, type: ForwardOffset>.self) + _v.finish() + } +} + +extension MyGame_Example_TypeAliases: Encodable { + + enum CodingKeys: String, CodingKey { + case i8 = "i8" + case u8 = "u8" + case i16 = "i16" + case u16 = "u16" + case i32 = "i32" + case u32 = "u32" + case i64 = "i64" + case u64 = "u64" + case f32 = "f32" + case f64 = "f64" + case v8 = "v8" + case vf64 = "vf64" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if i8 != 0 { + try container.encodeIfPresent(i8, forKey: .i8) + } + if u8 != 0 { + try container.encodeIfPresent(u8, forKey: .u8) + } + if i16 != 0 { + try container.encodeIfPresent(i16, forKey: .i16) + } + if u16 != 0 { + try container.encodeIfPresent(u16, forKey: .u16) + } + if i32 != 0 { + try container.encodeIfPresent(i32, forKey: .i32) + } + if u32 != 0 { + try container.encodeIfPresent(u32, forKey: .u32) + } + if i64 != 0 { + try container.encodeIfPresent(i64, forKey: .i64) + } + if u64 != 0 { + try container.encodeIfPresent(u64, forKey: .u64) + } + if f32 != 0.0 { + try container.encodeIfPresent(f32, forKey: .f32) + } + if f64 != 0.0 { + try container.encodeIfPresent(f64, forKey: .f64) + } + if v8Count > 0 { + try container.encodeIfPresent(v8, forKey: .v8) + } + if vf64Count > 0 { + try container.encodeIfPresent(vf64, forKey: .vf64) + } + } +} + +public class MyGame_Example_TypeAliasesT: NativeObject { + + public var i8: Int8 + public var u8: UInt8 + public var i16: Int16 + public var u16: UInt16 + public var i32: Int32 + public var u32: UInt32 + public var i64: Int64 + public var u64: UInt64 + public var f32: Float32 + public var f64: Double + public var v8: [Int8] + public var vf64: [Double] + + public init(_ _t: inout MyGame_Example_TypeAliases) { + i8 = _t.i8 + u8 = _t.u8 + i16 = _t.i16 + u16 = _t.u16 + i32 = _t.i32 + u32 = _t.u32 + i64 = _t.i64 + u64 = _t.u64 + f32 = _t.f32 + f64 = _t.f64 + v8 = [] + for index in 0..<_t.v8Count { + v8.append(_t.v8(at: index)) + } + vf64 = [] + for index in 0..<_t.vf64Count { + vf64.append(_t.vf64(at: index)) + } + } + + public init() { + i8 = 0 + u8 = 0 + i16 = 0 + u16 = 0 + i32 = 0 + u32 = 0 + i64 = 0 + u64 = 0 + f32 = 0.0 + f64 = 0.0 + v8 = [] + vf64 = [] + } + + public func serialize() -> ByteBuffer { return serialize(type: MyGame_Example_TypeAliases.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/more_defaults_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/more_defaults_generated.swift new file mode 100644 index 00000000000..bdafcf7bdf8 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/more_defaults_generated.swift @@ -0,0 +1,220 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public enum ABC: Int32, Enum, Verifiable { + public typealias T = Int32 + public static var byteSize: Int { return MemoryLayout.size } + public var value: Int32 { return self.rawValue } + case a = 0 + case b = 1 + case c = 2 + + public static var max: ABC { return .c } + public static var min: ABC { return .a } +} + +extension ABC: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .a: try container.encode("A") + case .b: try container.encode("B") + case .c: try container.encode("C") + } + } +} + +public struct MoreDefaults: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case ints = 4 + case floats = 6 + case emptyString = 8 + case someString = 10 + case abcs = 12 + case bools = 14 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var hasInts: Bool { let o = _accessor.offset(VTOFFSET.ints.v); return o == 0 ? false : true } + public var intsCount: Int32 { let o = _accessor.offset(VTOFFSET.ints.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func ints(at index: Int32) -> Int32 { let o = _accessor.offset(VTOFFSET.ints.v); return o == 0 ? 0 : _accessor.directRead(of: Int32.self, offset: _accessor.vector(at: o) + index * 4) } + public var ints: [Int32] { return _accessor.getVector(at: VTOFFSET.ints.v) ?? [] } + public var hasFloats: Bool { let o = _accessor.offset(VTOFFSET.floats.v); return o == 0 ? false : true } + public var floatsCount: Int32 { let o = _accessor.offset(VTOFFSET.floats.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func floats(at index: Int32) -> Float32 { let o = _accessor.offset(VTOFFSET.floats.v); return o == 0 ? 0 : _accessor.directRead(of: Float32.self, offset: _accessor.vector(at: o) + index * 4) } + public var floats: [Float32] { return _accessor.getVector(at: VTOFFSET.floats.v) ?? [] } + public var emptyString: String? { let o = _accessor.offset(VTOFFSET.emptyString.v); return o == 0 ? "" : _accessor.string(at: o) } + public var emptyStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.emptyString.v) } + public var someString: String? { let o = _accessor.offset(VTOFFSET.someString.v); return o == 0 ? "some" : _accessor.string(at: o) } + public var someStringSegmentArray: [UInt8]? { return _accessor.getVector(at: VTOFFSET.someString.v) } + public var hasAbcs: Bool { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? false : true } + public var abcsCount: Int32 { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func abcs(at index: Int32) -> ABC? { let o = _accessor.offset(VTOFFSET.abcs.v); return o == 0 ? ABC.a : ABC(rawValue: _accessor.directRead(of: Int32.self, offset: _accessor.vector(at: o) + index * 4)) } + public var hasBools: Bool { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? false : true } + public var boolsCount: Int32 { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func bools(at index: Int32) -> Bool { let o = _accessor.offset(VTOFFSET.bools.v); return o == 0 ? true : _accessor.directRead(of: Bool.self, offset: _accessor.vector(at: o) + index * 1) } + public var bools: [Bool] { return _accessor.getVector(at: VTOFFSET.bools.v) ?? [] } + public static func startMoreDefaults(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 6) } + public static func addVectorOf(ints: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: ints, at: VTOFFSET.ints.p) } + public static func addVectorOf(floats: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: floats, at: VTOFFSET.floats.p) } + public static func add(emptyString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: emptyString, at: VTOFFSET.emptyString.p) } + public static func add(someString: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: someString, at: VTOFFSET.someString.p) } + public static func addVectorOf(abcs: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: abcs, at: VTOFFSET.abcs.p) } + public static func addVectorOf(bools: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: bools, at: VTOFFSET.bools.p) } + public static func endMoreDefaults(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createMoreDefaults( + _ fbb: inout FlatBufferBuilder, + intsVectorOffset ints: Offset = Offset(), + floatsVectorOffset floats: Offset = Offset(), + emptyStringOffset emptyString: Offset = Offset(), + someStringOffset someString: Offset = Offset(), + abcsVectorOffset abcs: Offset = Offset(), + boolsVectorOffset bools: Offset = Offset() + ) -> Offset { + let __start = MoreDefaults.startMoreDefaults(&fbb) + MoreDefaults.addVectorOf(ints: ints, &fbb) + MoreDefaults.addVectorOf(floats: floats, &fbb) + MoreDefaults.add(emptyString: emptyString, &fbb) + MoreDefaults.add(someString: someString, &fbb) + MoreDefaults.addVectorOf(abcs: abcs, &fbb) + MoreDefaults.addVectorOf(bools: bools, &fbb) + return MoreDefaults.endMoreDefaults(&fbb, start: __start) + } + + + public mutating func unpack() -> MoreDefaultsT { + return MoreDefaultsT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MoreDefaultsT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MoreDefaultsT) -> Offset { + let __ints = builder.createVector(obj.ints) + let __floats = builder.createVector(obj.floats) + let __emptyString: Offset + if let s = obj.emptyString { + __emptyString = builder.create(string: s) + } else { + __emptyString = Offset() + } + + let __someString: Offset + if let s = obj.someString { + __someString = builder.create(string: s) + } else { + __someString = Offset() + } + + let __abcs = builder.createVector(obj.abcs) + let __bools = builder.createVector(obj.bools) + let __root = MoreDefaults.startMoreDefaults(&builder) + MoreDefaults.addVectorOf(ints: __ints, &builder) + MoreDefaults.addVectorOf(floats: __floats, &builder) + MoreDefaults.add(emptyString: __emptyString, &builder) + MoreDefaults.add(someString: __someString, &builder) + MoreDefaults.addVectorOf(abcs: __abcs, &builder) + MoreDefaults.addVectorOf(bools: __bools, &builder) + return MoreDefaults.endMoreDefaults(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.ints.p, fieldName: "ints", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.floats.p, fieldName: "floats", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.emptyString.p, fieldName: "emptyString", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.someString.p, fieldName: "someString", required: false, type: ForwardOffset.self) + try _v.visit(field: VTOFFSET.abcs.p, fieldName: "abcs", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.bools.p, fieldName: "bools", required: false, type: ForwardOffset>.self) + _v.finish() + } +} + +extension MoreDefaults: Encodable { + + enum CodingKeys: String, CodingKey { + case ints = "ints" + case floats = "floats" + case emptyString = "empty_string" + case someString = "some_string" + case abcs = "abcs" + case bools = "bools" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if intsCount > 0 { + try container.encodeIfPresent(ints, forKey: .ints) + } + if floatsCount > 0 { + try container.encodeIfPresent(floats, forKey: .floats) + } + try container.encodeIfPresent(emptyString, forKey: .emptyString) + try container.encodeIfPresent(someString, forKey: .someString) + if abcsCount > 0 { + var contentEncoder = container.nestedUnkeyedContainer(forKey: .abcs) + for index in 0.. 0 { + try container.encodeIfPresent(bools, forKey: .bools) + } + } +} + +public class MoreDefaultsT: NativeObject { + + public var ints: [Int32] + public var floats: [Float32] + public var emptyString: String? + public var someString: String? + public var abcs: [ABC] + public var bools: [Bool] + + public init(_ _t: inout MoreDefaults) { + ints = [] + for index in 0..<_t.intsCount { + ints.append(_t.ints(at: index)) + } + floats = [] + for index in 0..<_t.floatsCount { + floats.append(_t.floats(at: index)) + } + emptyString = _t.emptyString + someString = _t.someString + abcs = [] + for index in 0..<_t.abcsCount { + abcs.append(_t.abcs(at: index)!) + } + bools = [] + for index in 0..<_t.boolsCount { + bools.append(_t.bools(at: index)) + } + } + + public init() { + ints = [] + floats = [] + emptyString = "" + someString = "some" + abcs = [] + bools = [] + } + + public func serialize() -> ByteBuffer { return serialize(type: MoreDefaults.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/nan_inf_test_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/nan_inf_test_generated.swift new file mode 100644 index 00000000000..1efa5160bd3 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/nan_inf_test_generated.swift @@ -0,0 +1,114 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public struct Swift_Tests_NanInfTable: FlatBufferObject, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case defaultNan = 4 + case defaultInf = 6 + case defaultNinf = 8 + case valueNan = 10 + case valueInf = 12 + case valueNinf = 14 + case value = 16 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var defaultNan: Double { let o = _accessor.offset(VTOFFSET.defaultNan.v); return o == 0 ? .nan : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultInf: Double { let o = _accessor.offset(VTOFFSET.defaultInf.v); return o == 0 ? .infinity : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultNinf: Double { let o = _accessor.offset(VTOFFSET.defaultNinf.v); return o == 0 ? -.infinity : _accessor.readBuffer(of: Double.self, at: o) } + public var valueNan: Double { let o = _accessor.offset(VTOFFSET.valueNan.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var valueInf: Double { let o = _accessor.offset(VTOFFSET.valueInf.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var valueNinf: Double { let o = _accessor.offset(VTOFFSET.valueNinf.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var value: Double { let o = _accessor.offset(VTOFFSET.value.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public static func startNanInfTable(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 7) } + public static func add(defaultNan: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultNan, def: .nan, at: VTOFFSET.defaultNan.p) } + public static func add(defaultInf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultInf, def: .infinity, at: VTOFFSET.defaultInf.p) } + public static func add(defaultNinf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultNinf, def: -.infinity, at: VTOFFSET.defaultNinf.p) } + public static func add(valueNan: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueNan, def: 0.0, at: VTOFFSET.valueNan.p) } + public static func add(valueInf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueInf, def: 0.0, at: VTOFFSET.valueInf.p) } + public static func add(valueNinf: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: valueNinf, def: 0.0, at: VTOFFSET.valueNinf.p) } + public static func add(value: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: value, def: 0.0, at: VTOFFSET.value.p) } + public static func endNanInfTable(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createNanInfTable( + _ fbb: inout FlatBufferBuilder, + defaultNan: Double = .nan, + defaultInf: Double = .infinity, + defaultNinf: Double = -.infinity, + valueNan: Double = 0.0, + valueInf: Double = 0.0, + valueNinf: Double = 0.0, + value: Double = 0.0 + ) -> Offset { + let __start = Swift_Tests_NanInfTable.startNanInfTable(&fbb) + Swift_Tests_NanInfTable.add(defaultNan: defaultNan, &fbb) + Swift_Tests_NanInfTable.add(defaultInf: defaultInf, &fbb) + Swift_Tests_NanInfTable.add(defaultNinf: defaultNinf, &fbb) + Swift_Tests_NanInfTable.add(valueNan: valueNan, &fbb) + Swift_Tests_NanInfTable.add(valueInf: valueInf, &fbb) + Swift_Tests_NanInfTable.add(valueNinf: valueNinf, &fbb) + Swift_Tests_NanInfTable.add(value: value, &fbb) + return Swift_Tests_NanInfTable.endNanInfTable(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.defaultNan.p, fieldName: "defaultNan", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultInf.p, fieldName: "defaultInf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultNinf.p, fieldName: "defaultNinf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.valueNan.p, fieldName: "valueNan", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.valueInf.p, fieldName: "valueInf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.valueNinf.p, fieldName: "valueNinf", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.value.p, fieldName: "value", required: false, type: Double.self) + _v.finish() + } +} + +extension Swift_Tests_NanInfTable: Encodable { + + enum CodingKeys: String, CodingKey { + case defaultNan = "default_nan" + case defaultInf = "default_inf" + case defaultNinf = "default_ninf" + case valueNan = "value_nan" + case valueInf = "value_inf" + case valueNinf = "value_ninf" + case value = "value" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if !defaultNan.isNaN { + try container.encodeIfPresent(defaultNan, forKey: .defaultNan) + } + if defaultInf != .infinity { + try container.encodeIfPresent(defaultInf, forKey: .defaultInf) + } + if defaultNinf != -.infinity { + try container.encodeIfPresent(defaultNinf, forKey: .defaultNinf) + } + if valueNan != 0.0 { + try container.encodeIfPresent(valueNan, forKey: .valueNan) + } + if valueInf != 0.0 { + try container.encodeIfPresent(valueInf, forKey: .valueInf) + } + if valueNinf != 0.0 { + try container.encodeIfPresent(valueNinf, forKey: .valueNinf) + } + if value != 0.0 { + try container.encodeIfPresent(value, forKey: .value) + } + } +} + diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift new file mode 100644 index 00000000000..d413e5340f9 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/optional_scalars_generated.swift @@ -0,0 +1,407 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public enum optional_scalars_OptionalByte: Int8, Enum, Verifiable { + public typealias T = Int8 + public static var byteSize: Int { return MemoryLayout.size } + public var value: Int8 { return self.rawValue } + case none_ = 0 + case one = 1 + case two = 2 + + public static var max: optional_scalars_OptionalByte { return .two } + public static var min: optional_scalars_OptionalByte { return .none_ } +} + +extension optional_scalars_OptionalByte: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("None") + case .one: try container.encode("One") + case .two: try container.encode("Two") + } + } +} + +public struct optional_scalars_ScalarStuff: FlatBufferObject, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "NULL" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: optional_scalars_ScalarStuff.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case justI8 = 4 + case maybeI8 = 6 + case defaultI8 = 8 + case justU8 = 10 + case maybeU8 = 12 + case defaultU8 = 14 + case justI16 = 16 + case maybeI16 = 18 + case defaultI16 = 20 + case justU16 = 22 + case maybeU16 = 24 + case defaultU16 = 26 + case justI32 = 28 + case maybeI32 = 30 + case defaultI32 = 32 + case justU32 = 34 + case maybeU32 = 36 + case defaultU32 = 38 + case justI64 = 40 + case maybeI64 = 42 + case defaultI64 = 44 + case justU64 = 46 + case maybeU64 = 48 + case defaultU64 = 50 + case justF32 = 52 + case maybeF32 = 54 + case defaultF32 = 56 + case justF64 = 58 + case maybeF64 = 60 + case defaultF64 = 62 + case justBool = 64 + case maybeBool = 66 + case defaultBool = 68 + case justEnum = 70 + case maybeEnum = 72 + case defaultEnum = 74 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var justI8: Int8 { let o = _accessor.offset(VTOFFSET.justI8.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int8.self, at: o) } + public var maybeI8: Int8? { let o = _accessor.offset(VTOFFSET.maybeI8.v); return o == 0 ? nil : _accessor.readBuffer(of: Int8.self, at: o) } + public var defaultI8: Int8 { let o = _accessor.offset(VTOFFSET.defaultI8.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int8.self, at: o) } + public var justU8: UInt8 { let o = _accessor.offset(VTOFFSET.justU8.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt8.self, at: o) } + public var maybeU8: UInt8? { let o = _accessor.offset(VTOFFSET.maybeU8.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt8.self, at: o) } + public var defaultU8: UInt8 { let o = _accessor.offset(VTOFFSET.defaultU8.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt8.self, at: o) } + public var justI16: Int16 { let o = _accessor.offset(VTOFFSET.justI16.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int16.self, at: o) } + public var maybeI16: Int16? { let o = _accessor.offset(VTOFFSET.maybeI16.v); return o == 0 ? nil : _accessor.readBuffer(of: Int16.self, at: o) } + public var defaultI16: Int16 { let o = _accessor.offset(VTOFFSET.defaultI16.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int16.self, at: o) } + public var justU16: UInt16 { let o = _accessor.offset(VTOFFSET.justU16.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt16.self, at: o) } + public var maybeU16: UInt16? { let o = _accessor.offset(VTOFFSET.maybeU16.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt16.self, at: o) } + public var defaultU16: UInt16 { let o = _accessor.offset(VTOFFSET.defaultU16.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt16.self, at: o) } + public var justI32: Int32 { let o = _accessor.offset(VTOFFSET.justI32.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + public var maybeI32: Int32? { let o = _accessor.offset(VTOFFSET.maybeI32.v); return o == 0 ? nil : _accessor.readBuffer(of: Int32.self, at: o) } + public var defaultI32: Int32 { let o = _accessor.offset(VTOFFSET.defaultI32.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int32.self, at: o) } + public var justU32: UInt32 { let o = _accessor.offset(VTOFFSET.justU32.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt32.self, at: o) } + public var maybeU32: UInt32? { let o = _accessor.offset(VTOFFSET.maybeU32.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt32.self, at: o) } + public var defaultU32: UInt32 { let o = _accessor.offset(VTOFFSET.defaultU32.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt32.self, at: o) } + public var justI64: Int64 { let o = _accessor.offset(VTOFFSET.justI64.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int64.self, at: o) } + public var maybeI64: Int64? { let o = _accessor.offset(VTOFFSET.maybeI64.v); return o == 0 ? nil : _accessor.readBuffer(of: Int64.self, at: o) } + public var defaultI64: Int64 { let o = _accessor.offset(VTOFFSET.defaultI64.v); return o == 0 ? 42 : _accessor.readBuffer(of: Int64.self, at: o) } + public var justU64: UInt64 { let o = _accessor.offset(VTOFFSET.justU64.v); return o == 0 ? 0 : _accessor.readBuffer(of: UInt64.self, at: o) } + public var maybeU64: UInt64? { let o = _accessor.offset(VTOFFSET.maybeU64.v); return o == 0 ? nil : _accessor.readBuffer(of: UInt64.self, at: o) } + public var defaultU64: UInt64 { let o = _accessor.offset(VTOFFSET.defaultU64.v); return o == 0 ? 42 : _accessor.readBuffer(of: UInt64.self, at: o) } + public var justF32: Float32 { let o = _accessor.offset(VTOFFSET.justF32.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Float32.self, at: o) } + public var maybeF32: Float32? { let o = _accessor.offset(VTOFFSET.maybeF32.v); return o == 0 ? nil : _accessor.readBuffer(of: Float32.self, at: o) } + public var defaultF32: Float32 { let o = _accessor.offset(VTOFFSET.defaultF32.v); return o == 0 ? 42.0 : _accessor.readBuffer(of: Float32.self, at: o) } + public var justF64: Double { let o = _accessor.offset(VTOFFSET.justF64.v); return o == 0 ? 0.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var maybeF64: Double? { let o = _accessor.offset(VTOFFSET.maybeF64.v); return o == 0 ? nil : _accessor.readBuffer(of: Double.self, at: o) } + public var defaultF64: Double { let o = _accessor.offset(VTOFFSET.defaultF64.v); return o == 0 ? 42.0 : _accessor.readBuffer(of: Double.self, at: o) } + public var justBool: Bool { let o = _accessor.offset(VTOFFSET.justBool.v); return o == 0 ? false : _accessor.readBuffer(of: Bool.self, at: o) } + public var maybeBool: Bool? { let o = _accessor.offset(VTOFFSET.maybeBool.v); return o == 0 ? nil : _accessor.readBuffer(of: Bool.self, at: o) } + public var defaultBool: Bool { let o = _accessor.offset(VTOFFSET.defaultBool.v); return o == 0 ? true : _accessor.readBuffer(of: Bool.self, at: o) } + public var justEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VTOFFSET.justEnum.v); return o == 0 ? .none_ : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .none_ } + public var maybeEnum: optional_scalars_OptionalByte? { let o = _accessor.offset(VTOFFSET.maybeEnum.v); return o == 0 ? nil : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? nil } + public var defaultEnum: optional_scalars_OptionalByte { let o = _accessor.offset(VTOFFSET.defaultEnum.v); return o == 0 ? .one : optional_scalars_OptionalByte(rawValue: _accessor.readBuffer(of: Int8.self, at: o)) ?? .one } + public static func startScalarStuff(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 36) } + public static func add(justI8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI8, def: 0, at: VTOFFSET.justI8.p) } + public static func add(maybeI8: Int8?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI8, at: VTOFFSET.maybeI8.p) } + public static func add(defaultI8: Int8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI8, def: 42, at: VTOFFSET.defaultI8.p) } + public static func add(justU8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU8, def: 0, at: VTOFFSET.justU8.p) } + public static func add(maybeU8: UInt8?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU8, at: VTOFFSET.maybeU8.p) } + public static func add(defaultU8: UInt8, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU8, def: 42, at: VTOFFSET.defaultU8.p) } + public static func add(justI16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI16, def: 0, at: VTOFFSET.justI16.p) } + public static func add(maybeI16: Int16?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI16, at: VTOFFSET.maybeI16.p) } + public static func add(defaultI16: Int16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI16, def: 42, at: VTOFFSET.defaultI16.p) } + public static func add(justU16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU16, def: 0, at: VTOFFSET.justU16.p) } + public static func add(maybeU16: UInt16?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU16, at: VTOFFSET.maybeU16.p) } + public static func add(defaultU16: UInt16, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU16, def: 42, at: VTOFFSET.defaultU16.p) } + public static func add(justI32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI32, def: 0, at: VTOFFSET.justI32.p) } + public static func add(maybeI32: Int32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI32, at: VTOFFSET.maybeI32.p) } + public static func add(defaultI32: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI32, def: 42, at: VTOFFSET.defaultI32.p) } + public static func add(justU32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU32, def: 0, at: VTOFFSET.justU32.p) } + public static func add(maybeU32: UInt32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU32, at: VTOFFSET.maybeU32.p) } + public static func add(defaultU32: UInt32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU32, def: 42, at: VTOFFSET.defaultU32.p) } + public static func add(justI64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justI64, def: 0, at: VTOFFSET.justI64.p) } + public static func add(maybeI64: Int64?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeI64, at: VTOFFSET.maybeI64.p) } + public static func add(defaultI64: Int64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultI64, def: 42, at: VTOFFSET.defaultI64.p) } + public static func add(justU64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justU64, def: 0, at: VTOFFSET.justU64.p) } + public static func add(maybeU64: UInt64?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeU64, at: VTOFFSET.maybeU64.p) } + public static func add(defaultU64: UInt64, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultU64, def: 42, at: VTOFFSET.defaultU64.p) } + public static func add(justF32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justF32, def: 0.0, at: VTOFFSET.justF32.p) } + public static func add(maybeF32: Float32?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeF32, at: VTOFFSET.maybeF32.p) } + public static func add(defaultF32: Float32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultF32, def: 42.0, at: VTOFFSET.defaultF32.p) } + public static func add(justF64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justF64, def: 0.0, at: VTOFFSET.justF64.p) } + public static func add(maybeF64: Double?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeF64, at: VTOFFSET.maybeF64.p) } + public static func add(defaultF64: Double, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultF64, def: 42.0, at: VTOFFSET.defaultF64.p) } + public static func add(justBool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justBool, def: false, + at: VTOFFSET.justBool.p) } + public static func add(maybeBool: Bool?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeBool, at: VTOFFSET.maybeBool.p) } + public static func add(defaultBool: Bool, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultBool, def: true, + at: VTOFFSET.defaultBool.p) } + public static func add(justEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: justEnum.rawValue, def: 0, at: VTOFFSET.justEnum.p) } + public static func add(maybeEnum: optional_scalars_OptionalByte?, _ fbb: inout FlatBufferBuilder) { fbb.add(element: maybeEnum?.rawValue, at: VTOFFSET.maybeEnum.p) } + public static func add(defaultEnum: optional_scalars_OptionalByte, _ fbb: inout FlatBufferBuilder) { fbb.add(element: defaultEnum.rawValue, def: 1, at: VTOFFSET.defaultEnum.p) } + public static func endScalarStuff(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createScalarStuff( + _ fbb: inout FlatBufferBuilder, + justI8: Int8 = 0, + maybeI8: Int8? = nil, + defaultI8: Int8 = 42, + justU8: UInt8 = 0, + maybeU8: UInt8? = nil, + defaultU8: UInt8 = 42, + justI16: Int16 = 0, + maybeI16: Int16? = nil, + defaultI16: Int16 = 42, + justU16: UInt16 = 0, + maybeU16: UInt16? = nil, + defaultU16: UInt16 = 42, + justI32: Int32 = 0, + maybeI32: Int32? = nil, + defaultI32: Int32 = 42, + justU32: UInt32 = 0, + maybeU32: UInt32? = nil, + defaultU32: UInt32 = 42, + justI64: Int64 = 0, + maybeI64: Int64? = nil, + defaultI64: Int64 = 42, + justU64: UInt64 = 0, + maybeU64: UInt64? = nil, + defaultU64: UInt64 = 42, + justF32: Float32 = 0.0, + maybeF32: Float32? = nil, + defaultF32: Float32 = 42.0, + justF64: Double = 0.0, + maybeF64: Double? = nil, + defaultF64: Double = 42.0, + justBool: Bool = false, + maybeBool: Bool? = nil, + defaultBool: Bool = true, + justEnum: optional_scalars_OptionalByte = .none_, + maybeEnum: optional_scalars_OptionalByte? = nil, + defaultEnum: optional_scalars_OptionalByte = .one + ) -> Offset { + let __start = optional_scalars_ScalarStuff.startScalarStuff(&fbb) + optional_scalars_ScalarStuff.add(justI8: justI8, &fbb) + optional_scalars_ScalarStuff.add(maybeI8: maybeI8, &fbb) + optional_scalars_ScalarStuff.add(defaultI8: defaultI8, &fbb) + optional_scalars_ScalarStuff.add(justU8: justU8, &fbb) + optional_scalars_ScalarStuff.add(maybeU8: maybeU8, &fbb) + optional_scalars_ScalarStuff.add(defaultU8: defaultU8, &fbb) + optional_scalars_ScalarStuff.add(justI16: justI16, &fbb) + optional_scalars_ScalarStuff.add(maybeI16: maybeI16, &fbb) + optional_scalars_ScalarStuff.add(defaultI16: defaultI16, &fbb) + optional_scalars_ScalarStuff.add(justU16: justU16, &fbb) + optional_scalars_ScalarStuff.add(maybeU16: maybeU16, &fbb) + optional_scalars_ScalarStuff.add(defaultU16: defaultU16, &fbb) + optional_scalars_ScalarStuff.add(justI32: justI32, &fbb) + optional_scalars_ScalarStuff.add(maybeI32: maybeI32, &fbb) + optional_scalars_ScalarStuff.add(defaultI32: defaultI32, &fbb) + optional_scalars_ScalarStuff.add(justU32: justU32, &fbb) + optional_scalars_ScalarStuff.add(maybeU32: maybeU32, &fbb) + optional_scalars_ScalarStuff.add(defaultU32: defaultU32, &fbb) + optional_scalars_ScalarStuff.add(justI64: justI64, &fbb) + optional_scalars_ScalarStuff.add(maybeI64: maybeI64, &fbb) + optional_scalars_ScalarStuff.add(defaultI64: defaultI64, &fbb) + optional_scalars_ScalarStuff.add(justU64: justU64, &fbb) + optional_scalars_ScalarStuff.add(maybeU64: maybeU64, &fbb) + optional_scalars_ScalarStuff.add(defaultU64: defaultU64, &fbb) + optional_scalars_ScalarStuff.add(justF32: justF32, &fbb) + optional_scalars_ScalarStuff.add(maybeF32: maybeF32, &fbb) + optional_scalars_ScalarStuff.add(defaultF32: defaultF32, &fbb) + optional_scalars_ScalarStuff.add(justF64: justF64, &fbb) + optional_scalars_ScalarStuff.add(maybeF64: maybeF64, &fbb) + optional_scalars_ScalarStuff.add(defaultF64: defaultF64, &fbb) + optional_scalars_ScalarStuff.add(justBool: justBool, &fbb) + optional_scalars_ScalarStuff.add(maybeBool: maybeBool, &fbb) + optional_scalars_ScalarStuff.add(defaultBool: defaultBool, &fbb) + optional_scalars_ScalarStuff.add(justEnum: justEnum, &fbb) + optional_scalars_ScalarStuff.add(maybeEnum: maybeEnum, &fbb) + optional_scalars_ScalarStuff.add(defaultEnum: defaultEnum, &fbb) + return optional_scalars_ScalarStuff.endScalarStuff(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.justI8.p, fieldName: "justI8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.maybeI8.p, fieldName: "maybeI8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.defaultI8.p, fieldName: "defaultI8", required: false, type: Int8.self) + try _v.visit(field: VTOFFSET.justU8.p, fieldName: "justU8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.maybeU8.p, fieldName: "maybeU8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.defaultU8.p, fieldName: "defaultU8", required: false, type: UInt8.self) + try _v.visit(field: VTOFFSET.justI16.p, fieldName: "justI16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.maybeI16.p, fieldName: "maybeI16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.defaultI16.p, fieldName: "defaultI16", required: false, type: Int16.self) + try _v.visit(field: VTOFFSET.justU16.p, fieldName: "justU16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.maybeU16.p, fieldName: "maybeU16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.defaultU16.p, fieldName: "defaultU16", required: false, type: UInt16.self) + try _v.visit(field: VTOFFSET.justI32.p, fieldName: "justI32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.maybeI32.p, fieldName: "maybeI32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.defaultI32.p, fieldName: "defaultI32", required: false, type: Int32.self) + try _v.visit(field: VTOFFSET.justU32.p, fieldName: "justU32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.maybeU32.p, fieldName: "maybeU32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.defaultU32.p, fieldName: "defaultU32", required: false, type: UInt32.self) + try _v.visit(field: VTOFFSET.justI64.p, fieldName: "justI64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.maybeI64.p, fieldName: "maybeI64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.defaultI64.p, fieldName: "defaultI64", required: false, type: Int64.self) + try _v.visit(field: VTOFFSET.justU64.p, fieldName: "justU64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.maybeU64.p, fieldName: "maybeU64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.defaultU64.p, fieldName: "defaultU64", required: false, type: UInt64.self) + try _v.visit(field: VTOFFSET.justF32.p, fieldName: "justF32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.maybeF32.p, fieldName: "maybeF32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.defaultF32.p, fieldName: "defaultF32", required: false, type: Float32.self) + try _v.visit(field: VTOFFSET.justF64.p, fieldName: "justF64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.maybeF64.p, fieldName: "maybeF64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.defaultF64.p, fieldName: "defaultF64", required: false, type: Double.self) + try _v.visit(field: VTOFFSET.justBool.p, fieldName: "justBool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.maybeBool.p, fieldName: "maybeBool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.defaultBool.p, fieldName: "defaultBool", required: false, type: Bool.self) + try _v.visit(field: VTOFFSET.justEnum.p, fieldName: "justEnum", required: false, type: optional_scalars_OptionalByte.self) + try _v.visit(field: VTOFFSET.maybeEnum.p, fieldName: "maybeEnum", required: false, type: optional_scalars_OptionalByte.self) + try _v.visit(field: VTOFFSET.defaultEnum.p, fieldName: "defaultEnum", required: false, type: optional_scalars_OptionalByte.self) + _v.finish() + } +} + +extension optional_scalars_ScalarStuff: Encodable { + + enum CodingKeys: String, CodingKey { + case justI8 = "just_i8" + case maybeI8 = "maybe_i8" + case defaultI8 = "default_i8" + case justU8 = "just_u8" + case maybeU8 = "maybe_u8" + case defaultU8 = "default_u8" + case justI16 = "just_i16" + case maybeI16 = "maybe_i16" + case defaultI16 = "default_i16" + case justU16 = "just_u16" + case maybeU16 = "maybe_u16" + case defaultU16 = "default_u16" + case justI32 = "just_i32" + case maybeI32 = "maybe_i32" + case defaultI32 = "default_i32" + case justU32 = "just_u32" + case maybeU32 = "maybe_u32" + case defaultU32 = "default_u32" + case justI64 = "just_i64" + case maybeI64 = "maybe_i64" + case defaultI64 = "default_i64" + case justU64 = "just_u64" + case maybeU64 = "maybe_u64" + case defaultU64 = "default_u64" + case justF32 = "just_f32" + case maybeF32 = "maybe_f32" + case defaultF32 = "default_f32" + case justF64 = "just_f64" + case maybeF64 = "maybe_f64" + case defaultF64 = "default_f64" + case justBool = "just_bool" + case maybeBool = "maybe_bool" + case defaultBool = "default_bool" + case justEnum = "just_enum" + case maybeEnum = "maybe_enum" + case defaultEnum = "default_enum" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if justI8 != 0 { + try container.encodeIfPresent(justI8, forKey: .justI8) + } + try container.encodeIfPresent(maybeI8, forKey: .maybeI8) + if defaultI8 != 42 { + try container.encodeIfPresent(defaultI8, forKey: .defaultI8) + } + if justU8 != 0 { + try container.encodeIfPresent(justU8, forKey: .justU8) + } + try container.encodeIfPresent(maybeU8, forKey: .maybeU8) + if defaultU8 != 42 { + try container.encodeIfPresent(defaultU8, forKey: .defaultU8) + } + if justI16 != 0 { + try container.encodeIfPresent(justI16, forKey: .justI16) + } + try container.encodeIfPresent(maybeI16, forKey: .maybeI16) + if defaultI16 != 42 { + try container.encodeIfPresent(defaultI16, forKey: .defaultI16) + } + if justU16 != 0 { + try container.encodeIfPresent(justU16, forKey: .justU16) + } + try container.encodeIfPresent(maybeU16, forKey: .maybeU16) + if defaultU16 != 42 { + try container.encodeIfPresent(defaultU16, forKey: .defaultU16) + } + if justI32 != 0 { + try container.encodeIfPresent(justI32, forKey: .justI32) + } + try container.encodeIfPresent(maybeI32, forKey: .maybeI32) + if defaultI32 != 42 { + try container.encodeIfPresent(defaultI32, forKey: .defaultI32) + } + if justU32 != 0 { + try container.encodeIfPresent(justU32, forKey: .justU32) + } + try container.encodeIfPresent(maybeU32, forKey: .maybeU32) + if defaultU32 != 42 { + try container.encodeIfPresent(defaultU32, forKey: .defaultU32) + } + if justI64 != 0 { + try container.encodeIfPresent(justI64, forKey: .justI64) + } + try container.encodeIfPresent(maybeI64, forKey: .maybeI64) + if defaultI64 != 42 { + try container.encodeIfPresent(defaultI64, forKey: .defaultI64) + } + if justU64 != 0 { + try container.encodeIfPresent(justU64, forKey: .justU64) + } + try container.encodeIfPresent(maybeU64, forKey: .maybeU64) + if defaultU64 != 42 { + try container.encodeIfPresent(defaultU64, forKey: .defaultU64) + } + if justF32 != 0.0 { + try container.encodeIfPresent(justF32, forKey: .justF32) + } + try container.encodeIfPresent(maybeF32, forKey: .maybeF32) + if defaultF32 != 42.0 { + try container.encodeIfPresent(defaultF32, forKey: .defaultF32) + } + if justF64 != 0.0 { + try container.encodeIfPresent(justF64, forKey: .justF64) + } + try container.encodeIfPresent(maybeF64, forKey: .maybeF64) + if defaultF64 != 42.0 { + try container.encodeIfPresent(defaultF64, forKey: .defaultF64) + } + if justBool != false { + try container.encodeIfPresent(justBool, forKey: .justBool) + } + try container.encodeIfPresent(maybeBool, forKey: .maybeBool) + if defaultBool != true { + try container.encodeIfPresent(defaultBool, forKey: .defaultBool) + } + if justEnum != .none_ { + try container.encodeIfPresent(justEnum, forKey: .justEnum) + } + try container.encodeIfPresent(maybeEnum, forKey: .maybeEnum) + if defaultEnum != .one { + try container.encodeIfPresent(defaultEnum, forKey: .defaultEnum) + } + } +} + diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift new file mode 100644 index 00000000000..6574c665213 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/union_vector_generated.swift @@ -0,0 +1,732 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public enum Character: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case mulan = 1 + case rapunzel = 2 + case belle = 3 + case bookfan = 4 + case other = 5 + case unused = 6 + + public static var max: Character { return .unused } + public static var min: Character { return .none_ } +} + +extension Character: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .mulan: try container.encode("MuLan") + case .rapunzel: try container.encode("Rapunzel") + case .belle: try container.encode("Belle") + case .bookfan: try container.encode("BookFan") + case .other: try container.encode("Other") + case .unused: try container.encode("Unused") + } + } +} + +public struct CharacterUnion { + public var type: Character + public var value: NativeObject? + public init(_ v: NativeObject?, type: Character) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .mulan: + var __obj = value as? AttackerT + return Attacker.pack(&builder, obj: &__obj) + case .rapunzel: + var __obj = value as? Rapunzel + return Rapunzel_Mutable.pack(&builder, obj: &__obj) + case .belle: + var __obj = value as? BookReader + return BookReader_Mutable.pack(&builder, obj: &__obj) + case .bookfan: + var __obj = value as? BookReader + return BookReader_Mutable.pack(&builder, obj: &__obj) + case .other: + var __obj = value as? String + return String.pack(&builder, obj: &__obj) + case .unused: + var __obj = value as? String + return String.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public enum Gadget: UInt8, UnionEnum { + public typealias T = UInt8 + + public init?(value: T) { + self.init(rawValue: value) + } + + public static var byteSize: Int { return MemoryLayout.size } + public var value: UInt8 { return self.rawValue } + case none_ = 0 + case fallingtub = 1 + case handfan = 2 + + public static var max: Gadget { return .handfan } + public static var min: Gadget { return .none_ } +} + +extension Gadget: Encodable { + public func encode(to encoder: Encoder) throws { + var container = encoder.singleValueContainer() + switch self { + case .none_: try container.encode("NONE") + case .fallingtub: try container.encode("FallingTub") + case .handfan: try container.encode("HandFan") + } + } +} + +public struct GadgetUnion { + public var type: Gadget + public var value: NativeObject? + public init(_ v: NativeObject?, type: Gadget) { + self.type = type + self.value = v + } + public func pack(builder: inout FlatBufferBuilder) -> Offset { + switch type { + case .fallingtub: + var __obj = value as? FallingTub + return FallingTub_Mutable.pack(&builder, obj: &__obj) + case .handfan: + var __obj = value as? HandFanT + return HandFan.pack(&builder, obj: &__obj) + default: return Offset() + } + } +} +public struct Rapunzel: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _hairLength: Int32 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _hairLength = _accessor.readBuffer(of: Int32.self, at: 0) + } + + public init(hairLength: Int32) { + _hairLength = hairLength + } + + public init() { + _hairLength = 0 + } + + public init(_ _t: inout Rapunzel_Mutable) { + _hairLength = _t.hairLength + } + + public var hairLength: Int32 { _hairLength } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: Rapunzel.self) + } +} + +extension Rapunzel: Encodable { + + enum CodingKeys: String, CodingKey { + case hairLength = "hair_length" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if hairLength != 0 { + try container.encodeIfPresent(hairLength, forKey: .hairLength) + } + } +} + +public struct Rapunzel_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var hairLength: Int32 { return _accessor.readBuffer(of: Int32.self, at: 0) } + @discardableResult public func mutate(hairLength: Int32) -> Bool { return _accessor.mutate(hairLength, index: 0) } + + + public mutating func unpack() -> Rapunzel { + return Rapunzel(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Rapunzel?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout Rapunzel) -> Offset { + return builder.create(struct: obj) + } +} + +public struct BookReader: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _booksRead: Int32 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _booksRead = _accessor.readBuffer(of: Int32.self, at: 0) + } + + public init(booksRead: Int32) { + _booksRead = booksRead + } + + public init() { + _booksRead = 0 + } + + public init(_ _t: inout BookReader_Mutable) { + _booksRead = _t.booksRead + } + + public var booksRead: Int32 { _booksRead } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: BookReader.self) + } +} + +extension BookReader: Encodable { + + enum CodingKeys: String, CodingKey { + case booksRead = "books_read" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if booksRead != 0 { + try container.encodeIfPresent(booksRead, forKey: .booksRead) + } + } +} + +public struct BookReader_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var booksRead: Int32 { return _accessor.readBuffer(of: Int32.self, at: 0) } + @discardableResult public func mutate(booksRead: Int32) -> Bool { return _accessor.mutate(booksRead, index: 0) } + + + public mutating func unpack() -> BookReader { + return BookReader(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReader?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout BookReader) -> Offset { + return builder.create(struct: obj) + } +} + +public struct FallingTub: NativeStruct, Verifiable, FlatbuffersInitializable, NativeObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + + private var _weight: Int32 + + public init(_ bb: ByteBuffer, o: Int32) { + let _accessor = Struct(bb: bb, position: o) + _weight = _accessor.readBuffer(of: Int32.self, at: 0) + } + + public init(weight: Int32) { + _weight = weight + } + + public init() { + _weight = 0 + } + + public init(_ _t: inout FallingTub_Mutable) { + _weight = _t.weight + } + + public var weight: Int32 { _weight } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + try verifier.inBuffer(position: position, of: FallingTub.self) + } +} + +extension FallingTub: Encodable { + + enum CodingKeys: String, CodingKey { + case weight = "weight" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if weight != 0 { + try container.encodeIfPresent(weight, forKey: .weight) + } + } +} + +public struct FallingTub_Mutable: FlatBufferObject { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Struct + + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Struct(bb: bb, position: o) } + + public var weight: Int32 { return _accessor.readBuffer(of: Int32.self, at: 0) } + @discardableResult public func mutate(weight: Int32) -> Bool { return _accessor.mutate(weight, index: 0) } + + + public mutating func unpack() -> FallingTub { + return FallingTub(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout FallingTub?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout FallingTub) -> Offset { + return builder.create(struct: obj) + } +} + +public struct Attacker: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MOVI" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: Attacker.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case swordAttackDamage = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var swordAttackDamage: Int32 { let o = _accessor.offset(VTOFFSET.swordAttackDamage.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(swordAttackDamage: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.swordAttackDamage.v); return _accessor.mutate(swordAttackDamage, index: o) } + public static func startAttacker(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(swordAttackDamage: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: swordAttackDamage, def: 0, at: VTOFFSET.swordAttackDamage.p) } + public static func endAttacker(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createAttacker( + _ fbb: inout FlatBufferBuilder, + swordAttackDamage: Int32 = 0 + ) -> Offset { + let __start = Attacker.startAttacker(&fbb) + Attacker.add(swordAttackDamage: swordAttackDamage, &fbb) + return Attacker.endAttacker(&fbb, start: __start) + } + + + public mutating func unpack() -> AttackerT { + return AttackerT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout AttackerT) -> Offset { + let __root = Attacker.startAttacker(&builder) + Attacker.add(swordAttackDamage: obj.swordAttackDamage, &builder) + return Attacker.endAttacker(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.swordAttackDamage.p, fieldName: "swordAttackDamage", required: false, type: Int32.self) + _v.finish() + } +} + +extension Attacker: Encodable { + + enum CodingKeys: String, CodingKey { + case swordAttackDamage = "sword_attack_damage" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if swordAttackDamage != 0 { + try container.encodeIfPresent(swordAttackDamage, forKey: .swordAttackDamage) + } + } +} + +public class AttackerT: NativeObject { + + public var swordAttackDamage: Int32 + + public init(_ _t: inout Attacker) { + swordAttackDamage = _t.swordAttackDamage + } + + public init() { + swordAttackDamage = 0 + } + + public func serialize() -> ByteBuffer { return serialize(type: Attacker.self) } + +} +public struct HandFan: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MOVI" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: HandFan.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case length = 4 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var length: Int32 { let o = _accessor.offset(VTOFFSET.length.v); return o == 0 ? 0 : _accessor.readBuffer(of: Int32.self, at: o) } + @discardableResult public func mutate(length: Int32) -> Bool {let o = _accessor.offset(VTOFFSET.length.v); return _accessor.mutate(length, index: o) } + public static func startHandFan(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 1) } + public static func add(length: Int32, _ fbb: inout FlatBufferBuilder) { fbb.add(element: length, def: 0, at: VTOFFSET.length.p) } + public static func endHandFan(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createHandFan( + _ fbb: inout FlatBufferBuilder, + length: Int32 = 0 + ) -> Offset { + let __start = HandFan.startHandFan(&fbb) + HandFan.add(length: length, &fbb) + return HandFan.endHandFan(&fbb, start: __start) + } + + + public mutating func unpack() -> HandFanT { + return HandFanT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout HandFanT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout HandFanT) -> Offset { + let __root = HandFan.startHandFan(&builder) + HandFan.add(length: obj.length, &builder) + return HandFan.endHandFan(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.length.p, fieldName: "length", required: false, type: Int32.self) + _v.finish() + } +} + +extension HandFan: Encodable { + + enum CodingKeys: String, CodingKey { + case length = "length" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if length != 0 { + try container.encodeIfPresent(length, forKey: .length) + } + } +} + +public class HandFanT: NativeObject { + + public var length: Int32 + + public init(_ _t: inout HandFan) { + length = _t.length + } + + public init() { + length = 0 + } + + public func serialize() -> ByteBuffer { return serialize(type: HandFan.self) } + +} +public struct Movie: FlatBufferObject, Verifiable, ObjectAPIPacker { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + public static var id: String { "MOVI" } + public static func finish(_ fbb: inout FlatBufferBuilder, end: Offset, prefix: Bool = false) { fbb.finish(offset: end, fileId: Movie.id, addPrefix: prefix) } + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case mainCharacterType = 4 + case mainCharacter = 6 + case charactersType = 8 + case characters = 10 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var mainCharacterType: Character { let o = _accessor.offset(VTOFFSET.mainCharacterType.v); return o == 0 ? .none_ : Character(rawValue: _accessor.readBuffer(of: UInt8.self, at: o)) ?? .none_ } + public func mainCharacter(type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.mainCharacter.v); return o == 0 ? nil : _accessor.union(o) } + public var hasCharactersType: Bool { let o = _accessor.offset(VTOFFSET.charactersType.v); return o == 0 ? false : true } + public var charactersTypeCount: Int32 { let o = _accessor.offset(VTOFFSET.charactersType.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func charactersType(at index: Int32) -> Character? { let o = _accessor.offset(VTOFFSET.charactersType.v); return o == 0 ? Character.none_ : Character(rawValue: _accessor.directRead(of: UInt8.self, offset: _accessor.vector(at: o) + index * 1)) } + public var hasCharacters: Bool { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? false : true } + public var charactersCount: Int32 { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func characters(at index: Int32, type: T.Type) -> T? { let o = _accessor.offset(VTOFFSET.characters.v); return o == 0 ? nil : _accessor.directUnion(_accessor.vector(at: o) + index * 4) } + public static func startMovie(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 4) } + public static func add(mainCharacterType: Character, _ fbb: inout FlatBufferBuilder) { fbb.add(element: mainCharacterType.rawValue, def: 0, at: VTOFFSET.mainCharacterType.p) } + public static func add(mainCharacter: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: mainCharacter, at: VTOFFSET.mainCharacter.p) } + public static func addVectorOf(charactersType: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: charactersType, at: VTOFFSET.charactersType.p) } + public static func addVectorOf(characters: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: characters, at: VTOFFSET.characters.p) } + public static func endMovie(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createMovie( + _ fbb: inout FlatBufferBuilder, + mainCharacterType: Character = .none_, + mainCharacterOffset mainCharacter: Offset = Offset(), + charactersTypeVectorOffset charactersType: Offset = Offset(), + charactersVectorOffset characters: Offset = Offset() + ) -> Offset { + let __start = Movie.startMovie(&fbb) + Movie.add(mainCharacterType: mainCharacterType, &fbb) + Movie.add(mainCharacter: mainCharacter, &fbb) + Movie.addVectorOf(charactersType: charactersType, &fbb) + Movie.addVectorOf(characters: characters, &fbb) + return Movie.endMovie(&fbb, start: __start) + } + + + public mutating func unpack() -> MovieT { + return MovieT(&self) + } + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT?) -> Offset { + guard var obj = obj else { return Offset() } + return pack(&builder, obj: &obj) + } + + public static func pack(_ builder: inout FlatBufferBuilder, obj: inout MovieT) -> Offset { + let __mainCharacter = obj.mainCharacter?.pack(builder: &builder) ?? Offset() + var __characters__: [Offset] = [] + for i in obj.characters { + guard let off = i?.pack(builder: &builder) else { continue } + __characters__.append(off) + } + let __characters = builder.createVector(ofOffsets: __characters__) + let __charactersType = builder.createVector(obj.characters.compactMap { $0?.type }) + let __root = Movie.startMovie(&builder) + if let o = obj.mainCharacter?.type { + Movie.add(mainCharacterType: o, &builder) + Movie.add(mainCharacter: __mainCharacter, &builder) + } + + Movie.addVectorOf(charactersType: __charactersType, &builder) + Movie.addVectorOf(characters: __characters, &builder) + return Movie.endMovie(&builder, start: __root) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(unionKey: VTOFFSET.mainCharacterType.p, unionField: VTOFFSET.mainCharacter.p, unionKeyName: "mainCharacterType", fieldName: "mainCharacter", required: false, completion: { (verifier, key: Character, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .mulan: + try ForwardOffset.verify(&verifier, at: pos, of: Attacker.self) + case .rapunzel: + try Rapunzel.verify(&verifier, at: pos, of: Rapunzel.self) + case .belle: + try BookReader.verify(&verifier, at: pos, of: BookReader.self) + case .bookfan: + try BookReader.verify(&verifier, at: pos, of: BookReader.self) + case .other: + try ForwardOffset.verify(&verifier, at: pos, of: String.self) + case .unused: + try ForwardOffset.verify(&verifier, at: pos, of: String.self) + } + }) + try _v.visitUnionVector(unionKey: VTOFFSET.charactersType.p, unionField: VTOFFSET.characters.p, unionKeyName: "charactersType", fieldName: "characters", required: false, completion: { (verifier, key: Character, pos) in + switch key { + case .none_: + break // NOTE - SWIFT doesnt support none + case .mulan: + try ForwardOffset.verify(&verifier, at: pos, of: Attacker.self) + case .rapunzel: + try Rapunzel.verify(&verifier, at: pos, of: Rapunzel.self) + case .belle: + try BookReader.verify(&verifier, at: pos, of: BookReader.self) + case .bookfan: + try BookReader.verify(&verifier, at: pos, of: BookReader.self) + case .other: + try ForwardOffset.verify(&verifier, at: pos, of: String.self) + case .unused: + try ForwardOffset.verify(&verifier, at: pos, of: String.self) + } + }) + _v.finish() + } +} + +extension Movie: Encodable { + + enum CodingKeys: String, CodingKey { + case mainCharacterType = "main_character_type" + case mainCharacter = "main_character" + case charactersType = "characters_type" + case characters = "characters" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if mainCharacterType != .none_ { + try container.encodeIfPresent(mainCharacterType, forKey: .mainCharacterType) + } + switch mainCharacterType { + case .mulan: + let _v = mainCharacter(type: Attacker.self) + try container.encodeIfPresent(_v, forKey: .mainCharacter) + case .rapunzel: + let _v = mainCharacter(type: Rapunzel.self) + try container.encodeIfPresent(_v, forKey: .mainCharacter) + case .belle: + let _v = mainCharacter(type: BookReader.self) + try container.encodeIfPresent(_v, forKey: .mainCharacter) + case .bookfan: + let _v = mainCharacter(type: BookReader.self) + try container.encodeIfPresent(_v, forKey: .mainCharacter) + case .other: + let _v = mainCharacter(type: String.self) + try container.encodeIfPresent(_v, forKey: .mainCharacter) + case .unused: + let _v = mainCharacter(type: String.self) + try container.encodeIfPresent(_v, forKey: .mainCharacter) + default: break; + } + if charactersCount > 0 { + var enumsEncoder = container.nestedUnkeyedContainer(forKey: .charactersType) + var contentEncoder = container.nestedUnkeyedContainer(forKey: .characters) + for index in 0.. ByteBuffer { return serialize(type: Movie.self) } + +} diff --git a/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/vector_has_test_generated.swift b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/vector_has_test_generated.swift new file mode 100644 index 00000000000..fef6b4fe9d7 --- /dev/null +++ b/third_party/flatbuffers/tests/swift/tests/Tests/FlatBuffers.Test.SwiftTests/vector_has_test_generated.swift @@ -0,0 +1,83 @@ +// automatically generated by the FlatBuffers compiler, do not modify +// swiftlint:disable all +// swiftformat:disable all + +import FlatBuffers + +public struct Swift_Tests_Vectors: FlatBufferObject, Verifiable { + + static func validateVersion() { FlatBuffersVersion_25_2_10() } + public var __buffer: ByteBuffer! { return _accessor.bb } + private var _accessor: Table + + private init(_ t: Table) { _accessor = t } + public init(_ bb: ByteBuffer, o: Int32) { _accessor = Table(bb: bb, position: o) } + + private enum VTOFFSET: VOffset { + case none_ = 4 + case empty = 6 + case array = 8 + var v: Int32 { Int32(self.rawValue) } + var p: VOffset { self.rawValue } + } + + public var hasNone: Bool { let o = _accessor.offset(VTOFFSET.none_.v); return o == 0 ? false : true } + public var none_Count: Int32 { let o = _accessor.offset(VTOFFSET.none_.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func none_(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.none_.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var none_: [UInt64] { return _accessor.getVector(at: VTOFFSET.none_.v) ?? [] } + public var hasEmpty: Bool { let o = _accessor.offset(VTOFFSET.empty.v); return o == 0 ? false : true } + public var emptyCount: Int32 { let o = _accessor.offset(VTOFFSET.empty.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func empty(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.empty.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var empty: [UInt64] { return _accessor.getVector(at: VTOFFSET.empty.v) ?? [] } + public var hasArray: Bool { let o = _accessor.offset(VTOFFSET.array.v); return o == 0 ? false : true } + public var arrayCount: Int32 { let o = _accessor.offset(VTOFFSET.array.v); return o == 0 ? 0 : _accessor.vector(count: o) } + public func array(at index: Int32) -> UInt64 { let o = _accessor.offset(VTOFFSET.array.v); return o == 0 ? 0 : _accessor.directRead(of: UInt64.self, offset: _accessor.vector(at: o) + index * 8) } + public var array: [UInt64] { return _accessor.getVector(at: VTOFFSET.array.v) ?? [] } + public static func startVectors(_ fbb: inout FlatBufferBuilder) -> UOffset { fbb.startTable(with: 3) } + public static func addVectorOf(none_: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: none_, at: VTOFFSET.none_.p) } + public static func addVectorOf(empty: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: empty, at: VTOFFSET.empty.p) } + public static func addVectorOf(array: Offset, _ fbb: inout FlatBufferBuilder) { fbb.add(offset: array, at: VTOFFSET.array.p) } + public static func endVectors(_ fbb: inout FlatBufferBuilder, start: UOffset) -> Offset { let end = Offset(offset: fbb.endTable(at: start)); return end } + public static func createVectors( + _ fbb: inout FlatBufferBuilder, + none_VectorOffset none_: Offset = Offset(), + emptyVectorOffset empty: Offset = Offset(), + arrayVectorOffset array: Offset = Offset() + ) -> Offset { + let __start = Swift_Tests_Vectors.startVectors(&fbb) + Swift_Tests_Vectors.addVectorOf(none_: none_, &fbb) + Swift_Tests_Vectors.addVectorOf(empty: empty, &fbb) + Swift_Tests_Vectors.addVectorOf(array: array, &fbb) + return Swift_Tests_Vectors.endVectors(&fbb, start: __start) + } + + public static func verify(_ verifier: inout Verifier, at position: Int, of type: T.Type) throws where T: Verifiable { + var _v = try verifier.visitTable(at: position) + try _v.visit(field: VTOFFSET.none_.p, fieldName: "none_", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.empty.p, fieldName: "empty", required: false, type: ForwardOffset>.self) + try _v.visit(field: VTOFFSET.array.p, fieldName: "array", required: false, type: ForwardOffset>.self) + _v.finish() + } +} + +extension Swift_Tests_Vectors: Encodable { + + enum CodingKeys: String, CodingKey { + case none_ = "none" + case empty = "empty" + case array = "array" + } + public func encode(to encoder: Encoder) throws { + var container = encoder.container(keyedBy: CodingKeys.self) + if none_Count > 0 { + try container.encodeIfPresent(none_, forKey: .none_) + } + if emptyCount > 0 { + try container.encodeIfPresent(empty, forKey: .empty) + } + if arrayCount > 0 { + try container.encodeIfPresent(array, forKey: .array) + } + } +} + diff --git a/third_party/flatbuffers/tests/swift/tests/monsterdata_test.mon b/third_party/flatbuffers/tests/swift/tests/monsterdata_test.mon new file mode 100644 index 00000000000..ba6cf278694 Binary files /dev/null and b/third_party/flatbuffers/tests/swift/tests/monsterdata_test.mon differ diff --git a/third_party/flatbuffers/tests/test.cpp b/third_party/flatbuffers/tests/test.cpp new file mode 100644 index 00000000000..af8cd63479a --- /dev/null +++ b/third_party/flatbuffers/tests/test.cpp @@ -0,0 +1,1767 @@ +/* + * Copyright 2014 Google Inc. All rights reserved. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +#include + +#include +#include +#include +#include + +#if defined(__ANDROID__) +#define INCLUDE_64_BIT_TESTS 0 +#else +#define INCLUDE_64_BIT_TESTS 1 +#endif + +#include "alignment_test.h" +#include "evolution_test.h" +#include "flatbuffers/flatbuffers.h" +#include "flatbuffers/idl.h" +#include "flatbuffers/minireflect.h" +#include "flatbuffers/reflection_generated.h" +#include "flatbuffers/registry.h" +#include "flatbuffers/util.h" +#include "fuzz_test.h" +#include "json_test.h" +#include "key_field_test.h" +#include "monster_test.h" +#include "monster_test_generated.h" +#include "native_inline_table_test_generated.h" +#include "optional_scalars_test.h" +#include "parser_test.h" +#include "proto_test.h" +#include "reflection_test.h" +#include "tests/union_vector/union_vector_generated.h" +#include "union_underlying_type_test_generated.h" +#if !defined(_MSC_VER) || _MSC_VER >= 1700 +# include "tests/arrays_test_generated.h" +#endif +#if INCLUDE_64_BIT_TESTS +#include "tests/64bit/offset64_test.h" +#endif +#include "flexbuffers_test.h" +#include "is_quiet_nan.h" +#include "monster_test_bfbs_generated.h" // Generated using --bfbs-comments --bfbs-builtins --cpp --bfbs-gen-embed +#include "native_type_test_generated.h" +#include "test_assert.h" +#include "util_test.h" + +void FlatBufferBuilderTest(); + +namespace flatbuffers { +namespace tests { +namespace { + +// clang-format off +// Check that char* and uint8_t* are interoperable types. +// The reinterpret_cast<> between the pointers are used to simplify data loading. +static_assert(flatbuffers::is_same::value || + flatbuffers::is_same::value, + "unexpected uint8_t type"); + +#if defined(FLATBUFFERS_HAS_NEW_STRTOD) && (FLATBUFFERS_HAS_NEW_STRTOD > 0) + // Ensure IEEE-754 support if tests of floats with NaN/Inf will run. + static_assert(std::numeric_limits::is_iec559 && + std::numeric_limits::is_iec559, + "IEC-559 (IEEE-754) standard required"); +#endif +// clang-format on + +using namespace MyGame::Example; + +void TriviallyCopyableTest() { + // clang-format off + #if __GNUG__ && __GNUC__ < 5 && \ + !(defined(__clang__) && __clang_major__ >= 16) + TEST_EQ(__is_trivially_copyable(Vec3), true); + #else + #if __cplusplus >= 201103L + TEST_EQ(std::is_trivially_copyable::value, true); + #endif + #endif + // clang-format on +} + +// Guard against -Wunused-function on platforms without file tests. +#ifndef FLATBUFFERS_NO_FILE_TESTS +void GenerateTableTextTest(const std::string &tests_data_path) { + std::string schemafile; + std::string jsonfile; + bool ok = + flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(), + false, &schemafile) && + flatbuffers::LoadFile((tests_data_path + "monsterdata_test.json").c_str(), + false, &jsonfile); + TEST_EQ(ok, true); + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + flatbuffers::IDLOptions opt; + opt.indent_step = -1; + flatbuffers::Parser parser(opt); + ok = parser.Parse(schemafile.c_str(), include_directories) && + parser.Parse(jsonfile.c_str(), include_directories); + TEST_EQ(ok, true); + // Test root table + const Monster *monster = GetMonster(parser.builder_.GetBufferPointer()); + const auto abilities = monster->testarrayofsortedstruct(); + TEST_EQ(abilities->size(), 3); + TEST_EQ(abilities->Get(0)->id(), 0); + TEST_EQ(abilities->Get(0)->distance(), 45); + TEST_EQ(abilities->Get(1)->id(), 1); + TEST_EQ(abilities->Get(1)->distance(), 21); + TEST_EQ(abilities->Get(2)->id(), 5); + TEST_EQ(abilities->Get(2)->distance(), 12); + + std::string jsongen; + auto result = GenTextFromTable(parser, monster, "MyGame.Example.Monster", + &jsongen); + TEST_NULL(result); + // Test sub table + const Vec3 *pos = monster->pos(); + jsongen.clear(); + result = GenTextFromTable(parser, pos, "MyGame.Example.Vec3", &jsongen); + TEST_NULL(result); + TEST_EQ_STR( + jsongen.c_str(), + "{x: 1.0,y: 2.0,z: 3.0,test1: 3.0,test2: \"Green\",test3: {a: 5,b: 6}}"); + const Test &test3 = pos->test3(); + jsongen.clear(); + result = + GenTextFromTable(parser, &test3, "MyGame.Example.Test", &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), "{a: 5,b: 6}"); + const Test *test4 = monster->test4()->Get(0); + jsongen.clear(); + result = + GenTextFromTable(parser, test4, "MyGame.Example.Test", &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), "{a: 10,b: 20}"); +} + +void MultiFileNameClashTest(const std::string &tests_data_path) { + const auto name_clash_path = + flatbuffers::ConCatPathFileName(tests_data_path, "name_clash_test"); + const char *include_directories[] = { name_clash_path.c_str() }; + + // Load valid 2 file Flatbuffer schema + const auto valid_path = + flatbuffers::ConCatPathFileName(name_clash_path, "valid_test1.fbs"); + std::string valid_schema; + TEST_ASSERT(flatbuffers::LoadFile(valid_path.c_str(), false, &valid_schema)); + // Clashing table and union names in different namespaces must be parsable + TEST_ASSERT( + flatbuffers::Parser().Parse(valid_schema.c_str(), include_directories)); + + flatbuffers::Parser p; + TEST_ASSERT(p.Parse(valid_schema.c_str(), include_directories)); + + // Load invalid 2 file Flatbuffer schema + const auto invalid_path = + flatbuffers::ConCatPathFileName(name_clash_path, "invalid_test1.fbs"); + std::string invalid_schema; + TEST_ASSERT( + flatbuffers::LoadFile(invalid_path.c_str(), false, &invalid_schema)); + // Clashing table and union names in same namespace must fail to parse + TEST_EQ( + flatbuffers::Parser().Parse(invalid_schema.c_str(), include_directories), + false); +} + +void InvalidNestedFlatbufferTest(const std::string &tests_data_path) { + // First, load and parse FlatBuffer schema (.fbs) + std::string schemafile; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "monster_test.fbs").c_str(), + false, &schemafile), + true); + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + flatbuffers::Parser parser1; + TEST_EQ(parser1.Parse(schemafile.c_str(), include_directories), true); + + // "color" inside nested flatbuffer contains invalid enum value + TEST_EQ(parser1.Parse("{ name: \"Bender\", testnestedflatbuffer: { name: " + "\"Leela\", color: \"nonexistent\"}}"), + false); +} + +void UnionVectorTest(const std::string &tests_data_path) { + // load FlatBuffer fbs schema and json. + std::string schemafile, jsonfile; + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "union_vector/union_vector.fbs").c_str(), + false, &schemafile), + true); + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "union_vector/union_vector.json").c_str(), + false, &jsonfile), + true); + + // parse schema. + flatbuffers::IDLOptions idl_opts; + idl_opts.lang_to_generate |= flatbuffers::IDLOptions::kBinary; + flatbuffers::Parser parser(idl_opts); + TEST_EQ(parser.Parse(schemafile.c_str()), true); + + flatbuffers::FlatBufferBuilder fbb; + + // union types. + std::vector types; + types.push_back(static_cast(Character_Belle)); + types.push_back(static_cast(Character_MuLan)); + types.push_back(static_cast(Character_BookFan)); + types.push_back(static_cast(Character_Other)); + types.push_back(static_cast(Character_Unused)); + + // union values. + std::vector> characters; + characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/7)).Union()); + characters.push_back(CreateAttacker(fbb, /*sword_attack_damage=*/5).Union()); + characters.push_back(fbb.CreateStruct(BookReader(/*books_read=*/2)).Union()); + characters.push_back(fbb.CreateString("Other").Union()); + characters.push_back(fbb.CreateString("Unused").Union()); + + // create Movie. + const auto movie_offset = + CreateMovie(fbb, Character_Rapunzel, + fbb.CreateStruct(Rapunzel(/*hair_length=*/6)).Union(), + fbb.CreateVector(types), fbb.CreateVector(characters)); + FinishMovieBuffer(fbb, movie_offset); + + flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize()); + TEST_EQ(VerifyMovieBuffer(verifier), true); + + auto flat_movie = GetMovie(fbb.GetBufferPointer()); + + auto TestMovie = [](const Movie *movie) { + TEST_EQ(movie->main_character_type() == Character_Rapunzel, true); + + auto cts = movie->characters_type(); + TEST_EQ(movie->characters_type()->size(), 5); + TEST_EQ(cts->GetEnum(0) == Character_Belle, true); + TEST_EQ(cts->GetEnum(1) == Character_MuLan, true); + TEST_EQ(cts->GetEnum(2) == Character_BookFan, true); + TEST_EQ(cts->GetEnum(3) == Character_Other, true); + TEST_EQ(cts->GetEnum(4) == Character_Unused, true); + + auto rapunzel = movie->main_character_as_Rapunzel(); + TEST_NOTNULL(rapunzel); + TEST_EQ(rapunzel->hair_length(), 6); + + auto cs = movie->characters(); + TEST_EQ(cs->size(), 5); + auto belle = cs->GetAs(0); + TEST_EQ(belle->books_read(), 7); + auto mu_lan = cs->GetAs(1); + TEST_EQ(mu_lan->sword_attack_damage(), 5); + auto book_fan = cs->GetAs(2); + TEST_EQ(book_fan->books_read(), 2); + auto other = cs->GetAsString(3); + TEST_EQ_STR(other->c_str(), "Other"); + auto unused = cs->GetAsString(4); + TEST_EQ_STR(unused->c_str(), "Unused"); + }; + + TestMovie(flat_movie); + + // Also test the JSON we loaded above. + TEST_EQ(parser.Parse(jsonfile.c_str()), true); + auto jbuf = parser.builder_.GetBufferPointer(); + flatbuffers::Verifier jverifier(jbuf, parser.builder_.GetSize()); + TEST_EQ(VerifyMovieBuffer(jverifier), true); + TestMovie(GetMovie(jbuf)); + + auto movie_object = flat_movie->UnPack(); + TEST_EQ(movie_object->main_character.AsRapunzel()->hair_length(), 6); + TEST_EQ(movie_object->characters[0].AsBelle()->books_read(), 7); + TEST_EQ(movie_object->characters[1].AsMuLan()->sword_attack_damage, 5); + TEST_EQ(movie_object->characters[2].AsBookFan()->books_read(), 2); + TEST_EQ_STR(movie_object->characters[3].AsOther()->c_str(), "Other"); + TEST_EQ_STR(movie_object->characters[4].AsUnused()->c_str(), "Unused"); + + fbb.Clear(); + fbb.Finish(Movie::Pack(fbb, movie_object)); + + delete movie_object; + + auto repacked_movie = GetMovie(fbb.GetBufferPointer()); + + TestMovie(repacked_movie); + + // Generate text using mini-reflection. + auto s = + flatbuffers::FlatBufferToString(fbb.GetBufferPointer(), MovieTypeTable()); + TEST_EQ_STR( + s.c_str(), + "{ main_character_type: Rapunzel, main_character: { hair_length: 6 }, " + "characters_type: [ Belle, MuLan, BookFan, Other, Unused ], " + "characters: [ { books_read: 7 }, { sword_attack_damage: 5 }, " + "{ books_read: 2 }, \"Other\", \"Unused\" ] }"); + + flatbuffers::ToStringVisitor visitor("\n", true, " "); + IterateFlatBuffer(fbb.GetBufferPointer(), MovieTypeTable(), &visitor); + TEST_EQ_STR(visitor.s.c_str(), + "{\n" + " \"main_character_type\": \"Rapunzel\",\n" + " \"main_character\": {\n" + " \"hair_length\": 6\n" + " },\n" + " \"characters_type\": [\n" + " \"Belle\",\n" + " \"MuLan\",\n" + " \"BookFan\",\n" + " \"Other\",\n" + " \"Unused\"\n" + " ],\n" + " \"characters\": [\n" + " {\n" + " \"books_read\": 7\n" + " },\n" + " {\n" + " \"sword_attack_damage\": 5\n" + " },\n" + " {\n" + " \"books_read\": 2\n" + " },\n" + " \"Other\",\n" + " \"Unused\"\n" + " ]\n" + "}"); + + // Generate text using parsed schema. + std::string jsongen; + auto result = GenText(parser, fbb.GetBufferPointer(), &jsongen); + TEST_NULL(result); + TEST_EQ_STR(jsongen.c_str(), + "{\n" + " main_character_type: \"Rapunzel\",\n" + " main_character: {\n" + " hair_length: 6\n" + " },\n" + " characters_type: [\n" + " \"Belle\",\n" + " \"MuLan\",\n" + " \"BookFan\",\n" + " \"Other\",\n" + " \"Unused\"\n" + " ],\n" + " characters: [\n" + " {\n" + " books_read: 7\n" + " },\n" + " {\n" + " sword_attack_damage: 5\n" + " },\n" + " {\n" + " books_read: 2\n" + " },\n" + " \"Other\",\n" + " \"Unused\"\n" + " ]\n" + "}\n"); + + // Simple test with reflection. + parser.Serialize(); + auto schema = reflection::GetSchema(parser.builder_.GetBufferPointer()); + auto ok = flatbuffers::Verify(*schema, *schema->root_table(), + fbb.GetBufferPointer(), fbb.GetSize()); + TEST_EQ(ok, true); + + flatbuffers::Parser parser2(idl_opts); + TEST_EQ(parser2.Parse("struct Bool { b:bool; }" + "union Any { Bool }" + "table Root { a:Any; }" + "root_type Root;"), + true); + TEST_EQ(parser2.Parse("{a_type:Bool,a:{b:true}}"), true); +} +#endif + +void EndianSwapTest() { + TEST_EQ(flatbuffers::EndianSwap(static_cast(0x1234)), 0x3412); + TEST_EQ(flatbuffers::EndianSwap(static_cast(0x12345678)), + 0x78563412); + TEST_EQ(flatbuffers::EndianSwap(static_cast(0x1234567890ABCDEF)), + 0xEFCDAB9078563412); + TEST_EQ(flatbuffers::EndianSwap(flatbuffers::EndianSwap(3.14f)), 3.14f); +} + +void UninitializedVectorTest() { + flatbuffers::FlatBufferBuilder builder; + + Test *buf = nullptr; + auto vector_offset = + builder.CreateUninitializedVectorOfStructs(2, &buf); + TEST_NOTNULL(buf); + buf[0] = Test(10, 20); + buf[1] = Test(30, 40); + + auto required_name = builder.CreateString("myMonster"); + auto monster_builder = MonsterBuilder(builder); + monster_builder.add_name( + required_name); // required field mandated for monster. + monster_builder.add_test4(vector_offset); + builder.Finish(monster_builder.Finish()); + + auto p = builder.GetBufferPointer(); + auto uvt = flatbuffers::GetRoot(p); + TEST_NOTNULL(uvt); + auto vec = uvt->test4(); + TEST_NOTNULL(vec); + auto test_0 = vec->Get(0); + auto test_1 = vec->Get(1); + TEST_EQ(test_0->a(), 10); + TEST_EQ(test_0->b(), 20); + TEST_EQ(test_1->a(), 30); + TEST_EQ(test_1->b(), 40); +} + +void EqualOperatorTest() { + MonsterT a; + MonsterT b; + // We have to reset the fields that are NaN to zero to allow the equality + // to evaluate to true. + TEST_EQ(std::isnan(a.nan_default), true); + TEST_EQ(std::isnan(b.nan_default), true); + a.nan_default = 0; + b.nan_default = 0; + TEST_EQ(b == a, true); + TEST_EQ(b != a, false); + + b.mana = 33; + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + b.mana = 150; + TEST_EQ(b == a, true); + TEST_EQ(b != a, false); + + b.inventory.push_back(3); + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + b.inventory.clear(); + TEST_EQ(b == a, true); + TEST_EQ(b != a, false); + + a.enemy.reset(new MonsterT()); + a.enemy->nan_default = 0; + TEST_EQ(b != a, true); + a.enemy->mana = 33; + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + + b.enemy.reset(new MonsterT()); + b.enemy->nan_default = 0; + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + b.enemy->mana = 33; + TEST_EQ(b == a, true); + TEST_EQ(b != a, false); + + a.enemy.reset(nullptr); + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + b.enemy->mana = 150; + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + a.enemy.reset(new MonsterT()); + a.enemy->nan_default = 0; + TEST_EQ(b == a, true); + TEST_EQ(b != a, false); + + b.enemy.reset(nullptr); + + b.test.type = Any_Monster; + TEST_EQ(b == a, false); + TEST_EQ(b != a, true); + + // Test that vector of tables are compared by value and not by reference. + { + // Two tables are equal by default. + MonsterT a, b; + a.nan_default = 0; + b.nan_default = 0; + TEST_EQ(a == b, true); + + // Adding only a table to one of the monster vectors should make it not + // equal (due to size mistmatch). + a.testarrayoftables.push_back( + flatbuffers::unique_ptr(new MonsterT)); + a.testarrayoftables.back()->nan_default = 0; + TEST_EQ(a == b, false); + + // Adding an equalivant table to the other monster vector should make it + // equal again. + b.testarrayoftables.push_back( + flatbuffers::unique_ptr(new MonsterT)); + b.testarrayoftables.back()->nan_default = 0; + TEST_EQ(a == b, true); + + // Create two new monsters that are different. + auto c = flatbuffers::unique_ptr(new MonsterT); + auto d = flatbuffers::unique_ptr(new MonsterT); + c->nan_default = 0; + d->nan_default = 0; + c->hp = 1; + d->hp = 2; + TEST_EQ(c == d, false); + + // Adding them to the original monsters should also make them different. + a.testarrayoftables.push_back(std::move(c)); + b.testarrayoftables.push_back(std::move(d)); + TEST_EQ(a == b, false); + + // Remove the mismatching monsters to get back to equality + a.testarrayoftables.pop_back(); + b.testarrayoftables.pop_back(); + TEST_EQ(a == b, true); + + // Check that nullptr are OK. + a.testarrayoftables.push_back(nullptr); + b.testarrayoftables.push_back( + flatbuffers::unique_ptr(new MonsterT)); + TEST_EQ(a == b, false); + } +} + +void CreateSharedStringTest() { + flatbuffers::FlatBufferBuilder builder; + const auto one1 = builder.CreateSharedString("one"); + const auto two = builder.CreateSharedString("two"); + const auto one2 = builder.CreateSharedString("one"); + TEST_EQ(one1.o, one2.o); + const auto onetwo = builder.CreateSharedString("onetwo"); + TEST_EQ(onetwo.o != one1.o, true); + TEST_EQ(onetwo.o != two.o, true); + + // Support for embedded nulls + const char chars_b[] = { 'a', '\0', 'b' }; + const char chars_c[] = { 'a', '\0', 'c' }; + const auto null_b1 = builder.CreateSharedString(chars_b, sizeof(chars_b)); + const auto null_c = builder.CreateSharedString(chars_c, sizeof(chars_c)); + const auto null_b2 = builder.CreateSharedString(chars_b, sizeof(chars_b)); + TEST_EQ(null_b1.o != null_c.o, true); // Issue#5058 repro + TEST_EQ(null_b1.o, null_b2.o); + + // Put the strings into an array for round trip verification. + std::array, 7> array = { + one1, two, one2, onetwo, null_b1, null_c, null_b2 + }; + const auto vector_offset = + builder.CreateVector>(array); + MonsterBuilder monster_builder(builder); + monster_builder.add_name(two); + monster_builder.add_testarrayofstring(vector_offset); + builder.Finish(monster_builder.Finish()); + + // Read the Monster back. + const auto *monster = + flatbuffers::GetRoot(builder.GetBufferPointer()); + TEST_EQ_STR(monster->name()->c_str(), "two"); + const auto *testarrayofstring = monster->testarrayofstring(); + TEST_EQ(testarrayofstring->size(), flatbuffers::uoffset_t(7)); + const auto &a = *testarrayofstring; + TEST_EQ_STR(a[0]->c_str(), "one"); + TEST_EQ_STR(a[1]->c_str(), "two"); + TEST_EQ_STR(a[2]->c_str(), "one"); + TEST_EQ_STR(a[3]->c_str(), "onetwo"); + TEST_EQ(a[4]->str(), (std::string(chars_b, sizeof(chars_b)))); + TEST_EQ(a[5]->str(), (std::string(chars_c, sizeof(chars_c)))); + TEST_EQ(a[6]->str(), (std::string(chars_b, sizeof(chars_b)))); + + // Make sure String::operator< works, too, since it is related to + // StringOffsetCompare. + TEST_EQ((*a[0]) < (*a[1]), true); + TEST_EQ((*a[1]) < (*a[0]), false); + TEST_EQ((*a[1]) < (*a[2]), false); + TEST_EQ((*a[2]) < (*a[1]), true); + TEST_EQ((*a[4]) < (*a[3]), true); + TEST_EQ((*a[5]) < (*a[4]), false); + TEST_EQ((*a[5]) < (*a[4]), false); + TEST_EQ((*a[6]) < (*a[5]), true); +} + +#if !defined(FLATBUFFERS_USE_STD_SPAN) && !defined(FLATBUFFERS_SPAN_MINIMAL) +void FlatbuffersSpanTest() { + // Compile-time checking of non-const [] to const [] conversions. + using flatbuffers::internal::is_span_convertible; + (void)is_span_convertible::type(123); + (void)is_span_convertible::type(123); + (void)is_span_convertible::type(123); + (void)is_span_convertible::type(123); + (void)is_span_convertible::type(123); + (void)is_span_convertible::type(123); + (void)is_span_convertible::type(123); + + using flatbuffers::span; + span c1; + TEST_EQ(c1.size(), 0); + span c2; + TEST_EQ(c2.size(), 0); + span c3; + TEST_EQ(c3.size(), 0); + TEST_ASSERT(c1.empty() && c2.empty() && c3.empty()); + + int i_data7[7] = { 0, 1, 2, 3, 4, 5, 6 }; + span i1(&i_data7[0], 7); + span i2(i1); // make dynamic from static + TEST_EQ(i1.size(), 7); + TEST_EQ(i1.empty(), false); + TEST_EQ(i1.size(), i2.size()); + TEST_EQ(i1.data(), i_data7); + TEST_EQ(i1[2], 2); + // Make const span from a non-const one. + span i3(i1); + // Construct from a C-array. + span i4(i_data7); + span i5(i_data7); + span i6(i_data7); + span i7(i_data7); + TEST_EQ(i7.size(), 7); + // Check construction from a const array. + const int i_cdata5[5] = { 4, 3, 2, 1, 0 }; + span i8(i_cdata5); + span i9(i_cdata5); + TEST_EQ(i9.size(), 5); + // Construction from a (ptr, size) pair. + span i10(i_data7, 7); + span i11(i_data7, 7); + TEST_EQ(i11.size(), 7); + span i12(i_cdata5, 5); + span i13(i_cdata5, 5); + TEST_EQ(i13.size(), 5); + // Construction from std::array. + std::array i_arr6 = { { 0, 1, 2, 3, 4, 5 } }; + span i14(i_arr6); + span i15(i_arr6); + span i16(i_arr6); + span i17(i_arr6); + TEST_EQ(i17.size(), 6); + const std::array i_carr8 = { { 0, 1, 2, 3, 4, 5, 6, 7 } }; + span i18(i_carr8); + span i19(i_carr8); + TEST_EQ(i18.size(), 8); + TEST_EQ(i19.size(), 8); + TEST_EQ(i19[7], 7); + // Check compatibility with flatbuffers::Array. + int fbs_int3_underlaying[3] = { 0 }; + int fbs_int3_data[3] = { 1, 2, 3 }; + auto &fbs_int3 = flatbuffers::CastToArray(fbs_int3_underlaying); + fbs_int3.CopyFromSpan(fbs_int3_data); + TEST_EQ(fbs_int3.Get(1), 2); + const int fbs_cint3_data[3] = { 2, 3, 4 }; + fbs_int3.CopyFromSpan(fbs_cint3_data); + TEST_EQ(fbs_int3.Get(1), 3); + // Check with Array + enum class Dummy : uint16_t { Zero = 0, One, Two }; + Dummy fbs_dummy3_underlaying[3] = {}; + Dummy fbs_dummy3_data[3] = { Dummy::One, Dummy::Two, Dummy::Two }; + auto &fbs_dummy3 = flatbuffers::CastToArray(fbs_dummy3_underlaying); + fbs_dummy3.CopyFromSpan(fbs_dummy3_data); + TEST_EQ(fbs_dummy3.Get(1), Dummy::Two); +} +#else +void FlatbuffersSpanTest() {} +#endif + +// VS10 does not support typed enums, exclude from tests +#if !defined(_MSC_VER) || _MSC_VER >= 1700 +void FixedLengthArrayTest() { + // Generate an ArrayTable containing one ArrayStruct. + flatbuffers::FlatBufferBuilder fbb; + MyGame::Example::NestedStruct nStruct0(MyGame::Example::TestEnum::B); + TEST_NOTNULL(nStruct0.mutable_a()); + nStruct0.mutable_a()->Mutate(0, 1); + nStruct0.mutable_a()->Mutate(1, 2); + TEST_NOTNULL(nStruct0.mutable_c()); + nStruct0.mutable_c()->Mutate(0, MyGame::Example::TestEnum::C); + nStruct0.mutable_c()->Mutate(1, MyGame::Example::TestEnum::A); + TEST_NOTNULL(nStruct0.mutable_d()); + nStruct0.mutable_d()->Mutate(0, flatbuffers::numeric_limits::max()); + nStruct0.mutable_d()->Mutate(1, flatbuffers::numeric_limits::min()); + MyGame::Example::NestedStruct nStruct1(MyGame::Example::TestEnum::C); + TEST_NOTNULL(nStruct1.mutable_a()); + nStruct1.mutable_a()->Mutate(0, 3); + nStruct1.mutable_a()->Mutate(1, 4); + TEST_NOTNULL(nStruct1.mutable_c()); + nStruct1.mutable_c()->Mutate(0, MyGame::Example::TestEnum::C); + nStruct1.mutable_c()->Mutate(1, MyGame::Example::TestEnum::A); + TEST_NOTNULL(nStruct1.mutable_d()); + nStruct1.mutable_d()->Mutate(0, flatbuffers::numeric_limits::min()); + nStruct1.mutable_d()->Mutate(1, flatbuffers::numeric_limits::max()); + MyGame::Example::ArrayStruct aStruct(2, 12, 1); + TEST_NOTNULL(aStruct.b()); + TEST_NOTNULL(aStruct.mutable_b()); + TEST_NOTNULL(aStruct.mutable_d()); + TEST_NOTNULL(aStruct.mutable_f()); + for (int i = 0; i < aStruct.b()->size(); i++) + aStruct.mutable_b()->Mutate(i, i + 1); + aStruct.mutable_d()->Mutate(0, nStruct0); + aStruct.mutable_d()->Mutate(1, nStruct1); + auto aTable = MyGame::Example::CreateArrayTable(fbb, &aStruct); + MyGame::Example::FinishArrayTableBuffer(fbb, aTable); + // Verify correctness of the ArrayTable. + flatbuffers::Verifier verifier(fbb.GetBufferPointer(), fbb.GetSize()); + TEST_ASSERT(MyGame::Example::VerifyArrayTableBuffer(verifier)); + // Do test. + auto p = MyGame::Example::GetMutableArrayTable(fbb.GetBufferPointer()); + auto mArStruct = p->mutable_a(); + TEST_NOTNULL(mArStruct); + TEST_NOTNULL(mArStruct->b()); + TEST_NOTNULL(mArStruct->d()); + TEST_NOTNULL(mArStruct->f()); + TEST_NOTNULL(mArStruct->mutable_b()); + TEST_NOTNULL(mArStruct->mutable_d()); + TEST_NOTNULL(mArStruct->mutable_f()); + TEST_EQ(mArStruct->a(), 2); + TEST_EQ(mArStruct->b()->size(), 15); + mArStruct->mutable_b()->Mutate(14, -14); + TEST_EQ(mArStruct->b()->Get(14), -14); + TEST_EQ(mArStruct->c(), 12); + TEST_NOTNULL(mArStruct->d()->Get(0)); + TEST_NOTNULL(mArStruct->d()->Get(0)->a()); + TEST_EQ(mArStruct->d()->Get(0)->a()->Get(0), 1); + TEST_EQ(mArStruct->d()->Get(0)->a()->Get(1), 2); + TEST_NOTNULL(mArStruct->d()->Get(1)); + TEST_NOTNULL(mArStruct->d()->Get(1)->a()); + TEST_EQ(mArStruct->d()->Get(1)->a()->Get(0), 3); + TEST_EQ(mArStruct->d()->Get(1)->a()->Get(1), 4); + TEST_NOTNULL(mArStruct->mutable_d()->GetMutablePointer(1)); + TEST_NOTNULL(mArStruct->mutable_d()->GetMutablePointer(1)->mutable_a()); + mArStruct->mutable_d()->GetMutablePointer(1)->mutable_a()->Mutate(1, 5); + TEST_EQ(5, mArStruct->d()->Get(1)->a()->Get(1)); + TEST_EQ(MyGame::Example::TestEnum::B, mArStruct->d()->Get(0)->b()); + TEST_NOTNULL(mArStruct->d()->Get(0)->c()); + TEST_EQ(MyGame::Example::TestEnum::C, mArStruct->d()->Get(0)->c()->Get(0)); + TEST_EQ(MyGame::Example::TestEnum::A, mArStruct->d()->Get(0)->c()->Get(1)); + TEST_EQ(flatbuffers::numeric_limits::max(), + mArStruct->d()->Get(0)->d()->Get(0)); + TEST_EQ(flatbuffers::numeric_limits::min(), + mArStruct->d()->Get(0)->d()->Get(1)); + TEST_EQ(MyGame::Example::TestEnum::C, mArStruct->d()->Get(1)->b()); + TEST_NOTNULL(mArStruct->d()->Get(1)->c()); + TEST_EQ(MyGame::Example::TestEnum::C, mArStruct->d()->Get(1)->c()->Get(0)); + TEST_EQ(MyGame::Example::TestEnum::A, mArStruct->d()->Get(1)->c()->Get(1)); + TEST_EQ(flatbuffers::numeric_limits::min(), + mArStruct->d()->Get(1)->d()->Get(0)); + TEST_EQ(flatbuffers::numeric_limits::max(), + mArStruct->d()->Get(1)->d()->Get(1)); + for (int i = 0; i < mArStruct->b()->size() - 1; i++) + TEST_EQ(mArStruct->b()->Get(i), i + 1); + // Check alignment + TEST_EQ(0, reinterpret_cast(mArStruct->d()) % 8); + TEST_EQ(0, reinterpret_cast(mArStruct->f()) % 8); + + // Check if default constructor set all memory zero + const size_t arr_size = sizeof(MyGame::Example::ArrayStruct); + char non_zero_memory[arr_size]; + // set memory chunk of size ArrayStruct to 1's + std::memset(static_cast(non_zero_memory), 1, arr_size); + // after placement-new it should be all 0's +# if defined(_MSC_VER) && defined(_DEBUG) +# undef new +# endif + MyGame::Example::ArrayStruct *ap = + new (non_zero_memory) MyGame::Example::ArrayStruct; +# if defined(_MSC_VER) && defined(_DEBUG) +# define new DEBUG_NEW +# endif + (void)ap; + for (size_t i = 0; i < arr_size; ++i) { TEST_EQ(non_zero_memory[i], 0); } +} +#else +void FixedLengthArrayTest() {} +#endif // !defined(_MSC_VER) || _MSC_VER >= 1700 + +#if !defined(FLATBUFFERS_SPAN_MINIMAL) && \ + (!defined(_MSC_VER) || _MSC_VER >= 1700) +void FixedLengthArrayConstructorTest() { + const int32_t nested_a[2] = { 1, 2 }; + MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A, + MyGame::Example::TestEnum::B }; + const int64_t int64_2[2] = { -2, -1 }; + + std::array init_d = { + { MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B, + nested_c, int64_2), + MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::A, + nested_c, + std::array{ { 12, 13 } }) } + }; + + MyGame::Example::ArrayStruct arr_struct( + 8.125, + std::array{ + { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }, + -17, init_d, 10, int64_2); + TEST_EQ(arr_struct.a(), 8.125); + TEST_EQ(arr_struct.b()->Get(2), 3); + TEST_EQ(arr_struct.c(), -17); + + TEST_NOTNULL(arr_struct.d()); + const auto &arr_d_0 = *arr_struct.d()->Get(0); + TEST_EQ(arr_d_0.a()->Get(0), 1); + TEST_EQ(arr_d_0.a()->Get(1), 2); + TEST_EQ(arr_d_0.b(), MyGame::Example::TestEnum::B); + TEST_EQ(arr_d_0.c()->Get(0), MyGame::Example::TestEnum::A); + TEST_EQ(arr_d_0.c()->Get(1), MyGame::Example::TestEnum::B); + TEST_EQ(arr_d_0.d()->Get(0), -2); + TEST_EQ(arr_d_0.d()->Get(1), -1); + const auto &arr_d_1 = *arr_struct.d()->Get(1); + TEST_EQ(arr_d_1.a()->Get(0), 1); + TEST_EQ(arr_d_1.a()->Get(1), 2); + TEST_EQ(arr_d_1.b(), MyGame::Example::TestEnum::A); + TEST_EQ(arr_d_1.c()->Get(0), MyGame::Example::TestEnum::A); + TEST_EQ(arr_d_1.c()->Get(1), MyGame::Example::TestEnum::B); + TEST_EQ(arr_d_1.d()->Get(0), 12); + TEST_EQ(arr_d_1.d()->Get(1), 13); + + TEST_EQ(arr_struct.e(), 10); + TEST_EQ(arr_struct.f()->Get(0), -2); + TEST_EQ(arr_struct.f()->Get(1), -1); +} +#else +void FixedLengthArrayConstructorTest() {} +#endif + +void FixedLengthArrayOperatorEqualTest() { + const int32_t nested_a[2] = { 1, 2 }; + MyGame::Example::TestEnum nested_c[2] = { MyGame::Example::TestEnum::A, + MyGame::Example::TestEnum::B }; + + MyGame::Example::TestEnum nested_cc[2] = { MyGame::Example::TestEnum::A, + MyGame::Example::TestEnum::C }; + const int64_t int64_2[2] = { -2, -1 }; + + std::array init_d = { + { MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B, + nested_c, int64_2), + MyGame::Example::NestedStruct(nested_a, MyGame::Example::TestEnum::B, + nested_c, + std::array{ { -2, -1 } }) } + }; + + auto different = MyGame::Example::NestedStruct( + nested_a, MyGame::Example::TestEnum::B, nested_cc, + std::array{ { -2, -1 } }); + + TEST_ASSERT(init_d[0] == init_d[1]); + TEST_ASSERT(init_d[0] != different); + + std::array arr_struct = { + MyGame::Example::ArrayStruct( + 8.125, + std::array{ + { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }, + -17, init_d, 10, int64_2), + + MyGame::Example::ArrayStruct( + 8.125, + std::array{ + { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }, + -17, init_d, 10, int64_2), + + MyGame::Example::ArrayStruct( + 8.125, + std::array{ + { 1000, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 } }, + -17, init_d, 10, int64_2) + }; + + TEST_ASSERT(arr_struct[0] == arr_struct[1]); + TEST_ASSERT(arr_struct[1] != arr_struct[2]); +} + +void NativeTypeTest() { + const int N = 3; + + Geometry::ApplicationDataT src_data; + src_data.vectors.reserve(N); + src_data.vectors_alt.reserve(N); + + for (int i = 0; i < N; ++i) { + src_data.vectors.push_back( + Native::Vector3D(10 * i + 0.1f, 10 * i + 0.2f, 10 * i + 0.3f)); + src_data.vectors_alt.push_back( + Native::Vector3D(20 * i + 0.1f, 20 * i + 0.2f, 20 * i + 0.3f)); + } + + flatbuffers::FlatBufferBuilder fbb; + fbb.Finish(Geometry::ApplicationData::Pack(fbb, &src_data)); + + auto dstDataT = Geometry::UnPackApplicationData(fbb.GetBufferPointer()); + + for (int i = 0; i < N; ++i) { + const Native::Vector3D &v = dstDataT->vectors[i]; + TEST_EQ(v.x, 10 * i + 0.1f); + TEST_EQ(v.y, 10 * i + 0.2f); + TEST_EQ(v.z, 10 * i + 0.3f); + + const Native::Vector3D &v2 = dstDataT->vectors_alt[i]; + TEST_EQ(v2.x, 20 * i + 0.1f); + TEST_EQ(v2.y, 20 * i + 0.2f); + TEST_EQ(v2.z, 20 * i + 0.3f); + } +} + +// Guard against -Wunused-function on platforms without file tests. +#ifndef FLATBUFFERS_NO_FILE_TESTS +// VS10 does not support typed enums, exclude from tests +# if !defined(_MSC_VER) || _MSC_VER >= 1700 +void FixedLengthArrayJsonTest(const std::string &tests_data_path, bool binary) { + // load FlatBuffer schema (.fbs) and JSON from disk + std::string schemafile; + std::string jsonfile; + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "arrays_test." + (binary ? "bfbs" : "fbs")) + .c_str(), + binary, &schemafile), + true); + TEST_EQ( + flatbuffers::LoadFile((tests_data_path + "arrays_test.golden").c_str(), + false, &jsonfile), + true); + + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parserOrg, parserGen; + if (binary) { + flatbuffers::Verifier verifier( + reinterpret_cast(schemafile.c_str()), + schemafile.size()); + TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); + TEST_EQ(parserOrg.Deserialize( + reinterpret_cast(schemafile.c_str()), + schemafile.size()), + true); + TEST_EQ(parserGen.Deserialize( + reinterpret_cast(schemafile.c_str()), + schemafile.size()), + true); + } else { + TEST_EQ(parserOrg.Parse(schemafile.c_str()), true); + TEST_EQ(parserGen.Parse(schemafile.c_str()), true); + } + TEST_EQ(parserOrg.Parse(jsonfile.c_str()), true); + + // First, verify it, just in case: + flatbuffers::Verifier verifierOrg(parserOrg.builder_.GetBufferPointer(), + parserOrg.builder_.GetSize()); + TEST_EQ(VerifyArrayTableBuffer(verifierOrg), true); + + // Export to JSON + std::string jsonGen; + TEST_NULL( + GenText(parserOrg, parserOrg.builder_.GetBufferPointer(), &jsonGen)); + + // Import from JSON + TEST_EQ(parserGen.Parse(jsonGen.c_str()), true); + + // Verify buffer from generated JSON + flatbuffers::Verifier verifierGen(parserGen.builder_.GetBufferPointer(), + parserGen.builder_.GetSize()); + TEST_EQ(VerifyArrayTableBuffer(verifierGen), true); + + // Compare generated buffer to original + TEST_EQ(parserOrg.builder_.GetSize(), parserGen.builder_.GetSize()); + TEST_EQ(std::memcmp(parserOrg.builder_.GetBufferPointer(), + parserGen.builder_.GetBufferPointer(), + parserOrg.builder_.GetSize()), + 0); +} + +void FixedLengthArraySpanTest(const std::string &tests_data_path) { + // load FlatBuffer schema (.fbs) and JSON from disk + std::string schemafile; + std::string jsonfile; + TEST_EQ(flatbuffers::LoadFile((tests_data_path + "arrays_test.fbs").c_str(), + false, &schemafile), + true); + TEST_EQ( + flatbuffers::LoadFile((tests_data_path + "arrays_test.golden").c_str(), + false, &jsonfile), + true); + + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parser; + TEST_EQ(parser.Parse(schemafile.c_str()), true); + TEST_EQ(parser.Parse(jsonfile.c_str()), true); + auto &fbb = parser.builder_; + auto verifier = flatbuffers::Verifier(fbb.GetBufferPointer(), fbb.GetSize()); + TEST_EQ(true, VerifyArrayTableBuffer(verifier)); + + auto p = MyGame::Example::GetMutableArrayTable(fbb.GetBufferPointer()); + TEST_NOTNULL(p); + auto table_struct = p->mutable_a(); + TEST_NOTNULL(table_struct); + TEST_EQ(2, table_struct->d()->size()); + TEST_NOTNULL(table_struct->d()); + TEST_NOTNULL(table_struct->mutable_d()); + // test array of structs + auto const_d = flatbuffers::make_span(*table_struct->d()); + auto mutable_d = flatbuffers::make_span(*table_struct->mutable_d()); + TEST_EQ(2, const_d.size()); + TEST_EQ(2, mutable_d.size()); + TEST_ASSERT(const_d[0] == mutable_d[0]); + TEST_ASSERT(const_d[1] == mutable_d[1]); + mutable_d[0] = const_d[0]; // mutate + // test scalars + auto &const_nested = const_d[0]; + auto &mutable_nested = mutable_d[0]; + static_assert(sizeof(MyGame::Example::TestEnum) == sizeof(uint8_t), + "TestEnum's underlaying type must by byte"); + TEST_NOTNULL(const_nested.d()); + TEST_NOTNULL(mutable_nested.d()); + { + flatbuffers::span const_d_c = + flatbuffers::make_span(*const_nested.c()); + auto mutable_d_c = flatbuffers::make_span(*mutable_nested.mutable_c()); + TEST_EQ(2, const_d_c.size()); + TEST_EQ(2, mutable_d_c.size()); + TEST_EQ(MyGame::Example::TestEnum::C, const_d_c[0]); + TEST_EQ(MyGame::Example::TestEnum::B, const_d_c[1]); + TEST_ASSERT(mutable_d_c.end() == std::copy(const_d_c.begin(), + const_d_c.end(), + mutable_d_c.begin())); + TEST_ASSERT( + std::equal(const_d_c.begin(), const_d_c.end(), mutable_d_c.begin())); + } + // test little endian array of int32 +# if FLATBUFFERS_LITTLEENDIAN + { + flatbuffers::span const_d_a = + flatbuffers::make_span(*const_nested.a()); + auto mutable_d_a = flatbuffers::make_span(*mutable_nested.mutable_a()); + TEST_EQ(2, const_d_a.size()); + TEST_EQ(2, mutable_d_a.size()); + TEST_EQ(-1, const_d_a[0]); + TEST_EQ(2, const_d_a[1]); + TEST_ASSERT(mutable_d_a.end() == std::copy(const_d_a.begin(), + const_d_a.end(), + mutable_d_a.begin())); + TEST_ASSERT( + std::equal(const_d_a.begin(), const_d_a.end(), mutable_d_a.begin())); + } +# endif +} +# else +void FixedLengthArrayJsonTest(bool /*binary*/) {} +void FixedLengthArraySpanTest() {} +# endif + +void TestEmbeddedBinarySchema(const std::string &tests_data_path) { + // load JSON from disk + std::string jsonfile; + TEST_EQ(flatbuffers::LoadFile( + (tests_data_path + "monsterdata_test.golden").c_str(), false, + &jsonfile), + true); + + // parse schema first, so we can use it to parse the data after + flatbuffers::Parser parserOrg, parserGen; + flatbuffers::Verifier verifier(MyGame::Example::MonsterBinarySchema::data(), + MyGame::Example::MonsterBinarySchema::size()); + TEST_EQ(reflection::VerifySchemaBuffer(verifier), true); + TEST_EQ(parserOrg.Deserialize(MyGame::Example::MonsterBinarySchema::data(), + MyGame::Example::MonsterBinarySchema::size()), + true); + TEST_EQ(parserGen.Deserialize(MyGame::Example::MonsterBinarySchema::data(), + MyGame::Example::MonsterBinarySchema::size()), + true); + TEST_EQ(parserOrg.Parse(jsonfile.c_str()), true); + + // First, verify it, just in case: + flatbuffers::Verifier verifierOrg(parserOrg.builder_.GetBufferPointer(), + parserOrg.builder_.GetSize()); + TEST_EQ(VerifyMonsterBuffer(verifierOrg), true); + + // Export to JSON + std::string jsonGen; + TEST_NULL( + GenText(parserOrg, parserOrg.builder_.GetBufferPointer(), &jsonGen)); + + // Import from JSON + TEST_EQ(parserGen.Parse(jsonGen.c_str()), true); + + // Verify buffer from generated JSON + flatbuffers::Verifier verifierGen(parserGen.builder_.GetBufferPointer(), + parserGen.builder_.GetSize()); + TEST_EQ(VerifyMonsterBuffer(verifierGen), true); + + // Compare generated buffer to original + TEST_EQ(parserOrg.builder_.GetSize(), parserGen.builder_.GetSize()); + TEST_EQ(std::memcmp(parserOrg.builder_.GetBufferPointer(), + parserGen.builder_.GetBufferPointer(), + parserOrg.builder_.GetSize()), + 0); +} +#endif + +template void EmbeddedSchemaAccessByType() { + // Get the binary schema from the Type itself. + // Verify the schema is OK. + flatbuffers::Verifier verifierEmbeddedSchema( + T::TableType::BinarySchema::data(), T::TableType::BinarySchema::size()); + TEST_EQ(reflection::VerifySchemaBuffer(verifierEmbeddedSchema), true); + + // Reflect it. + auto schema = reflection::GetSchema(T::TableType::BinarySchema::data()); + + // This should equal the expected root table. + TEST_EQ_STR(schema->root_table()->name()->c_str(), "MyGame.Example.Monster"); +} + +void EmbeddedSchemaAccess() { + // Get the binary schema for the monster. + // Verify the schema is OK. + flatbuffers::Verifier verifierEmbeddedSchema(Monster::BinarySchema::data(), + Monster::BinarySchema::size()); + TEST_EQ(reflection::VerifySchemaBuffer(verifierEmbeddedSchema), true); + + // Reflect it. + auto schema = reflection::GetSchema(Monster::BinarySchema::data()); + + // This should equal the expected root table. + TEST_EQ_STR(schema->root_table()->name()->c_str(), "MyGame.Example.Monster"); + + // Repeat above, but do so through a template parameter: + EmbeddedSchemaAccessByType(); +} + +void NestedVerifierTest() { + // Create a nested monster. + flatbuffers::FlatBufferBuilder nested_builder; + FinishMonsterBuffer( + nested_builder, + CreateMonster(nested_builder, nullptr, 0, 0, + nested_builder.CreateString("NestedMonster"))); + + // Verify the nested monster + flatbuffers::Verifier verifier(nested_builder.GetBufferPointer(), + nested_builder.GetSize()); + TEST_EQ(true, VerifyMonsterBuffer(verifier)); + + { + // Create the outer monster. + flatbuffers::FlatBufferBuilder builder; + + // Add the nested monster as a vector of bytes. + auto nested_monster_bytes = builder.CreateVector( + nested_builder.GetBufferPointer(), nested_builder.GetSize()); + + auto name = builder.CreateString("OuterMonster"); + + MonsterBuilder mon_builder(builder); + mon_builder.add_name(name); + mon_builder.add_testnestedflatbuffer(nested_monster_bytes); + FinishMonsterBuffer(builder, mon_builder.Finish()); + + // Verify the root monster, which includes verifing the nested monster + flatbuffers::Verifier verifier(builder.GetBufferPointer(), + builder.GetSize()); + TEST_EQ(true, VerifyMonsterBuffer(verifier)); + } + + { + // Create the outer monster. + flatbuffers::FlatBufferBuilder builder; + + // Purposely invalidate the nested flatbuffer setting its length to 1, an + // invalid length. + uint8_t invalid_nested_buffer[1]; + auto nested_monster_bytes = builder.CreateVector(invalid_nested_buffer, 1); + + auto name = builder.CreateString("OuterMonster"); + + MonsterBuilder mon_builder(builder); + mon_builder.add_name(name); + mon_builder.add_testnestedflatbuffer(nested_monster_bytes); + FinishMonsterBuffer(builder, mon_builder.Finish()); + + // Verify the root monster fails, since the included nested monster fails. + flatbuffers::Verifier verifier(builder.GetBufferPointer(), + builder.GetSize()); + TEST_EQ(false, VerifyMonsterBuffer(verifier)); + + // Verify the root monster succeeds, since we've disabled checking nested + // flatbuffers + flatbuffers::Verifier::Options options; + options.check_nested_flatbuffers = false; + flatbuffers::Verifier no_check_nested(builder.GetBufferPointer(), + builder.GetSize(), options); + TEST_EQ(true, VerifyMonsterBuffer(no_check_nested)); + } + + { + // Create the outer monster. + flatbuffers::FlatBufferBuilder builder; + + // Purposely invalidate the nested flatbuffer setting its length to 0, an + // invalid length. + uint8_t *invalid_nested_buffer = nullptr; + auto nested_monster_bytes = builder.CreateVector(invalid_nested_buffer, 0); + + auto name = builder.CreateString("OuterMonster"); + + MonsterBuilder mon_builder(builder); + mon_builder.add_name(name); + mon_builder.add_testnestedflatbuffer(nested_monster_bytes); + FinishMonsterBuffer(builder, mon_builder.Finish()); + + // Verify the root monster fails, since the included nested monster fails. + flatbuffers::Verifier verifier(builder.GetBufferPointer(), + builder.GetSize()); + TEST_EQ(false, VerifyMonsterBuffer(verifier)); + } +} + +template +void TestIterators(const std::vector &expected, const Container &tested) { + TEST_ASSERT(tested.rbegin().base() == tested.end()); + TEST_ASSERT(tested.crbegin().base() == tested.cend()); + TEST_ASSERT(tested.rend().base() == tested.begin()); + TEST_ASSERT(tested.crend().base() == tested.cbegin()); + + size_t k = 0; + for (auto it = tested.begin(); it != tested.end(); ++it, ++k) { + const auto &e = expected.at(k); + TEST_EQ(*it, e); + } + TEST_EQ(k, expected.size()); + + k = expected.size(); + for (auto it = tested.rbegin(); it != tested.rend(); ++it, --k) { + const auto &e = expected.at(k - 1); + TEST_EQ(*it, e); + } + TEST_EQ(k, 0); +} + +void FlatbuffersIteratorsTest() { + { + flatbuffers::FlatBufferBuilder fbb; + const std::vector inv_data = { 1, 2, 3 }; + { + auto mon_name = fbb.CreateString("MyMonster"); // key, mandatory + auto inv_vec = fbb.CreateVector(inv_data); + auto empty_i64_vec = + fbb.CreateVector(static_cast(nullptr), 0); + MonsterBuilder mb(fbb); + mb.add_name(mon_name); + mb.add_inventory(inv_vec); + mb.add_vector_of_longs(empty_i64_vec); + FinishMonsterBuffer(fbb, mb.Finish()); + } + const auto &mon = *flatbuffers::GetRoot(fbb.GetBufferPointer()); + + TEST_EQ_STR("MyMonster", mon.name()->c_str()); + TEST_ASSERT(mon.inventory()); + TEST_ASSERT(mon.vector_of_longs()); + TestIterators(inv_data, *mon.inventory()); + TestIterators(std::vector(), *mon.vector_of_longs()); + } + + { + flatbuffers::FlatBufferBuilder fbb; + MyGame::Example::ArrayStruct aStruct; + MyGame::Example::FinishArrayTableBuffer( + fbb, MyGame::Example::CreateArrayTable(fbb, &aStruct)); + const auto &array_table = + *flatbuffers::GetRoot(fbb.GetBufferPointer()); + TEST_ASSERT(array_table.a()); + auto &int_15 = *array_table.a()->b(); + TestIterators(std::vector(15, 0), int_15); + } +} + +void PrivateAnnotationsLeaks() { + // Simple schemas and a "has optional scalar" sentinal. + std::vector schemas; + std::vector failure_schemas; + + // (private) (table/struct) + schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC (private) { mana: int; }"); + + // (public) (table/struct) + schemas.push_back( + "table Monster { mana: int; }" + "struct ABC { mana: int; }"); + + // (private) (union) containing (private) (table/struct) + schemas.push_back( + "table Monster (private) { mana: int; } " + "struct ABC (private) { mana: int; } " + "union Any (private) { Monster, ABC } "); + + // (public) (union) containing (public) (table/struct) + schemas.push_back( + "table Monster { mana: int; }" + "struct ABC { mana: int; }" + "union Any { Monster, ABC }"); + + // (private) (table/struct/enum) + schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC (private) { mana: int; }" + "enum Race:byte (private) { None = -1, Human = 0, }"); + + // (public) (table/struct/enum) + schemas.push_back( + "table Monster { mana: int; }" + "struct ABC { mana: int; }" + "enum Race:byte { None = -1, Human = 0, }"); + + // (private) (union) containing (private) (table/struct) + schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC (private) { mana: int; }" + "enum Race:byte (private) { None = -1, Human = 0, }" + "union Any (private) { Monster, ABC }"); + + // (public) (union) containing (public) (table/struct) + schemas.push_back( + "table Monster { mana: int; }" + "struct ABC { mana: int; }" + "enum Race:byte { None = -1, Human = 0, }" + "union Any { Monster, ABC }"); + + // (private) (table), (public struct) + schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC { mana: int; }"); + + // (private) (table), (public) (struct/enum) + schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC { mana: int; }" + "enum Race:byte { None = -1, Human = 0, }"); + + // (public) (struct) containing (public) (enum) + schemas.push_back( + "enum Race:byte { None = -1, Human = 0, }" + "table Monster { mana: int; }" + "struct ABC { mana: int; type: Race; }"); + + // (public) (union) containing (private) (table) & (public) (struct) + failure_schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC { mana: int; }" + "union Any { Monster, ABC }"); + + // (public) (union) containing (private) (table/struct) + failure_schemas.push_back( + "table Monster (private) { mana: int; }" + "struct ABC (private) { mana: int; }" + "enum Race:byte { None = -1, Human = 0, }" + "union Any { Monster, ABC }"); + + // (public) (table) containing (private) (struct) + failure_schemas.push_back( + "table Monster { mana: int; ab: ABC; }" + "struct ABC (private) { mana: int; }"); + + // (public) (struct) containing (private) (enum) + failure_schemas.push_back( + "enum Race:byte (private) { None = -1, Human = 0, }" + "table Monster { mana: int; }" + "struct ABC { mana: int; type: Race; }"); + + flatbuffers::IDLOptions opts; + opts.lang_to_generate = flatbuffers::IDLOptions::Language::kSwift; + opts.no_leak_private_annotations = true; + + for (auto schema = schemas.begin(); schema < schemas.end(); schema++) { + flatbuffers::Parser parser(opts); + TEST_ASSERT(parser.Parse(schema->c_str())); + } + + for (auto schema = failure_schemas.begin(); schema < failure_schemas.end(); + schema++) { + flatbuffers::Parser parser(opts); + TEST_EQ(false, parser.Parse(schema->c_str())); + } + + opts.no_leak_private_annotations = false; + + for (auto schema = schemas.begin(); schema < schemas.end(); schema++) { + flatbuffers::Parser parser(opts); + TEST_ASSERT(parser.Parse(schema->c_str())); + } + + for (auto schema = failure_schemas.begin(); schema < failure_schemas.end(); + schema++) { + flatbuffers::Parser parser(opts); + TEST_ASSERT(parser.Parse(schema->c_str())); + } +} + +void VectorSpanTest() { + flatbuffers::FlatBufferBuilder builder; + + auto mloc = CreateMonster( + builder, nullptr, 0, 0, builder.CreateString("Monster"), + builder.CreateVector({ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 })); + + FinishMonsterBuffer(builder, mloc); + + auto monster = GetMonster(builder.GetBufferPointer()); + auto mutable_monster = GetMutableMonster(builder.GetBufferPointer()); + + { // using references + TEST_NOTNULL(monster->inventory()); + + flatbuffers::span const_inventory = + flatbuffers::make_span(*monster->inventory()); + TEST_EQ(const_inventory.size(), 10); + TEST_EQ(const_inventory[0], 0); + TEST_EQ(const_inventory[9], 9); + + flatbuffers::span mutable_inventory = + flatbuffers::make_span(*mutable_monster->mutable_inventory()); + TEST_EQ(mutable_inventory.size(), 10); + TEST_EQ(mutable_inventory[0], 0); + TEST_EQ(mutable_inventory[9], 9); + + mutable_inventory[0] = 42; + TEST_EQ(mutable_inventory[0], 42); + + mutable_inventory[0] = 0; + TEST_EQ(mutable_inventory[0], 0); + } + + { // using pointers + TEST_EQ(flatbuffers::VectorLength(monster->inventory()), 10); + + flatbuffers::span const_inventory = + flatbuffers::make_span(monster->inventory()); + TEST_EQ(const_inventory.size(), 10); + TEST_EQ(const_inventory[0], 0); + TEST_EQ(const_inventory[9], 9); + + flatbuffers::span mutable_inventory = + flatbuffers::make_span(mutable_monster->mutable_inventory()); + TEST_EQ(mutable_inventory.size(), 10); + TEST_EQ(mutable_inventory[0], 0); + TEST_EQ(mutable_inventory[9], 9); + + mutable_inventory[0] = 42; + TEST_EQ(mutable_inventory[0], 42); + + mutable_inventory[0] = 0; + TEST_EQ(mutable_inventory[0], 0); + } + + { + TEST_ASSERT(nullptr == monster->testnestedflatbuffer()); + + TEST_EQ(flatbuffers::VectorLength(monster->testnestedflatbuffer()), 0); + + flatbuffers::span const_nested = + flatbuffers::make_span(monster->testnestedflatbuffer()); + TEST_ASSERT(const_nested.empty()); + + flatbuffers::span mutable_nested = + flatbuffers::make_span(mutable_monster->mutable_testnestedflatbuffer()); + TEST_ASSERT(mutable_nested.empty()); + } +} + +void NativeInlineTableVectorTest() { + TestNativeInlineTableT test; + for (int i = 0; i < 10; ++i) { + NativeInlineTableT t; + t.a = i; + test.t.push_back(t); + } + + flatbuffers::FlatBufferBuilder fbb; + auto offset = TestNativeInlineTable::Pack(fbb, &test); + fbb.Finish(offset); + + auto *root = + flatbuffers::GetRoot(fbb.GetBufferPointer()); + TestNativeInlineTableT unpacked; + root->UnPackTo(&unpacked); + + for (int i = 0; i < 10; ++i) { TEST_ASSERT(unpacked.t[i] == test.t[i]); } + + TEST_ASSERT(unpacked.t == test.t); +} + +// Guard against -Wunused-function on platforms without file tests. +#ifndef FLATBUFFERS_NO_FILE_TESTS +void DoNotRequireEofTest(const std::string &tests_data_path) { + std::string schemafile; + bool ok = flatbuffers::LoadFile( + (tests_data_path + "monster_test.fbs").c_str(), false, &schemafile); + TEST_EQ(ok, true); + auto include_test_path = + flatbuffers::ConCatPathFileName(tests_data_path, "include_test"); + const char *include_directories[] = { tests_data_path.c_str(), + include_test_path.c_str(), nullptr }; + flatbuffers::IDLOptions opt; + opt.require_json_eof = false; + flatbuffers::Parser parser(opt); + ok = parser.Parse(schemafile.c_str(), include_directories); + TEST_EQ(ok, true); + + const char *str = R"(Some text at the beginning. { + "name": "Blob", + "hp": 5 + }{ + "name": "Imp", + "hp": 10 + } + Some extra text at the end too. + )"; + const char *tableStart = std::strchr(str, '{'); + ok = parser.ParseJson(tableStart); + TEST_EQ(ok, true); + + const Monster *monster = GetMonster(parser.builder_.GetBufferPointer()); + TEST_EQ_STR(monster->name()->c_str(), "Blob"); + TEST_EQ(monster->hp(), 5); + + tableStart += parser.BytesConsumed(); + + ok = parser.ParseJson(tableStart); + TEST_EQ(ok, true); + + monster = GetMonster(parser.builder_.GetBufferPointer()); + TEST_EQ_STR(monster->name()->c_str(), "Imp"); + TEST_EQ(monster->hp(), 10); +} +#endif + +void UnionUnderlyingTypeTest() { + using namespace UnionUnderlyingType; + TEST_ASSERT(sizeof(ABC) == sizeof(uint32_t)); + TEST_ASSERT(static_cast(ABC::A) == 555); + TEST_ASSERT(static_cast(ABC::B) == 666); + TEST_ASSERT(static_cast(ABC::C) == 777); + + DT buffer; + AT a; + a.a = 42; + BT b; + b.b = "foo"; + CT c; + c.c = true; + buffer.test_union = ABCUnion(); + buffer.test_union.Set(a); + buffer.test_vector_of_union.resize(3); + buffer.test_vector_of_union[0].Set(a); + buffer.test_vector_of_union[1].Set(b); + buffer.test_vector_of_union[2].Set(c); + + flatbuffers::FlatBufferBuilder fbb; + auto offset = D::Pack(fbb, &buffer); + fbb.Finish(offset); + + auto *root = + flatbuffers::GetRoot(fbb.GetBufferPointer()); + DT unpacked; + root->UnPackTo(&unpacked); + + TEST_ASSERT(unpacked.test_union == buffer.test_union); + TEST_ASSERT(unpacked.test_vector_of_union == buffer.test_vector_of_union); + +} + +static void Offset64Tests() { +#if INCLUDE_64_BIT_TESTS + Offset64Test(); + Offset64SerializedFirst(); + Offset64NestedFlatBuffer(); + Offset64CreateDirect(); + Offset64Evolution(); + Offset64VectorOfStructs(); + Offset64SizePrefix(); + Offset64ManyVectors(); + Offset64ForceAlign(); +#endif +} + +int FlatBufferTests(const std::string &tests_data_path) { + // Run our various test suites: + + std::string rawbuf; + auto flatbuf1 = CreateFlatBufferTest(rawbuf); + auto flatbuf = std::move(flatbuf1); // Test move assignment. + + AccessFlatBufferTest(reinterpret_cast(rawbuf.c_str()), + rawbuf.length()); + AccessFlatBufferTest(flatbuf.data(), flatbuf.size()); + + MutateFlatBuffersTest(flatbuf.data(), flatbuf.size()); + + ObjectFlatBuffersTest(flatbuf.data()); + UnPackTo(flatbuf.data()); + + MiniReflectFlatBuffersTest(flatbuf.data()); + MiniReflectFixedLengthArrayTest(); + + SizePrefixedTest(); + + AlignmentTest(); + +#ifndef FLATBUFFERS_NO_FILE_TESTS + ParseAndGenerateTextTest(tests_data_path, false); + ParseAndGenerateTextTest(tests_data_path, true); + FixedLengthArrayJsonTest(tests_data_path, false); + FixedLengthArrayJsonTest(tests_data_path, true); + ReflectionTest(tests_data_path, flatbuf.data(), flatbuf.size()); + ParseProtoTest(tests_data_path); + EvolutionTest(tests_data_path); + UnionDeprecationTest(tests_data_path); + UnionVectorTest(tests_data_path); + GenerateTableTextTest(tests_data_path); + TestEmbeddedBinarySchema(tests_data_path); + JsonOptionalTest(tests_data_path, false); + JsonOptionalTest(tests_data_path, true); + MultiFileNameClashTest(tests_data_path); + InvalidNestedFlatbufferTest(tests_data_path); + JsonDefaultTest(tests_data_path); + JsonEnumsTest(tests_data_path); + TestMonsterExtraFloats(tests_data_path); + ParseIncorrectMonsterJsonTest(tests_data_path); + FixedLengthArraySpanTest(tests_data_path); + DoNotRequireEofTest(tests_data_path); + JsonUnionStructTest(); +#else + // Guard against -Wunused-parameter. + (void)tests_data_path; +#endif + + UtilConvertCase(); + + FuzzTest1(); + FuzzTest2(); + + TriviallyCopyableTest(); + ErrorTest(); + ValueTest(); + EnumValueTest(); + NestedListTest(); + EnumStringsTest(); + EnumNamesTest(); + EnumOutOfRangeTest(); + IntegerOutOfRangeTest(); + IntegerBoundaryTest(); + UnicodeTest(); + UnicodeTestAllowNonUTF8(); + UnicodeTestGenerateTextFailsOnNonUTF8(); + UnicodeSurrogatesTest(); + UnicodeInvalidSurrogatesTest(); + InvalidUTF8Test(); + UnknownFieldsTest(); + ParseUnionTest(); + ValidSameNameDifferentNamespaceTest(); + ConformTest(); + ParseProtoBufAsciiTest(); + TypeAliasesTest(); + EndianSwapTest(); + CreateSharedStringTest(); + FlexBuffersTest(); + FlexBuffersReuseBugTest(); + FlexBuffersDeprecatedTest(); + UninitializedVectorTest(); + EqualOperatorTest(); + NumericUtilsTest(); + IsAsciiUtilsTest(); + ValidFloatTest(); + InvalidFloatTest(); + FixedLengthArrayTest(); + NativeTypeTest(); + OptionalScalarsTest(); + ParseFlexbuffersFromJsonWithNullTest(); + FlatbuffersSpanTest(); + FixedLengthArrayConstructorTest(); + FixedLengthArrayOperatorEqualTest(); + FieldIdentifierTest(); + StringVectorDefaultsTest(); + FlexBuffersFloatingPointTest(); + FlatbuffersIteratorsTest(); + WarningsAsErrorsTest(); + NestedVerifierTest(); + PrivateAnnotationsLeaks(); + JsonUnsortedArrayTest(); + VectorSpanTest(); + NativeInlineTableVectorTest(); + FixedSizedScalarKeyInStructTest(); + StructKeyInStructTest(); + NestedStructKeyInStructTest(); + FixedSizedStructArrayKeyInStructTest(); + EmbeddedSchemaAccess(); + Offset64Tests(); + UnionUnderlyingTypeTest(); + return 0; +} +} // namespace +} // namespace tests +} // namespace flatbuffers + +int main(int argc, const char *argv[]) { + std::string tests_data_path = "tests/"; + + for (int argi = 1; argi < argc; argi++) { + std::string arg = argv[argi]; + if (arg == "--test_path") { + if (++argi >= argc) { + fprintf(stderr, "error: missing path following: %s\n", arg.c_str()); + exit(1); + } + // Override default path if provided one. + tests_data_path = argv[argi]; + + } else { + fprintf(stderr, "error: Unknown argument: %s\n", arg.c_str()); + exit(1); + } + } + + InitTestEngine(); + + std::string req_locale; + if (flatbuffers::ReadEnvironmentVariable("FLATBUFFERS_TEST_LOCALE", + &req_locale)) { + TEST_OUTPUT_LINE("The environment variable FLATBUFFERS_TEST_LOCALE=%s", + req_locale.c_str()); + req_locale = flatbuffers::RemoveStringQuotes(req_locale); + std::string the_locale; + TEST_ASSERT_FUNC( + flatbuffers::SetGlobalTestLocale(req_locale.c_str(), &the_locale)); + TEST_OUTPUT_LINE("The global C-locale changed: %s", the_locale.c_str()); + } + +#ifdef FLATBUFFERS_TEST_PATH_PREFIX + tests_data_path = + FLATBUFFERS_STRING(FLATBUFFERS_TEST_PATH_PREFIX) + tests_data_path; +#endif + + flatbuffers::tests::FlatBufferTests(tests_data_path); + FlatBufferBuilderTest(); + + if (!testing_fails) { + TEST_OUTPUT_LINE("ALL TESTS PASSED"); + } else { + TEST_OUTPUT_LINE("%d FAILED TESTS", testing_fails); + } + return CloseTestEngine(); +} diff --git a/third_party/flatbuffers/tests/test.fbs b/third_party/flatbuffers/tests/test.fbs new file mode 100644 index 00000000000..791f7f7b5c0 --- /dev/null +++ b/third_party/flatbuffers/tests/test.fbs @@ -0,0 +1,85 @@ +// Generated from test.proto + +include "imported.fbs"; + +namespace proto.test; + +/// Enum doc comment. +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + /// Enum 2nd value doc comment misaligned. + BAR = 5, +} + +namespace proto.test.ProtoMessage_.OtherMessage_; + +enum ProtoEnum : int { + NUL = 0, + FOO = 1, + BAR = 2, + BAZ = 3, +} + +namespace proto.test; + +/// 2nd table doc comment with +/// many lines. +table ProtoMessage { + c:int = 16; + d:long; + p:uint; + e:ulong; + /// doc comment for f. + f:int = -1; + g:long; + h:uint; + q:ulong; + i:int; + j:long; + /// doc comment for k. + k:bool; + /// doc comment for l on 2 + /// lines + l:string (required); + m:[ubyte]; + n:proto.test.ProtoMessage_.OtherMessage; + o:[string]; + z:proto.test.ImportedMessage; + /// doc comment for r. + r:proto.test.ProtoMessage_.Anonymous0; + outer_enum:proto.test.ProtoEnum; + u:float = +inf; + v:float = +inf; + w:float = -inf; + grades:[proto.test.ProtoMessage_.GradesEntry]; + other_message_map:[proto.test.ProtoMessage_.OtherMessageMapEntry]; +} + +namespace proto.test.ProtoMessage_; + +table OtherMessage { + a:double; + /// doc comment for b. + b:float = 3.14149; + foo_bar_baz:proto.test.ProtoMessage_.OtherMessage_.ProtoEnum; +} + +table Anonymous0 { + /// doc comment for s. + s:proto.test.ImportedMessage; + /// doc comment for t on 2 + /// lines. + t:proto.test.ProtoMessage_.OtherMessage; +} + +table GradesEntry { + key:string (key); + value:float; +} + +table OtherMessageMapEntry { + key:string (key); + value:proto.test.ProtoMessage_.OtherMessage; +} + diff --git a/third_party/flatbuffers/tests/test_assert.cpp b/third_party/flatbuffers/tests/test_assert.cpp new file mode 100644 index 00000000000..32dece982f6 --- /dev/null +++ b/third_party/flatbuffers/tests/test_assert.cpp @@ -0,0 +1,69 @@ +#include "test_assert.h" + +#include + +#ifdef _MSC_VER +# include +# include +#endif + +int testing_fails = 0; +static TestFailEventListener fail_listener_ = nullptr; + +void TestFail(const char *expval, const char *val, const char *exp, + const char *file, int line, const char *func) { + TEST_OUTPUT_LINE("EXPECTED: \"%s\"", expval); + TEST_OUTPUT_LINE("VALUE: \"%s\"", val); + TEST_OUTPUT_LINE("TEST FAILED: %s:%d, %s in %s", file, line, exp, + func ? func : ""); + testing_fails++; + + // Notify, emulate 'gtest::OnTestPartResult' event handler. + if (fail_listener_) (*fail_listener_)(expval, val, exp, file, line, func); + + assert(0); // ignored in Release if NDEBUG defined +} + +void TestEqStr(const char *expval, const char *val, const char *exp, + const char *file, int line, const char *func) { + if (strcmp(expval, val) != 0) { + TestFail(expval, val, exp, file, line, func); + } +} + +#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING) && defined(_MSC_VER) && \ + defined(_DEBUG) +# define FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC +#endif + +void InitTestEngine(TestFailEventListener listener) { + testing_fails = 0; + // Disable stdout buffering to prevent information lost on assertion or core + // dump. + setvbuf(stdout, nullptr, _IONBF, 0); + setvbuf(stderr, nullptr, _IONBF, 0); + + // clang-format off + + #if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC) + // For more thorough checking: + // _CRTDBG_DELAY_FREE_MEM_DF | _CRTDBG_CHECK_ALWAYS_DF + auto flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + _CrtSetDbgFlag(flags | _CRTDBG_ALLOC_MEM_DF); + #endif + // clang-format on + + fail_listener_ = listener; +} + +int CloseTestEngine(bool force_report) { + if (!testing_fails || force_report) { +#if defined(FLATBUFFERS_MEMORY_LEAK_TRACKING_MSVC) + auto flags = _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG); + flags &= ~_CRTDBG_DELAY_FREE_MEM_DF; + flags |= _CRTDBG_LEAK_CHECK_DF; + _CrtSetDbgFlag(flags); +#endif + } + return (0 != testing_fails); +} diff --git a/third_party/flatbuffers/tests/test_assert.h b/third_party/flatbuffers/tests/test_assert.h new file mode 100644 index 00000000000..16048b165d5 --- /dev/null +++ b/third_party/flatbuffers/tests/test_assert.h @@ -0,0 +1,131 @@ +#ifndef TEST_ASSERT_H +#define TEST_ASSERT_H + +#include "flatbuffers/base.h" +#include "flatbuffers/util.h" + +// clang-format off + +#ifdef __ANDROID__ + #include + #define TEST_OUTPUT_LINE(...) \ + __android_log_print(ANDROID_LOG_INFO, "FlatBuffers", __VA_ARGS__) + #define FLATBUFFERS_NO_FILE_TESTS +#else + #define TEST_OUTPUT_LINE(...) \ + do { printf(__VA_ARGS__); printf("\n"); } while(!flatbuffers::IsConstTrue(true)) +#endif + +#define TEST_EQ(exp, val) TestEq(exp, val, "'" #exp "' != '" #val "'", __FILE__, __LINE__, "") +#define TEST_NE(exp, val) TestNe(exp, val, "'" #exp "' == '" #val "'", __FILE__, __LINE__, "") +#define TEST_ASSERT(val) TestEq(true, !!(val), "'" "true" "' != '" #val "'", __FILE__, __LINE__, "") +#define TEST_NULL(val) TestEq(true, (val) == nullptr, "'" "nullptr" "' != '" #val "'", __FILE__, __LINE__, "") +#define TEST_NOTNULL(val) TestEq(true, (val) != nullptr, "'" "nullptr" "' == '" #val "'", __FILE__, __LINE__, "") +#define TEST_EQ_STR(exp, val) TestEqStr(exp, val, "'" #exp "' != '" #val "'", __FILE__, __LINE__, "") + +#ifdef _WIN32 + #define TEST_ASSERT_FUNC(val) TestEq(true, !!(val), "'" "true" "' != '" #val "'", __FILE__, __LINE__, __FUNCTION__) + #define TEST_EQ_FUNC(exp, val) TestEq(exp, val, "'" #exp "' != '" #val "'", __FILE__, __LINE__, __FUNCTION__) +#else + #define TEST_ASSERT_FUNC(val) TestEq(true, !!(val), "'" "true" "' != '" #val "'", __FILE__, __LINE__, __PRETTY_FUNCTION__) + #define TEST_EQ_FUNC(exp, val) TestEq(exp, val, "'" #exp "' != '" #val "'", __FILE__, __LINE__, __PRETTY_FUNCTION__) +#endif + +// clang-format on + +extern int testing_fails; + +// Listener of TestFail, like 'gtest::OnTestPartResult' event handler. +// Called in TestFail after a failed assertion. +typedef bool (*TestFailEventListener)(const char *expval, const char *val, + const char *exp, const char *file, + int line, const char *func); + +// Prepare test engine (MSVC assertion setup, etc). +// listener - this function will be notified on each TestFail call. +void InitTestEngine(TestFailEventListener listener = nullptr); + +// Release all test-engine resources. +// Prints or schedule a debug report if all test passed. +// Returns 0 if all tests passed or 1 otherwise. +// Memory leak report: FLATBUFFERS_MEMORY_LEAK_TRACKING && _MSC_VER && _DEBUG. +int CloseTestEngine(bool force_report = false); + +// Write captured state to a log and terminate test run. +void TestFail(const char *expval, const char *val, const char *exp, + const char *file, int line, const char *func = nullptr); + +void TestEqStr(const char *expval, const char *val, const char *exp, + const char *file, int line, const char *func = nullptr); + +// Workaround for `enum class` printing. +// There is an issue with the printing of enums with a fixed underlying type. +// These enums are generated by `flatc` if `--scoped-enums` is active. +// All modern compilers have problems with `std::stringstream&<<(T v)` if T is +// an enum with fixed type. For details see DR1601: +// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_defects.html#1601 +// https://stackoverflow.com/questions/34336024/ambiguous-overload-when-writing-an-enum-with-an-enum-base-but-only-with-clang + +template::value> +struct underlying_of_scalar { + static_assert(flatbuffers::is_scalar::value, "invalid type T"); + typedef T type; +}; + +template struct underlying_of_scalar { +// clang-format off + // There are old compilers without full C++11 support (see stl_emulation.h). + #if defined(FLATBUFFERS_TEMPLATES_ALIASES) + using type = typename std::underlying_type::type; + #else + typedef int64_t type; + #endif + // clang-format on +}; + +template +typename underlying_of_scalar::type scalar_as_underlying(T v) { + return static_cast::type>(v); +} + +template +void TestEq(T expval, U val, const char *exp, const char *file, int line, + const char *func) { + if (static_cast(expval) != val) { + TestFail(flatbuffers::NumToString(scalar_as_underlying(expval)).c_str(), + flatbuffers::NumToString(scalar_as_underlying(val)).c_str(), exp, + file, line, func); + } +} + +template<> +inline void TestEq(std::string expval, + std::string val, const char *exp, + const char *file, int line, + const char *func) { + if (expval != val) { + TestFail(expval.c_str(), val.c_str(), exp, file, line, func); + } +} + +template +void TestNe(T expval, U val, const char *exp, const char *file, int line, + const char *func) { + if (static_cast(expval) == val) { + TestFail(flatbuffers::NumToString(scalar_as_underlying(expval)).c_str(), + flatbuffers::NumToString(scalar_as_underlying(val)).c_str(), exp, + file, line, func); + } +} + +template<> +inline void TestNe(std::string expval, + std::string val, const char *exp, + const char *file, int line, + const char *func) { + if (expval == val) { + TestFail(expval.c_str(), val.c_str(), exp, file, line, func); + } +} + +#endif // !TEST_ASSERT_H diff --git a/third_party/flatbuffers/tests/test_builder.cpp b/third_party/flatbuffers/tests/test_builder.cpp new file mode 100644 index 00000000000..8b14a92aea6 --- /dev/null +++ b/third_party/flatbuffers/tests/test_builder.cpp @@ -0,0 +1,149 @@ +#include "test_builder.h" + +#include "flatbuffers/flatbuffer_builder.h" +#include "flatbuffers/stl_emulation.h" +#include "monster_test_generated.h" + +using namespace MyGame::Example; +using namespace flatbuffers; + +struct OwnedAllocator : public DefaultAllocator {}; + +class TestHeapBuilder : public FlatBufferBuilder { + private: + TestHeapBuilder(const TestHeapBuilder &); + TestHeapBuilder &operator=(const TestHeapBuilder &); + + public: + TestHeapBuilder() : FlatBufferBuilder(2048, new OwnedAllocator(), true) {} + + TestHeapBuilder(TestHeapBuilder &&other) + : FlatBufferBuilder(std::move(other)) {} + + TestHeapBuilder &operator=(TestHeapBuilder &&other) { + FlatBufferBuilder::operator=(std::move(other)); + return *this; + } +}; + +// This class simulates flatbuffers::grpc::detail::SliceAllocatorMember +struct AllocatorMember { + flatbuffers::DefaultAllocator member_allocator_; +}; + +struct GrpcLikeMessageBuilder : private AllocatorMember, + public FlatBufferBuilder { + private: + GrpcLikeMessageBuilder(const GrpcLikeMessageBuilder &); + GrpcLikeMessageBuilder &operator=(const GrpcLikeMessageBuilder &); + + public: + GrpcLikeMessageBuilder() + : FlatBufferBuilder(1024, &member_allocator_, false) {} + + GrpcLikeMessageBuilder(GrpcLikeMessageBuilder &&other) + : FlatBufferBuilder(1024, &member_allocator_, false) { + // Default construct and swap idiom. + Swap(other); + } + + GrpcLikeMessageBuilder &operator=(GrpcLikeMessageBuilder &&other) { + // Construct temporary and swap idiom + GrpcLikeMessageBuilder temp(std::move(other)); + Swap(temp); + return *this; + } + + void Swap(GrpcLikeMessageBuilder &other) { + // No need to swap member_allocator_ because it's stateless. + FlatBufferBuilder::Swap(other); + // After swapping the FlatBufferBuilder, we swap back the allocator, which + // restores the original allocator back in place. This is necessary because + // MessageBuilder's allocator is its own member (SliceAllocatorMember). The + // allocator passed to FlatBufferBuilder::vector_downward must point to this + // member. + buf_.swap_allocator(other.buf_); + } +}; + +flatbuffers::Offset populate1( + flatbuffers::FlatBufferBuilder &builder) { + auto name_offset = builder.CreateString(m1_name()); + return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m1_color()); +} + +flatbuffers::Offset populate2( + flatbuffers::FlatBufferBuilder &builder) { + auto name_offset = builder.CreateString(m2_name()); + return CreateMonster(builder, nullptr, 0, 0, name_offset, 0, m2_color()); +} + +uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size, + size_t &offset) { + return fbb.ReleaseRaw(size, offset); +} + +void free_raw(flatbuffers::grpc::MessageBuilder &, uint8_t *) { + // release_raw_base calls FlatBufferBuilder::ReleaseRaw on the argument + // MessageBuilder. It's semantically wrong as MessageBuilder has its own + // ReleaseRaw member function that takes three arguments. In such cases + // though, ~MessageBuilder() invokes ~SliceAllocator() that takes care of + // deleting memory as it calls grpc_slice_unref. Obviously, this behavior is + // very surprising as the pointer returned by FlatBufferBuilder::ReleaseRaw is + // not valid as soon as MessageBuilder goes out of scope. This problem does + // not occur with FlatBufferBuilder. +} + +void free_raw(flatbuffers::FlatBufferBuilder &, uint8_t *buf) { + flatbuffers::DefaultAllocator().deallocate(buf, 0); +} + +bool verify(const flatbuffers::DetachedBuffer &buf, + const std::string &expected_name, Color color) { + const Monster *monster = flatbuffers::GetRoot(buf.data()); + return (monster->name()->str() == expected_name) && + (monster->color() == color); +} + +bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name, + Color color) { + const Monster *monster = flatbuffers::GetRoot(buf + offset); + return (monster->name()->str() == expected_name) && + (monster->color() == color); +} + +bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, + const std::string &expected_name, Color color) { + flatbuffers::DetachedBuffer buf = fbb.Release(); + return verify(buf, expected_name, color); +} + +// forward-declared in test.cpp +void FlatBufferBuilderTest(); + +void FlatBufferBuilderTest() { + using flatbuffers::FlatBufferBuilder; + + BuilderTests::all_tests(); + BuilderTests::all_tests(); + BuilderTests::all_tests(); + + BuilderReuseTestSelector tests[4] = { + REUSABLE_AFTER_RELEASE, REUSABLE_AFTER_RELEASE_RAW, + REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN, + REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN + }; + + BuilderReuseTests::run_tests( + TestSelector(tests, tests + 4)); + BuilderReuseTests::run_tests( + TestSelector(tests, tests + 4)); + BuilderReuseTests::run_tests( + TestSelector(tests, tests + 4)); +} + +// forward-declared in test_builder.h +void CheckTestGeneratedIsValid(const MyGame::Example::Color &); + +// Link-time check using pointer type. +void CheckTestGeneratedIsValid(const MyGame::Example::Color &) {} diff --git a/third_party/flatbuffers/tests/test_builder.h b/third_party/flatbuffers/tests/test_builder.h new file mode 100644 index 00000000000..8a214bab949 --- /dev/null +++ b/third_party/flatbuffers/tests/test_builder.h @@ -0,0 +1,300 @@ +#ifndef TEST_BUILDER_H +#define TEST_BUILDER_H + +#include +#include + +#include "flatbuffers/flatbuffers.h" +#include "monster_test_generated.h" +#include "test_assert.h" + +using MyGame::Example::Color; +using MyGame::Example::Monster; + +namespace flatbuffers { +namespace grpc { +class MessageBuilder; +} +} // namespace flatbuffers + +inline std::string m1_name() { return "Cyberdemon"; } +inline std::string m2_name() { return "Imp"; } +inline MyGame::Example::Color m1_color() { + return MyGame::Example::Color_Red; +} +inline MyGame::Example::Color m2_color() { + return MyGame::Example::Color_Green; +} +inline void m1_color_check() { + // Ensure that all compilation units see the same monster_test_generated.h. + extern void CheckTestGeneratedIsValid(const MyGame::Example::Color&); + CheckTestGeneratedIsValid(m1_color()); +} + +flatbuffers::Offset populate1(flatbuffers::FlatBufferBuilder &builder); +flatbuffers::Offset populate2(flatbuffers::FlatBufferBuilder &builder); + +uint8_t *release_raw_base(flatbuffers::FlatBufferBuilder &fbb, size_t &size, + size_t &offset); + +void free_raw(flatbuffers::grpc::MessageBuilder &mbb, uint8_t *buf); +void free_raw(flatbuffers::FlatBufferBuilder &fbb, uint8_t *buf); + +bool verify(const flatbuffers::DetachedBuffer &buf, + const std::string &expected_name, Color color); +bool verify(const uint8_t *buf, size_t offset, const std::string &expected_name, + Color color); + +bool release_n_verify(flatbuffers::FlatBufferBuilder &fbb, + const std::string &expected_name, Color color); +bool release_n_verify(flatbuffers::grpc::MessageBuilder &mbb, + const std::string &expected_name, Color color); + +// Invokes this function when testing the following Builder types +// FlatBufferBuilder, TestHeapBuilder, and GrpcLikeMessageBuilder +template +void builder_move_assign_after_releaseraw_test(Builder b1) { + auto root_offset1 = populate1(b1); + b1.Finish(root_offset1); + size_t size, offset; + + uint8_t *rr = b1.ReleaseRaw(size, offset); + std::shared_ptr raw( + rr, [size](uint8_t *ptr) { + flatbuffers::DefaultAllocator::dealloc(ptr, size); + }); + Builder src; + auto root_offset2 = populate2(src); + src.Finish(root_offset2); + auto src_size = src.GetSize(); + // Move into a released builder. + b1 = std::move(src); + TEST_EQ_FUNC(b1.GetSize(), src_size); + TEST_ASSERT_FUNC(release_n_verify(b1, m2_name(), m2_color())); + TEST_EQ_FUNC(src.GetSize(), 0); +} + +void builder_move_assign_after_releaseraw_test( + flatbuffers::grpc::MessageBuilder b1); + +template +struct BuilderTests { + static void empty_builder_movector_test() { + SrcBuilder src; + size_t src_size = src.GetSize(); + DestBuilder dst(std::move(src)); + size_t dst_size = dst.GetSize(); + TEST_EQ_FUNC(src_size, 0); + TEST_EQ_FUNC(src_size, dst_size); + } + + static void nonempty_builder_movector_test() { + SrcBuilder src; + populate1(src); + size_t src_size = src.GetSize(); + DestBuilder dst(std::move(src)); + TEST_EQ_FUNC(src_size, dst.GetSize()); + TEST_EQ_FUNC(src.GetSize(), 0); + } + + static void builder_movector_before_finish_test() { + SrcBuilder src; + auto root_offset1 = populate1(src); + DestBuilder dst(std::move(src)); + dst.Finish(root_offset1); + TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color())); + TEST_EQ_FUNC(src.GetSize(), 0); + } + + static void builder_movector_after_finish_test() { + SrcBuilder src; + auto root_offset1 = populate1(src); + src.Finish(root_offset1); + auto src_size = src.GetSize(); + DestBuilder dst(std::move(src)); + TEST_EQ_FUNC(dst.GetSize(), src_size); + TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color())); + TEST_EQ_FUNC(src.GetSize(), 0); + } + + static void builder_move_assign_before_finish_test() { + SrcBuilder src; + auto root_offset1 = populate1(src); + DestBuilder dst; + populate2(dst); + dst = std::move(src); + dst.Finish(root_offset1); + TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color())); + TEST_EQ_FUNC(src.GetSize(), 0); + } + + static void builder_move_assign_after_finish_test() { + SrcBuilder src; + auto root_offset1 = populate1(src); + src.Finish(root_offset1); + auto src_size = src.GetSize(); + DestBuilder dst; + auto root_offset2 = populate2(dst); + dst.Finish(root_offset2); + dst = std::move(src); + TEST_EQ_FUNC(dst.GetSize(), src_size); + TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color())); + TEST_EQ_FUNC(src.GetSize(), 0); + } + + static void builder_move_assign_after_release_test() { + DestBuilder dst; + auto root_offset1 = populate1(dst); + dst.Finish(root_offset1); + { + flatbuffers::DetachedBuffer dst_detached = dst.Release(); + // detached buffer is deleted + } + SrcBuilder src; + auto root_offset2 = populate2(src); + src.Finish(root_offset2); + auto src_size = src.GetSize(); + // Move into a released builder. + dst = std::move(src); + TEST_EQ_FUNC(dst.GetSize(), src_size); + TEST_ASSERT_FUNC(release_n_verify(dst, m2_name(), m2_color())); + TEST_EQ_FUNC(src.GetSize(), 0); + } + + static void builder_swap_before_finish_test( + bool run = std::is_same::value) { + /// Swap is allowed only when lhs and rhs are the same concrete type. + if (run) { + SrcBuilder src; + auto root_offset1 = populate1(src); + auto size1 = src.GetSize(); + DestBuilder dst; + auto root_offset2 = populate2(dst); + auto size2 = dst.GetSize(); + src.Swap(dst); + src.Finish(root_offset2); + dst.Finish(root_offset1); + TEST_EQ_FUNC(src.GetSize() > size2, true); + TEST_EQ_FUNC(dst.GetSize() > size1, true); + TEST_ASSERT_FUNC(release_n_verify(src, m2_name(), m2_color())); + TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color())); + } + } + + static void builder_swap_after_finish_test( + bool run = std::is_same::value) { + /// Swap is allowed only when lhs and rhs are the same concrete type. + if (run) { + SrcBuilder src; + auto root_offset1 = populate1(src); + src.Finish(root_offset1); + auto size1 = src.GetSize(); + DestBuilder dst; + auto root_offset2 = populate2(dst); + dst.Finish(root_offset2); + auto size2 = dst.GetSize(); + src.Swap(dst); + TEST_EQ_FUNC(src.GetSize(), size2); + TEST_EQ_FUNC(dst.GetSize(), size1); + TEST_ASSERT_FUNC(release_n_verify(src, m2_name(), m2_color())); + TEST_ASSERT_FUNC(release_n_verify(dst, m1_name(), m1_color())); + } + } + + static void all_tests() { + empty_builder_movector_test(); + nonempty_builder_movector_test(); + builder_movector_before_finish_test(); + builder_movector_after_finish_test(); + builder_move_assign_before_finish_test(); + builder_move_assign_after_finish_test(); + builder_move_assign_after_release_test(); + builder_move_assign_after_releaseraw_test(DestBuilder()); + builder_swap_before_finish_test(); + builder_swap_after_finish_test(); + } +}; + +enum BuilderReuseTestSelector { + REUSABLE_AFTER_RELEASE = 1, + REUSABLE_AFTER_RELEASE_RAW = 2, + REUSABLE_AFTER_RELEASE_MESSAGE = 3, + REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN = 4, + REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN = 5, + REUSABLE_AFTER_RELEASE_MESSAGE_AND_MOVE_ASSIGN = 6 +}; + +typedef std::set TestSelector; + +template struct BuilderReuseTests { + static void builder_reusable_after_release_test(TestSelector selector) { + if (!selector.count(REUSABLE_AFTER_RELEASE)) { return; } + + DestBuilder fbb; + std::vector buffers; + for (int i = 0; i < 5; ++i) { + auto root_offset1 = populate1(fbb); + fbb.Finish(root_offset1); + buffers.push_back(fbb.Release()); + TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color())); + } + } + + static void builder_reusable_after_releaseraw_test(TestSelector selector) { + if (!selector.count(REUSABLE_AFTER_RELEASE_RAW)) { return; } + + DestBuilder fbb; + for (int i = 0; i < 5; ++i) { + auto root_offset1 = populate1(fbb); + fbb.Finish(root_offset1); + size_t size, offset; + uint8_t *buf = release_raw_base(fbb, size, offset); + TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color())); + free_raw(fbb, buf); + } + } + + static void builder_reusable_after_release_and_move_assign_test( + TestSelector selector) { + if (!selector.count(REUSABLE_AFTER_RELEASE_AND_MOVE_ASSIGN)) { return; } + + DestBuilder dst; + std::vector buffers; + for (int i = 0; i < 5; ++i) { + auto root_offset1 = populate1(dst); + dst.Finish(root_offset1); + buffers.push_back(dst.Release()); + TEST_ASSERT_FUNC(verify(buffers[i], m1_name(), m1_color())); + SrcBuilder src; + dst = std::move(src); + TEST_EQ_FUNC(src.GetSize(), 0); + } + } + + static void builder_reusable_after_releaseraw_and_move_assign_test( + TestSelector selector) { + if (!selector.count(REUSABLE_AFTER_RELEASE_RAW_AND_MOVE_ASSIGN)) { return; } + + DestBuilder dst; + for (int i = 0; i < 5; ++i) { + auto root_offset1 = populate1(dst); + dst.Finish(root_offset1); + size_t size, offset; + uint8_t *buf = release_raw_base(dst, size, offset); + TEST_ASSERT_FUNC(verify(buf, offset, m1_name(), m1_color())); + free_raw(dst, buf); + SrcBuilder src; + dst = std::move(src); + TEST_EQ_FUNC(src.GetSize(), 0); + } + } + + static void run_tests(TestSelector selector) { + builder_reusable_after_release_test(selector); + builder_reusable_after_releaseraw_test(selector); + builder_reusable_after_release_and_move_assign_test(selector); + builder_reusable_after_releaseraw_and_move_assign_test(selector); + } +}; + +#endif // TEST_BUILDER_H diff --git a/third_party/flatbuffers/tests/ts/BUILD.bazel b/third_party/flatbuffers/tests/ts/BUILD.bazel new file mode 100644 index 00000000000..cb5e6ad629b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/BUILD.bazel @@ -0,0 +1,62 @@ +load("@aspect_rules_js//js:defs.bzl", "js_test") +load("@aspect_rules_js//npm:defs.bzl", "npm_link_package") +load("//:typescript.bzl", "flatbuffer_ts_library") + +package(default_visibility = ["//visibility:private"]) + +# This is a copy of //ts:node_modules/flatbuffers. The rules_js-based tests +# require this target to live in the same or a parent package. Since we don't +# want to put rules_js targets in the root package, we create a copy here. +npm_link_package( + name = "node_modules/flatbuffers", + src = "//ts:flatbuffers", + root_package = "tests/ts", +) + +flatbuffer_ts_library( + name = "typescript_ts_fbs", + srcs = ["typescript_keywords.fbs"], + deps = [ + "//reflection/ts:reflection_ts_fbs", + "//tests/ts/test_dir:include_ts_fbs", + "//tests/ts/test_dir:typescript_transitive_ts_fbs", + ], +) + +TEST_DATA = glob([ + "my-game/*.js", + "my-game/example/*.js", + "my-game/example2/*.js", +]) + +TEST_UNION_VECTOR_DATA = glob([ + "union_vector/*.js", +]) + +TEST_COMPLEX_ARRAYS_DATA = glob([ + "arrays_test_complex/**/*.js", +]) + +# Here we're running the tests against the checked-in generated files. These +# are kept up-to-date with a CI-based mechanism. The intent of running these +# tests here via bazel is not to validate that they're up-to-date. Instead, we +# just want to make it easy to run these tests while making other changes. For +# example, this is useful when making changes to the rules_js setup to validate +# that the basic infrastructure is still working. +[js_test( + name = "%s_test" % test, + chdir = package_name(), + data = data + [ + "package.json", + "//tests:test_data_copied_to_bin", + "//tests/ts:node_modules/flatbuffers", + ], + entry_point = "%s.js" % test, +) for test, data in ( + ("JavaScriptTest", TEST_DATA), + ("JavaScriptUnionVectorTest", TEST_UNION_VECTOR_DATA), + # TODO(philsc): Figure out how to run this test with flexbuffers available. + # At the moment the flexbuffer library is not exposed as a bazel target. + #("JavaScriptFlexBuffersTest", TBD_DATA) + ("JavaScriptComplexArraysTest", TEST_COMPLEX_ARRAYS_DATA), +)] diff --git a/third_party/flatbuffers/tests/ts/JavaScriptComplexArraysTest.js b/third_party/flatbuffers/tests/ts/JavaScriptComplexArraysTest.js new file mode 100644 index 00000000000..36469e577e6 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptComplexArraysTest.js @@ -0,0 +1,126 @@ +/* global BigInt */ + +import assert from 'assert'; +import { readFileSync, writeFileSync } from 'fs'; +import * as flatbuffers from 'flatbuffers'; +import { ArrayStructT } from './arrays_test_complex/my-game/example/array-struct.js' +import { ArrayTable, ArrayTableT } from './arrays_test_complex/my-game/example/array-table.js' +import { InnerStructT } from './arrays_test_complex/my-game/example/inner-struct.js' +import { NestedStructT } from './arrays_test_complex/my-game/example/nested-struct.js' +import { OuterStructT } from './arrays_test_complex/my-game/example/outer-struct.js' +import { TestEnum } from './arrays_test_complex/my-game/example/test-enum.js' +// eslint-disable-next-line @typescript-eslint/no-explicit-any +BigInt.prototype.toJSON = function () { + return this.toString(); +}; +function fbObjToObj(fbObj) { + const ret = {}; + for (const propName of Object.keys(fbObj)) { + const key = propName; + const prop = fbObj[key]; + if (prop.valueOf) { + ret[key] = prop.valueOf(); + } else if (typeof prop === 'object') { + ret[key] = fbObjToObj(prop); + } + } + return ret; +} +function testBuild(monFile, jsFile) { + const arrayTable = new ArrayTableT( + 'Complex Array Test', + new ArrayStructT( + 221.139008, + [-700, -600, -500, -400, -300, -200, -100, 0, 100, 200, 300, 400, 500, 600, 700], + 13, + [ + new NestedStructT( + [233, -123], + TestEnum.B, + [TestEnum.A, TestEnum.C], + [ + new OuterStructT( + false, + 123.456, + new InnerStructT( + 123456792.0, + [13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1], + 91, + BigInt('9007199254740999') + ), + [ + new InnerStructT( + -987654321.9876, + [255, 254, 253, 252, 251, 250, 249, 248, 247, 246, 245, 244, 243], + 123, + BigInt('9007199254741000') + ), + new InnerStructT( + 123000987.9876, + [101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113], + -123, + BigInt('9007199254741000') + ), + ], + new InnerStructT( + 987654321.9876, + [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], + 19, + BigInt('9007199254741000') + ), + [111000111.222, 222000222.111, 333000333.333, 444000444.444] + ), + ] + ), + ], + -123456789 + ) + ); + const builder = new flatbuffers.Builder(); + builder.finish(arrayTable.pack(builder)); + if (jsFile) { + const obj = fbObjToObj(arrayTable); + writeFileSync(jsFile, `export default ${JSON.stringify(obj, null, 2)}`); + } + if (monFile) { + writeFileSync(monFile, builder.asUint8Array()); + } + return builder.asUint8Array(); +} +function testParse(monFile, jsFile, buffer) { + if (!buffer) { + if (!monFile) { + console.log(`Please specify mon file read the buffer from.`); + process.exit(1); + } + buffer = readFileSync(monFile); + } + const byteBuffer = new flatbuffers.ByteBuffer(new Uint8Array(buffer)); + const arrayTable = ArrayTable.getRootAsArrayTable(byteBuffer).unpack(); + const json = JSON.stringify(arrayTable, null, 2); + if (jsFile) { + writeFileSync(jsFile, `export default ${json}`); + } + return arrayTable; +} +if (process.argv[2] === 'build') { + testBuild(process.argv[3], process.argv[4]); +} else if (process.argv[2] === 'parse') { + testParse(process.argv[3], process.argv[4], null); +} else { + const arr = testBuild(null, null); + const parsed = testParse(null, null, Buffer.from(arr)); + assert.strictEqual(parsed.a, 'Complex Array Test', 'String Test'); + assert.strictEqual(parsed?.cUnderscore?.aUnderscore, 221.13900756835938, 'Float Test'); + assert.deepEqual(parsed?.cUnderscore?.bUnderscore, [-700, -600, -500, -400, -300, -200, -100, 0, 100, 200, 300, 400, 500, 600, 700], 'Array of signed integers'); + assert.strictEqual(parsed?.cUnderscore.d?.[0].dOuter[0].d[1].a, 123000987.9876, 'Float in deep'); + assert.deepEqual(parsed?.cUnderscore?.d[0].dOuter?.[0]?.e, { + a: 987654321.9876, + b: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13], + c: 19, + dUnderscore: '9007199254741000', + }, 'Object in deep'); + assert.deepEqual(parsed?.cUnderscore.g, ['0', '0'], 'Last object'); + + console.log('Arrays test: completed successfully'); +} diff --git a/third_party/flatbuffers/tests/ts/JavaScriptFlexBuffersTest.js b/third_party/flatbuffers/tests/ts/JavaScriptFlexBuffersTest.js new file mode 100644 index 00000000000..04e670c2e77 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptFlexBuffersTest.js @@ -0,0 +1,390 @@ +// Run this using JavaScriptTest.sh +import assert from 'assert' +import fs from 'fs' +import * as flexbuffers from 'flatbuffers/js/flexbuffers.js' + +function main() { + testSingleValueBuffers(); + testGoldBuffer(); + testEncode(); + testIndirectAdd(); + testIndirectWithCache(); + testMapBuilder(); + testRoundTrip(); + testRoundTripWithBuilder(); + testDeduplicationOff(); + testBugWhereOffestWereStoredAsIntInsteadOfUInt(); + + console.log('FlexBuffers test: completed successfully'); +} + +function testSingleValueBuffers() { + { + const ref = flexbuffers.toReference(new Uint8Array([0, 0, 1]).buffer); + assert.strictEqual(true, ref.isNull()); + } + + function _assert(object, buffer) { + assert.deepStrictEqual(flexbuffers.toObject(new Uint8Array(buffer).buffer), object); + } + _assert(true, [1, 104, 1]); + _assert(false, [0, 104, 1]); + _assert(25, [25, 4, 1]); + _assert(-25, [231, 4, 1]); + _assert(230, [230, 8, 1]); + _assert(230, [230, 0, 5, 2]); + _assert(-1025, [255, 251, 5, 2]); + _assert(1025, [1, 4, 9, 2]); + _assert(2147483647, [255, 255, 255, 127, 6, 4]); + _assert(-2147483648, [0, 0, 0, 128, 6, 4]); + _assert(4294967295n, [255, 255, 255, 255, 0, 0, 0, 0, 7, 8]); + _assert(9223372036854775807n, [255, 255, 255, 255, 255, 255, 255, 127, 7, 8]); + _assert(-9223372036854775808n, [0, 0, 0, 0, 0, 0, 0, 128, 7, 8]); + _assert(18446744073709551615n, [255, 255, 255, 255, 255, 255, 255, 255, 11, 8]); + _assert(4.5, [0, 0, 144, 64, 14, 4]); + _assert(0.10000000149011612, [205, 204, 204, 61, 14, 4]); + _assert(0.1, [154, 153, 153, 153, 153, 153, 185, 63, 15, 8]); + _assert(-1025, [255, 251, 5, 2]); + _assert("Maxim", [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]); + _assert("hello 😱", [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]); + _assert({a:12}, [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]); + _assert({"":45, "a": 12}, [0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]); +} + +function testEncode() { + function _assert(value, buffer) { + assert.deepStrictEqual(flexbuffers.encode(value), new Uint8Array(buffer)); + } + _assert(null, [0, 0, 1]); + _assert(true, [1, 104, 1]); + _assert(false, [0, 104, 1]); + _assert(1, [1, 4, 1]); + _assert(230, [230, 0, 5, 2]); + _assert(1025, [1, 4, 5, 2]); + _assert(-1025, [255, 251, 5, 2]); + _assert(0x100000001, [1, 0, 0, 0, 1, 0, 0, 0, 7, 8]); + _assert(0.1, [154, 153, 153, 153, 153, 153, 185, 63, 15, 8]); + _assert(0.5, [0, 0, 0, 63, 14, 4]); + _assert(new Uint8Array([1, 2, 3]), [3, 1, 2, 3, 3, 100, 1]); + _assert("Maxim", [5, 77, 97, 120, 105, 109, 0, 6, 20, 1]); + _assert("hello 😱", [10, 104, 101, 108, 108, 111, 32, 240, 159, 152, 177, 0, 11, 20, 1]); + _assert([1, 2], [1, 2, 2, 64, 1]); + _assert([-1, 256], [255, 255, 0, 1, 4, 65, 1]); + _assert([-45, 256000], [211, 255, 255, 255, 0, 232, 3, 0, 8, 66, 1]); + _assert([1.1, -256.0], [2, 0, 0, 0, 0, 0, 0, 0, 154, 153, 153, 153, 153, 153, 241, 63, 0, 255, 255, 255, 255, 255, 255, 255, 15, 5, 18, 43, 1]); + _assert([1, 2, 4], [1, 2, 4, 3, 76, 1]); + _assert([-1, 256, 4], [255, 255, 0, 1, 4, 0, 6, 77, 1]); + _assert([[61], 64], [1, 61, 2, 2, 64, 44, 4, 4, 40, 1]); + _assert(["foo", "bar", "baz"], [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 3, 15, 11, 7, 3, 60, 1]); + _assert(["foo", "bar", "baz", "foo", "bar", "baz"], [3, 102, 111, 111, 0, 3, 98, 97, 114, 0, 3, 98, 97, 122, 0, 6, 15, 11, 7, 18, 14, 10, 6, 60, 1]); + _assert([true, false, true], [3, 1, 0, 1, 3, 144, 1]); + _assert(['foo', 1, -5, 1.3, true], [ + 3, 102, 111, 111, 0, 0, 0, 0, + 5, 0, 0, 0, 0, 0, 0, 0, + 15, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, + 251, 255, 255, 255, 255, 255, 255, 255, + 205, 204, 204, 204, 204, 204, 244, 63, + 1, 0, 0, 0, 0, 0, 0, 0, + 20, 4, 4, 15, 104, 45, 43, 1 + ]); + _assert([1, 3.3, 'max', true, null, false], [ + 3, 109, 97, 120, 0, 0, 0, 0, + 6, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, + 102, 102, 102, 102, 102, 102, 10, 64, + 31, 0, 0, 0, 0, 0, 0, 0, + 1, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, + 4, 15, 20, 104, 0, 104, 54, 43, 1 + ]); + _assert({"a": 12}, [97, 0, 1, 3, 1, 1, 1, 12, 4, 2, 36, 1]); + _assert({"a": 12, "":45}, [0, 97, 0, 2, 4, 4, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1]); + // JS currently does not support key vector offset sharing + _assert([{'something':12}, {'something': 45}], [ + 115, 111, 109, 101, 116, 104, 105, 110, 103, 0, + 1, 11, 1, 1, 1, 12, 4, 6, 1, 1, 45, 4, 2, 8, 4, 36, 36, 4, 40, 1 + ]); +} + +function testDeduplicationOff() { + let buffer = flexbuffers.encode([{'something':12}, {'something': 45}], 1, true, true, false); + assert.deepStrictEqual(buffer, new Uint8Array([ + 115, 111, 109, 101, 116, 104, 105, 110, 103, + 0, 1, 11, 1, 1, 1, 12, 4, 1, + 18, 1, 1, 1, 45, 4, 2, 10, 4, + 36, 36, 4, 40, 1 + ])); + + buffer = flexbuffers.encode([{'something':12}, {'something': 45}], 1, true, false, false); + assert.deepStrictEqual(buffer, new Uint8Array([ + 115, 111, 109, 101, 116, 104, 105, 110, 103, 0, + 1, 11, 1, 1, 1, 12, 4, 115, 111, 109, + 101, 116, 104, 105, 110, 103, 0, 1, 11, 1, + 1, 1, 45, 4, 2, 20, 4, 36, 36, 4, + 40, 1 + ])); + + buffer = flexbuffers.encode(['something', 'something', 'dark'], 1, true, false, false); + assert.deepStrictEqual(buffer, new Uint8Array([ + 9, 115, 111, 109, 101, 116, 104, + 105, 110, 103, 0, 4, 100, 97, + 114, 107, 0, 3, 17, 18, 8, + 3, 60, 1 + ])); + + buffer = flexbuffers.encode(['something', 'something', 'dark'], 1, false, false, false); + assert.deepStrictEqual(buffer, new Uint8Array([ + 9, 115, 111, 109, 101, 116, 104, 105, 110, + 103, 0, 9, 115, 111, 109, 101, 116, 104, + 105, 110, 103, 0, 4, 100, 97, 114, 107, + 0, 3, 28, 18, 8, 3, 60, 1 + ])); +} + +function testIndirectAdd() { + function _assertInt(buffer, value, indirect = false, cache = false) { + const builder = flexbuffers.builder(); + builder.addInt(value, indirect, cache); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array(buffer)); + } + function _assertUInt(buffer, value, indirect = false, cache = false) { + const builder = flexbuffers.builder(); + builder.addUInt(value, indirect, cache); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array(buffer)); + } + function _assertFloat(buffer, value, indirect = false, cache = false) { + const builder = flexbuffers.builder(); + builder.addFloat(value, indirect, cache); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array(buffer)); + } + _assertInt([0, 4, 1], 0); + _assertInt([0, 1, 24, 1], 0, true); + _assertInt([255, 0, 5, 2], 255); + + _assertUInt([0, 8, 1], 0); + _assertUInt([0, 1, 28, 1], 0, true); + _assertUInt([255, 8, 1], 255); + + _assertUInt([185, 115, 175, 118, 250, 84, 8, 0, 11, 8], 2345234523452345); + _assertUInt([185, 115, 175, 118, 250, 84, 8, 0, 8, 31, 1], 2345234523452345, true); + _assertInt([185, 115, 175, 118, 250, 84, 8, 0, 7, 8], 2345234523452345); + _assertInt([185, 115, 175, 118, 250, 84, 8, 0, 8, 27, 1], 2345234523452345, true); + + _assertFloat([154, 153, 153, 153, 153, 153, 185, 63, 15, 8], 0.1); + _assertFloat([154, 153, 153, 153, 153, 153, 185, 63, 8, 35, 1], 0.1, true); + _assertFloat([0, 0, 0, 0, 14, 4], 0); + _assertFloat([0, 0, 0, 0, 4, 34, 1], 0, true); +} + +function testIndirectWithCache() { + function _assertInt(buffer, values) { + const builder = flexbuffers.builder(); + builder.startVector(); + values.forEach(v => { + builder.addInt(v, true, true) + }); + builder.end(); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array(buffer)); + } + + function _assertUInt(buffer, values) { + const builder = flexbuffers.builder(); + builder.startVector(); + values.forEach(v => { + builder.addUInt(v, true, true); + }); + builder.end(); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array(buffer)); + } + + function _assertFloat(buffer, values) { + const builder = flexbuffers.builder(); + builder.startVector(); + values.forEach(v => { + builder.addFloat(v, true, true); + }); + builder.end(); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array(buffer)); + } + + _assertInt( + [185, 115, 175, 118, 250, 84, 8, 0, 4, 9, 10, 11, 12, 27, 27, 27, 27, 8, 40, 1], + [2345234523452345, 2345234523452345, 2345234523452345, 2345234523452345] + ); + + _assertUInt( + [185, 115, 175, 118, 250, 84, 8, 0, 4, 9, 10, 11, 12, 31, 31, 31, 31, 8, 40, 1], + [2345234523452345, 2345234523452345, 2345234523452345, 2345234523452345] + ); + + _assertFloat( + [154, 153, 153, 153, 153, 153, 185, 63, 4, 9, 10, 11, 12, 35, 35, 35, 35, 8, 40, 1], + [0.1, 0.1, 0.1, 0.1] + ); +} + +function testMapBuilder() { + const builder = flexbuffers.builder(); + builder.startMap(); + builder.addKey('a'); + builder.add(12); + builder.addKey(''); + builder.add(45); + builder.end(); + const data = builder.finish(); + assert.deepStrictEqual(data, new Uint8Array([97, 0, 0, 2, 2, 5, 2, 1, 2, 45, 12, 4, 4, 4, 36, 1])); +} + +function testRoundTrip() { + const example = { + "age": 35, + "flags": [true, false, true, true], + "weight": 72.5, + "name": "Maxim", + "address": { + "city": "Bla", + "zip": "12345", + "countryCode": "XX", + } + }; + + function _assert(value) { + let buffer = flexbuffers.encode(value, 1); + let o = flexbuffers.toObject(buffer.buffer); + assert.deepStrictEqual(o, value); + } + + _assert(example); + _assert(0x100000001n); + _assert({ test_number: 72.6 }) +} + +function testRoundTripWithBuilder() { + const example = { + "age": 35, + "flags": [true, false, true, true], + "weight": 72.5, + "name": "Maxim", + "address": { + "city": "Bla", + "zip": "12345", + "countryCode": "XX", + } + }; + + const builder = flexbuffers.builder(); + builder.startMap(); + + builder.addKey('age'); + builder.add(35); + + builder.addKey('flags'); + builder.startVector(); + builder.add(true); + builder.add(false); + builder.add(true); + builder.add(true); + builder.end(); + + builder.addKey("weight"); + builder.add(72.5); + + builder.addKey("name"); + builder.add("Maxim"); + + builder.addKey("address"); + + builder.startMap(); + builder.addKey("city"); + builder.add("Bla"); + builder.addKey("zip"); + builder.add("12345"); + builder.addKey("countryCode"); + builder.add("XX"); + builder.end(); + + builder.end(); + + const data = builder.finish(); + let o = flexbuffers.toObject(data.buffer); + assert.deepStrictEqual(o, example); + + let root = flexbuffers.toReference(data.buffer); + assert.strictEqual(root.isMap(), true); + assert.strictEqual(root.get("age").numericValue(), 35); + assert.strictEqual(root.get("age").intValue(), 35); + assert.strictEqual(root.get("name").stringValue(), "Maxim"); + assert.strictEqual(root.get("weight").floatValue(), 72.5); + assert.strictEqual(root.get("weight").numericValue(), 72.5); + let flags = root.get("flags"); + assert.strictEqual(flags.isVector(), true); + assert.strictEqual(flags.length(), 4); + assert.strictEqual(flags.get(0).boolValue(), true); + assert.strictEqual(flags.get(1).boolValue(), false); + assert.strictEqual(flags.get(2).boolValue(), true); + assert.strictEqual(flags.get(3).boolValue(), true); + + let address = root.get("address"); + assert.strictEqual(address.isMap(), true); + assert.strictEqual(address.length(), 3); + assert.strictEqual(address.get("city").stringValue(), "Bla"); + assert.strictEqual(address.get("zip").stringValue(), "12345"); + assert.strictEqual(address.get("countryCode").stringValue(), "XX"); +} + +function testGoldBuffer() { + const data = new Uint8Array(fs.readFileSync('../gold_flexbuffer_example.bin')).buffer; + const b1 = flexbuffers.toReference(data).get("bools").get(1); + assert.strictEqual(b1.isBool(), true); + assert.strictEqual(b1.boolValue(), false); + + const blob = flexbuffers.toReference(data).get("vec").get(3); + assert.strictEqual(blob.isBlob(), true); + assert.deepStrictEqual(blob.blobValue(), new Uint8Array([77])); + + const o = flexbuffers.toObject(data); + assert.deepStrictEqual(o, { + bool: true, + bools: [true, false, true, false], + bar: [1, 2, 3], + bar3: [1, 2, 3], + foo: 100, + mymap: {foo:'Fred'}, + vec: [-100, 'Fred', 4, new Uint8Array([77]), false, 4] + }); +} + +function testBugWhereOffestWereStoredAsIntInsteadOfUInt() { + // Reported in https://github.com/google/flatbuffers/issues/5949#issuecomment-688421193 + const object = {'channels_in': 64, 'dilation_height_factor': 1, 'dilation_width_factor': 1, 'fused_activation_function': 1, 'pad_values': 1, 'padding': 0, 'stride_height': 1, 'stride_width': 1}; + let data1 = flexbuffers.encode(object); + const data = [99, 104, 97, 110, 110, 101, 108, 115, 95, 105, 110, 0, + 100, 105, 108, 97, 116, 105, 111, 110, 95, 104, 101, 105, 103, 104, 116, 95, 102, 97, 99, 116, 111, 114, 0, + 100, 105, 108, 97, 116, 105, 111, 110, 95, 119, 105, 100, 116, 104, 95, 102, 97, 99, 116, 111, 114, 0, + 102, 117, 115, 101, 100, 95, 97, 99, 116, 105, 118, 97, 116, 105, 111, 110, 95, 102, 117, 110, 99, 116, 105, 111, 110, 0, + 112, 97, 100, 95, 118, 97, 108, 117, 101, 115, 0, 112, 97, 100, 100, 105, 110, 103, 0, + 115, 116, 114, 105, 100, 101, 95, 104, 101, 105, 103, 104, 116, 0, + 115, 116, 114, 105, 100, 101, 95, 119, 105, 100, 116, 104, 0, + 8, 130, 119, 97, 76, 51, 41, 34, 21, 8, 1, 8, 64, 1, 1, 1, 1, 0, 1, 1, 4, 4, 4, 4, 4, 4, 4, 4, 16, 36, 1]; + let object2 = flexbuffers.toObject(new Uint8Array(data).buffer); + let object1 = flexbuffers.toObject(new Uint8Array(data1).buffer); + assert.deepStrictEqual(object, object2); + assert.deepStrictEqual(object, object1); + assert.strictEqual(data.length, data1.length); + let ref = flexbuffers.toReference(new Uint8Array(data).buffer); + assert.strictEqual(ref.isMap(), true); + assert.strictEqual(ref.length(), 8); + assert.strictEqual(ref.get("channels_in").numericValue(), 64); + assert.strictEqual(ref.get("padding").isNumber(), true); +} + +main(); + diff --git a/third_party/flatbuffers/tests/ts/JavaScriptRequiredStringTest.js b/third_party/flatbuffers/tests/ts/JavaScriptRequiredStringTest.js new file mode 100644 index 00000000000..6023ef80325 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptRequiredStringTest.js @@ -0,0 +1,32 @@ +import assert from 'assert' +import * as flatbuffers from 'flatbuffers'; +import { Foo } from './required-strings/foo.js'; + + +var builder = new flatbuffers.Builder(); + +function main() { + testMissingFirstRequiredString(); + builder.clear(); + testMissingSecondRequiredString(); +} + +function testMissingFirstRequiredString() { + const undefined_string = builder.createString(undefined); + const defined_string = builder.createString('cat'); + + assert.throws(() => Foo.createFoo( + builder, undefined_string, defined_string + )); +} + +function testMissingSecondRequiredString() { + const defined_string = builder.createString('cat'); + const undefined_string = builder.createString(undefined); + + assert.throws(() => Foo.createFoo( + builder, defined_string, undefined_string + )); +} + +main(); diff --git a/third_party/flatbuffers/tests/ts/JavaScriptTest.js b/third_party/flatbuffers/tests/ts/JavaScriptTest.js new file mode 100644 index 00000000000..1226e2e5dda --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptTest.js @@ -0,0 +1,497 @@ +// Run this using JavaScriptTest.sh +import assert from 'assert' +import fs from 'fs' +import * as flatbuffers from 'flatbuffers' + +import { Monster, MonsterT } from './my-game/example/monster.js' +import { Test, TestT } from './my-game/example/test.js' +import { Stat } from './my-game/example/stat.js' +import { Vec3 } from './my-game/example/vec3.js' +import { Color } from './my-game/example/color.js'; +import { Any } from './my-game/example/any.js'; + +function main() { + + // First, let's test reading a FlatBuffer generated by C++ code: + // This file was generated from monsterdata_test.json + var data = new Uint8Array(fs.readFileSync('../monsterdata_test.mon')); + + // Now test it: + + var bb = new flatbuffers.ByteBuffer(data); + testBuffer(bb); + + // Second, let's create a FlatBuffer from scratch in JavaScript, and test it also. + // We use an initial size of 1 to exercise the reallocation algorithm, + // normally a size larger than the typical FlatBuffer you generate would be + // better for performance. + var fbb = new flatbuffers.Builder(1); + createMonster(fbb); + serializeAndTest(fbb); + testObjApiPack(fbb); + + // clear the builder, repeat tests + var clearIterations = 100; + var startingCapacity = fbb.bb.capacity(); + for (var i = 0; i < clearIterations; i++) { + fbb.clear(); + createMonster(fbb); + serializeAndTest(fbb); + testObjApiPack(fbb); + } + // the capacity of our buffer shouldn't increase with the same size payload + assert.strictEqual(fbb.bb.capacity(), startingCapacity); + + test64bit(); + testUnicode(); + fuzzTest1(); + testNullStrings(); + testSharedStrings(); + testVectorOfStructs(); + testCreateByteVector(); + + console.log('FlatBuffers test: completed successfully'); +} + +function createMonster(fbb) { + // We set up the same values as monsterdata.json: + + var str = fbb.createString('MyMonster'); + + var inv = Monster.createInventoryVector(fbb, [0, 1, 2, 3, 4]); + + var fred = fbb.createString('Fred'); + Monster.startMonster(fbb); + Monster.addName(fbb, fred); + var mon2 = Monster.endMonster(fbb); + + Monster.startTest4Vector(fbb, 2); + Test.createTest(fbb, 10, 20); + Test.createTest(fbb, 30, 40); + var test4 = fbb.endVector(); + + var testArrayOfString = Monster.createTestarrayofstringVector(fbb, [ + fbb.createString('test1'), + fbb.createString('test2') + ]); + + var testVectorOfLongs = Monster.createVectorOfLongsVector(fbb, [ + 1n, + 101010100n + ]); + + Monster.startMonster(fbb); + Monster.addPos(fbb, Vec3.createVec3(fbb, 1, 2, 3, 3, Color.Green, 5, 6)); + Monster.addHp(fbb, 80); + Monster.addName(fbb, str); + Monster.addInventory(fbb, inv); + Monster.addTestType(fbb, Any.Monster); + Monster.addTest(fbb, mon2); + Monster.addTest4(fbb, test4); + Monster.addTestarrayofstring(fbb, testArrayOfString); + Monster.addVectorOfLongs(fbb, testVectorOfLongs); + Monster.addTestbool(fbb, true); + var mon = Monster.endMonster(fbb); + + Monster.finishMonsterBuffer(fbb, mon); +} + +function serializeAndTest(fbb) { + // Write the result to a file for debugging purposes: + // Note that the binaries are not necessarily identical, since the JSON + // parser may serialize in a slightly different order than the above + // JavaScript code. They are functionally equivalent though. + + fs.writeFileSync('monsterdata_javascript_wire.mon', Buffer.from(fbb.asUint8Array())); + + // Tests mutation first. This will verify that we did not trample any other + // part of the byte buffer. + testMutation(fbb.dataBuffer()); + + testBuffer(fbb.dataBuffer()); +} + +function testMutation(bb) { + var monster = Monster.getRootAsMonster(bb); + + monster.mutate_hp(120); + assert.strictEqual(monster.hp(), 120); + + monster.mutate_hp(80); + assert.strictEqual(monster.hp(), 80); + + var manaRes = monster.mutate_mana(10); + assert.strictEqual(manaRes, false); // Field was NOT present, because default value. + + // TODO: There is not the availability to mutate structs or vectors. +} + +function testObjApiPack(fbb) { + fbb.clear(); + createMonster(fbb); + let monster_t = Monster.getRootAsMonster(fbb.dataBuffer()).unpack(); + fbb.clear(); + Monster.finishMonsterBuffer(fbb, monster_t.pack(fbb)); + serializeAndTest(fbb); +} + +function testObjApiUnpack(monster) { + assert.strictEqual(monster.hp, 80); + assert.strictEqual(monster.mana, 150); // default + + assert.strictEqual(monster.name, 'MyMonster'); + + let pos = monster.pos; + assert.strictEqual(pos.x, 1); + assert.strictEqual(pos.y, 2); + assert.strictEqual(pos.z, 3); + assert.strictEqual(pos.test1, 3); + assert.strictEqual(pos.test2, Color.Green); + let test3 = pos.test3; + assert.strictEqual(test3.a, 5); + assert.strictEqual(test3.b, 6); + + assert.strictEqual(monster.testType, Any.Monster); + let monster2 = monster.test; + assert.strictEqual(monster2 != null, true); + assert.strictEqual(monster2 instanceof MonsterT, true); + assert.strictEqual(monster2.name, 'Fred'); + + assert.strictEqual(monster.inventory.length, 5); + let invsum = 0; + for (let i = 0; i < monster.inventory.length; i++) { + invsum += monster.inventory[i]; + } + assert.strictEqual(invsum, 10); + + let test_0 = monster.test4[0]; + let test_1 = monster.test4[1]; + assert.strictEqual(monster.test4.length, 2); + assert.strictEqual(test_0.a + test_0.b + test_1.a + test_1.b, 100); + + assert.strictEqual(monster.testarrayofstring.length, 2); + assert.strictEqual(monster.testarrayofstring[0], 'test1'); + assert.strictEqual(monster.testarrayofstring[1], 'test2'); + + assert.strictEqual(monster.testbool, true); +} + +function testBuffer(bb) { + assert.ok(Monster.bufferHasIdentifier(bb)); + + var monster = Monster.getRootAsMonster(bb); + + assert.strictEqual(monster.hp(), 80); + assert.strictEqual(monster.mana(), 150); // default + + assert.strictEqual(monster.name(), 'MyMonster'); + + var pos = monster.pos(); + assert.strictEqual(pos.x(), 1); + assert.strictEqual(pos.y(), 2); + assert.strictEqual(pos.z(), 3); + assert.strictEqual(pos.test1(), 3); + assert.strictEqual(pos.test2(), Color.Green); + var t = pos.test3(); + assert.strictEqual(t.a(), 5); + assert.strictEqual(t.b(), 6); + + assert.strictEqual(monster.testType(), Any.Monster); + var monster2 = new Monster(); + assert.strictEqual(monster.test(monster2) != null, true); + assert.strictEqual(monster2.name(), 'Fred'); + + assert.strictEqual(monster.inventoryLength(), 5); + var invsum = 0; + for (var i = 0; i < monster.inventoryLength(); i++) { + invsum += monster.inventory(i); + } + assert.strictEqual(invsum, 10); + + var invsum2 = 0; + var invArr = monster.inventoryArray(); + for (var i = 0; i < invArr.length; i++) { + invsum2 += invArr[i]; + } + assert.strictEqual(invsum2, 10); + + let longSum = 0n; + for (let idx = 0; idx < monster.vectorOfLongsLength(); ++idx) { + longSum += monster.vectorOfLongs(idx); + } + assert.strictEqual(longSum, 101010101n); + + var test_0 = monster.test4(0); + var test_1 = monster.test4(1); + assert.strictEqual(monster.test4Length(), 2); + assert.strictEqual(test_0.a() + test_0.b() + test_1.a() + test_1.b(), 100); + + assert.strictEqual(monster.testarrayofstringLength(), 2); + assert.strictEqual(monster.testarrayofstring(0), 'test1'); + assert.strictEqual(monster.testarrayofstring(1), 'test2'); + + assert.strictEqual(monster.testbool(), true); + + let monster_t = monster.unpack(); + testObjApiUnpack(monster_t); + + let monster2_t = new MonsterT(); + monster.unpackTo(monster2_t); + testObjApiUnpack(monster2_t); +} + +function test64bit() { + var fbb = new flatbuffers.Builder(); + var required = fbb.createString('required'); + + Stat.startStat(fbb); + var stat2 = Stat.endStat(fbb); + + Monster.startMonster(fbb); + Monster.addName(fbb, required); + Monster.addTestempty(fbb, stat2); + var mon2 = Monster.endMonster(fbb); + + Stat.startStat(fbb); + // 2541551405100253985 = 0x2345678987654321 + Stat.addVal(fbb, 0x2345678987654321n); + var stat = Stat.endStat(fbb); + + Monster.startMonster(fbb); + Monster.addName(fbb, required); + Monster.addEnemy(fbb, mon2); + Monster.addTestempty(fbb, stat); + var mon = Monster.endMonster(fbb); + + Monster.finishMonsterBuffer(fbb, mon); + var bytes = fbb.asUint8Array(); + + //////////////////////////////////////////////////////////////// + + var bb = new flatbuffers.ByteBuffer(bytes); + assert.ok(Monster.bufferHasIdentifier(bb)); + var mon = Monster.getRootAsMonster(bb); + + var stat = mon.testempty(); + assert.strictEqual(stat != null, true); + assert.strictEqual(stat.val() != null, true); + assert.strictEqual(stat.val(), 2541551405100253985n); + + var mon2 = mon.enemy(); + assert.strictEqual(mon2 != null, true); + stat = mon2.testempty(); + assert.strictEqual(stat != null, true); + assert.strictEqual(stat.val() != null, true); + assert.strictEqual(stat.val(), 0n); // default value +} + +function testUnicode() { + var correct = fs.readFileSync('../unicode_test.mon'); + var json = JSON.parse(fs.readFileSync('../unicode_test.json', 'utf8')); + + // Test reading + function testReadingUnicode(bb) { + var monster = Monster.getRootAsMonster(bb); + assert.strictEqual(monster.name(), json.name); + assert.deepEqual(Buffer.from(monster.name(flatbuffers.Encoding.UTF8_BYTES)), Buffer.from(json.name)); + assert.strictEqual(monster.testarrayoftablesLength(), json.testarrayoftables.length); + json.testarrayoftables.forEach(function(table, i) { + var value = monster.testarrayoftables(i); + assert.strictEqual(value.name(), table.name); + assert.deepEqual(Buffer.from(value.name(flatbuffers.Encoding.UTF8_BYTES)), Buffer.from(table.name)); + }); + assert.strictEqual(monster.testarrayofstringLength(), json.testarrayofstring.length); + json.testarrayofstring.forEach(function(string, i) { + assert.strictEqual(monster.testarrayofstring(i), string); + assert.deepEqual(Buffer.from(monster.testarrayofstring(i, flatbuffers.Encoding.UTF8_BYTES)), Buffer.from(string)); + }); + } + testReadingUnicode(new flatbuffers.ByteBuffer(new Uint8Array(correct))); + + // Test writing + var fbb = new flatbuffers.Builder(); + var name = fbb.createString(json.name); + var testarrayoftablesOffsets = json.testarrayoftables.map(function(table) { + var name = fbb.createString(new Uint8Array(Buffer.from(table.name))); + Monster.startMonster(fbb); + Monster.addName(fbb, name); + return Monster.endMonster(fbb); + }); + var testarrayoftablesOffset = Monster.createTestarrayoftablesVector(fbb, + testarrayoftablesOffsets); + var testarrayofstringOffset = Monster.createTestarrayofstringVector(fbb, + json.testarrayofstring.map(function(string) { return fbb.createString(string); })); + Monster.startMonster(fbb); + Monster.addTestarrayofstring(fbb, testarrayofstringOffset); + Monster.addTestarrayoftables(fbb, testarrayoftablesOffset); + Monster.addName(fbb, name); + Monster.finishSizePrefixedMonsterBuffer(fbb, Monster.endMonster(fbb)); + var bb = new flatbuffers.ByteBuffer(fbb.asUint8Array()) + bb.setPosition(4); + testReadingUnicode(bb); +} + +var __imul = Math.imul ? Math.imul : function(a, b) { + var ah = a >> 16 & 65535; + var bh = b >> 16 & 65535; + var al = a & 65535; + var bl = b & 65535; + return al * bl + (ah * bl + al * bh << 16) | 0; +}; + +// Include simple random number generator to ensure results will be the +// same cross platform. +// http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator +var lcg_seed = 48271; + +function lcg_rand() { + return lcg_seed = (__imul(lcg_seed, 279470273) >>> 0) % 4294967291; +} + +function lcg_reset() { + lcg_seed = 48271; +} + +// Converts a Field ID to a virtual table offset. +function fieldIndexToOffset(field_id) { + // Should correspond to what EndTable() below builds up. + var fixed_fields = 2; // Vtable size and Object Size. + return (field_id + fixed_fields) * 2; +} + +// Low level stress/fuzz test: serialize/deserialize a variety of +// different kinds of data in different combinations +function fuzzTest1() { + + // Values we're testing against: chosen to ensure no bits get chopped + // off anywhere, and also be different from eachother. + var bool_val = true; + var char_val = -127; // 0x81 + var uchar_val = 0xFF; + var short_val = -32222; // 0x8222; + var ushort_val = 0xFEEE; + var int_val = 0x83333333 | 0; + var uint_val = 0xFDDDDDDD; + var long_val = BigInt.asIntN(64, 0x8444444444444444n); + var ulong_val = BigInt.asUintN(64, 0xFCCCCCCCCCCCCCCCn); + var float_val = new Float32Array([3.14159])[0]; + var double_val = 3.14159265359; + + var test_values_max = 11; + var fields_per_object = 4; + var num_fuzz_objects = 10000; // The higher, the more thorough :) + + var builder = new flatbuffers.Builder(); + + lcg_reset(); // Keep it deterministic. + + var objects = []; + + // Generate num_fuzz_objects random objects each consisting of + // fields_per_object fields, each of a random type. + for (var i = 0; i < num_fuzz_objects; i++) { + builder.startObject(fields_per_object); + for (var f = 0; f < fields_per_object; f++) { + var choice = lcg_rand() % test_values_max; + switch (choice) { + case 0: builder.addFieldInt8(f, bool_val, 0); break; + case 1: builder.addFieldInt8(f, char_val, 0); break; + case 2: builder.addFieldInt8(f, uchar_val, 0); break; + case 3: builder.addFieldInt16(f, short_val, 0); break; + case 4: builder.addFieldInt16(f, ushort_val, 0); break; + case 5: builder.addFieldInt32(f, int_val, 0); break; + case 6: builder.addFieldInt32(f, uint_val, 0); break; + case 7: builder.addFieldInt64(f, long_val, 0n); break; + case 8: builder.addFieldInt64(f, ulong_val, 0n); break; + case 9: builder.addFieldFloat32(f, float_val, 0); break; + case 10: builder.addFieldFloat64(f, double_val, 0); break; + } + } + objects.push(builder.endObject()); + } + builder.prep(8, 0); // Align whole buffer. + + lcg_reset(); // Reset. + + builder.finish(objects[objects.length - 1]); + var bytes = new Uint8Array(builder.asUint8Array()); + var view = new DataView(bytes.buffer); + + // Test that all objects we generated are readable and return the + // expected values. We generate random objects in the same order + // so this is deterministic. + for (var i = 0; i < num_fuzz_objects; i++) { + var offset = bytes.length - objects[i]; + for (var f = 0; f < fields_per_object; f++) { + var choice = lcg_rand() % test_values_max; + var vtable_offset = fieldIndexToOffset(f); + var vtable = offset - view.getInt32(offset, true); + assert.ok(vtable_offset < view.getInt16(vtable, true)); + var field_offset = offset + view.getInt16(vtable + vtable_offset, true); + switch (choice) { + case 0: assert.strictEqual(!!view.getInt8(field_offset), bool_val); break; + case 1: assert.strictEqual(view.getInt8(field_offset), char_val); break; + case 2: assert.strictEqual(view.getUint8(field_offset), uchar_val); break; + case 3: assert.strictEqual(view.getInt16(field_offset, true), short_val); break; + case 4: assert.strictEqual(view.getUint16(field_offset, true), ushort_val); break; + case 5: assert.strictEqual(view.getInt32(field_offset, true), int_val); break; + case 6: assert.strictEqual(view.getUint32(field_offset, true), uint_val); break; + case 7: assert.strictEqual(view.getBigInt64(field_offset, true), long_val); break; + case 8: assert.strictEqual(view.getBigUint64(field_offset, true), ulong_val); break; + case 9: assert.strictEqual(view.getFloat32(field_offset, true), float_val); break; + case 10: assert.strictEqual(view.getFloat64(field_offset, true), double_val); break; + } + } + } +} + +function testSharedStrings() { + var shared_string = "Hello world"; + var builder = new flatbuffers.Builder(); + let mainOffset = builder.createSharedString(shared_string); + assert.strictEqual(builder.createSharedString(shared_string), mainOffset); +} + +function testNullStrings() { + var builder = new flatbuffers.Builder(); + assert.strictEqual(builder.createString(null), 0); + assert.strictEqual(builder.createSharedString(null), 0); + assert.strictEqual(builder.createString(undefined), 0); + assert.strictEqual(builder.createSharedString(undefined), 0); +} + +function testVectorOfStructs() { + let monster = new MonsterT(); + monster.name = 'testVectorOfStructs'; + monster.test4 = [ + new TestT(1, 2), + new TestT(3, 4) + ]; + + let builder = new flatbuffers.Builder(); + builder.finish(monster.pack(builder)); + + let decodedMonster = Monster.getRootAsMonster(builder.dataBuffer()).unpack(); + assert.strictEqual(decodedMonster.test4[0].a, 1); + assert.strictEqual(decodedMonster.test4[0].b, 2); + assert.strictEqual(decodedMonster.test4[1].a, 3); + assert.strictEqual(decodedMonster.test4[1].b, 4); +} + +function testCreateByteVector() { + const data = Uint8Array.from([1, 2, 3, 4, 5]); + + const builder = new flatbuffers.Builder(); + const required = builder.createString("required"); + const offset = builder.createByteVector(data); + + Monster.startMonster(builder); + Monster.addName(builder, required); + Monster.addInventory(builder, offset) + builder.finish(Monster.endMonster(builder)); + + let decodedMonster = Monster.getRootAsMonster(builder.dataBuffer()); + assert.deepEqual(decodedMonster.inventoryArray(), data); +} + +main(); diff --git a/third_party/flatbuffers/tests/ts/JavaScriptTestv1.cjs b/third_party/flatbuffers/tests/ts/JavaScriptTestv1.cjs new file mode 100644 index 00000000000..6ca27275074 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptTestv1.cjs @@ -0,0 +1,367 @@ +// Run this using JavaScriptTest.sh +var assert = require('assert'); +var fs = require('fs'); + +var flatbuffers = require('../../js/flatbuffers'); +var MyGame = require(process.argv[2]).MyGame; + +function main() { + + // First, let's test reading a FlatBuffer generated by C++ code: + // This file was generated from monsterdata_test.json + var data = new Uint8Array(fs.readFileSync('../monsterdata_test.mon')); + + // Now test it: + + var bb = new flatbuffers.ByteBuffer(data); + testBuffer(bb); + + // Second, let's create a FlatBuffer from scratch in JavaScript, and test it also. + // We use an initial size of 1 to exercise the reallocation algorithm, + // normally a size larger than the typical FlatBuffer you generate would be + // better for performance. + var fbb = new flatbuffers.Builder(1); + createMonster(fbb); + serializeAndTest(fbb); + + // clear the builder, repeat tests + var clearIterations = 100; + var startingCapacity = fbb.bb.capacity(); + for (var i = 0; i < clearIterations; i++) { + fbb.clear(); + createMonster(fbb); + serializeAndTest(fbb); + } + // the capacity of our buffer shouldn't increase with the same size payload + assert.strictEqual(fbb.bb.capacity(), startingCapacity); + + test64bit(); + testUnicode(); + fuzzTest1(); + + console.log('FlatBuffers test: completed successfully'); +} + +function createMonster(fbb) { + // We set up the same values as monsterdata.json: + + var str = fbb.createString('MyMonster'); + + var inv = MyGame.Example.Monster.createInventoryVector(fbb, [0, 1, 2, 3, 4]); + + var fred = fbb.createString('Fred'); + MyGame.Example.Monster.startMonster(fbb); + MyGame.Example.Monster.addName(fbb, fred); + var mon2 = MyGame.Example.Monster.endMonster(fbb); + + MyGame.Example.Monster.startTest4Vector(fbb, 2); + MyGame.Example.Test.createTest(fbb, 10, 20); + MyGame.Example.Test.createTest(fbb, 30, 40); + var test4 = fbb.endVector(); + + var testArrayOfString = MyGame.Example.Monster.createTestarrayofstringVector(fbb, [ + fbb.createString('test1'), + fbb.createString('test2') + ]); + + MyGame.Example.Monster.startMonster(fbb); + MyGame.Example.Monster.addPos(fbb, MyGame.Example.Vec3.createVec3(fbb, 1, 2, 3, 3, MyGame.Example.Color.Green, 5, 6)); + MyGame.Example.Monster.addHp(fbb, 80); + MyGame.Example.Monster.addName(fbb, str); + MyGame.Example.Monster.addInventory(fbb, inv); + MyGame.Example.Monster.addTestType(fbb, MyGame.Example.Any.Monster); + MyGame.Example.Monster.addTest(fbb, mon2); + MyGame.Example.Monster.addTest4(fbb, test4); + MyGame.Example.Monster.addTestarrayofstring(fbb, testArrayOfString); + MyGame.Example.Monster.addTestbool(fbb, true); + var mon = MyGame.Example.Monster.endMonster(fbb); + + MyGame.Example.Monster.finishMonsterBuffer(fbb, mon); +} + +function serializeAndTest(fbb) { + // Write the result to a file for debugging purposes: + // Note that the binaries are not necessarily identical, since the JSON + // parser may serialize in a slightly different order than the above + // JavaScript code. They are functionally equivalent though. + + fs.writeFileSync('monsterdata_javascript_wire.mon', new Buffer(fbb.asUint8Array())); + + // Tests mutation first. This will verify that we did not trample any other + // part of the byte buffer. + testMutation(fbb.dataBuffer()); + + testBuffer(fbb.dataBuffer()); +} + +function testMutation(bb) { + var monster = MyGame.Example.Monster.getRootAsMonster(bb); + + monster.mutate_hp(120); + assert.strictEqual(monster.hp(), 120); + + monster.mutate_hp(80); + assert.strictEqual(monster.hp(), 80); + + var manaRes = monster.mutate_mana(10); + assert.strictEqual(manaRes, false); // Field was NOT present, because default value. + + // TODO: There is not the availability to mutate structs or vectors. +} + +function testBuffer(bb) { + assert.ok(MyGame.Example.Monster.bufferHasIdentifier(bb)); + + var monster = MyGame.Example.Monster.getRootAsMonster(bb); + + assert.strictEqual(monster.hp(), 80); + assert.strictEqual(monster.mana(), 150); // default + + assert.strictEqual(monster.name(), 'MyMonster'); + + var pos = monster.pos(); + assert.strictEqual(pos.x(), 1); + assert.strictEqual(pos.y(), 2); + assert.strictEqual(pos.z(), 3); + assert.strictEqual(pos.test1(), 3); + assert.strictEqual(pos.test2(), MyGame.Example.Color.Green); + var t = pos.test3(); + assert.strictEqual(t.a(), 5); + assert.strictEqual(t.b(), 6); + + assert.strictEqual(monster.testType(), MyGame.Example.Any.Monster); + var monster2 = new MyGame.Example.Monster(); + assert.strictEqual(monster.test(monster2) != null, true); + assert.strictEqual(monster2.name(), 'Fred'); + + assert.strictEqual(monster.inventoryLength(), 5); + var invsum = 0; + for (var i = 0; i < monster.inventoryLength(); i++) { + invsum += monster.inventory(i); + } + assert.strictEqual(invsum, 10); + + var invsum2 = 0; + var invArr = monster.inventoryArray(); + for (var i = 0; i < invArr.length; i++) { + invsum2 += invArr[i]; + } + assert.strictEqual(invsum2, 10); + + var test_0 = monster.test4(0); + var test_1 = monster.test4(1); + assert.strictEqual(monster.test4Length(), 2); + assert.strictEqual(test_0.a() + test_0.b() + test_1.a() + test_1.b(), 100); + + assert.strictEqual(monster.testarrayofstringLength(), 2); + assert.strictEqual(monster.testarrayofstring(0), 'test1'); + assert.strictEqual(monster.testarrayofstring(1), 'test2'); + + assert.strictEqual(monster.testbool(), true); +} + +function test64bit() { + var fbb = new flatbuffers.Builder(); + var required = fbb.createString('required'); + + MyGame.Example.Stat.startStat(fbb); + var stat2 = MyGame.Example.Stat.endStat(fbb); + + MyGame.Example.Monster.startMonster(fbb); + MyGame.Example.Monster.addName(fbb, required); + MyGame.Example.Monster.addTestempty(fbb, stat2); + var mon2 = MyGame.Example.Monster.endMonster(fbb); + + MyGame.Example.Stat.startStat(fbb); + MyGame.Example.Stat.addVal(fbb, 0x2345678987654321n); + var stat = MyGame.Example.Stat.endStat(fbb); + + MyGame.Example.Monster.startMonster(fbb); + MyGame.Example.Monster.addName(fbb, required); + MyGame.Example.Monster.addEnemy(fbb, mon2); + MyGame.Example.Monster.addTestempty(fbb, stat); + var mon = MyGame.Example.Monster.endMonster(fbb); + + MyGame.Example.Monster.finishMonsterBuffer(fbb, mon); + var bytes = fbb.asUint8Array(); + + //////////////////////////////////////////////////////////////// + + var bb = new flatbuffers.ByteBuffer(bytes); + assert.ok(MyGame.Example.Monster.bufferHasIdentifier(bb)); + var mon = MyGame.Example.Monster.getRootAsMonster(bb); + + var stat = mon.testempty(); + assert.strictEqual(stat != null, true); + assert.strictEqual(stat.val() != null, true); + assert.strictEqual(stat.val(), 2541551405100253985n); + + var mon2 = mon.enemy(); + assert.strictEqual(mon2 != null, true); + stat = mon2.testempty(); + assert.strictEqual(stat != null, true); + assert.strictEqual(stat.val() != null, true); + assert.strictEqual(stat.val(), 0n); // default value +} + +function testUnicode() { + var correct = fs.readFileSync('unicode_test.mon'); + var json = JSON.parse(fs.readFileSync('../unicode_test.json', 'utf8')); + + // Test reading + function testReadingUnicode(bb) { + var monster = MyGame.Example.Monster.getRootAsMonster(bb); + assert.strictEqual(monster.name(), json.name); + assert.deepEqual(new Buffer(monster.name(flatbuffers.Encoding.UTF8_BYTES)), new Buffer(json.name)); + assert.strictEqual(monster.testarrayoftablesLength(), json.testarrayoftables.length); + json.testarrayoftables.forEach(function(table, i) { + var value = monster.testarrayoftables(i); + assert.strictEqual(value.name(), table.name); + assert.deepEqual(new Buffer(value.name(flatbuffers.Encoding.UTF8_BYTES)), new Buffer(table.name)); + }); + assert.strictEqual(monster.testarrayofstringLength(), json.testarrayofstring.length); + json.testarrayofstring.forEach(function(string, i) { + assert.strictEqual(monster.testarrayofstring(i), string); + assert.deepEqual(new Buffer(monster.testarrayofstring(i, flatbuffers.Encoding.UTF8_BYTES)), new Buffer(string)); + }); + } + testReadingUnicode(new flatbuffers.ByteBuffer(new Uint8Array(correct))); + + // Test writing + var fbb = new flatbuffers.Builder(); + var name = fbb.createString(json.name); + var testarrayoftablesOffsets = json.testarrayoftables.map(function(table) { + var name = fbb.createString(new Uint8Array(new Buffer(table.name))); + MyGame.Example.Monster.startMonster(fbb); + MyGame.Example.Monster.addName(fbb, name); + return MyGame.Example.Monster.endMonster(fbb); + }); + var testarrayoftablesOffset = MyGame.Example.Monster.createTestarrayoftablesVector(fbb, + testarrayoftablesOffsets); + var testarrayofstringOffset = MyGame.Example.Monster.createTestarrayofstringVector(fbb, + json.testarrayofstring.map(function(string) { return fbb.createString(string); })); + MyGame.Example.Monster.startMonster(fbb); + MyGame.Example.Monster.addTestarrayofstring(fbb, testarrayofstringOffset); + MyGame.Example.Monster.addTestarrayoftables(fbb, testarrayoftablesOffset); + MyGame.Example.Monster.addName(fbb, name); + MyGame.Example.Monster.finishSizePrefixedMonsterBuffer(fbb, MyGame.Example.Monster.endMonster(fbb)); + var bb = new flatbuffers.ByteBuffer(fbb.asUint8Array()) + bb.setPosition(4); + testReadingUnicode(bb); +} + +var __imul = Math.imul ? Math.imul : function(a, b) { + var ah = a >> 16 & 65535; + var bh = b >> 16 & 65535; + var al = a & 65535; + var bl = b & 65535; + return al * bl + (ah * bl + al * bh << 16) | 0; +}; + +// Include simple random number generator to ensure results will be the +// same cross platform. +// http://en.wikipedia.org/wiki/Park%E2%80%93Miller_random_number_generator +var lcg_seed = 48271; + +function lcg_rand() { + return lcg_seed = (__imul(lcg_seed, 279470273) >>> 0) % 4294967291; +} + +function lcg_reset() { + lcg_seed = 48271; +} + +// Converts a Field ID to a virtual table offset. +function fieldIndexToOffset(field_id) { + // Should correspond to what EndTable() below builds up. + var fixed_fields = 2; // Vtable size and Object Size. + return (field_id + fixed_fields) * 2; +} + +// Low level stress/fuzz test: serialize/deserialize a variety of +// different kinds of data in different combinations +function fuzzTest1() { + + // Values we're testing against: chosen to ensure no bits get chopped + // off anywhere, and also be different from eachother. + var bool_val = true; + var char_val = -127; // 0x81 + var uchar_val = 0xFF; + var short_val = -32222; // 0x8222; + var ushort_val = 0xFEEE; + var int_val = 0x83333333 | 0; + var uint_val = 0xFDDDDDDD; + var long_val = BigInt.asIntN(64, 0x8444444444444444n); + var ulong_val = BigInt.asUintN(64, 0xFCCCCCCCCCCCCCCCn); + var float_val = new Float32Array([3.14159])[0]; + var double_val = 3.14159265359; + + var test_values_max = 11; + var fields_per_object = 4; + var num_fuzz_objects = 10000; // The higher, the more thorough :) + + var builder = new flatbuffers.Builder(); + + lcg_reset(); // Keep it deterministic. + + var objects = []; + + // Generate num_fuzz_objects random objects each consisting of + // fields_per_object fields, each of a random type. + for (var i = 0; i < num_fuzz_objects; i++) { + builder.startObject(fields_per_object); + for (var f = 0; f < fields_per_object; f++) { + var choice = lcg_rand() % test_values_max; + switch (choice) { + case 0: builder.addFieldInt8(f, bool_val, 0); break; + case 1: builder.addFieldInt8(f, char_val, 0); break; + case 2: builder.addFieldInt8(f, uchar_val, 0); break; + case 3: builder.addFieldInt16(f, short_val, 0); break; + case 4: builder.addFieldInt16(f, ushort_val, 0); break; + case 5: builder.addFieldInt32(f, int_val, 0); break; + case 6: builder.addFieldInt32(f, uint_val, 0); break; + case 7: builder.addFieldInt64(f, long_val, 0n); break; + case 8: builder.addFieldInt64(f, ulong_val, 0n); break; + case 9: builder.addFieldFloat32(f, float_val, 0); break; + case 10: builder.addFieldFloat64(f, double_val, 0); break; + } + } + objects.push(builder.endObject()); + } + builder.prep(8, 0); // Align whole buffer. + + lcg_reset(); // Reset. + + builder.finish(objects[objects.length - 1]); + var bytes = new Uint8Array(builder.asUint8Array()); + var view = new DataView(bytes.buffer); + + // Test that all objects we generated are readable and return the + // expected values. We generate random objects in the same order + // so this is deterministic. + for (var i = 0; i < num_fuzz_objects; i++) { + var offset = bytes.length - objects[i]; + for (var f = 0; f < fields_per_object; f++) { + var choice = lcg_rand() % test_values_max; + var vtable_offset = fieldIndexToOffset(f); + var vtable = offset - view.getInt32(offset, true); + assert.ok(vtable_offset < view.getInt16(vtable, true)); + var field_offset = offset + view.getInt16(vtable + vtable_offset, true); + switch (choice) { + case 0: assert.strictEqual(!!view.getInt8(field_offset), bool_val); break; + case 1: assert.strictEqual(view.getInt8(field_offset), char_val); break; + case 2: assert.strictEqual(view.getUint8(field_offset), uchar_val); break; + case 3: assert.strictEqual(view.getInt16(field_offset, true), short_val); break; + case 4: assert.strictEqual(view.getUint16(field_offset, true), ushort_val); break; + case 5: assert.strictEqual(view.getInt32(field_offset, true), int_val); break; + case 6: assert.strictEqual(view.getUint32(field_offset, true), uint_val); break; + case 7: assert.strictEqual(view.getBigInt64(field_offset, true), long_val); break; + case 8: assert.strictEqual(view.getBigUint64(field_offset, true), ulong_val); break; + case 9: assert.strictEqual(view.getFloat32(field_offset, true), float_val); break; + case 10: assert.strictEqual(view.getFloat64(field_offset, true), double_val); break; + } + } + } +} + +main(); \ No newline at end of file diff --git a/third_party/flatbuffers/tests/ts/JavaScriptUnionUnderlyingTypeTest.js b/third_party/flatbuffers/tests/ts/JavaScriptUnionUnderlyingTypeTest.js new file mode 100644 index 00000000000..6a324ca43ec --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptUnionUnderlyingTypeTest.js @@ -0,0 +1,26 @@ +import assert from 'assert' +import * as flatbuffers from 'flatbuffers' +import {UnionUnderlyingType as Test} from './union_underlying_type_test.js' + +function main() { + let a = new Test.AT(); + a.a = 1; + let b = new Test.BT(); + b.b = "foo"; + let c = new Test.CT(); + c.c = true; + let d = new Test.DT(); + d.testUnionType = Test.ABC.A; + d.testUnion = a; + d.testVectorOfUnionType = [Test.ABC.A, Test.ABC.B, Test.ABC.C]; + d.testVectorOfUnion = [a, b, c]; + + let fbb = new flatbuffers.Builder(); + let offset = d.pack(fbb); + fbb.finish(offset); + + let unpacked = Test.D.getRootAsD(fbb.dataBuffer()).unpack(); + assert.equal(JSON.stringify(unpacked), JSON.stringify(d)); +} + +main() \ No newline at end of file diff --git a/third_party/flatbuffers/tests/ts/JavaScriptUnionVectorTest.js b/third_party/flatbuffers/tests/ts/JavaScriptUnionVectorTest.js new file mode 100644 index 00000000000..18857d673af --- /dev/null +++ b/third_party/flatbuffers/tests/ts/JavaScriptUnionVectorTest.js @@ -0,0 +1,111 @@ +import assert from 'assert' +import * as flatbuffers from 'flatbuffers' + +import { Character } from './union_vector/character.js' +import { BookReader, BookReaderT } from './union_vector/book-reader.js' +import { Attacker, AttackerT } from './union_vector/attacker.js' +import { Movie, MovieT } from './union_vector/movie.js' + +var charTypes = [ + Character.Belle, + Character.MuLan, + Character.BookFan, + Character.Other +]; + +function testMovieBuf(movie) { + assert.strictEqual(movie.charactersTypeLength(), charTypes.length); + assert.strictEqual(movie.charactersLength(), movie.charactersTypeLength()); + + for (var i = 0; i < charTypes.length; ++i) { + assert.strictEqual(movie.charactersType(i), charTypes[i]); + } + + var bookReader7 = movie.characters(0, new BookReader()); + assert.strictEqual(bookReader7.booksRead(), 7); + + var attacker = movie.characters(1, new Attacker()); + assert.strictEqual(attacker.swordAttackDamage(), 5); + + var bookReader2 = movie.characters(2, new BookReader()); + assert.strictEqual(bookReader2.booksRead(), 2); + + var other = movie.characters(3, ''); + assert.strictEqual(other, "I am other"); +} + +function testMovieUnpack(movie) { + assert.strictEqual(movie.charactersType.length, charTypes.length); + assert.strictEqual(movie.characters.length, movie.charactersType.length); + + for (var i = 0; i < charTypes.length; ++i) { + assert.strictEqual(movie.charactersType[i], charTypes[i]); + } + + var bookReader7 = movie.characters[0]; + assert.strictEqual(bookReader7 instanceof BookReaderT, true); + assert.strictEqual(bookReader7.booksRead, 7); + + var attacker = movie.characters[1]; + assert.strictEqual(attacker instanceof AttackerT, true); + assert.strictEqual(attacker.swordAttackDamage, 5); + + var bookReader2 = movie.characters[2]; + assert.strictEqual(bookReader2 instanceof BookReaderT, true); + assert.strictEqual(bookReader2.booksRead, 2); + + var other = movie.characters[3]; + assert.strictEqual(other, "I am other"); +} + +function createMovie(fbb) { + Attacker.startAttacker(fbb); + Attacker.addSwordAttackDamage(fbb, 5); + var attackerOffset = Attacker.endAttacker(fbb); + + var charTypesOffset = Movie.createCharactersTypeVector(fbb, charTypes); + var charsOffset = 0; + + let otherOffset = fbb.createString("I am other"); + + charsOffset = Movie.createCharactersVector( + fbb, + [ + BookReader.createBookReader(fbb, 7), + attackerOffset, + BookReader.createBookReader(fbb, 2), + otherOffset + ] + ); + + Movie.startMovie(fbb); + Movie.addCharactersType(fbb, charTypesOffset); + Movie.addCharacters(fbb, charsOffset); + Movie.finishMovieBuffer(fbb, Movie.endMovie(fbb)) +} + +function main() { + var fbb = new flatbuffers.Builder(); + + createMovie(fbb); + + var buf = new flatbuffers.ByteBuffer(fbb.asUint8Array()); + + var movie = Movie.getRootAsMovie(buf); + testMovieBuf(movie); + + testMovieUnpack(movie.unpack()); + + var movie_to = new MovieT(); + movie.unpackTo(movie_to); + testMovieUnpack(movie_to); + + fbb.clear(); + Movie.finishMovieBuffer(fbb, movie_to.pack(fbb)); + var unpackBuf = new flatbuffers.ByteBuffer(fbb.asUint8Array()); + testMovieBuf(Movie.getRootAsMovie(unpackBuf)); + + console.log('FlatBuffers union vector test: completed successfully'); +} + +main(); diff --git a/third_party/flatbuffers/tests/ts/TypeScriptTest.py b/third_party/flatbuffers/tests/ts/TypeScriptTest.py new file mode 100755 index 00000000000..c6c7cb7f993 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/TypeScriptTest.py @@ -0,0 +1,140 @@ +#!/usr/bin/env python3 +# +# Copyright 2022 Google Inc. All rights reserved. +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +import platform +import shutil +import subprocess +import sys +from pathlib import Path + +# Get the path where this script is located so we can invoke the script from +# any directory and have the paths work correctly. +tests_path = Path(__file__).parent.resolve() + +# Get the root path as an absolute path, so all derived paths are absolute. +root_path = tests_path.parent.parent.absolute() + +# Windows works with subprocess.run a bit differently. +is_windows = platform.system() == "Windows" + +# Get the location of the flatc executable +flatc_exe = Path("flatc.exe" if is_windows else "flatc") + +# Find and assert flatc compiler is present. +if root_path in flatc_exe.parents: + flatc_exe = flatc_exe.relative_to(root_path) +flatc_path = Path(root_path, flatc_exe) +assert flatc_path.exists(), "Cannot find the flatc compiler " + str(flatc_path) + +def check_call(args, cwd=tests_path): + subprocess.check_call(args, cwd=str(cwd), shell=is_windows) + +# Execute the flatc compiler with the specified parameters +def flatc(options, schema, prefix=None, include=None, data=None, cwd=tests_path): + print("Invoking flatc on schema " + str(schema)) + cmd = [str(flatc_path)] + options + if prefix: + cmd += ["-o"] + [prefix] + if include: + cmd += ["-I"] + [include] + cmd += [schema] if isinstance(schema, str) else schema + if data: + cmd += [data] if isinstance(data, str) else data + check_call(cmd) + +# Execute esbuild with the specified parameters +def esbuild(input, output): + cmd = ["esbuild", input, "--outfile=" + output] + cmd += ["--format=cjs", "--bundle", "--external:flatbuffers"] + check_call(cmd) + +print("Removing node_modules/ directory...") +shutil.rmtree(Path(tests_path, "node_modules"), ignore_errors=True) + +check_call(["npm", "install", "--silent"]) + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings", "--gen-mutable", "--gen-object-api", "--ts-entry-points", "--ts-flat-files"], + schema="../monster_test.fbs", + include="../include_test", +) +esbuild("monster_test.ts", "monster_test_generated.cjs") + +flatc( + options=["--gen-object-api", "-b"], + schema="../monster_test.fbs", + include="../include_test", + data="../unicode_test.json", +) + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings", "--gen-mutable", "--gen-object-api", "--ts-entry-points", "--ts-flat-files"], + schema="../union_vector/union_vector.fbs", + prefix="union_vector", +) +esbuild("union_vector/union_vector.ts", "union_vector/union_vector_generated.cjs") + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings"], + schema="../optional_scalars.fbs", +) + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings", "--ts-no-import-ext"], + schema="../optional_scalars.fbs", + prefix="no_import_ext", +) + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings", "--gen-object-api", "--ts-entry-points", "--ts-flat-files"], + schema="arrays_test_complex/arrays_test_complex.fbs", + prefix="arrays_test_complex" +) +esbuild("arrays_test_complex/my-game/example.ts", "arrays_test_complex/arrays_test_complex_generated.cjs") + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings", "--gen-mutable", "--gen-object-api", "--ts-entry-points", "--ts-flat-files"], + schema=[ + "typescript_keywords.fbs", + "test_dir/typescript_include.fbs", + "test_dir/typescript_transitive_include.fbs", + "../../reflection/reflection.fbs", + ], + include="../../", +) +esbuild("typescript_keywords.ts", "typescript_keywords_generated.cjs") + +flatc( + options=["--ts", "--reflect-names", "--gen-name-strings", "--gen-mutable", "--gen-object-api", "--ts-entry-points", "--ts-flat-files"], + schema="../union_underlying_type_test.fbs" +) + +print("Running TypeScript Compiler...") +check_call(["tsc"]) +print("Running TypeScript Compiler in old node resolution mode for no_import_ext...") +check_call(["tsc", "-p", "./tsconfig.node.json"]) + +NODE_CMD = ["node"] + +print("Running TypeScript Tests...") +check_call(NODE_CMD + ["JavaScriptTest"]) +check_call(NODE_CMD + ["JavaScriptUnionVectorTest"]) +check_call(NODE_CMD + ["JavaScriptFlexBuffersTest"]) +check_call(NODE_CMD + ["JavaScriptComplexArraysTest"]) +check_call(NODE_CMD + ["JavaScriptUnionUnderlyingTypeTest"]) + +print("Running old v1 TypeScript Tests...") +check_call(NODE_CMD + ["JavaScriptTestv1.cjs", "./monster_test_generated.cjs"]) diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/arrays_test_complex.fbs b/third_party/flatbuffers/tests/ts/arrays_test_complex/arrays_test_complex.fbs new file mode 100644 index 00000000000..3ef59150529 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/arrays_test_complex.fbs @@ -0,0 +1,46 @@ +namespace MyGame.Example; + +enum TestEnum : byte { A, B, C } + +struct InnerStruct { + a:float64; + b:[ubyte:13]; + c:int8; + d_underscore:int64; +} + +struct OuterStruct { + a:bool; + b:double; + c_underscore:InnerStruct; + d:[InnerStruct:3]; + e:InnerStruct; + f:[float64:4]; +} + +struct NestedStruct{ + a:[int:2]; + b:TestEnum; + c_underscore:[TestEnum:2]; + d_outer:[OuterStruct:5]; + e:[int64:2]; +} + +struct ArrayStruct{ + a_underscore:float; + b_underscore:[int:0xF]; + c:byte; + d:[NestedStruct:2]; + e:int32; + f:[OuterStruct:2]; + g:[int64:2]; +} + +table ArrayTable{ + a:string; + c_underscore:ArrayStruct; +} + +root_type ArrayTable; +file_identifier "RHUB"; +file_extension "mon"; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/arrays_test_complex_generated.cjs b/third_party/flatbuffers/tests/ts/arrays_test_complex/arrays_test_complex_generated.cjs new file mode 100644 index 00000000000..7bb2bbeb3e9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/arrays_test_complex_generated.cjs @@ -0,0 +1,460 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// arrays_test_complex/my-game/example.ts +var example_exports = {}; +__export(example_exports, { + ArrayStruct: () => ArrayStruct, + ArrayStructT: () => ArrayStructT, + ArrayTable: () => ArrayTable, + ArrayTableT: () => ArrayTableT, + InnerStruct: () => InnerStruct, + InnerStructT: () => InnerStructT, + NestedStruct: () => NestedStruct, + NestedStructT: () => NestedStructT, + OuterStruct: () => OuterStruct, + OuterStructT: () => OuterStructT, + TestEnum: () => TestEnum +}); +module.exports = __toCommonJS(example_exports); + +// arrays_test_complex/my-game/example/inner-struct.js +var InnerStruct = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return this.bb.readFloat64(this.bb_pos); + } + b(index) { + return this.bb.readUint8(this.bb_pos + 8 + index); + } + c() { + return this.bb.readInt8(this.bb_pos + 21); + } + dUnderscore() { + return this.bb.readInt64(this.bb_pos + 24); + } + static getFullyQualifiedName() { + return "MyGame.Example.InnerStruct"; + } + static sizeOf() { + return 32; + } + static createInnerStruct(builder, a, b, c, d_underscore) { + builder.prep(8, 32); + builder.writeInt64(BigInt(d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(c); + for (let i = 12; i >= 0; --i) { + builder.writeInt8(b?.[i] ?? 0); + } + builder.writeFloat64(a); + return builder.offset(); + } + unpack() { + return new InnerStructT(this.a(), this.bb.createScalarList(this.b.bind(this), 13), this.c(), this.dUnderscore()); + } + unpackTo(_o) { + _o.a = this.a(); + _o.b = this.bb.createScalarList(this.b.bind(this), 13); + _o.c = this.c(); + _o.dUnderscore = this.dUnderscore(); + } +}; +var InnerStructT = class { + constructor(a = 0, b = [], c = 0, dUnderscore = BigInt("0")) { + this.a = a; + this.b = b; + this.c = c; + this.dUnderscore = dUnderscore; + } + pack(builder) { + return InnerStruct.createInnerStruct(builder, this.a, this.b, this.c, this.dUnderscore); + } +}; + +// arrays_test_complex/my-game/example/outer-struct.js +var OuterStruct = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return !!this.bb.readInt8(this.bb_pos); + } + b() { + return this.bb.readFloat64(this.bb_pos + 8); + } + cUnderscore(obj) { + return (obj || new InnerStruct()).__init(this.bb_pos + 16, this.bb); + } + d(index, obj) { + return (obj || new InnerStruct()).__init(this.bb_pos + 48 + index * 32, this.bb); + } + e(obj) { + return (obj || new InnerStruct()).__init(this.bb_pos + 144, this.bb); + } + f(index) { + return this.bb.readFloat64(this.bb_pos + 176 + index * 8); + } + static getFullyQualifiedName() { + return "MyGame.Example.OuterStruct"; + } + static sizeOf() { + return 208; + } + static createOuterStruct(builder, a, b, c_underscore_a, c_underscore_b, c_underscore_c, c_underscore_d_underscore, d, e_a, e_b, e_c, e_d_underscore, f) { + builder.prep(8, 208); + for (let i = 3; i >= 0; --i) { + builder.writeFloat64(f?.[i] ?? 0); + } + builder.prep(8, 32); + builder.writeInt64(BigInt(e_d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(e_c); + for (let i = 12; i >= 0; --i) { + builder.writeInt8(e_b?.[i] ?? 0); + } + builder.writeFloat64(e_a); + for (let i = 2; i >= 0; --i) { + const item = d?.[i]; + if (item instanceof InnerStructT) { + item.pack(builder); + continue; + } + InnerStruct.createInnerStruct(builder, item?.a, item?.b, item?.c, item?.dUnderscore); + } + builder.prep(8, 32); + builder.writeInt64(BigInt(c_underscore_d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(c_underscore_c); + for (let i = 12; i >= 0; --i) { + builder.writeInt8(c_underscore_b?.[i] ?? 0); + } + builder.writeFloat64(c_underscore_a); + builder.writeFloat64(b); + builder.pad(7); + builder.writeInt8(Number(Boolean(a))); + return builder.offset(); + } + unpack() { + return new OuterStructT(this.a(), this.b(), this.cUnderscore() !== null ? this.cUnderscore().unpack() : null, this.bb.createObjList(this.d.bind(this), 3), this.e() !== null ? this.e().unpack() : null, this.bb.createScalarList(this.f.bind(this), 4)); + } + unpackTo(_o) { + _o.a = this.a(); + _o.b = this.b(); + _o.cUnderscore = this.cUnderscore() !== null ? this.cUnderscore().unpack() : null; + _o.d = this.bb.createObjList(this.d.bind(this), 3); + _o.e = this.e() !== null ? this.e().unpack() : null; + _o.f = this.bb.createScalarList(this.f.bind(this), 4); + } +}; +var OuterStructT = class { + constructor(a = false, b = 0, cUnderscore = null, d = [], e = null, f = []) { + this.a = a; + this.b = b; + this.cUnderscore = cUnderscore; + this.d = d; + this.e = e; + this.f = f; + } + pack(builder) { + return OuterStruct.createOuterStruct(builder, this.a, this.b, this.cUnderscore?.a ?? 0, this.cUnderscore?.b ?? [], this.cUnderscore?.c ?? 0, this.cUnderscore?.dUnderscore ?? BigInt(0), this.d, this.e?.a ?? 0, this.e?.b ?? [], this.e?.c ?? 0, this.e?.dUnderscore ?? BigInt(0), this.f); + } +}; + +// arrays_test_complex/my-game/example/test-enum.js +var TestEnum; +(function(TestEnum2) { + TestEnum2[TestEnum2["A"] = 0] = "A"; + TestEnum2[TestEnum2["B"] = 1] = "B"; + TestEnum2[TestEnum2["C"] = 2] = "C"; +})(TestEnum || (TestEnum = {})); + +// arrays_test_complex/my-game/example/nested-struct.js +var NestedStruct = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a(index) { + return this.bb.readInt32(this.bb_pos + 0 + index * 4); + } + b() { + return this.bb.readInt8(this.bb_pos + 8); + } + cUnderscore(index) { + return this.bb.readInt8(this.bb_pos + 9 + index); + } + dOuter(index, obj) { + return (obj || new OuterStruct()).__init(this.bb_pos + 16 + index * 208, this.bb); + } + e(index) { + return this.bb.readInt64(this.bb_pos + 1056 + index * 8); + } + static getFullyQualifiedName() { + return "MyGame.Example.NestedStruct"; + } + static sizeOf() { + return 1072; + } + static createNestedStruct(builder, a, b, c_underscore, d_outer, e) { + builder.prep(8, 1072); + for (let i = 1; i >= 0; --i) { + builder.writeInt64(BigInt(e?.[i] ?? 0)); + } + for (let i = 4; i >= 0; --i) { + const item = d_outer?.[i]; + if (item instanceof OuterStructT) { + item.pack(builder); + continue; + } + OuterStruct.createOuterStruct(builder, item?.a, item?.b, item?.cUnderscore?.a ?? 0, item?.cUnderscore?.b ?? [], item?.cUnderscore?.c ?? 0, item?.cUnderscore?.dUnderscore ?? BigInt(0), item?.d, item?.e?.a ?? 0, item?.e?.b ?? [], item?.e?.c ?? 0, item?.e?.dUnderscore ?? BigInt(0), item?.f); + } + builder.pad(5); + for (let i = 1; i >= 0; --i) { + builder.writeInt8(c_underscore?.[i] ?? 0); + } + builder.writeInt8(b); + for (let i = 1; i >= 0; --i) { + builder.writeInt32(a?.[i] ?? 0); + } + return builder.offset(); + } + unpack() { + return new NestedStructT(this.bb.createScalarList(this.a.bind(this), 2), this.b(), this.bb.createScalarList(this.cUnderscore.bind(this), 2), this.bb.createObjList(this.dOuter.bind(this), 5), this.bb.createScalarList(this.e.bind(this), 2)); + } + unpackTo(_o) { + _o.a = this.bb.createScalarList(this.a.bind(this), 2); + _o.b = this.b(); + _o.cUnderscore = this.bb.createScalarList(this.cUnderscore.bind(this), 2); + _o.dOuter = this.bb.createObjList(this.dOuter.bind(this), 5); + _o.e = this.bb.createScalarList(this.e.bind(this), 2); + } +}; +var NestedStructT = class { + constructor(a = [], b = TestEnum.A, cUnderscore = [TestEnum.A, TestEnum.A], dOuter = [], e = []) { + this.a = a; + this.b = b; + this.cUnderscore = cUnderscore; + this.dOuter = dOuter; + this.e = e; + } + pack(builder) { + return NestedStruct.createNestedStruct(builder, this.a, this.b, this.cUnderscore, this.dOuter, this.e); + } +}; + +// arrays_test_complex/my-game/example/array-struct.js +var ArrayStruct = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + aUnderscore() { + return this.bb.readFloat32(this.bb_pos); + } + bUnderscore(index) { + return this.bb.readInt32(this.bb_pos + 4 + index * 4); + } + c() { + return this.bb.readInt8(this.bb_pos + 64); + } + d(index, obj) { + return (obj || new NestedStruct()).__init(this.bb_pos + 72 + index * 1072, this.bb); + } + e() { + return this.bb.readInt32(this.bb_pos + 2216); + } + f(index, obj) { + return (obj || new OuterStruct()).__init(this.bb_pos + 2224 + index * 208, this.bb); + } + g(index) { + return this.bb.readInt64(this.bb_pos + 2640 + index * 8); + } + static getFullyQualifiedName() { + return "MyGame.Example.ArrayStruct"; + } + static sizeOf() { + return 2656; + } + static createArrayStruct(builder, a_underscore, b_underscore, c, d, e, f, g) { + builder.prep(8, 2656); + for (let i = 1; i >= 0; --i) { + builder.writeInt64(BigInt(g?.[i] ?? 0)); + } + for (let i = 1; i >= 0; --i) { + const item = f?.[i]; + if (item instanceof OuterStructT) { + item.pack(builder); + continue; + } + OuterStruct.createOuterStruct(builder, item?.a, item?.b, item?.cUnderscore?.a ?? 0, item?.cUnderscore?.b ?? [], item?.cUnderscore?.c ?? 0, item?.cUnderscore?.dUnderscore ?? BigInt(0), item?.d, item?.e?.a ?? 0, item?.e?.b ?? [], item?.e?.c ?? 0, item?.e?.dUnderscore ?? BigInt(0), item?.f); + } + builder.pad(4); + builder.writeInt32(e); + for (let i = 1; i >= 0; --i) { + const item = d?.[i]; + if (item instanceof NestedStructT) { + item.pack(builder); + continue; + } + NestedStruct.createNestedStruct(builder, item?.a, item?.b, item?.cUnderscore, item?.dOuter, item?.e); + } + builder.pad(7); + builder.writeInt8(c); + for (let i = 14; i >= 0; --i) { + builder.writeInt32(b_underscore?.[i] ?? 0); + } + builder.writeFloat32(a_underscore); + return builder.offset(); + } + unpack() { + return new ArrayStructT(this.aUnderscore(), this.bb.createScalarList(this.bUnderscore.bind(this), 15), this.c(), this.bb.createObjList(this.d.bind(this), 2), this.e(), this.bb.createObjList(this.f.bind(this), 2), this.bb.createScalarList(this.g.bind(this), 2)); + } + unpackTo(_o) { + _o.aUnderscore = this.aUnderscore(); + _o.bUnderscore = this.bb.createScalarList(this.bUnderscore.bind(this), 15); + _o.c = this.c(); + _o.d = this.bb.createObjList(this.d.bind(this), 2); + _o.e = this.e(); + _o.f = this.bb.createObjList(this.f.bind(this), 2); + _o.g = this.bb.createScalarList(this.g.bind(this), 2); + } +}; +var ArrayStructT = class { + constructor(aUnderscore = 0, bUnderscore = [], c = 0, d = [], e = 0, f = [], g = []) { + this.aUnderscore = aUnderscore; + this.bUnderscore = bUnderscore; + this.c = c; + this.d = d; + this.e = e; + this.f = f; + this.g = g; + } + pack(builder) { + return ArrayStruct.createArrayStruct(builder, this.aUnderscore, this.bUnderscore, this.c, this.d, this.e, this.f, this.g); + } +}; + +// arrays_test_complex/my-game/example/array-table.js +var flatbuffers = __toESM(require("flatbuffers"), 1); +var ArrayTable = class _ArrayTable { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsArrayTable(bb, obj) { + return (obj || new _ArrayTable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsArrayTable(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new _ArrayTable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier("RHUB"); + } + a(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + cUnderscore(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new ArrayStruct()).__init(this.bb_pos + offset, this.bb) : null; + } + static getFullyQualifiedName() { + return "MyGame.Example.ArrayTable"; + } + static startArrayTable(builder) { + builder.startObject(2); + } + static addA(builder, aOffset) { + builder.addFieldOffset(0, aOffset, 0); + } + static addCUnderscore(builder, cUnderscoreOffset) { + builder.addFieldStruct(1, cUnderscoreOffset, 0); + } + static endArrayTable(builder) { + const offset = builder.endObject(); + return offset; + } + static finishArrayTableBuffer(builder, offset) { + builder.finish(offset, "RHUB"); + } + static finishSizePrefixedArrayTableBuffer(builder, offset) { + builder.finish(offset, "RHUB", true); + } + unpack() { + return new ArrayTableT(this.a(), this.cUnderscore() !== null ? this.cUnderscore().unpack() : null); + } + unpackTo(_o) { + _o.a = this.a(); + _o.cUnderscore = this.cUnderscore() !== null ? this.cUnderscore().unpack() : null; + } +}; +var ArrayTableT = class { + constructor(a = null, cUnderscore = null) { + this.a = a; + this.cUnderscore = cUnderscore; + } + pack(builder) { + const a = this.a !== null ? builder.createString(this.a) : 0; + ArrayTable.startArrayTable(builder); + ArrayTable.addA(builder, a); + ArrayTable.addCUnderscore(builder, this.cUnderscore !== null ? this.cUnderscore.pack(builder) : 0); + return ArrayTable.endArrayTable(builder); + } +}; diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.d.ts new file mode 100644 index 00000000000..a3c1a81e120 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.d.ts @@ -0,0 +1,6 @@ +export { ArrayStruct, ArrayStructT } from './example/array-struct.js'; +export { ArrayTable, ArrayTableT } from './example/array-table.js'; +export { InnerStruct, InnerStructT } from './example/inner-struct.js'; +export { NestedStruct, NestedStructT } from './example/nested-struct.js'; +export { OuterStruct, OuterStructT } from './example/outer-struct.js'; +export { TestEnum } from './example/test-enum.js'; diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.js new file mode 100644 index 00000000000..d9405e14236 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.js @@ -0,0 +1,8 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { ArrayStruct, ArrayStructT } from './example/array-struct.js'; +export { ArrayTable, ArrayTableT } from './example/array-table.js'; +export { InnerStruct, InnerStructT } from './example/inner-struct.js'; +export { NestedStruct, NestedStructT } from './example/nested-struct.js'; +export { OuterStruct, OuterStructT } from './example/outer-struct.js'; +export { TestEnum } from './example/test-enum.js'; diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.ts new file mode 100644 index 00000000000..4f1d63b4e20 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example.ts @@ -0,0 +1,10 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { ArrayStruct, ArrayStructT } from './example/array-struct.js'; +export { ArrayTable, ArrayTableT } from './example/array-table.js'; +export { InnerStruct, InnerStructT } from './example/inner-struct.js'; +export { NestedStruct, NestedStructT } from './example/nested-struct.js'; +export { OuterStruct, OuterStructT } from './example/outer-struct.js'; +export { TestEnum } from './example/test-enum.js'; diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.d.ts new file mode 100644 index 00000000000..80acd750766 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.d.ts @@ -0,0 +1,31 @@ +import * as flatbuffers from 'flatbuffers'; +import { NestedStruct, NestedStructT } from '../../my-game/example/nested-struct.js'; +import { OuterStruct, OuterStructT } from '../../my-game/example/outer-struct.js'; +export declare class ArrayStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): ArrayStruct; + aUnderscore(): number; + bUnderscore(index: number): number | null; + c(): number; + d(index: number, obj?: NestedStruct): NestedStruct | null; + e(): number; + f(index: number, obj?: OuterStruct): OuterStruct | null; + g(index: number): bigint | null; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createArrayStruct(builder: flatbuffers.Builder, a_underscore: number, b_underscore: number[] | null, c: number, d: (any | NestedStructT)[] | null, e: number, f: (any | OuterStructT)[] | null, g: bigint[] | null): flatbuffers.Offset; + unpack(): ArrayStructT; + unpackTo(_o: ArrayStructT): void; +} +export declare class ArrayStructT implements flatbuffers.IGeneratedObject { + aUnderscore: number; + bUnderscore: (number)[]; + c: number; + d: (NestedStructT)[]; + e: number; + f: (OuterStructT)[]; + g: (bigint)[]; + constructor(aUnderscore?: number, bUnderscore?: (number)[], c?: number, d?: (NestedStructT)[], e?: number, f?: (OuterStructT)[], g?: (bigint)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.js new file mode 100644 index 00000000000..9350571d52d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.js @@ -0,0 +1,98 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import { NestedStruct, NestedStructT } from '../../my-game/example/nested-struct.js'; +import { OuterStruct, OuterStructT } from '../../my-game/example/outer-struct.js'; +export class ArrayStruct { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + aUnderscore() { + return this.bb.readFloat32(this.bb_pos); + } + bUnderscore(index) { + return this.bb.readInt32(this.bb_pos + 4 + index * 4); + } + c() { + return this.bb.readInt8(this.bb_pos + 64); + } + d(index, obj) { + return (obj || new NestedStruct()).__init(this.bb_pos + 72 + index * 1072, this.bb); + } + e() { + return this.bb.readInt32(this.bb_pos + 2216); + } + f(index, obj) { + return (obj || new OuterStruct()).__init(this.bb_pos + 2224 + index * 208, this.bb); + } + g(index) { + return this.bb.readInt64(this.bb_pos + 2640 + index * 8); + } + static getFullyQualifiedName() { + return 'MyGame.Example.ArrayStruct'; + } + static sizeOf() { + return 2656; + } + static createArrayStruct(builder, a_underscore, b_underscore, c, d, e, f, g) { + builder.prep(8, 2656); + for (let i = 1; i >= 0; --i) { + builder.writeInt64(BigInt(g?.[i] ?? 0)); + } + for (let i = 1; i >= 0; --i) { + const item = f?.[i]; + if (item instanceof OuterStructT) { + item.pack(builder); + continue; + } + OuterStruct.createOuterStruct(builder, item?.a, item?.b, (item?.cUnderscore?.a ?? 0), (item?.cUnderscore?.b ?? []), (item?.cUnderscore?.c ?? 0), (item?.cUnderscore?.dUnderscore ?? BigInt(0)), item?.d, (item?.e?.a ?? 0), (item?.e?.b ?? []), (item?.e?.c ?? 0), (item?.e?.dUnderscore ?? BigInt(0)), item?.f); + } + builder.pad(4); + builder.writeInt32(e); + for (let i = 1; i >= 0; --i) { + const item = d?.[i]; + if (item instanceof NestedStructT) { + item.pack(builder); + continue; + } + NestedStruct.createNestedStruct(builder, item?.a, item?.b, item?.cUnderscore, item?.dOuter, item?.e); + } + builder.pad(7); + builder.writeInt8(c); + for (let i = 14; i >= 0; --i) { + builder.writeInt32((b_underscore?.[i] ?? 0)); + } + builder.writeFloat32(a_underscore); + return builder.offset(); + } + unpack() { + return new ArrayStructT(this.aUnderscore(), this.bb.createScalarList(this.bUnderscore.bind(this), 15), this.c(), this.bb.createObjList(this.d.bind(this), 2), this.e(), this.bb.createObjList(this.f.bind(this), 2), this.bb.createScalarList(this.g.bind(this), 2)); + } + unpackTo(_o) { + _o.aUnderscore = this.aUnderscore(); + _o.bUnderscore = this.bb.createScalarList(this.bUnderscore.bind(this), 15); + _o.c = this.c(); + _o.d = this.bb.createObjList(this.d.bind(this), 2); + _o.e = this.e(); + _o.f = this.bb.createObjList(this.f.bind(this), 2); + _o.g = this.bb.createScalarList(this.g.bind(this), 2); + } +} +export class ArrayStructT { + constructor(aUnderscore = 0.0, bUnderscore = [], c = 0, d = [], e = 0, f = [], g = []) { + this.aUnderscore = aUnderscore; + this.bUnderscore = bUnderscore; + this.c = c; + this.d = d; + this.e = e; + this.f = f; + this.g = g; + } + pack(builder) { + return ArrayStruct.createArrayStruct(builder, this.aUnderscore, this.bUnderscore, this.c, this.d, this.e, this.f, this.g); + } +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.ts new file mode 100644 index 00000000000..6d542448c9b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-struct.ts @@ -0,0 +1,168 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { NestedStruct, NestedStructT } from '../../my-game/example/nested-struct.js'; +import { OuterStruct, OuterStructT } from '../../my-game/example/outer-struct.js'; + + +export class ArrayStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):ArrayStruct { + this.bb_pos = i; + this.bb = bb; + return this; +} + +aUnderscore():number { + return this.bb!.readFloat32(this.bb_pos); +} + +bUnderscore(index: number):number|null { + return this.bb!.readInt32(this.bb_pos + 4 + index * 4); +} + +c():number { + return this.bb!.readInt8(this.bb_pos + 64); +} + +d(index: number, obj?:NestedStruct):NestedStruct|null { + return (obj || new NestedStruct()).__init(this.bb_pos + 72 + index * 1072, this.bb!); +} + +e():number { + return this.bb!.readInt32(this.bb_pos + 2216); +} + +f(index: number, obj?:OuterStruct):OuterStruct|null { + return (obj || new OuterStruct()).__init(this.bb_pos + 2224 + index * 208, this.bb!); +} + +g(index: number):bigint|null { + return this.bb!.readInt64(this.bb_pos + 2640 + index * 8); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.ArrayStruct'; +} + +static sizeOf():number { + return 2656; +} + +static createArrayStruct(builder:flatbuffers.Builder, a_underscore: number, b_underscore: number[]|null, c: number, d: (any|NestedStructT)[]|null, e: number, f: (any|OuterStructT)[]|null, g: bigint[]|null):flatbuffers.Offset { + builder.prep(8, 2656); + + for (let i = 1; i >= 0; --i) { + builder.writeInt64(BigInt(g?.[i] ?? 0)); + } + + + for (let i = 1; i >= 0; --i) { + const item = f?.[i]; + + if (item instanceof OuterStructT) { + item.pack(builder); + continue; + } + + OuterStruct.createOuterStruct(builder, + item?.a, + item?.b, + (item?.cUnderscore?.a ?? 0), + (item?.cUnderscore?.b ?? []), + (item?.cUnderscore?.c ?? 0), + (item?.cUnderscore?.dUnderscore ?? BigInt(0)), + item?.d, + (item?.e?.a ?? 0), + (item?.e?.b ?? []), + (item?.e?.c ?? 0), + (item?.e?.dUnderscore ?? BigInt(0)), + item?.f + ); + } + + builder.pad(4); + builder.writeInt32(e); + + for (let i = 1; i >= 0; --i) { + const item = d?.[i]; + + if (item instanceof NestedStructT) { + item.pack(builder); + continue; + } + + NestedStruct.createNestedStruct(builder, + item?.a, + item?.b, + item?.cUnderscore, + item?.dOuter, + item?.e + ); + } + + builder.pad(7); + builder.writeInt8(c); + + for (let i = 14; i >= 0; --i) { + builder.writeInt32((b_underscore?.[i] ?? 0)); + + } + + builder.writeFloat32(a_underscore); + return builder.offset(); +} + + +unpack(): ArrayStructT { + return new ArrayStructT( + this.aUnderscore(), + this.bb!.createScalarList(this.bUnderscore.bind(this), 15), + this.c(), + this.bb!.createObjList(this.d.bind(this), 2), + this.e(), + this.bb!.createObjList(this.f.bind(this), 2), + this.bb!.createScalarList(this.g.bind(this), 2) + ); +} + + +unpackTo(_o: ArrayStructT): void { + _o.aUnderscore = this.aUnderscore(); + _o.bUnderscore = this.bb!.createScalarList(this.bUnderscore.bind(this), 15); + _o.c = this.c(); + _o.d = this.bb!.createObjList(this.d.bind(this), 2); + _o.e = this.e(); + _o.f = this.bb!.createObjList(this.f.bind(this), 2); + _o.g = this.bb!.createScalarList(this.g.bind(this), 2); +} +} + +export class ArrayStructT implements flatbuffers.IGeneratedObject { +constructor( + public aUnderscore: number = 0.0, + public bUnderscore: (number)[] = [], + public c: number = 0, + public d: (NestedStructT)[] = [], + public e: number = 0, + public f: (OuterStructT)[] = [], + public g: (bigint)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return ArrayStruct.createArrayStruct(builder, + this.aUnderscore, + this.bUnderscore, + this.c, + this.d, + this.e, + this.f, + this.g + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.d.ts new file mode 100644 index 00000000000..d4ddd067762 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.d.ts @@ -0,0 +1,28 @@ +import * as flatbuffers from 'flatbuffers'; +import { ArrayStruct, ArrayStructT } from '../../my-game/example/array-struct.js'; +export declare class ArrayTable implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): ArrayTable; + static getRootAsArrayTable(bb: flatbuffers.ByteBuffer, obj?: ArrayTable): ArrayTable; + static getSizePrefixedRootAsArrayTable(bb: flatbuffers.ByteBuffer, obj?: ArrayTable): ArrayTable; + static bufferHasIdentifier(bb: flatbuffers.ByteBuffer): boolean; + a(): string | null; + a(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + cUnderscore(obj?: ArrayStruct): ArrayStruct | null; + static getFullyQualifiedName(): string; + static startArrayTable(builder: flatbuffers.Builder): void; + static addA(builder: flatbuffers.Builder, aOffset: flatbuffers.Offset): void; + static addCUnderscore(builder: flatbuffers.Builder, cUnderscoreOffset: flatbuffers.Offset): void; + static endArrayTable(builder: flatbuffers.Builder): flatbuffers.Offset; + static finishArrayTableBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static finishSizePrefixedArrayTableBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + unpack(): ArrayTableT; + unpackTo(_o: ArrayTableT): void; +} +export declare class ArrayTableT implements flatbuffers.IGeneratedObject { + a: string | Uint8Array | null; + cUnderscore: ArrayStructT | null; + constructor(a?: string | Uint8Array | null, cUnderscore?: ArrayStructT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.js new file mode 100644 index 00000000000..9dc6ffdeb24 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.js @@ -0,0 +1,75 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { ArrayStruct } from '../../my-game/example/array-struct.js'; +export class ArrayTable { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsArrayTable(bb, obj) { + return (obj || new ArrayTable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsArrayTable(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new ArrayTable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier('RHUB'); + } + a(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + cUnderscore(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new ArrayStruct()).__init(this.bb_pos + offset, this.bb) : null; + } + static getFullyQualifiedName() { + return 'MyGame.Example.ArrayTable'; + } + static startArrayTable(builder) { + builder.startObject(2); + } + static addA(builder, aOffset) { + builder.addFieldOffset(0, aOffset, 0); + } + static addCUnderscore(builder, cUnderscoreOffset) { + builder.addFieldStruct(1, cUnderscoreOffset, 0); + } + static endArrayTable(builder) { + const offset = builder.endObject(); + return offset; + } + static finishArrayTableBuffer(builder, offset) { + builder.finish(offset, 'RHUB'); + } + static finishSizePrefixedArrayTableBuffer(builder, offset) { + builder.finish(offset, 'RHUB', true); + } + unpack() { + return new ArrayTableT(this.a(), (this.cUnderscore() !== null ? this.cUnderscore().unpack() : null)); + } + unpackTo(_o) { + _o.a = this.a(); + _o.cUnderscore = (this.cUnderscore() !== null ? this.cUnderscore().unpack() : null); + } +} +export class ArrayTableT { + constructor(a = null, cUnderscore = null) { + this.a = a; + this.cUnderscore = cUnderscore; + } + pack(builder) { + const a = (this.a !== null ? builder.createString(this.a) : 0); + ArrayTable.startArrayTable(builder); + ArrayTable.addA(builder, a); + ArrayTable.addCUnderscore(builder, (this.cUnderscore !== null ? this.cUnderscore.pack(builder) : 0)); + return ArrayTable.endArrayTable(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.ts new file mode 100644 index 00000000000..ef94eaad9b5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/array-table.ts @@ -0,0 +1,104 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { ArrayStruct, ArrayStructT } from '../../my-game/example/array-struct.js'; + + +export class ArrayTable implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):ArrayTable { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsArrayTable(bb:flatbuffers.ByteBuffer, obj?:ArrayTable):ArrayTable { + return (obj || new ArrayTable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsArrayTable(bb:flatbuffers.ByteBuffer, obj?:ArrayTable):ArrayTable { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new ArrayTable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean { + return bb.__has_identifier('RHUB'); +} + +a():string|null +a(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +a(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +cUnderscore(obj?:ArrayStruct):ArrayStruct|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new ArrayStruct()).__init(this.bb_pos + offset, this.bb!) : null; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.ArrayTable'; +} + +static startArrayTable(builder:flatbuffers.Builder) { + builder.startObject(2); +} + +static addA(builder:flatbuffers.Builder, aOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, aOffset, 0); +} + +static addCUnderscore(builder:flatbuffers.Builder, cUnderscoreOffset:flatbuffers.Offset) { + builder.addFieldStruct(1, cUnderscoreOffset, 0); +} + +static endArrayTable(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static finishArrayTableBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'RHUB'); +} + +static finishSizePrefixedArrayTableBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'RHUB', true); +} + + +unpack(): ArrayTableT { + return new ArrayTableT( + this.a(), + (this.cUnderscore() !== null ? this.cUnderscore()!.unpack() : null) + ); +} + + +unpackTo(_o: ArrayTableT): void { + _o.a = this.a(); + _o.cUnderscore = (this.cUnderscore() !== null ? this.cUnderscore()!.unpack() : null); +} +} + +export class ArrayTableT implements flatbuffers.IGeneratedObject { +constructor( + public a: string|Uint8Array|null = null, + public cUnderscore: ArrayStructT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const a = (this.a !== null ? builder.createString(this.a!) : 0); + + ArrayTable.startArrayTable(builder); + ArrayTable.addA(builder, a); + ArrayTable.addCUnderscore(builder, (this.cUnderscore !== null ? this.cUnderscore!.pack(builder) : 0)); + + return ArrayTable.endArrayTable(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.d.ts new file mode 100644 index 00000000000..a54d02bcb10 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.d.ts @@ -0,0 +1,23 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class InnerStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): InnerStruct; + a(): number; + b(index: number): number | null; + c(): number; + dUnderscore(): bigint; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createInnerStruct(builder: flatbuffers.Builder, a: number, b: number[] | null, c: number, d_underscore: bigint): flatbuffers.Offset; + unpack(): InnerStructT; + unpackTo(_o: InnerStructT): void; +} +export declare class InnerStructT implements flatbuffers.IGeneratedObject { + a: number; + b: (number)[]; + c: number; + dUnderscore: bigint; + constructor(a?: number, b?: (number)[], c?: number, dUnderscore?: bigint); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.js new file mode 100644 index 00000000000..e8ed9736221 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.js @@ -0,0 +1,61 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class InnerStruct { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return this.bb.readFloat64(this.bb_pos); + } + b(index) { + return this.bb.readUint8(this.bb_pos + 8 + index); + } + c() { + return this.bb.readInt8(this.bb_pos + 21); + } + dUnderscore() { + return this.bb.readInt64(this.bb_pos + 24); + } + static getFullyQualifiedName() { + return 'MyGame.Example.InnerStruct'; + } + static sizeOf() { + return 32; + } + static createInnerStruct(builder, a, b, c, d_underscore) { + builder.prep(8, 32); + builder.writeInt64(BigInt(d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(c); + for (let i = 12; i >= 0; --i) { + builder.writeInt8((b?.[i] ?? 0)); + } + builder.writeFloat64(a); + return builder.offset(); + } + unpack() { + return new InnerStructT(this.a(), this.bb.createScalarList(this.b.bind(this), 13), this.c(), this.dUnderscore()); + } + unpackTo(_o) { + _o.a = this.a(); + _o.b = this.bb.createScalarList(this.b.bind(this), 13); + _o.c = this.c(); + _o.dUnderscore = this.dUnderscore(); + } +} +export class InnerStructT { + constructor(a = 0.0, b = [], c = 0, dUnderscore = BigInt('0')) { + this.a = a; + this.b = b; + this.c = c; + this.dUnderscore = dUnderscore; + } + pack(builder) { + return InnerStruct.createInnerStruct(builder, this.a, this.b, this.c, this.dUnderscore); + } +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.ts new file mode 100644 index 00000000000..cff7a58432d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/inner-struct.ts @@ -0,0 +1,93 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class InnerStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):InnerStruct { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a():number { + return this.bb!.readFloat64(this.bb_pos); +} + +b(index: number):number|null { + return this.bb!.readUint8(this.bb_pos + 8 + index); +} + +c():number { + return this.bb!.readInt8(this.bb_pos + 21); +} + +dUnderscore():bigint { + return this.bb!.readInt64(this.bb_pos + 24); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.InnerStruct'; +} + +static sizeOf():number { + return 32; +} + +static createInnerStruct(builder:flatbuffers.Builder, a: number, b: number[]|null, c: number, d_underscore: bigint):flatbuffers.Offset { + builder.prep(8, 32); + builder.writeInt64(BigInt(d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(c); + + for (let i = 12; i >= 0; --i) { + builder.writeInt8((b?.[i] ?? 0)); + + } + + builder.writeFloat64(a); + return builder.offset(); +} + + +unpack(): InnerStructT { + return new InnerStructT( + this.a(), + this.bb!.createScalarList(this.b.bind(this), 13), + this.c(), + this.dUnderscore() + ); +} + + +unpackTo(_o: InnerStructT): void { + _o.a = this.a(); + _o.b = this.bb!.createScalarList(this.b.bind(this), 13); + _o.c = this.c(); + _o.dUnderscore = this.dUnderscore(); +} +} + +export class InnerStructT implements flatbuffers.IGeneratedObject { +constructor( + public a: number = 0.0, + public b: (number)[] = [], + public c: number = 0, + public dUnderscore: bigint = BigInt('0') +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return InnerStruct.createInnerStruct(builder, + this.a, + this.b, + this.c, + this.dUnderscore + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.d.ts new file mode 100644 index 00000000000..98fe48d0ab1 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.d.ts @@ -0,0 +1,27 @@ +import * as flatbuffers from 'flatbuffers'; +import { OuterStruct, OuterStructT } from '../../my-game/example/outer-struct.js'; +import { TestEnum } from '../../my-game/example/test-enum.js'; +export declare class NestedStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): NestedStruct; + a(index: number): number | null; + b(): TestEnum; + cUnderscore(index: number): TestEnum | null; + dOuter(index: number, obj?: OuterStruct): OuterStruct | null; + e(index: number): bigint | null; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createNestedStruct(builder: flatbuffers.Builder, a: number[] | null, b: TestEnum, c_underscore: number[] | null, d_outer: (any | OuterStructT)[] | null, e: bigint[] | null): flatbuffers.Offset; + unpack(): NestedStructT; + unpackTo(_o: NestedStructT): void; +} +export declare class NestedStructT implements flatbuffers.IGeneratedObject { + a: (number)[]; + b: TestEnum; + cUnderscore: (TestEnum)[]; + dOuter: (OuterStructT)[]; + e: (bigint)[]; + constructor(a?: (number)[], b?: TestEnum, cUnderscore?: (TestEnum)[], dOuter?: (OuterStructT)[], e?: (bigint)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.js new file mode 100644 index 00000000000..067061769a7 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.js @@ -0,0 +1,80 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import { OuterStruct, OuterStructT } from '../../my-game/example/outer-struct.js'; +import { TestEnum } from '../../my-game/example/test-enum.js'; +export class NestedStruct { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a(index) { + return this.bb.readInt32(this.bb_pos + 0 + index * 4); + } + b() { + return this.bb.readInt8(this.bb_pos + 8); + } + cUnderscore(index) { + return this.bb.readInt8(this.bb_pos + 9 + index); + } + dOuter(index, obj) { + return (obj || new OuterStruct()).__init(this.bb_pos + 16 + index * 208, this.bb); + } + e(index) { + return this.bb.readInt64(this.bb_pos + 1056 + index * 8); + } + static getFullyQualifiedName() { + return 'MyGame.Example.NestedStruct'; + } + static sizeOf() { + return 1072; + } + static createNestedStruct(builder, a, b, c_underscore, d_outer, e) { + builder.prep(8, 1072); + for (let i = 1; i >= 0; --i) { + builder.writeInt64(BigInt(e?.[i] ?? 0)); + } + for (let i = 4; i >= 0; --i) { + const item = d_outer?.[i]; + if (item instanceof OuterStructT) { + item.pack(builder); + continue; + } + OuterStruct.createOuterStruct(builder, item?.a, item?.b, (item?.cUnderscore?.a ?? 0), (item?.cUnderscore?.b ?? []), (item?.cUnderscore?.c ?? 0), (item?.cUnderscore?.dUnderscore ?? BigInt(0)), item?.d, (item?.e?.a ?? 0), (item?.e?.b ?? []), (item?.e?.c ?? 0), (item?.e?.dUnderscore ?? BigInt(0)), item?.f); + } + builder.pad(5); + for (let i = 1; i >= 0; --i) { + builder.writeInt8((c_underscore?.[i] ?? 0)); + } + builder.writeInt8(b); + for (let i = 1; i >= 0; --i) { + builder.writeInt32((a?.[i] ?? 0)); + } + return builder.offset(); + } + unpack() { + return new NestedStructT(this.bb.createScalarList(this.a.bind(this), 2), this.b(), this.bb.createScalarList(this.cUnderscore.bind(this), 2), this.bb.createObjList(this.dOuter.bind(this), 5), this.bb.createScalarList(this.e.bind(this), 2)); + } + unpackTo(_o) { + _o.a = this.bb.createScalarList(this.a.bind(this), 2); + _o.b = this.b(); + _o.cUnderscore = this.bb.createScalarList(this.cUnderscore.bind(this), 2); + _o.dOuter = this.bb.createObjList(this.dOuter.bind(this), 5); + _o.e = this.bb.createScalarList(this.e.bind(this), 2); + } +} +export class NestedStructT { + constructor(a = [], b = TestEnum.A, cUnderscore = [TestEnum.A, TestEnum.A], dOuter = [], e = []) { + this.a = a; + this.b = b; + this.cUnderscore = cUnderscore; + this.dOuter = dOuter; + this.e = e; + } + pack(builder) { + return NestedStruct.createNestedStruct(builder, this.a, this.b, this.cUnderscore, this.dOuter, this.e); + } +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.ts new file mode 100644 index 00000000000..3e9891887f6 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/nested-struct.ts @@ -0,0 +1,137 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { OuterStruct, OuterStructT } from '../../my-game/example/outer-struct.js'; +import { TestEnum } from '../../my-game/example/test-enum.js'; + + +export class NestedStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):NestedStruct { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a(index: number):number|null { + return this.bb!.readInt32(this.bb_pos + 0 + index * 4); +} + +b():TestEnum { + return this.bb!.readInt8(this.bb_pos + 8); +} + +cUnderscore(index: number):TestEnum|null { + return this.bb!.readInt8(this.bb_pos + 9 + index); +} + +dOuter(index: number, obj?:OuterStruct):OuterStruct|null { + return (obj || new OuterStruct()).__init(this.bb_pos + 16 + index * 208, this.bb!); +} + +e(index: number):bigint|null { + return this.bb!.readInt64(this.bb_pos + 1056 + index * 8); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.NestedStruct'; +} + +static sizeOf():number { + return 1072; +} + +static createNestedStruct(builder:flatbuffers.Builder, a: number[]|null, b: TestEnum, c_underscore: number[]|null, d_outer: (any|OuterStructT)[]|null, e: bigint[]|null):flatbuffers.Offset { + builder.prep(8, 1072); + + for (let i = 1; i >= 0; --i) { + builder.writeInt64(BigInt(e?.[i] ?? 0)); + } + + + for (let i = 4; i >= 0; --i) { + const item = d_outer?.[i]; + + if (item instanceof OuterStructT) { + item.pack(builder); + continue; + } + + OuterStruct.createOuterStruct(builder, + item?.a, + item?.b, + (item?.cUnderscore?.a ?? 0), + (item?.cUnderscore?.b ?? []), + (item?.cUnderscore?.c ?? 0), + (item?.cUnderscore?.dUnderscore ?? BigInt(0)), + item?.d, + (item?.e?.a ?? 0), + (item?.e?.b ?? []), + (item?.e?.c ?? 0), + (item?.e?.dUnderscore ?? BigInt(0)), + item?.f + ); + } + + builder.pad(5); + + for (let i = 1; i >= 0; --i) { + builder.writeInt8((c_underscore?.[i] ?? 0)); + + } + + builder.writeInt8(b); + + for (let i = 1; i >= 0; --i) { + builder.writeInt32((a?.[i] ?? 0)); + + } + + return builder.offset(); +} + + +unpack(): NestedStructT { + return new NestedStructT( + this.bb!.createScalarList(this.a.bind(this), 2), + this.b(), + this.bb!.createScalarList(this.cUnderscore.bind(this), 2), + this.bb!.createObjList(this.dOuter.bind(this), 5), + this.bb!.createScalarList(this.e.bind(this), 2) + ); +} + + +unpackTo(_o: NestedStructT): void { + _o.a = this.bb!.createScalarList(this.a.bind(this), 2); + _o.b = this.b(); + _o.cUnderscore = this.bb!.createScalarList(this.cUnderscore.bind(this), 2); + _o.dOuter = this.bb!.createObjList(this.dOuter.bind(this), 5); + _o.e = this.bb!.createScalarList(this.e.bind(this), 2); +} +} + +export class NestedStructT implements flatbuffers.IGeneratedObject { +constructor( + public a: (number)[] = [], + public b: TestEnum = TestEnum.A, + public cUnderscore: (TestEnum)[] = [TestEnum.A, TestEnum.A], + public dOuter: (OuterStructT)[] = [], + public e: (bigint)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return NestedStruct.createNestedStruct(builder, + this.a, + this.b, + this.cUnderscore, + this.dOuter, + this.e + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.d.ts new file mode 100644 index 00000000000..9c62cea782f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.d.ts @@ -0,0 +1,28 @@ +import * as flatbuffers from 'flatbuffers'; +import { InnerStruct, InnerStructT } from '../../my-game/example/inner-struct.js'; +export declare class OuterStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): OuterStruct; + a(): boolean; + b(): number; + cUnderscore(obj?: InnerStruct): InnerStruct | null; + d(index: number, obj?: InnerStruct): InnerStruct | null; + e(obj?: InnerStruct): InnerStruct | null; + f(index: number): number | null; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createOuterStruct(builder: flatbuffers.Builder, a: boolean, b: number, c_underscore_a: number, c_underscore_b: number[] | null, c_underscore_c: number, c_underscore_d_underscore: bigint, d: (any | InnerStructT)[] | null, e_a: number, e_b: number[] | null, e_c: number, e_d_underscore: bigint, f: number[] | null): flatbuffers.Offset; + unpack(): OuterStructT; + unpackTo(_o: OuterStructT): void; +} +export declare class OuterStructT implements flatbuffers.IGeneratedObject { + a: boolean; + b: number; + cUnderscore: InnerStructT | null; + d: (InnerStructT)[]; + e: InnerStructT | null; + f: (number)[]; + constructor(a?: boolean, b?: number, cUnderscore?: InnerStructT | null, d?: (InnerStructT)[], e?: InnerStructT | null, f?: (number)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.js new file mode 100644 index 00000000000..fab2c9633ab --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.js @@ -0,0 +1,95 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import { InnerStruct, InnerStructT } from '../../my-game/example/inner-struct.js'; +export class OuterStruct { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return !!this.bb.readInt8(this.bb_pos); + } + b() { + return this.bb.readFloat64(this.bb_pos + 8); + } + cUnderscore(obj) { + return (obj || new InnerStruct()).__init(this.bb_pos + 16, this.bb); + } + d(index, obj) { + return (obj || new InnerStruct()).__init(this.bb_pos + 48 + index * 32, this.bb); + } + e(obj) { + return (obj || new InnerStruct()).__init(this.bb_pos + 144, this.bb); + } + f(index) { + return this.bb.readFloat64(this.bb_pos + 176 + index * 8); + } + static getFullyQualifiedName() { + return 'MyGame.Example.OuterStruct'; + } + static sizeOf() { + return 208; + } + static createOuterStruct(builder, a, b, c_underscore_a, c_underscore_b, c_underscore_c, c_underscore_d_underscore, d, e_a, e_b, e_c, e_d_underscore, f) { + builder.prep(8, 208); + for (let i = 3; i >= 0; --i) { + builder.writeFloat64((f?.[i] ?? 0)); + } + builder.prep(8, 32); + builder.writeInt64(BigInt(e_d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(e_c); + for (let i = 12; i >= 0; --i) { + builder.writeInt8((e_b?.[i] ?? 0)); + } + builder.writeFloat64(e_a); + for (let i = 2; i >= 0; --i) { + const item = d?.[i]; + if (item instanceof InnerStructT) { + item.pack(builder); + continue; + } + InnerStruct.createInnerStruct(builder, item?.a, item?.b, item?.c, item?.dUnderscore); + } + builder.prep(8, 32); + builder.writeInt64(BigInt(c_underscore_d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(c_underscore_c); + for (let i = 12; i >= 0; --i) { + builder.writeInt8((c_underscore_b?.[i] ?? 0)); + } + builder.writeFloat64(c_underscore_a); + builder.writeFloat64(b); + builder.pad(7); + builder.writeInt8(Number(Boolean(a))); + return builder.offset(); + } + unpack() { + return new OuterStructT(this.a(), this.b(), (this.cUnderscore() !== null ? this.cUnderscore().unpack() : null), this.bb.createObjList(this.d.bind(this), 3), (this.e() !== null ? this.e().unpack() : null), this.bb.createScalarList(this.f.bind(this), 4)); + } + unpackTo(_o) { + _o.a = this.a(); + _o.b = this.b(); + _o.cUnderscore = (this.cUnderscore() !== null ? this.cUnderscore().unpack() : null); + _o.d = this.bb.createObjList(this.d.bind(this), 3); + _o.e = (this.e() !== null ? this.e().unpack() : null); + _o.f = this.bb.createScalarList(this.f.bind(this), 4); + } +} +export class OuterStructT { + constructor(a = false, b = 0.0, cUnderscore = null, d = [], e = null, f = []) { + this.a = a; + this.b = b; + this.cUnderscore = cUnderscore; + this.d = d; + this.e = e; + this.f = f; + } + pack(builder) { + return OuterStruct.createOuterStruct(builder, this.a, this.b, (this.cUnderscore?.a ?? 0), (this.cUnderscore?.b ?? []), (this.cUnderscore?.c ?? 0), (this.cUnderscore?.dUnderscore ?? BigInt(0)), this.d, (this.e?.a ?? 0), (this.e?.b ?? []), (this.e?.c ?? 0), (this.e?.dUnderscore ?? BigInt(0)), this.f); + } +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.ts new file mode 100644 index 00000000000..39fc0a72703 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/outer-struct.ts @@ -0,0 +1,154 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { InnerStruct, InnerStructT } from '../../my-game/example/inner-struct.js'; + + +export class OuterStruct implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):OuterStruct { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a():boolean { + return !!this.bb!.readInt8(this.bb_pos); +} + +b():number { + return this.bb!.readFloat64(this.bb_pos + 8); +} + +cUnderscore(obj?:InnerStruct):InnerStruct|null { + return (obj || new InnerStruct()).__init(this.bb_pos + 16, this.bb!); +} + +d(index: number, obj?:InnerStruct):InnerStruct|null { + return (obj || new InnerStruct()).__init(this.bb_pos + 48 + index * 32, this.bb!); +} + +e(obj?:InnerStruct):InnerStruct|null { + return (obj || new InnerStruct()).__init(this.bb_pos + 144, this.bb!); +} + +f(index: number):number|null { + return this.bb!.readFloat64(this.bb_pos + 176 + index * 8); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.OuterStruct'; +} + +static sizeOf():number { + return 208; +} + +static createOuterStruct(builder:flatbuffers.Builder, a: boolean, b: number, c_underscore_a: number, c_underscore_b: number[]|null, c_underscore_c: number, c_underscore_d_underscore: bigint, d: (any|InnerStructT)[]|null, e_a: number, e_b: number[]|null, e_c: number, e_d_underscore: bigint, f: number[]|null):flatbuffers.Offset { + builder.prep(8, 208); + + for (let i = 3; i >= 0; --i) { + builder.writeFloat64((f?.[i] ?? 0)); + + } + + builder.prep(8, 32); + builder.writeInt64(BigInt(e_d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(e_c); + + for (let i = 12; i >= 0; --i) { + builder.writeInt8((e_b?.[i] ?? 0)); + + } + + builder.writeFloat64(e_a); + + for (let i = 2; i >= 0; --i) { + const item = d?.[i]; + + if (item instanceof InnerStructT) { + item.pack(builder); + continue; + } + + InnerStruct.createInnerStruct(builder, + item?.a, + item?.b, + item?.c, + item?.dUnderscore + ); + } + + builder.prep(8, 32); + builder.writeInt64(BigInt(c_underscore_d_underscore ?? 0)); + builder.pad(2); + builder.writeInt8(c_underscore_c); + + for (let i = 12; i >= 0; --i) { + builder.writeInt8((c_underscore_b?.[i] ?? 0)); + + } + + builder.writeFloat64(c_underscore_a); + builder.writeFloat64(b); + builder.pad(7); + builder.writeInt8(Number(Boolean(a))); + return builder.offset(); +} + + +unpack(): OuterStructT { + return new OuterStructT( + this.a(), + this.b(), + (this.cUnderscore() !== null ? this.cUnderscore()!.unpack() : null), + this.bb!.createObjList(this.d.bind(this), 3), + (this.e() !== null ? this.e()!.unpack() : null), + this.bb!.createScalarList(this.f.bind(this), 4) + ); +} + + +unpackTo(_o: OuterStructT): void { + _o.a = this.a(); + _o.b = this.b(); + _o.cUnderscore = (this.cUnderscore() !== null ? this.cUnderscore()!.unpack() : null); + _o.d = this.bb!.createObjList(this.d.bind(this), 3); + _o.e = (this.e() !== null ? this.e()!.unpack() : null); + _o.f = this.bb!.createScalarList(this.f.bind(this), 4); +} +} + +export class OuterStructT implements flatbuffers.IGeneratedObject { +constructor( + public a: boolean = false, + public b: number = 0.0, + public cUnderscore: InnerStructT|null = null, + public d: (InnerStructT)[] = [], + public e: InnerStructT|null = null, + public f: (number)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return OuterStruct.createOuterStruct(builder, + this.a, + this.b, + (this.cUnderscore?.a ?? 0), + (this.cUnderscore?.b ?? []), + (this.cUnderscore?.c ?? 0), + (this.cUnderscore?.dUnderscore ?? BigInt(0)), + this.d, + (this.e?.a ?? 0), + (this.e?.b ?? []), + (this.e?.c ?? 0), + (this.e?.dUnderscore ?? BigInt(0)), + this.f + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.d.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.d.ts new file mode 100644 index 00000000000..291e04971fe --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.d.ts @@ -0,0 +1,5 @@ +export declare enum TestEnum { + A = 0, + B = 1, + C = 2 +} diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.js b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.js new file mode 100644 index 00000000000..abe18369f63 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.js @@ -0,0 +1,8 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var TestEnum; +(function (TestEnum) { + TestEnum[TestEnum["A"] = 0] = "A"; + TestEnum[TestEnum["B"] = 1] = "B"; + TestEnum[TestEnum["C"] = 2] = "C"; +})(TestEnum || (TestEnum = {})); diff --git a/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.ts b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.ts new file mode 100644 index 00000000000..d07713911c1 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/arrays_test_complex/my-game/example/test-enum.ts @@ -0,0 +1,9 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum TestEnum { + A = 0, + B = 1, + C = 2 +} diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.bazelignore b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.bazelignore new file mode 100644 index 00000000000..3c3629e647f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.bazelignore @@ -0,0 +1 @@ +node_modules diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.bazelrc b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.bazelrc new file mode 100644 index 00000000000..9eee37f9454 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.bazelrc @@ -0,0 +1,5 @@ +build --symlink_prefix=/ +# Honor the setting of `skipLibCheck` in the tsconfig.json file. +common --@aspect_rules_ts//ts:skipLibCheck=honor_tsconfig +# Use "tsc" as the transpiler when ts_project has no `transpiler` set. +common --@aspect_rules_ts//ts:default_to_tsc_transpiler diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.gitignore b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.gitignore new file mode 100644 index 00000000000..ac51a054d2d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.gitignore @@ -0,0 +1 @@ +bazel-* diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.npmrc b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.npmrc new file mode 120000 index 00000000000..6b271c2f964 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/.npmrc @@ -0,0 +1 @@ +../../../.npmrc \ No newline at end of file diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/BUILD.bazel b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/BUILD.bazel new file mode 100644 index 00000000000..8b97909d34f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/BUILD.bazel @@ -0,0 +1,41 @@ +load("@aspect_rules_js//js:defs.bzl", "js_test") +load("@aspect_rules_js//npm:defs.bzl", "npm_link_package") +load("@com_github_google_flatbuffers//:typescript.bzl", "flatbuffer_ts_library") +load("@npm//:defs.bzl", "npm_link_all_packages") + +npm_link_all_packages(name = "node_modules") + +npm_link_package( + name = "node_modules/flatbuffers", + src = "@com_github_google_flatbuffers//ts:flatbuffers", +) + +flatbuffer_ts_library( + name = "one_fbs", + srcs = ["one.fbs"], +) + +flatbuffer_ts_library( + name = "two_fbs", + srcs = ["two.fbs"], + deps = [":one_fbs"], +) + +js_test( + name = "import_test", + data = [ + "package.json", + ":node_modules/flatbuffers", + ":two_fbs", + ], + entry_point = "import_test.js", +) + +js_test( + name = "independent_deps_test", + data = [ + "package.json", + ":node_modules/lodash", + ], + entry_point = "independent_deps_test.js", +) diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/MODULE.bazel b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/MODULE.bazel new file mode 100644 index 00000000000..d3ddf665557 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/MODULE.bazel @@ -0,0 +1,39 @@ +module(name = "bazel_repository_test") + +bazel_dep(name = "flatbuffers", repo_name = "com_github_google_flatbuffers") +local_path_override( + module_name = "flatbuffers", + path = "../../../", +) + +bazel_dep( + name = "aspect_rules_esbuild", + version = "0.21.0", +) +bazel_dep( + name = "aspect_rules_js", + version = "2.1.3", +) +bazel_dep( + name = "aspect_rules_ts", + version = "3.4.0", +) +bazel_dep( + name = "rules_nodejs", + version = "6.3.3", +) + +npm = use_extension("@aspect_rules_js//npm:extensions.bzl", "npm") +npm.npm_translate_lock( + name = "npm", + npmrc = "//:.npmrc", + pnpm_lock = "//:pnpm-lock.yaml", + verify_node_modules_ignored = "//:.bazelignore", +) +use_repo(npm, "npm") + +node = use_extension("@rules_nodejs//nodejs:extensions.bzl", "node") +use_repo(node, "nodejs_linux_amd64") + +rules_ts_ext = use_extension("@aspect_rules_ts//ts:extensions.bzl", "ext") +use_repo(rules_ts_ext, "npm_typescript") diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/README.md b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/README.md new file mode 100644 index 00000000000..a8bf76e1831 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/README.md @@ -0,0 +1,8 @@ +This directory is not intended to be used independently of the flatbuffers +repository. Instead, this whole directory serves as a unit test for the +`rules_js` integration in the flatbuffers repo. + +Run this test from the top-level of the flatbuffers repo. +```console +$ bazel test //tests/ts:bazel_repository_test +``` diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/import_test.js b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/import_test.js new file mode 100644 index 00000000000..05e7929ffb0 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/import_test.js @@ -0,0 +1,28 @@ +import assert from 'assert' +import * as flatbuffers from 'flatbuffers' + +import two_cjs from './two_generated.cjs' + +const bazel_repository_test = two_cjs.bazel_repository_test; + +function main() { + // Validate building a table with a table field. + var fbb = new flatbuffers.Builder(1); + + bazel_repository_test.One.startOne(fbb); + bazel_repository_test.One.addInformation(fbb, 42); + var one = bazel_repository_test.One.endOne(fbb); + + bazel_repository_test.Two.startTwo(fbb); + bazel_repository_test.Two.addOne(fbb, one); + var two = bazel_repository_test.Two.endTwo(fbb); + + fbb.finish(two); + + // Call as a sanity check. Would be better to validate actual output here. + fbb.asUint8Array(); + + console.log('FlatBuffers bazel repository test: completed successfully'); +} + +main(); diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/independent_deps_test.js b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/independent_deps_test.js new file mode 100644 index 00000000000..02f72b4867e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/independent_deps_test.js @@ -0,0 +1,18 @@ +// This test has nothing to do with flatbuffers. It only exists to validate +// that other projects can use their own set of dependencies without having to +// explicitly pull in flatbuffers's dependencies. +// +// We pick lodash here not for any particular reason. It could be any package, +// really. I chose it because it's a relatively simple package. + +import assert from 'node:assert/strict' + +import _ from 'lodash' + +function main() { + console.log(_); + assert.deepStrictEqual(_.defaults({ 'a': 1 }, { 'a': 3, 'b': 2 }), { 'a': 1, 'b': 2 }); + assert.deepStrictEqual(_.partition([1, 2, 3, 4], n => n % 2), [[1, 3], [2, 4]]); +} + +main(); diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/one.fbs b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/one.fbs new file mode 100644 index 00000000000..318170913f4 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/one.fbs @@ -0,0 +1,7 @@ +namespace bazel_repository_test; + +table One { + information:int; +} + +root_type One; diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/package.json b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/package.json new file mode 100644 index 00000000000..2988b7e80f3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/package.json @@ -0,0 +1,8 @@ +{ + "name": "bazel_repository_test", + "type": "module", + "private": true, + "devDependencies": { + "lodash": "4.17.21" + } +} diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml new file mode 100644 index 00000000000..09183910901 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/pnpm-lock.yaml @@ -0,0 +1,12 @@ +lockfileVersion: '6.0' + +devDependencies: + lodash: + specifier: 4.17.21 + version: 4.17.21 + +packages: + + /lodash@4.17.21: + resolution: {integrity: sha512-v2kDEe57lecTulaDIuNTPy3Ry4gLGJ6Z1O3vE1krgXZNrsQ+LFTGHVxVjcXPs17LhbZVGedAJv8XZ1tvj5FvSg==} + dev: true diff --git a/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/two.fbs b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/two.fbs new file mode 100644 index 00000000000..8e0cdd879bb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/bazel_repository_test_dir/two.fbs @@ -0,0 +1,9 @@ +include 'one.fbs'; + +namespace bazel_repository_test; + +table Two { + one:One; +} + +root_type Two; diff --git a/third_party/flatbuffers/tests/ts/foobar.d.ts b/third_party/flatbuffers/tests/ts/foobar.d.ts new file mode 100644 index 00000000000..c920a8c3c11 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar.d.ts @@ -0,0 +1 @@ +export { Abc } from './foobar/abc.js'; diff --git a/third_party/flatbuffers/tests/ts/foobar.js b/third_party/flatbuffers/tests/ts/foobar.js new file mode 100644 index 00000000000..fa5fd6dbf3b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar.js @@ -0,0 +1,3 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { Abc } from './foobar/abc.js'; diff --git a/third_party/flatbuffers/tests/ts/foobar.ts b/third_party/flatbuffers/tests/ts/foobar.ts new file mode 100644 index 00000000000..e513600c603 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Abc } from './foobar/abc.js'; diff --git a/third_party/flatbuffers/tests/ts/foobar/abc.d.ts b/third_party/flatbuffers/tests/ts/foobar/abc.d.ts new file mode 100644 index 00000000000..874a35db0e9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/abc.d.ts @@ -0,0 +1,3 @@ +export declare enum Abc { + a = 0 +} diff --git a/third_party/flatbuffers/tests/ts/foobar/abc.js b/third_party/flatbuffers/tests/ts/foobar/abc.js new file mode 100644 index 00000000000..8c3aeb95286 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/abc.js @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var Abc; +(function (Abc) { + Abc[Abc["a"] = 0] = "a"; +})(Abc || (Abc = {})); diff --git a/third_party/flatbuffers/tests/ts/foobar/abc.ts b/third_party/flatbuffers/tests/ts/foobar/abc.ts new file mode 100644 index 00000000000..308713cc642 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/abc.ts @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum Abc { + a = 0 +} diff --git a/third_party/flatbuffers/tests/ts/foobar/class.d.ts b/third_party/flatbuffers/tests/ts/foobar/class.d.ts new file mode 100644 index 00000000000..2815be18c25 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/class.d.ts @@ -0,0 +1,3 @@ +export declare enum class_ { + arguments_ = 0 +} diff --git a/third_party/flatbuffers/tests/ts/foobar/class.js b/third_party/flatbuffers/tests/ts/foobar/class.js new file mode 100644 index 00000000000..179ab6f0435 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/class.js @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var class_; +(function (class_) { + class_[class_["arguments_"] = 0] = "arguments_"; +})(class_ || (class_ = {})); diff --git a/third_party/flatbuffers/tests/ts/foobar/class.ts b/third_party/flatbuffers/tests/ts/foobar/class.ts new file mode 100644 index 00000000000..db45d22ca45 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/class.ts @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum class_ { + arguments_ = 0 +} diff --git a/third_party/flatbuffers/tests/ts/foobar/tab.ts b/third_party/flatbuffers/tests/ts/foobar/tab.ts new file mode 100644 index 00000000000..3af76d91da4 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/foobar/tab.ts @@ -0,0 +1,134 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Abc } from '../foobar/abc.js'; +import { class_ } from '../foobar/class.js'; + + +export class Tab implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Tab { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsTab(bb:flatbuffers.ByteBuffer, obj?:Tab):Tab { + return (obj || new Tab()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsTab(bb:flatbuffers.ByteBuffer, obj?:Tab):Tab { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Tab()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +abc():Abc { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : Abc.a; +} + +mutate_abc(value:Abc):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +arg():class_ { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : class_.arguments_; +} + +mutate_arg(value:class_):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'foobar.Tab'; +} + +static startTab(builder:flatbuffers.Builder) { + builder.startObject(3); +} + +static addAbc(builder:flatbuffers.Builder, abc:Abc) { + builder.addFieldInt32(0, abc, Abc.a); +} + +static addArg(builder:flatbuffers.Builder, arg:class_) { + builder.addFieldInt32(1, arg, class_.arguments_); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, nameOffset, 0); +} + +static endTab(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createTab(builder:flatbuffers.Builder, abc:Abc, arg:class_, nameOffset:flatbuffers.Offset):flatbuffers.Offset { + Tab.startTab(builder); + Tab.addAbc(builder, abc); + Tab.addArg(builder, arg); + Tab.addName(builder, nameOffset); + return Tab.endTab(builder); +} + +unpack(): TabT { + return new TabT( + this.abc(), + this.arg(), + this.name() + ); +} + + +unpackTo(_o: TabT): void { + _o.abc = this.abc(); + _o.arg = this.arg(); + _o.name = this.name(); +} +} + +export class TabT implements flatbuffers.IGeneratedObject { +constructor( + public abc: Abc = Abc.a, + public arg: class_ = class_.arguments_, + public name: string|Uint8Array|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + + return Tab.createTab(builder, + this.abc, + this.arg, + name + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/monster_test.d.ts b/third_party/flatbuffers/tests/ts/monster_test.d.ts new file mode 100644 index 00000000000..e89d898e45c --- /dev/null +++ b/third_party/flatbuffers/tests/ts/monster_test.d.ts @@ -0,0 +1,2 @@ +export { TableA, TableAT } from './table-a.js'; +export * as MyGame from './my-game.js'; diff --git a/third_party/flatbuffers/tests/ts/monster_test.js b/third_party/flatbuffers/tests/ts/monster_test.js new file mode 100644 index 00000000000..04d21753c1f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/monster_test.js @@ -0,0 +1,4 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { TableA, TableAT } from './table-a.js'; +export * as MyGame from './my-game.js'; diff --git a/third_party/flatbuffers/tests/ts/monster_test.ts b/third_party/flatbuffers/tests/ts/monster_test.ts new file mode 100644 index 00000000000..02e6f14a19c --- /dev/null +++ b/third_party/flatbuffers/tests/ts/monster_test.ts @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { TableA, TableAT } from './table-a.js'; +export * as MyGame from './my-game.js'; diff --git a/third_party/flatbuffers/tests/ts/monster_test_generated.cjs b/third_party/flatbuffers/tests/ts/monster_test_generated.cjs new file mode 100644 index 00000000000..d78fd5d052b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/monster_test_generated.cjs @@ -0,0 +1,2588 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// monster_test.ts +var monster_test_exports = {}; +__export(monster_test_exports, { + MyGame: () => my_game_exports, + TableA: () => TableA, + TableAT: () => TableAT +}); +module.exports = __toCommonJS(monster_test_exports); + +// table-a.js +var flatbuffers2 = __toESM(require("flatbuffers"), 1); + +// my-game/other-name-space/table-b.js +var flatbuffers = __toESM(require("flatbuffers"), 1); +var TableB = class _TableB { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTableB(bb, obj) { + return (obj || new _TableB()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTableB(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new _TableB()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + a(obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new TableA()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + static getFullyQualifiedName() { + return "MyGame.OtherNameSpace.TableB"; + } + static startTableB(builder) { + builder.startObject(1); + } + static addA(builder, aOffset) { + builder.addFieldOffset(0, aOffset, 0); + } + static endTableB(builder) { + const offset = builder.endObject(); + return offset; + } + static createTableB(builder, aOffset) { + _TableB.startTableB(builder); + _TableB.addA(builder, aOffset); + return _TableB.endTableB(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _TableB.getRootAsTableB(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new TableBT(this.a() !== null ? this.a().unpack() : null); + } + unpackTo(_o) { + _o.a = this.a() !== null ? this.a().unpack() : null; + } +}; +var TableBT = class { + constructor(a = null) { + this.a = a; + } + pack(builder) { + const a = this.a !== null ? this.a.pack(builder) : 0; + return TableB.createTableB(builder, a); + } +}; + +// table-a.js +var TableA = class _TableA { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTableA(bb, obj) { + return (obj || new _TableA()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTableA(bb, obj) { + bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH); + return (obj || new _TableA()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + b(obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new TableB()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + static getFullyQualifiedName() { + return "TableA"; + } + static startTableA(builder) { + builder.startObject(1); + } + static addB(builder, bOffset) { + builder.addFieldOffset(0, bOffset, 0); + } + static endTableA(builder) { + const offset = builder.endObject(); + return offset; + } + static createTableA(builder, bOffset) { + _TableA.startTableA(builder); + _TableA.addB(builder, bOffset); + return _TableA.endTableA(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _TableA.getRootAsTableA(new flatbuffers2.ByteBuffer(buffer)); + } + unpack() { + return new TableAT(this.b() !== null ? this.b().unpack() : null); + } + unpackTo(_o) { + _o.b = this.b() !== null ? this.b().unpack() : null; + } +}; +var TableAT = class { + constructor(b = null) { + this.b = b; + } + pack(builder) { + const b = this.b !== null ? this.b.pack(builder) : 0; + return TableA.createTableA(builder, b); + } +}; + +// my-game.js +var my_game_exports = {}; +__export(my_game_exports, { + Example: () => example_exports, + Example2: () => example2_exports, + InParentNamespace: () => InParentNamespace, + InParentNamespaceT: () => InParentNamespaceT, + OtherNameSpace: () => other_name_space_exports +}); + +// my-game/in-parent-namespace.js +var flatbuffers3 = __toESM(require("flatbuffers"), 1); +var InParentNamespace = class _InParentNamespace { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsInParentNamespace(bb, obj) { + return (obj || new _InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsInParentNamespace(bb, obj) { + bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH); + return (obj || new _InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getFullyQualifiedName() { + return "MyGame.InParentNamespace"; + } + static startInParentNamespace(builder) { + builder.startObject(0); + } + static endInParentNamespace(builder) { + const offset = builder.endObject(); + return offset; + } + static createInParentNamespace(builder) { + _InParentNamespace.startInParentNamespace(builder); + return _InParentNamespace.endInParentNamespace(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _InParentNamespace.getRootAsInParentNamespace(new flatbuffers3.ByteBuffer(buffer)); + } + unpack() { + return new InParentNamespaceT(); + } + unpackTo(_o) { + } +}; +var InParentNamespaceT = class { + constructor() { + } + pack(builder) { + return InParentNamespace.createInParentNamespace(builder); + } +}; + +// my-game/example.js +var example_exports = {}; +__export(example_exports, { + Ability: () => Ability, + AbilityT: () => AbilityT, + Any: () => Any, + AnyAmbiguousAliases: () => AnyAmbiguousAliases, + AnyUniqueAliases: () => AnyUniqueAliases, + Color: () => Color, + LongEnum: () => LongEnum, + Monster: () => Monster2, + MonsterT: () => MonsterT2, + Race: () => Race, + Referrable: () => Referrable, + ReferrableT: () => ReferrableT, + Stat: () => Stat, + StatT: () => StatT, + StructOfStructs: () => StructOfStructs, + StructOfStructsOfStructs: () => StructOfStructsOfStructs, + StructOfStructsOfStructsT: () => StructOfStructsOfStructsT, + StructOfStructsT: () => StructOfStructsT, + Test: () => Test, + TestSimpleTableWithEnum: () => TestSimpleTableWithEnum, + TestSimpleTableWithEnumT: () => TestSimpleTableWithEnumT, + TestT: () => TestT, + TypeAliases: () => TypeAliases, + TypeAliasesT: () => TypeAliasesT, + Vec3: () => Vec3, + Vec3T: () => Vec3T +}); + +// my-game/example/ability.js +var Ability = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + id() { + return this.bb.readUint32(this.bb_pos); + } + mutate_id(value) { + this.bb.writeUint32(this.bb_pos + 0, value); + return true; + } + distance() { + return this.bb.readUint32(this.bb_pos + 4); + } + mutate_distance(value) { + this.bb.writeUint32(this.bb_pos + 4, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.Example.Ability"; + } + static sizeOf() { + return 8; + } + static createAbility(builder, id, distance) { + builder.prep(4, 8); + builder.writeInt32(distance); + builder.writeInt32(id); + return builder.offset(); + } + unpack() { + return new AbilityT(this.id(), this.distance()); + } + unpackTo(_o) { + _o.id = this.id(); + _o.distance = this.distance(); + } +}; +var AbilityT = class { + constructor(id = 0, distance = 0) { + this.id = id; + this.distance = distance; + } + pack(builder) { + return Ability.createAbility(builder, this.id, this.distance); + } +}; + +// my-game/example2/monster.js +var flatbuffers4 = __toESM(require("flatbuffers"), 1); +var Monster = class _Monster { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMonster(bb, obj) { + return (obj || new _Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMonster(bb, obj) { + bb.setPosition(bb.position() + flatbuffers4.SIZE_PREFIX_LENGTH); + return (obj || new _Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getFullyQualifiedName() { + return "MyGame.Example2.Monster"; + } + static startMonster(builder) { + builder.startObject(0); + } + static endMonster(builder) { + const offset = builder.endObject(); + return offset; + } + static createMonster(builder) { + _Monster.startMonster(builder); + return _Monster.endMonster(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _Monster.getRootAsMonster(new flatbuffers4.ByteBuffer(buffer)); + } + unpack() { + return new MonsterT(); + } + unpackTo(_o) { + } +}; +var MonsterT = class { + constructor() { + } + pack(builder) { + return Monster.createMonster(builder); + } +}; + +// my-game/example/monster.js +var flatbuffers8 = __toESM(require("flatbuffers"), 1); + +// my-game/example/any-ambiguous-aliases.js +var AnyAmbiguousAliases; +(function(AnyAmbiguousAliases2) { + AnyAmbiguousAliases2[AnyAmbiguousAliases2["NONE"] = 0] = "NONE"; + AnyAmbiguousAliases2[AnyAmbiguousAliases2["M1"] = 1] = "M1"; + AnyAmbiguousAliases2[AnyAmbiguousAliases2["M2"] = 2] = "M2"; + AnyAmbiguousAliases2[AnyAmbiguousAliases2["M3"] = 3] = "M3"; +})(AnyAmbiguousAliases || (AnyAmbiguousAliases = {})); +function unionToAnyAmbiguousAliases(type, accessor) { + switch (AnyAmbiguousAliases[type]) { + case "NONE": + return null; + case "M1": + return accessor(new Monster2()); + case "M2": + return accessor(new Monster2()); + case "M3": + return accessor(new Monster2()); + default: + return null; + } +} + +// my-game/example/test-simple-table-with-enum.js +var flatbuffers5 = __toESM(require("flatbuffers"), 1); + +// my-game/example/color.js +var Color; +(function(Color2) { + Color2[Color2["Red"] = 1] = "Red"; + Color2[Color2["Green"] = 2] = "Green"; + Color2[Color2["Blue"] = 8] = "Blue"; +})(Color || (Color = {})); + +// my-game/example/test-simple-table-with-enum.js +var TestSimpleTableWithEnum = class _TestSimpleTableWithEnum { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTestSimpleTableWithEnum(bb, obj) { + return (obj || new _TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTestSimpleTableWithEnum(bb, obj) { + bb.setPosition(bb.position() + flatbuffers5.SIZE_PREFIX_LENGTH); + return (obj || new _TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + color() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Color.Green; + } + mutate_color(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeUint8(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.Example.TestSimpleTableWithEnum"; + } + static startTestSimpleTableWithEnum(builder) { + builder.startObject(1); + } + static addColor(builder, color) { + builder.addFieldInt8(0, color, Color.Green); + } + static endTestSimpleTableWithEnum(builder) { + const offset = builder.endObject(); + return offset; + } + static createTestSimpleTableWithEnum(builder, color) { + _TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder); + _TestSimpleTableWithEnum.addColor(builder, color); + return _TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum(new flatbuffers5.ByteBuffer(buffer)); + } + unpack() { + return new TestSimpleTableWithEnumT(this.color()); + } + unpackTo(_o) { + _o.color = this.color(); + } +}; +var TestSimpleTableWithEnumT = class { + constructor(color = Color.Green) { + this.color = color; + } + pack(builder) { + return TestSimpleTableWithEnum.createTestSimpleTableWithEnum(builder, this.color); + } +}; + +// my-game/example/any-unique-aliases.js +var AnyUniqueAliases; +(function(AnyUniqueAliases2) { + AnyUniqueAliases2[AnyUniqueAliases2["NONE"] = 0] = "NONE"; + AnyUniqueAliases2[AnyUniqueAliases2["M"] = 1] = "M"; + AnyUniqueAliases2[AnyUniqueAliases2["TS"] = 2] = "TS"; + AnyUniqueAliases2[AnyUniqueAliases2["M2"] = 3] = "M2"; +})(AnyUniqueAliases || (AnyUniqueAliases = {})); +function unionToAnyUniqueAliases(type, accessor) { + switch (AnyUniqueAliases[type]) { + case "NONE": + return null; + case "M": + return accessor(new Monster2()); + case "TS": + return accessor(new TestSimpleTableWithEnum()); + case "M2": + return accessor(new Monster()); + default: + return null; + } +} + +// my-game/example/race.js +var Race; +(function(Race2) { + Race2[Race2["None"] = -1] = "None"; + Race2[Race2["Human"] = 0] = "Human"; + Race2[Race2["Dwarf"] = 1] = "Dwarf"; + Race2[Race2["Elf"] = 2] = "Elf"; +})(Race || (Race = {})); + +// my-game/example/referrable.js +var flatbuffers6 = __toESM(require("flatbuffers"), 1); +var Referrable = class _Referrable { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsReferrable(bb, obj) { + return (obj || new _Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsReferrable(bb, obj) { + bb.setPosition(bb.position() + flatbuffers6.SIZE_PREFIX_LENGTH); + return (obj || new _Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + id() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_id(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.Example.Referrable"; + } + static startReferrable(builder) { + builder.startObject(1); + } + static addId(builder, id) { + builder.addFieldInt64(0, id, BigInt("0")); + } + static endReferrable(builder) { + const offset = builder.endObject(); + return offset; + } + static createReferrable(builder, id) { + _Referrable.startReferrable(builder); + _Referrable.addId(builder, id); + return _Referrable.endReferrable(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _Referrable.getRootAsReferrable(new flatbuffers6.ByteBuffer(buffer)); + } + unpack() { + return new ReferrableT(this.id()); + } + unpackTo(_o) { + _o.id = this.id(); + } +}; +var ReferrableT = class { + constructor(id = BigInt("0")) { + this.id = id; + } + pack(builder) { + return Referrable.createReferrable(builder, this.id); + } +}; + +// my-game/example/stat.js +var flatbuffers7 = __toESM(require("flatbuffers"), 1); +var Stat = class _Stat { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsStat(bb, obj) { + return (obj || new _Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsStat(bb, obj) { + bb.setPosition(bb.position() + flatbuffers7.SIZE_PREFIX_LENGTH); + return (obj || new _Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + id(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + val() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_val(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + count() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_count(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.Example.Stat"; + } + static startStat(builder) { + builder.startObject(3); + } + static addId(builder, idOffset) { + builder.addFieldOffset(0, idOffset, 0); + } + static addVal(builder, val) { + builder.addFieldInt64(1, val, BigInt("0")); + } + static addCount(builder, count) { + builder.addFieldInt16(2, count, 0); + } + static endStat(builder) { + const offset = builder.endObject(); + return offset; + } + static createStat(builder, idOffset, val, count) { + _Stat.startStat(builder); + _Stat.addId(builder, idOffset); + _Stat.addVal(builder, val); + _Stat.addCount(builder, count); + return _Stat.endStat(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _Stat.getRootAsStat(new flatbuffers7.ByteBuffer(buffer)); + } + unpack() { + return new StatT(this.id(), this.val(), this.count()); + } + unpackTo(_o) { + _o.id = this.id(); + _o.val = this.val(); + _o.count = this.count(); + } +}; +var StatT = class { + constructor(id = null, val = BigInt("0"), count = 0) { + this.id = id; + this.val = val; + this.count = count; + } + pack(builder) { + const id = this.id !== null ? builder.createString(this.id) : 0; + return Stat.createStat(builder, id, this.val, this.count); + } +}; + +// my-game/example/test.js +var Test = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return this.bb.readInt16(this.bb_pos); + } + mutate_a(value) { + this.bb.writeInt16(this.bb_pos + 0, value); + return true; + } + b() { + return this.bb.readInt8(this.bb_pos + 2); + } + mutate_b(value) { + this.bb.writeInt8(this.bb_pos + 2, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.Example.Test"; + } + static sizeOf() { + return 4; + } + static createTest(builder, a, b) { + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(b); + builder.writeInt16(a); + return builder.offset(); + } + unpack() { + return new TestT(this.a(), this.b()); + } + unpackTo(_o) { + _o.a = this.a(); + _o.b = this.b(); + } +}; +var TestT = class { + constructor(a = 0, b = 0) { + this.a = a; + this.b = b; + } + pack(builder) { + return Test.createTest(builder, this.a, this.b); + } +}; + +// my-game/example/vec3.js +var Vec3 = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + x() { + return this.bb.readFloat32(this.bb_pos); + } + mutate_x(value) { + this.bb.writeFloat32(this.bb_pos + 0, value); + return true; + } + y() { + return this.bb.readFloat32(this.bb_pos + 4); + } + mutate_y(value) { + this.bb.writeFloat32(this.bb_pos + 4, value); + return true; + } + z() { + return this.bb.readFloat32(this.bb_pos + 8); + } + mutate_z(value) { + this.bb.writeFloat32(this.bb_pos + 8, value); + return true; + } + test1() { + return this.bb.readFloat64(this.bb_pos + 16); + } + mutate_test1(value) { + this.bb.writeFloat64(this.bb_pos + 16, value); + return true; + } + test2() { + return this.bb.readUint8(this.bb_pos + 24); + } + mutate_test2(value) { + this.bb.writeUint8(this.bb_pos + 24, value); + return true; + } + test3(obj) { + return (obj || new Test()).__init(this.bb_pos + 26, this.bb); + } + static getFullyQualifiedName() { + return "MyGame.Example.Vec3"; + } + static sizeOf() { + return 32; + } + static createVec3(builder, x, y, z, test1, test2, test3_a, test3_b) { + builder.prep(8, 32); + builder.pad(2); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(test3_b); + builder.writeInt16(test3_a); + builder.pad(1); + builder.writeInt8(test2); + builder.writeFloat64(test1); + builder.pad(4); + builder.writeFloat32(z); + builder.writeFloat32(y); + builder.writeFloat32(x); + return builder.offset(); + } + unpack() { + return new Vec3T(this.x(), this.y(), this.z(), this.test1(), this.test2(), this.test3() !== null ? this.test3().unpack() : null); + } + unpackTo(_o) { + _o.x = this.x(); + _o.y = this.y(); + _o.z = this.z(); + _o.test1 = this.test1(); + _o.test2 = this.test2(); + _o.test3 = this.test3() !== null ? this.test3().unpack() : null; + } +}; +var Vec3T = class { + constructor(x = 0, y = 0, z = 0, test1 = 0, test2 = Color.Red, test3 = null) { + this.x = x; + this.y = y; + this.z = z; + this.test1 = test1; + this.test2 = test2; + this.test3 = test3; + } + pack(builder) { + return Vec3.createVec3(builder, this.x, this.y, this.z, this.test1, this.test2, this.test3?.a ?? 0, this.test3?.b ?? 0); + } +}; + +// my-game/example/monster.js +var Monster2 = class _Monster { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMonster(bb, obj) { + return (obj || new _Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMonster(bb, obj) { + bb.setPosition(bb.position() + flatbuffers8.SIZE_PREFIX_LENGTH); + return (obj || new _Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier("MONS"); + } + pos(obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new Vec3()).__init(this.bb_pos + offset, this.bb) : null; + } + mana() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 150; + } + mutate_mana(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt16(this.bb_pos + offset, value); + return true; + } + hp() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 100; + } + mutate_hp(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt16(this.bb_pos + offset, value); + return true; + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + inventory(index) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + inventoryLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + inventoryArray() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + color() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Color.Blue; + } + mutate_color(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeUint8(this.bb_pos + offset, value); + return true; + } + testType() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Any.NONE; + } + test(obj) { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + test4(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? (obj || new Test()).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null; + } + test4Length() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testarrayofstring(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + testarrayofstringLength() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * an example documentation comment: this will end up in the generated code + * multiline too + */ + testarrayoftables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? (obj || new _Monster()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + testarrayoftablesLength() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + enemy(obj) { + const offset = this.bb.__offset(this.bb_pos, 28); + return offset ? (obj || new _Monster()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + testnestedflatbuffer(index) { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + testnestedflatbufferLength() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testnestedflatbufferArray() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + testempty(obj) { + const offset = this.bb.__offset(this.bb_pos, 32); + return offset ? (obj || new Stat()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + testbool() { + const offset = this.bb.__offset(this.bb_pos, 34); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_testbool(value) { + const offset = this.bb.__offset(this.bb_pos, 34); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + testhashs32Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 36); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_testhashs32_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 36); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + testhashu32Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 38); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_testhashu32_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 38); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + testhashs64Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 40); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_testhashs64_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 40); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + testhashu64Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 42); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_testhashu64_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 42); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + testhashs32Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 44); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_testhashs32_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 44); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + testhashu32Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 46); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_testhashu32_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 46); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + testhashs64Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 48); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_testhashs64_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 48); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + testhashu64Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 50); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_testhashu64_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 50); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + testarrayofbools(index) { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? !!this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : false; + } + testarrayofboolsLength() { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testarrayofboolsArray() { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + testf() { + const offset = this.bb.__offset(this.bb_pos, 54); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.14159; + } + mutate_testf(value) { + const offset = this.bb.__offset(this.bb_pos, 54); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + testf2() { + const offset = this.bb.__offset(this.bb_pos, 56); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3; + } + mutate_testf2(value) { + const offset = this.bb.__offset(this.bb_pos, 56); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + testf3() { + const offset = this.bb.__offset(this.bb_pos, 58); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0; + } + mutate_testf3(value) { + const offset = this.bb.__offset(this.bb_pos, 58); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + testarrayofstring2(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 60); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + testarrayofstring2Length() { + const offset = this.bb.__offset(this.bb_pos, 60); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testarrayofsortedstruct(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 62); + return offset ? (obj || new Ability()).__init(this.bb.__vector(this.bb_pos + offset) + index * 8, this.bb) : null; + } + testarrayofsortedstructLength() { + const offset = this.bb.__offset(this.bb_pos, 62); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + flex(index) { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + flexLength() { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + flexArray() { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + test5(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 66); + return offset ? (obj || new Test()).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null; + } + test5Length() { + const offset = this.bb.__offset(this.bb_pos, 66); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfLongs(index) { + const offset = this.bb.__offset(this.bb_pos, 68); + return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfLongsLength() { + const offset = this.bb.__offset(this.bb_pos, 68); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfDoubles(index) { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; + } + vectorOfDoublesLength() { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfDoublesArray() { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + parentNamespaceTest(obj) { + const offset = this.bb.__offset(this.bb_pos, 72); + return offset ? (obj || new InParentNamespace()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + vectorOfReferrables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 74); + return offset ? (obj || new Referrable()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + vectorOfReferrablesLength() { + const offset = this.bb.__offset(this.bb_pos, 74); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + singleWeakReference() { + const offset = this.bb.__offset(this.bb_pos, 76); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_single_weak_reference(value) { + const offset = this.bb.__offset(this.bb_pos, 76); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + vectorOfWeakReferences(index) { + const offset = this.bb.__offset(this.bb_pos, 78); + return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfWeakReferencesLength() { + const offset = this.bb.__offset(this.bb_pos, 78); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfStrongReferrables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 80); + return offset ? (obj || new Referrable()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + vectorOfStrongReferrablesLength() { + const offset = this.bb.__offset(this.bb_pos, 80); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + coOwningReference() { + const offset = this.bb.__offset(this.bb_pos, 82); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_co_owning_reference(value) { + const offset = this.bb.__offset(this.bb_pos, 82); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + vectorOfCoOwningReferences(index) { + const offset = this.bb.__offset(this.bb_pos, 84); + return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfCoOwningReferencesLength() { + const offset = this.bb.__offset(this.bb_pos, 84); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + nonOwningReference() { + const offset = this.bb.__offset(this.bb_pos, 86); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_non_owning_reference(value) { + const offset = this.bb.__offset(this.bb_pos, 86); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + vectorOfNonOwningReferences(index) { + const offset = this.bb.__offset(this.bb_pos, 88); + return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfNonOwningReferencesLength() { + const offset = this.bb.__offset(this.bb_pos, 88); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + anyUniqueType() { + const offset = this.bb.__offset(this.bb_pos, 90); + return offset ? this.bb.readUint8(this.bb_pos + offset) : AnyUniqueAliases.NONE; + } + anyUnique(obj) { + const offset = this.bb.__offset(this.bb_pos, 92); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + anyAmbiguousType() { + const offset = this.bb.__offset(this.bb_pos, 94); + return offset ? this.bb.readUint8(this.bb_pos + offset) : AnyAmbiguousAliases.NONE; + } + anyAmbiguous(obj) { + const offset = this.bb.__offset(this.bb_pos, 96); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + vectorOfEnums(index) { + const offset = this.bb.__offset(this.bb_pos, 98); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + vectorOfEnumsLength() { + const offset = this.bb.__offset(this.bb_pos, 98); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfEnumsArray() { + const offset = this.bb.__offset(this.bb_pos, 98); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + signedEnum() { + const offset = this.bb.__offset(this.bb_pos, 100); + return offset ? this.bb.readInt8(this.bb_pos + offset) : Race.None; + } + mutate_signed_enum(value) { + const offset = this.bb.__offset(this.bb_pos, 100); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + testrequirednestedflatbuffer(index) { + const offset = this.bb.__offset(this.bb_pos, 102); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + testrequirednestedflatbufferLength() { + const offset = this.bb.__offset(this.bb_pos, 102); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testrequirednestedflatbufferArray() { + const offset = this.bb.__offset(this.bb_pos, 102); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + scalarKeySortedTables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 104); + return offset ? (obj || new Stat()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + scalarKeySortedTablesLength() { + const offset = this.bb.__offset(this.bb_pos, 104); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + nativeInline(obj) { + const offset = this.bb.__offset(this.bb_pos, 106); + return offset ? (obj || new Test()).__init(this.bb_pos + offset, this.bb) : null; + } + longEnumNonEnumDefault() { + const offset = this.bb.__offset(this.bb_pos, 108); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_long_enum_non_enum_default(value) { + const offset = this.bb.__offset(this.bb_pos, 108); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + longEnumNormalDefault() { + const offset = this.bb.__offset(this.bb_pos, 110); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("2"); + } + mutate_long_enum_normal_default(value) { + const offset = this.bb.__offset(this.bb_pos, 110); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + nanDefault() { + const offset = this.bb.__offset(this.bb_pos, 112); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : NaN; + } + mutate_nan_default(value) { + const offset = this.bb.__offset(this.bb_pos, 112); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + infDefault() { + const offset = this.bb.__offset(this.bb_pos, 114); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 114); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + positiveInfDefault() { + const offset = this.bb.__offset(this.bb_pos, 116); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_positive_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 116); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + infinityDefault() { + const offset = this.bb.__offset(this.bb_pos, 118); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_infinity_default(value) { + const offset = this.bb.__offset(this.bb_pos, 118); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + positiveInfinityDefault() { + const offset = this.bb.__offset(this.bb_pos, 120); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_positive_infinity_default(value) { + const offset = this.bb.__offset(this.bb_pos, 120); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + negativeInfDefault() { + const offset = this.bb.__offset(this.bb_pos, 122); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : -Infinity; + } + mutate_negative_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 122); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + negativeInfinityDefault() { + const offset = this.bb.__offset(this.bb_pos, 124); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : -Infinity; + } + mutate_negative_infinity_default(value) { + const offset = this.bb.__offset(this.bb_pos, 124); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + doubleInfDefault() { + const offset = this.bb.__offset(this.bb_pos, 126); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : Infinity; + } + mutate_double_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 126); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.Example.Monster"; + } + static startMonster(builder) { + builder.startObject(62); + } + static addPos(builder, posOffset) { + builder.addFieldStruct(0, posOffset, 0); + } + static addMana(builder, mana) { + builder.addFieldInt16(1, mana, 150); + } + static addHp(builder, hp) { + builder.addFieldInt16(2, hp, 100); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(3, nameOffset, 0); + } + static addInventory(builder, inventoryOffset) { + builder.addFieldOffset(5, inventoryOffset, 0); + } + static createInventoryVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startInventoryVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addColor(builder, color) { + builder.addFieldInt8(6, color, Color.Blue); + } + static addTestType(builder, testType) { + builder.addFieldInt8(7, testType, Any.NONE); + } + static addTest(builder, testOffset) { + builder.addFieldOffset(8, testOffset, 0); + } + static addTest4(builder, test4Offset) { + builder.addFieldOffset(9, test4Offset, 0); + } + static startTest4Vector(builder, numElems) { + builder.startVector(4, numElems, 2); + } + static addTestarrayofstring(builder, testarrayofstringOffset) { + builder.addFieldOffset(10, testarrayofstringOffset, 0); + } + static createTestarrayofstringVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestarrayofstringVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addTestarrayoftables(builder, testarrayoftablesOffset) { + builder.addFieldOffset(11, testarrayoftablesOffset, 0); + } + static createTestarrayoftablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestarrayoftablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addEnemy(builder, enemyOffset) { + builder.addFieldOffset(12, enemyOffset, 0); + } + static addTestnestedflatbuffer(builder, testnestedflatbufferOffset) { + builder.addFieldOffset(13, testnestedflatbufferOffset, 0); + } + static createTestnestedflatbufferVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startTestnestedflatbufferVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addTestempty(builder, testemptyOffset) { + builder.addFieldOffset(14, testemptyOffset, 0); + } + static addTestbool(builder, testbool) { + builder.addFieldInt8(15, +testbool, 0); + } + static addTesthashs32Fnv1(builder, testhashs32Fnv1) { + builder.addFieldInt32(16, testhashs32Fnv1, 0); + } + static addTesthashu32Fnv1(builder, testhashu32Fnv1) { + builder.addFieldInt32(17, testhashu32Fnv1, 0); + } + static addTesthashs64Fnv1(builder, testhashs64Fnv1) { + builder.addFieldInt64(18, testhashs64Fnv1, BigInt("0")); + } + static addTesthashu64Fnv1(builder, testhashu64Fnv1) { + builder.addFieldInt64(19, testhashu64Fnv1, BigInt("0")); + } + static addTesthashs32Fnv1a(builder, testhashs32Fnv1a) { + builder.addFieldInt32(20, testhashs32Fnv1a, 0); + } + static addTesthashu32Fnv1a(builder, testhashu32Fnv1a) { + builder.addFieldInt32(21, testhashu32Fnv1a, 0); + } + static addTesthashs64Fnv1a(builder, testhashs64Fnv1a) { + builder.addFieldInt64(22, testhashs64Fnv1a, BigInt("0")); + } + static addTesthashu64Fnv1a(builder, testhashu64Fnv1a) { + builder.addFieldInt64(23, testhashu64Fnv1a, BigInt("0")); + } + static addTestarrayofbools(builder, testarrayofboolsOffset) { + builder.addFieldOffset(24, testarrayofboolsOffset, 0); + } + static createTestarrayofboolsVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(+data[i]); + } + return builder.endVector(); + } + static startTestarrayofboolsVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addTestf(builder, testf) { + builder.addFieldFloat32(25, testf, 3.14159); + } + static addTestf2(builder, testf2) { + builder.addFieldFloat32(26, testf2, 3); + } + static addTestf3(builder, testf3) { + builder.addFieldFloat32(27, testf3, 0); + } + static addTestarrayofstring2(builder, testarrayofstring2Offset) { + builder.addFieldOffset(28, testarrayofstring2Offset, 0); + } + static createTestarrayofstring2Vector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestarrayofstring2Vector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addTestarrayofsortedstruct(builder, testarrayofsortedstructOffset) { + builder.addFieldOffset(29, testarrayofsortedstructOffset, 0); + } + static startTestarrayofsortedstructVector(builder, numElems) { + builder.startVector(8, numElems, 4); + } + static addFlex(builder, flexOffset) { + builder.addFieldOffset(30, flexOffset, 0); + } + static createFlexVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startFlexVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addTest5(builder, test5Offset) { + builder.addFieldOffset(31, test5Offset, 0); + } + static startTest5Vector(builder, numElems) { + builder.startVector(4, numElems, 2); + } + static addVectorOfLongs(builder, vectorOfLongsOffset) { + builder.addFieldOffset(32, vectorOfLongsOffset, 0); + } + static createVectorOfLongsVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfLongsVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addVectorOfDoubles(builder, vectorOfDoublesOffset) { + builder.addFieldOffset(33, vectorOfDoublesOffset, 0); + } + static createVectorOfDoublesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addFloat64(data[i]); + } + return builder.endVector(); + } + static startVectorOfDoublesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addParentNamespaceTest(builder, parentNamespaceTestOffset) { + builder.addFieldOffset(34, parentNamespaceTestOffset, 0); + } + static addVectorOfReferrables(builder, vectorOfReferrablesOffset) { + builder.addFieldOffset(35, vectorOfReferrablesOffset, 0); + } + static createVectorOfReferrablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startVectorOfReferrablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addSingleWeakReference(builder, singleWeakReference) { + builder.addFieldInt64(36, singleWeakReference, BigInt("0")); + } + static addVectorOfWeakReferences(builder, vectorOfWeakReferencesOffset) { + builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0); + } + static createVectorOfWeakReferencesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfWeakReferencesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addVectorOfStrongReferrables(builder, vectorOfStrongReferrablesOffset) { + builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0); + } + static createVectorOfStrongReferrablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startVectorOfStrongReferrablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addCoOwningReference(builder, coOwningReference) { + builder.addFieldInt64(39, coOwningReference, BigInt("0")); + } + static addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferencesOffset) { + builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0); + } + static createVectorOfCoOwningReferencesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfCoOwningReferencesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addNonOwningReference(builder, nonOwningReference) { + builder.addFieldInt64(41, nonOwningReference, BigInt("0")); + } + static addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferencesOffset) { + builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0); + } + static createVectorOfNonOwningReferencesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfNonOwningReferencesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addAnyUniqueType(builder, anyUniqueType) { + builder.addFieldInt8(43, anyUniqueType, AnyUniqueAliases.NONE); + } + static addAnyUnique(builder, anyUniqueOffset) { + builder.addFieldOffset(44, anyUniqueOffset, 0); + } + static addAnyAmbiguousType(builder, anyAmbiguousType) { + builder.addFieldInt8(45, anyAmbiguousType, AnyAmbiguousAliases.NONE); + } + static addAnyAmbiguous(builder, anyAmbiguousOffset) { + builder.addFieldOffset(46, anyAmbiguousOffset, 0); + } + static addVectorOfEnums(builder, vectorOfEnumsOffset) { + builder.addFieldOffset(47, vectorOfEnumsOffset, 0); + } + static createVectorOfEnumsVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startVectorOfEnumsVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addSignedEnum(builder, signedEnum) { + builder.addFieldInt8(48, signedEnum, Race.None); + } + static addTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset) { + builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0); + } + static createTestrequirednestedflatbufferVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startTestrequirednestedflatbufferVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addScalarKeySortedTables(builder, scalarKeySortedTablesOffset) { + builder.addFieldOffset(50, scalarKeySortedTablesOffset, 0); + } + static createScalarKeySortedTablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startScalarKeySortedTablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addNativeInline(builder, nativeInlineOffset) { + builder.addFieldStruct(51, nativeInlineOffset, 0); + } + static addLongEnumNonEnumDefault(builder, longEnumNonEnumDefault) { + builder.addFieldInt64(52, longEnumNonEnumDefault, BigInt("0")); + } + static addLongEnumNormalDefault(builder, longEnumNormalDefault) { + builder.addFieldInt64(53, longEnumNormalDefault, BigInt("2")); + } + static addNanDefault(builder, nanDefault) { + builder.addFieldFloat32(54, nanDefault, NaN); + } + static addInfDefault(builder, infDefault) { + builder.addFieldFloat32(55, infDefault, Infinity); + } + static addPositiveInfDefault(builder, positiveInfDefault) { + builder.addFieldFloat32(56, positiveInfDefault, Infinity); + } + static addInfinityDefault(builder, infinityDefault) { + builder.addFieldFloat32(57, infinityDefault, Infinity); + } + static addPositiveInfinityDefault(builder, positiveInfinityDefault) { + builder.addFieldFloat32(58, positiveInfinityDefault, Infinity); + } + static addNegativeInfDefault(builder, negativeInfDefault) { + builder.addFieldFloat32(59, negativeInfDefault, -Infinity); + } + static addNegativeInfinityDefault(builder, negativeInfinityDefault) { + builder.addFieldFloat32(60, negativeInfinityDefault, -Infinity); + } + static addDoubleInfDefault(builder, doubleInfDefault) { + builder.addFieldFloat64(61, doubleInfDefault, Infinity); + } + static endMonster(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 10); + return offset; + } + static finishMonsterBuffer(builder, offset) { + builder.finish(offset, "MONS"); + } + static finishSizePrefixedMonsterBuffer(builder, offset) { + builder.finish(offset, "MONS", true); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _Monster.getRootAsMonster(new flatbuffers8.ByteBuffer(buffer)); + } + unpack() { + return new MonsterT2(this.pos() !== null ? this.pos().unpack() : null, this.mana(), this.hp(), this.name(), this.bb.createScalarList(this.inventory.bind(this), this.inventoryLength()), this.color(), this.testType(), (() => { + const temp = unionToAny(this.testType(), this.test.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.bb.createObjList(this.test4.bind(this), this.test4Length()), this.bb.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()), this.bb.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()), this.enemy() !== null ? this.enemy().unpack() : null, this.bb.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()), this.testempty() !== null ? this.testempty().unpack() : null, this.testbool(), this.testhashs32Fnv1(), this.testhashu32Fnv1(), this.testhashs64Fnv1(), this.testhashu64Fnv1(), this.testhashs32Fnv1a(), this.testhashu32Fnv1a(), this.testhashs64Fnv1a(), this.testhashu64Fnv1a(), this.bb.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()), this.testf(), this.testf2(), this.testf3(), this.bb.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()), this.bb.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()), this.bb.createScalarList(this.flex.bind(this), this.flexLength()), this.bb.createObjList(this.test5.bind(this), this.test5Length()), this.bb.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()), this.bb.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()), this.parentNamespaceTest() !== null ? this.parentNamespaceTest().unpack() : null, this.bb.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()), this.singleWeakReference(), this.bb.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()), this.bb.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()), this.coOwningReference(), this.bb.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()), this.nonOwningReference(), this.bb.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()), this.anyUniqueType(), (() => { + const temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.anyAmbiguousType(), (() => { + const temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.bb.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()), this.signedEnum(), this.bb.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()), this.bb.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()), this.nativeInline() !== null ? this.nativeInline().unpack() : null, this.longEnumNonEnumDefault(), this.longEnumNormalDefault(), this.nanDefault(), this.infDefault(), this.positiveInfDefault(), this.infinityDefault(), this.positiveInfinityDefault(), this.negativeInfDefault(), this.negativeInfinityDefault(), this.doubleInfDefault()); + } + unpackTo(_o) { + _o.pos = this.pos() !== null ? this.pos().unpack() : null; + _o.mana = this.mana(); + _o.hp = this.hp(); + _o.name = this.name(); + _o.inventory = this.bb.createScalarList(this.inventory.bind(this), this.inventoryLength()); + _o.color = this.color(); + _o.testType = this.testType(); + _o.test = (() => { + const temp = unionToAny(this.testType(), this.test.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.test4 = this.bb.createObjList(this.test4.bind(this), this.test4Length()); + _o.testarrayofstring = this.bb.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()); + _o.testarrayoftables = this.bb.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()); + _o.enemy = this.enemy() !== null ? this.enemy().unpack() : null; + _o.testnestedflatbuffer = this.bb.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()); + _o.testempty = this.testempty() !== null ? this.testempty().unpack() : null; + _o.testbool = this.testbool(); + _o.testhashs32Fnv1 = this.testhashs32Fnv1(); + _o.testhashu32Fnv1 = this.testhashu32Fnv1(); + _o.testhashs64Fnv1 = this.testhashs64Fnv1(); + _o.testhashu64Fnv1 = this.testhashu64Fnv1(); + _o.testhashs32Fnv1a = this.testhashs32Fnv1a(); + _o.testhashu32Fnv1a = this.testhashu32Fnv1a(); + _o.testhashs64Fnv1a = this.testhashs64Fnv1a(); + _o.testhashu64Fnv1a = this.testhashu64Fnv1a(); + _o.testarrayofbools = this.bb.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()); + _o.testf = this.testf(); + _o.testf2 = this.testf2(); + _o.testf3 = this.testf3(); + _o.testarrayofstring2 = this.bb.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()); + _o.testarrayofsortedstruct = this.bb.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()); + _o.flex = this.bb.createScalarList(this.flex.bind(this), this.flexLength()); + _o.test5 = this.bb.createObjList(this.test5.bind(this), this.test5Length()); + _o.vectorOfLongs = this.bb.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()); + _o.vectorOfDoubles = this.bb.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()); + _o.parentNamespaceTest = this.parentNamespaceTest() !== null ? this.parentNamespaceTest().unpack() : null; + _o.vectorOfReferrables = this.bb.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()); + _o.singleWeakReference = this.singleWeakReference(); + _o.vectorOfWeakReferences = this.bb.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()); + _o.vectorOfStrongReferrables = this.bb.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()); + _o.coOwningReference = this.coOwningReference(); + _o.vectorOfCoOwningReferences = this.bb.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()); + _o.nonOwningReference = this.nonOwningReference(); + _o.vectorOfNonOwningReferences = this.bb.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()); + _o.anyUniqueType = this.anyUniqueType(); + _o.anyUnique = (() => { + const temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.anyAmbiguousType = this.anyAmbiguousType(); + _o.anyAmbiguous = (() => { + const temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.vectorOfEnums = this.bb.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()); + _o.signedEnum = this.signedEnum(); + _o.testrequirednestedflatbuffer = this.bb.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()); + _o.scalarKeySortedTables = this.bb.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()); + _o.nativeInline = this.nativeInline() !== null ? this.nativeInline().unpack() : null; + _o.longEnumNonEnumDefault = this.longEnumNonEnumDefault(); + _o.longEnumNormalDefault = this.longEnumNormalDefault(); + _o.nanDefault = this.nanDefault(); + _o.infDefault = this.infDefault(); + _o.positiveInfDefault = this.positiveInfDefault(); + _o.infinityDefault = this.infinityDefault(); + _o.positiveInfinityDefault = this.positiveInfinityDefault(); + _o.negativeInfDefault = this.negativeInfDefault(); + _o.negativeInfinityDefault = this.negativeInfinityDefault(); + _o.doubleInfDefault = this.doubleInfDefault(); + } +}; +var MonsterT2 = class { + constructor(pos = null, mana = 150, hp = 100, name = null, inventory = [], color = Color.Blue, testType = Any.NONE, test = null, test4 = [], testarrayofstring = [], testarrayoftables = [], enemy = null, testnestedflatbuffer = [], testempty = null, testbool = false, testhashs32Fnv1 = 0, testhashu32Fnv1 = 0, testhashs64Fnv1 = BigInt("0"), testhashu64Fnv1 = BigInt("0"), testhashs32Fnv1a = 0, testhashu32Fnv1a = 0, testhashs64Fnv1a = BigInt("0"), testhashu64Fnv1a = BigInt("0"), testarrayofbools = [], testf = 3.14159, testf2 = 3, testf3 = 0, testarrayofstring2 = [], testarrayofsortedstruct = [], flex = [], test5 = [], vectorOfLongs = [], vectorOfDoubles = [], parentNamespaceTest = null, vectorOfReferrables = [], singleWeakReference = BigInt("0"), vectorOfWeakReferences = [], vectorOfStrongReferrables = [], coOwningReference = BigInt("0"), vectorOfCoOwningReferences = [], nonOwningReference = BigInt("0"), vectorOfNonOwningReferences = [], anyUniqueType = AnyUniqueAliases.NONE, anyUnique = null, anyAmbiguousType = AnyAmbiguousAliases.NONE, anyAmbiguous = null, vectorOfEnums = [], signedEnum = Race.None, testrequirednestedflatbuffer = [], scalarKeySortedTables = [], nativeInline = null, longEnumNonEnumDefault = BigInt("0"), longEnumNormalDefault = BigInt("2"), nanDefault = NaN, infDefault = Infinity, positiveInfDefault = Infinity, infinityDefault = Infinity, positiveInfinityDefault = Infinity, negativeInfDefault = -Infinity, negativeInfinityDefault = -Infinity, doubleInfDefault = Infinity) { + this.pos = pos; + this.mana = mana; + this.hp = hp; + this.name = name; + this.inventory = inventory; + this.color = color; + this.testType = testType; + this.test = test; + this.test4 = test4; + this.testarrayofstring = testarrayofstring; + this.testarrayoftables = testarrayoftables; + this.enemy = enemy; + this.testnestedflatbuffer = testnestedflatbuffer; + this.testempty = testempty; + this.testbool = testbool; + this.testhashs32Fnv1 = testhashs32Fnv1; + this.testhashu32Fnv1 = testhashu32Fnv1; + this.testhashs64Fnv1 = testhashs64Fnv1; + this.testhashu64Fnv1 = testhashu64Fnv1; + this.testhashs32Fnv1a = testhashs32Fnv1a; + this.testhashu32Fnv1a = testhashu32Fnv1a; + this.testhashs64Fnv1a = testhashs64Fnv1a; + this.testhashu64Fnv1a = testhashu64Fnv1a; + this.testarrayofbools = testarrayofbools; + this.testf = testf; + this.testf2 = testf2; + this.testf3 = testf3; + this.testarrayofstring2 = testarrayofstring2; + this.testarrayofsortedstruct = testarrayofsortedstruct; + this.flex = flex; + this.test5 = test5; + this.vectorOfLongs = vectorOfLongs; + this.vectorOfDoubles = vectorOfDoubles; + this.parentNamespaceTest = parentNamespaceTest; + this.vectorOfReferrables = vectorOfReferrables; + this.singleWeakReference = singleWeakReference; + this.vectorOfWeakReferences = vectorOfWeakReferences; + this.vectorOfStrongReferrables = vectorOfStrongReferrables; + this.coOwningReference = coOwningReference; + this.vectorOfCoOwningReferences = vectorOfCoOwningReferences; + this.nonOwningReference = nonOwningReference; + this.vectorOfNonOwningReferences = vectorOfNonOwningReferences; + this.anyUniqueType = anyUniqueType; + this.anyUnique = anyUnique; + this.anyAmbiguousType = anyAmbiguousType; + this.anyAmbiguous = anyAmbiguous; + this.vectorOfEnums = vectorOfEnums; + this.signedEnum = signedEnum; + this.testrequirednestedflatbuffer = testrequirednestedflatbuffer; + this.scalarKeySortedTables = scalarKeySortedTables; + this.nativeInline = nativeInline; + this.longEnumNonEnumDefault = longEnumNonEnumDefault; + this.longEnumNormalDefault = longEnumNormalDefault; + this.nanDefault = nanDefault; + this.infDefault = infDefault; + this.positiveInfDefault = positiveInfDefault; + this.infinityDefault = infinityDefault; + this.positiveInfinityDefault = positiveInfinityDefault; + this.negativeInfDefault = negativeInfDefault; + this.negativeInfinityDefault = negativeInfinityDefault; + this.doubleInfDefault = doubleInfDefault; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const inventory = Monster2.createInventoryVector(builder, this.inventory); + const test = builder.createObjectOffset(this.test); + const test4 = builder.createStructOffsetList(this.test4, Monster2.startTest4Vector); + const testarrayofstring = Monster2.createTestarrayofstringVector(builder, builder.createObjectOffsetList(this.testarrayofstring)); + const testarrayoftables = Monster2.createTestarrayoftablesVector(builder, builder.createObjectOffsetList(this.testarrayoftables)); + const enemy = this.enemy !== null ? this.enemy.pack(builder) : 0; + const testnestedflatbuffer = Monster2.createTestnestedflatbufferVector(builder, this.testnestedflatbuffer); + const testempty = this.testempty !== null ? this.testempty.pack(builder) : 0; + const testarrayofbools = Monster2.createTestarrayofboolsVector(builder, this.testarrayofbools); + const testarrayofstring2 = Monster2.createTestarrayofstring2Vector(builder, builder.createObjectOffsetList(this.testarrayofstring2)); + const testarrayofsortedstruct = builder.createStructOffsetList(this.testarrayofsortedstruct, Monster2.startTestarrayofsortedstructVector); + const flex = Monster2.createFlexVector(builder, this.flex); + const test5 = builder.createStructOffsetList(this.test5, Monster2.startTest5Vector); + const vectorOfLongs = Monster2.createVectorOfLongsVector(builder, this.vectorOfLongs); + const vectorOfDoubles = Monster2.createVectorOfDoublesVector(builder, this.vectorOfDoubles); + const parentNamespaceTest = this.parentNamespaceTest !== null ? this.parentNamespaceTest.pack(builder) : 0; + const vectorOfReferrables = Monster2.createVectorOfReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfReferrables)); + const vectorOfWeakReferences = Monster2.createVectorOfWeakReferencesVector(builder, this.vectorOfWeakReferences); + const vectorOfStrongReferrables = Monster2.createVectorOfStrongReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfStrongReferrables)); + const vectorOfCoOwningReferences = Monster2.createVectorOfCoOwningReferencesVector(builder, this.vectorOfCoOwningReferences); + const vectorOfNonOwningReferences = Monster2.createVectorOfNonOwningReferencesVector(builder, this.vectorOfNonOwningReferences); + const anyUnique = builder.createObjectOffset(this.anyUnique); + const anyAmbiguous = builder.createObjectOffset(this.anyAmbiguous); + const vectorOfEnums = Monster2.createVectorOfEnumsVector(builder, this.vectorOfEnums); + const testrequirednestedflatbuffer = Monster2.createTestrequirednestedflatbufferVector(builder, this.testrequirednestedflatbuffer); + const scalarKeySortedTables = Monster2.createScalarKeySortedTablesVector(builder, builder.createObjectOffsetList(this.scalarKeySortedTables)); + Monster2.startMonster(builder); + Monster2.addPos(builder, this.pos !== null ? this.pos.pack(builder) : 0); + Monster2.addMana(builder, this.mana); + Monster2.addHp(builder, this.hp); + Monster2.addName(builder, name); + Monster2.addInventory(builder, inventory); + Monster2.addColor(builder, this.color); + Monster2.addTestType(builder, this.testType); + Monster2.addTest(builder, test); + Monster2.addTest4(builder, test4); + Monster2.addTestarrayofstring(builder, testarrayofstring); + Monster2.addTestarrayoftables(builder, testarrayoftables); + Monster2.addEnemy(builder, enemy); + Monster2.addTestnestedflatbuffer(builder, testnestedflatbuffer); + Monster2.addTestempty(builder, testempty); + Monster2.addTestbool(builder, this.testbool); + Monster2.addTesthashs32Fnv1(builder, this.testhashs32Fnv1); + Monster2.addTesthashu32Fnv1(builder, this.testhashu32Fnv1); + Monster2.addTesthashs64Fnv1(builder, this.testhashs64Fnv1); + Monster2.addTesthashu64Fnv1(builder, this.testhashu64Fnv1); + Monster2.addTesthashs32Fnv1a(builder, this.testhashs32Fnv1a); + Monster2.addTesthashu32Fnv1a(builder, this.testhashu32Fnv1a); + Monster2.addTesthashs64Fnv1a(builder, this.testhashs64Fnv1a); + Monster2.addTesthashu64Fnv1a(builder, this.testhashu64Fnv1a); + Monster2.addTestarrayofbools(builder, testarrayofbools); + Monster2.addTestf(builder, this.testf); + Monster2.addTestf2(builder, this.testf2); + Monster2.addTestf3(builder, this.testf3); + Monster2.addTestarrayofstring2(builder, testarrayofstring2); + Monster2.addTestarrayofsortedstruct(builder, testarrayofsortedstruct); + Monster2.addFlex(builder, flex); + Monster2.addTest5(builder, test5); + Monster2.addVectorOfLongs(builder, vectorOfLongs); + Monster2.addVectorOfDoubles(builder, vectorOfDoubles); + Monster2.addParentNamespaceTest(builder, parentNamespaceTest); + Monster2.addVectorOfReferrables(builder, vectorOfReferrables); + Monster2.addSingleWeakReference(builder, this.singleWeakReference); + Monster2.addVectorOfWeakReferences(builder, vectorOfWeakReferences); + Monster2.addVectorOfStrongReferrables(builder, vectorOfStrongReferrables); + Monster2.addCoOwningReference(builder, this.coOwningReference); + Monster2.addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences); + Monster2.addNonOwningReference(builder, this.nonOwningReference); + Monster2.addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences); + Monster2.addAnyUniqueType(builder, this.anyUniqueType); + Monster2.addAnyUnique(builder, anyUnique); + Monster2.addAnyAmbiguousType(builder, this.anyAmbiguousType); + Monster2.addAnyAmbiguous(builder, anyAmbiguous); + Monster2.addVectorOfEnums(builder, vectorOfEnums); + Monster2.addSignedEnum(builder, this.signedEnum); + Monster2.addTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer); + Monster2.addScalarKeySortedTables(builder, scalarKeySortedTables); + Monster2.addNativeInline(builder, this.nativeInline !== null ? this.nativeInline.pack(builder) : 0); + Monster2.addLongEnumNonEnumDefault(builder, this.longEnumNonEnumDefault); + Monster2.addLongEnumNormalDefault(builder, this.longEnumNormalDefault); + Monster2.addNanDefault(builder, this.nanDefault); + Monster2.addInfDefault(builder, this.infDefault); + Monster2.addPositiveInfDefault(builder, this.positiveInfDefault); + Monster2.addInfinityDefault(builder, this.infinityDefault); + Monster2.addPositiveInfinityDefault(builder, this.positiveInfinityDefault); + Monster2.addNegativeInfDefault(builder, this.negativeInfDefault); + Monster2.addNegativeInfinityDefault(builder, this.negativeInfinityDefault); + Monster2.addDoubleInfDefault(builder, this.doubleInfDefault); + return Monster2.endMonster(builder); + } +}; + +// my-game/example/any.js +var Any; +(function(Any2) { + Any2[Any2["NONE"] = 0] = "NONE"; + Any2[Any2["Monster"] = 1] = "Monster"; + Any2[Any2["TestSimpleTableWithEnum"] = 2] = "TestSimpleTableWithEnum"; + Any2[Any2["MyGame_Example2_Monster"] = 3] = "MyGame_Example2_Monster"; +})(Any || (Any = {})); +function unionToAny(type, accessor) { + switch (Any[type]) { + case "NONE": + return null; + case "Monster": + return accessor(new Monster2()); + case "TestSimpleTableWithEnum": + return accessor(new TestSimpleTableWithEnum()); + case "MyGame_Example2_Monster": + return accessor(new Monster()); + default: + return null; + } +} + +// my-game/example/long-enum.js +var LongEnum; +(function(LongEnum2) { + LongEnum2["LongOne"] = "2"; + LongEnum2["LongTwo"] = "4"; + LongEnum2["LongBig"] = "1099511627776"; +})(LongEnum || (LongEnum = {})); + +// my-game/example/struct-of-structs.js +var StructOfStructs = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a(obj) { + return (obj || new Ability()).__init(this.bb_pos, this.bb); + } + b(obj) { + return (obj || new Test()).__init(this.bb_pos + 8, this.bb); + } + c(obj) { + return (obj || new Ability()).__init(this.bb_pos + 12, this.bb); + } + static getFullyQualifiedName() { + return "MyGame.Example.StructOfStructs"; + } + static sizeOf() { + return 20; + } + static createStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance) { + builder.prep(4, 20); + builder.prep(4, 8); + builder.writeInt32(c_distance); + builder.writeInt32(c_id); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(b_b); + builder.writeInt16(b_a); + builder.prep(4, 8); + builder.writeInt32(a_distance); + builder.writeInt32(a_id); + return builder.offset(); + } + unpack() { + return new StructOfStructsT(this.a() !== null ? this.a().unpack() : null, this.b() !== null ? this.b().unpack() : null, this.c() !== null ? this.c().unpack() : null); + } + unpackTo(_o) { + _o.a = this.a() !== null ? this.a().unpack() : null; + _o.b = this.b() !== null ? this.b().unpack() : null; + _o.c = this.c() !== null ? this.c().unpack() : null; + } +}; +var StructOfStructsT = class { + constructor(a = null, b = null, c = null) { + this.a = a; + this.b = b; + this.c = c; + } + pack(builder) { + return StructOfStructs.createStructOfStructs(builder, this.a?.id ?? 0, this.a?.distance ?? 0, this.b?.a ?? 0, this.b?.b ?? 0, this.c?.id ?? 0, this.c?.distance ?? 0); + } +}; + +// my-game/example/struct-of-structs-of-structs.js +var StructOfStructsOfStructs = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a(obj) { + return (obj || new StructOfStructs()).__init(this.bb_pos, this.bb); + } + static getFullyQualifiedName() { + return "MyGame.Example.StructOfStructsOfStructs"; + } + static sizeOf() { + return 20; + } + static createStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, a_c_id, a_c_distance) { + builder.prep(4, 20); + builder.prep(4, 20); + builder.prep(4, 8); + builder.writeInt32(a_c_distance); + builder.writeInt32(a_c_id); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(a_b_b); + builder.writeInt16(a_b_a); + builder.prep(4, 8); + builder.writeInt32(a_a_distance); + builder.writeInt32(a_a_id); + return builder.offset(); + } + unpack() { + return new StructOfStructsOfStructsT(this.a() !== null ? this.a().unpack() : null); + } + unpackTo(_o) { + _o.a = this.a() !== null ? this.a().unpack() : null; + } +}; +var StructOfStructsOfStructsT = class { + constructor(a = null) { + this.a = a; + } + pack(builder) { + return StructOfStructsOfStructs.createStructOfStructsOfStructs(builder, this.a?.a?.id ?? 0, this.a?.a?.distance ?? 0, this.a?.b?.a ?? 0, this.a?.b?.b ?? 0, this.a?.c?.id ?? 0, this.a?.c?.distance ?? 0); + } +}; + +// my-game/example/type-aliases.js +var flatbuffers9 = __toESM(require("flatbuffers"), 1); +var TypeAliases = class _TypeAliases { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTypeAliases(bb, obj) { + return (obj || new _TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTypeAliases(bb, obj) { + bb.setPosition(bb.position() + flatbuffers9.SIZE_PREFIX_LENGTH); + return (obj || new _TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + i8() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : 0; + } + mutate_i8(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + u8() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readUint8(this.bb_pos + offset) : 0; + } + mutate_u8(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeUint8(this.bb_pos + offset, value); + return true; + } + i16() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 0; + } + mutate_i16(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt16(this.bb_pos + offset, value); + return true; + } + u16() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_u16(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + i32() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_i32(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + u32() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_u32(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + i64() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_i64(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + u64() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_u64(value) { + const offset = this.bb.__offset(this.bb_pos, 18); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + f32() { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0; + } + mutate_f32(value) { + const offset = this.bb.__offset(this.bb_pos, 20); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + f64() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0; + } + mutate_f64(value) { + const offset = this.bb.__offset(this.bb_pos, 22); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + v8(index) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + v8Length() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + v8Array() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + vf64(index) { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; + } + vf64Length() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vf64Array() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + static getFullyQualifiedName() { + return "MyGame.Example.TypeAliases"; + } + static startTypeAliases(builder) { + builder.startObject(12); + } + static addI8(builder, i8) { + builder.addFieldInt8(0, i8, 0); + } + static addU8(builder, u8) { + builder.addFieldInt8(1, u8, 0); + } + static addI16(builder, i16) { + builder.addFieldInt16(2, i16, 0); + } + static addU16(builder, u16) { + builder.addFieldInt16(3, u16, 0); + } + static addI32(builder, i32) { + builder.addFieldInt32(4, i32, 0); + } + static addU32(builder, u32) { + builder.addFieldInt32(5, u32, 0); + } + static addI64(builder, i64) { + builder.addFieldInt64(6, i64, BigInt("0")); + } + static addU64(builder, u64) { + builder.addFieldInt64(7, u64, BigInt("0")); + } + static addF32(builder, f32) { + builder.addFieldFloat32(8, f32, 0); + } + static addF64(builder, f64) { + builder.addFieldFloat64(9, f64, 0); + } + static addV8(builder, v8Offset) { + builder.addFieldOffset(10, v8Offset, 0); + } + static createV8Vector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startV8Vector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addVf64(builder, vf64Offset) { + builder.addFieldOffset(11, vf64Offset, 0); + } + static createVf64Vector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addFloat64(data[i]); + } + return builder.endVector(); + } + static startVf64Vector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static endTypeAliases(builder) { + const offset = builder.endObject(); + return offset; + } + static createTypeAliases(builder, i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, v8Offset, vf64Offset) { + _TypeAliases.startTypeAliases(builder); + _TypeAliases.addI8(builder, i8); + _TypeAliases.addU8(builder, u8); + _TypeAliases.addI16(builder, i16); + _TypeAliases.addU16(builder, u16); + _TypeAliases.addI32(builder, i32); + _TypeAliases.addU32(builder, u32); + _TypeAliases.addI64(builder, i64); + _TypeAliases.addU64(builder, u64); + _TypeAliases.addF32(builder, f32); + _TypeAliases.addF64(builder, f64); + _TypeAliases.addV8(builder, v8Offset); + _TypeAliases.addVf64(builder, vf64Offset); + return _TypeAliases.endTypeAliases(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return _TypeAliases.getRootAsTypeAliases(new flatbuffers9.ByteBuffer(buffer)); + } + unpack() { + return new TypeAliasesT(this.i8(), this.u8(), this.i16(), this.u16(), this.i32(), this.u32(), this.i64(), this.u64(), this.f32(), this.f64(), this.bb.createScalarList(this.v8.bind(this), this.v8Length()), this.bb.createScalarList(this.vf64.bind(this), this.vf64Length())); + } + unpackTo(_o) { + _o.i8 = this.i8(); + _o.u8 = this.u8(); + _o.i16 = this.i16(); + _o.u16 = this.u16(); + _o.i32 = this.i32(); + _o.u32 = this.u32(); + _o.i64 = this.i64(); + _o.u64 = this.u64(); + _o.f32 = this.f32(); + _o.f64 = this.f64(); + _o.v8 = this.bb.createScalarList(this.v8.bind(this), this.v8Length()); + _o.vf64 = this.bb.createScalarList(this.vf64.bind(this), this.vf64Length()); + } +}; +var TypeAliasesT = class { + constructor(i8 = 0, u8 = 0, i16 = 0, u16 = 0, i32 = 0, u32 = 0, i64 = BigInt("0"), u64 = BigInt("0"), f32 = 0, f64 = 0, v8 = [], vf64 = []) { + this.i8 = i8; + this.u8 = u8; + this.i16 = i16; + this.u16 = u16; + this.i32 = i32; + this.u32 = u32; + this.i64 = i64; + this.u64 = u64; + this.f32 = f32; + this.f64 = f64; + this.v8 = v8; + this.vf64 = vf64; + } + pack(builder) { + const v8 = TypeAliases.createV8Vector(builder, this.v8); + const vf64 = TypeAliases.createVf64Vector(builder, this.vf64); + return TypeAliases.createTypeAliases(builder, this.i8, this.u8, this.i16, this.u16, this.i32, this.u32, this.i64, this.u64, this.f32, this.f64, v8, vf64); + } +}; + +// my-game/example2.js +var example2_exports = {}; +__export(example2_exports, { + Monster: () => Monster, + MonsterT: () => MonsterT +}); + +// my-game/other-name-space.js +var other_name_space_exports = {}; +__export(other_name_space_exports, { + FromInclude: () => FromInclude, + TableB: () => TableB, + TableBT: () => TableBT, + Unused: () => Unused, + UnusedT: () => UnusedT +}); + +// my-game/other-name-space/from-include.js +var FromInclude; +(function(FromInclude2) { + FromInclude2["IncludeVal"] = "0"; +})(FromInclude || (FromInclude = {})); + +// my-game/other-name-space/unused.js +var Unused = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return this.bb.readInt32(this.bb_pos); + } + mutate_a(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return "MyGame.OtherNameSpace.Unused"; + } + static sizeOf() { + return 4; + } + static createUnused(builder, a) { + builder.prep(4, 4); + builder.writeInt32(a); + return builder.offset(); + } + unpack() { + return new UnusedT(this.a()); + } + unpackTo(_o) { + _o.a = this.a(); + } +}; +var UnusedT = class { + constructor(a = 0) { + this.a = a; + } + pack(builder) { + return Unused.createUnused(builder, this.a); + } +}; diff --git a/third_party/flatbuffers/tests/ts/monsterdata_javascript_wire.mon b/third_party/flatbuffers/tests/ts/monsterdata_javascript_wire.mon new file mode 100644 index 00000000000..7b0dc5b6419 Binary files /dev/null and b/third_party/flatbuffers/tests/ts/monsterdata_javascript_wire.mon differ diff --git a/third_party/flatbuffers/tests/ts/my-game.d.ts b/third_party/flatbuffers/tests/ts/my-game.d.ts new file mode 100644 index 00000000000..e82f8a3136e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game.d.ts @@ -0,0 +1,4 @@ +export { InParentNamespace, InParentNamespaceT } from './my-game/in-parent-namespace.js'; +export * as Example from './my-game/example.js'; +export * as Example2 from './my-game/example2.js'; +export * as OtherNameSpace from './my-game/other-name-space.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game.js b/third_party/flatbuffers/tests/ts/my-game.js new file mode 100644 index 00000000000..59aabe994e3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game.js @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { InParentNamespace, InParentNamespaceT } from './my-game/in-parent-namespace.js'; +export * as Example from './my-game/example.js'; +export * as Example2 from './my-game/example2.js'; +export * as OtherNameSpace from './my-game/other-name-space.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game.ts b/third_party/flatbuffers/tests/ts/my-game.ts new file mode 100644 index 00000000000..1ea9de7fc6e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game.ts @@ -0,0 +1,8 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { InParentNamespace, InParentNamespaceT } from './my-game/in-parent-namespace.js'; +export * as Example from './my-game/example.js'; +export * as Example2 from './my-game/example2.js'; +export * as OtherNameSpace from './my-game/other-name-space.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example.d.ts b/third_party/flatbuffers/tests/ts/my-game/example.d.ts new file mode 100644 index 00000000000..a09b7f849a6 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example.d.ts @@ -0,0 +1,16 @@ +export { Ability, AbilityT } from './example/ability.js'; +export { Any } from './example/any.js'; +export { AnyAmbiguousAliases } from './example/any-ambiguous-aliases.js'; +export { AnyUniqueAliases } from './example/any-unique-aliases.js'; +export { Color } from './example/color.js'; +export { LongEnum } from './example/long-enum.js'; +export { Monster, MonsterT } from './example/monster.js'; +export { Race } from './example/race.js'; +export { Referrable, ReferrableT } from './example/referrable.js'; +export { Stat, StatT } from './example/stat.js'; +export { StructOfStructs, StructOfStructsT } from './example/struct-of-structs.js'; +export { StructOfStructsOfStructs, StructOfStructsOfStructsT } from './example/struct-of-structs-of-structs.js'; +export { Test, TestT } from './example/test.js'; +export { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './example/test-simple-table-with-enum.js'; +export { TypeAliases, TypeAliasesT } from './example/type-aliases.js'; +export { Vec3, Vec3T } from './example/vec3.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example.js b/third_party/flatbuffers/tests/ts/my-game/example.js new file mode 100644 index 00000000000..d63f78c7771 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example.js @@ -0,0 +1,18 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { Ability, AbilityT } from './example/ability.js'; +export { Any } from './example/any.js'; +export { AnyAmbiguousAliases } from './example/any-ambiguous-aliases.js'; +export { AnyUniqueAliases } from './example/any-unique-aliases.js'; +export { Color } from './example/color.js'; +export { LongEnum } from './example/long-enum.js'; +export { Monster, MonsterT } from './example/monster.js'; +export { Race } from './example/race.js'; +export { Referrable, ReferrableT } from './example/referrable.js'; +export { Stat, StatT } from './example/stat.js'; +export { StructOfStructs, StructOfStructsT } from './example/struct-of-structs.js'; +export { StructOfStructsOfStructs, StructOfStructsOfStructsT } from './example/struct-of-structs-of-structs.js'; +export { Test, TestT } from './example/test.js'; +export { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './example/test-simple-table-with-enum.js'; +export { TypeAliases, TypeAliasesT } from './example/type-aliases.js'; +export { Vec3, Vec3T } from './example/vec3.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example.ts b/third_party/flatbuffers/tests/ts/my-game/example.ts new file mode 100644 index 00000000000..c12c2795172 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example.ts @@ -0,0 +1,20 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Ability, AbilityT } from './example/ability.js'; +export { Any } from './example/any.js'; +export { AnyAmbiguousAliases } from './example/any-ambiguous-aliases.js'; +export { AnyUniqueAliases } from './example/any-unique-aliases.js'; +export { Color } from './example/color.js'; +export { LongEnum } from './example/long-enum.js'; +export { Monster, MonsterT } from './example/monster.js'; +export { Race } from './example/race.js'; +export { Referrable, ReferrableT } from './example/referrable.js'; +export { Stat, StatT } from './example/stat.js'; +export { StructOfStructs, StructOfStructsT } from './example/struct-of-structs.js'; +export { StructOfStructsOfStructs, StructOfStructsOfStructsT } from './example/struct-of-structs-of-structs.js'; +export { Test, TestT } from './example/test.js'; +export { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from './example/test-simple-table-with-enum.js'; +export { TypeAliases, TypeAliasesT } from './example/type-aliases.js'; +export { Vec3, Vec3T } from './example/vec3.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example/ability.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/ability.d.ts new file mode 100644 index 00000000000..bbd00f0a1f5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/ability.d.ts @@ -0,0 +1,21 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Ability implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Ability; + id(): number; + mutate_id(value: number): boolean; + distance(): number; + mutate_distance(value: number): boolean; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createAbility(builder: flatbuffers.Builder, id: number, distance: number): flatbuffers.Offset; + unpack(): AbilityT; + unpackTo(_o: AbilityT): void; +} +export declare class AbilityT implements flatbuffers.IGeneratedObject { + id: number; + distance: number; + constructor(id?: number, distance?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/ability.js b/third_party/flatbuffers/tests/ts/my-game/example/ability.js new file mode 100644 index 00000000000..9fea3d6b4e5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/ability.js @@ -0,0 +1,54 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class Ability { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + id() { + return this.bb.readUint32(this.bb_pos); + } + mutate_id(value) { + this.bb.writeUint32(this.bb_pos + 0, value); + return true; + } + distance() { + return this.bb.readUint32(this.bb_pos + 4); + } + mutate_distance(value) { + this.bb.writeUint32(this.bb_pos + 4, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.Example.Ability'; + } + static sizeOf() { + return 8; + } + static createAbility(builder, id, distance) { + builder.prep(4, 8); + builder.writeInt32(distance); + builder.writeInt32(id); + return builder.offset(); + } + unpack() { + return new AbilityT(this.id(), this.distance()); + } + unpackTo(_o) { + _o.id = this.id(); + _o.distance = this.distance(); + } +} +export class AbilityT { + constructor(id = 0, distance = 0) { + this.id = id; + this.distance = distance; + } + pack(builder) { + return Ability.createAbility(builder, this.id, this.distance); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/ability.ts b/third_party/flatbuffers/tests/ts/my-game/example/ability.ts new file mode 100644 index 00000000000..e2dadc97795 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/ability.ts @@ -0,0 +1,79 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Ability implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Ability { + this.bb_pos = i; + this.bb = bb; + return this; +} + +id():number { + return this.bb!.readUint32(this.bb_pos); +} + +mutate_id(value:number):boolean { + this.bb!.writeUint32(this.bb_pos + 0, value); + return true; +} + +distance():number { + return this.bb!.readUint32(this.bb_pos + 4); +} + +mutate_distance(value:number):boolean { + this.bb!.writeUint32(this.bb_pos + 4, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.Ability'; +} + +static sizeOf():number { + return 8; +} + +static createAbility(builder:flatbuffers.Builder, id: number, distance: number):flatbuffers.Offset { + builder.prep(4, 8); + builder.writeInt32(distance); + builder.writeInt32(id); + return builder.offset(); +} + + +unpack(): AbilityT { + return new AbilityT( + this.id(), + this.distance() + ); +} + + +unpackTo(_o: AbilityT): void { + _o.id = this.id(); + _o.distance = this.distance(); +} +} + +export class AbilityT implements flatbuffers.IGeneratedObject { +constructor( + public id: number = 0, + public distance: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Ability.createAbility(builder, + this.id, + this.distance + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.d.ts new file mode 100644 index 00000000000..d625b0abb2f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.d.ts @@ -0,0 +1,9 @@ +import { Monster } from '../../my-game/example/monster.js'; +export declare enum AnyAmbiguousAliases { + NONE = 0, + M1 = 1, + M2 = 2, + M3 = 3 +} +export declare function unionToAnyAmbiguousAliases(type: AnyAmbiguousAliases, accessor: (obj: Monster) => Monster | null): Monster | null; +export declare function unionListToAnyAmbiguousAliases(type: AnyAmbiguousAliases, accessor: (index: number, obj: Monster) => Monster | null, index: number): Monster | null; diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.js b/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.js new file mode 100644 index 00000000000..11b6aac4616 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.js @@ -0,0 +1,28 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import { Monster } from '../../my-game/example/monster.js'; +export var AnyAmbiguousAliases; +(function (AnyAmbiguousAliases) { + AnyAmbiguousAliases[AnyAmbiguousAliases["NONE"] = 0] = "NONE"; + AnyAmbiguousAliases[AnyAmbiguousAliases["M1"] = 1] = "M1"; + AnyAmbiguousAliases[AnyAmbiguousAliases["M2"] = 2] = "M2"; + AnyAmbiguousAliases[AnyAmbiguousAliases["M3"] = 3] = "M3"; +})(AnyAmbiguousAliases || (AnyAmbiguousAliases = {})); +export function unionToAnyAmbiguousAliases(type, accessor) { + switch (AnyAmbiguousAliases[type]) { + case 'NONE': return null; + case 'M1': return accessor(new Monster()); + case 'M2': return accessor(new Monster()); + case 'M3': return accessor(new Monster()); + default: return null; + } +} +export function unionListToAnyAmbiguousAliases(type, accessor, index) { + switch (AnyAmbiguousAliases[type]) { + case 'NONE': return null; + case 'M1': return accessor(index, new Monster()); + case 'M2': return accessor(index, new Monster()); + case 'M3': return accessor(index, new Monster()); + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.ts b/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.ts new file mode 100644 index 00000000000..8e7a3a3b653 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any-ambiguous-aliases.ts @@ -0,0 +1,40 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import { Monster, MonsterT } from '../../my-game/example/monster.js'; + + +export enum AnyAmbiguousAliases { + NONE = 0, + M1 = 1, + M2 = 2, + M3 = 3 +} + +export function unionToAnyAmbiguousAliases( + type: AnyAmbiguousAliases, + accessor: (obj:Monster) => Monster|null +): Monster|null { + switch(AnyAmbiguousAliases[type]) { + case 'NONE': return null; + case 'M1': return accessor(new Monster())! as Monster; + case 'M2': return accessor(new Monster())! as Monster; + case 'M3': return accessor(new Monster())! as Monster; + default: return null; + } +} + +export function unionListToAnyAmbiguousAliases( + type: AnyAmbiguousAliases, + accessor: (index: number, obj:Monster) => Monster|null, + index: number +): Monster|null { + switch(AnyAmbiguousAliases[type]) { + case 'NONE': return null; + case 'M1': return accessor(index, new Monster())! as Monster; + case 'M2': return accessor(index, new Monster())! as Monster; + case 'M3': return accessor(index, new Monster())! as Monster; + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.d.ts new file mode 100644 index 00000000000..14463bc5e11 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.d.ts @@ -0,0 +1,11 @@ +import { Monster as MyGame_Example2_Monster } from '../../my-game/example2/monster.js'; +import { Monster } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum } from '../../my-game/example/test-simple-table-with-enum.js'; +export declare enum AnyUniqueAliases { + NONE = 0, + M = 1, + TS = 2, + M2 = 3 +} +export declare function unionToAnyUniqueAliases(type: AnyUniqueAliases, accessor: (obj: Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum) => Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null): Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null; +export declare function unionListToAnyUniqueAliases(type: AnyUniqueAliases, accessor: (index: number, obj: Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum) => Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null, index: number): Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null; diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.js b/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.js new file mode 100644 index 00000000000..b254029355b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.js @@ -0,0 +1,30 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import { Monster as MyGame_Example2_Monster } from '../../my-game/example2/monster.js'; +import { Monster } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum } from '../../my-game/example/test-simple-table-with-enum.js'; +export var AnyUniqueAliases; +(function (AnyUniqueAliases) { + AnyUniqueAliases[AnyUniqueAliases["NONE"] = 0] = "NONE"; + AnyUniqueAliases[AnyUniqueAliases["M"] = 1] = "M"; + AnyUniqueAliases[AnyUniqueAliases["TS"] = 2] = "TS"; + AnyUniqueAliases[AnyUniqueAliases["M2"] = 3] = "M2"; +})(AnyUniqueAliases || (AnyUniqueAliases = {})); +export function unionToAnyUniqueAliases(type, accessor) { + switch (AnyUniqueAliases[type]) { + case 'NONE': return null; + case 'M': return accessor(new Monster()); + case 'TS': return accessor(new TestSimpleTableWithEnum()); + case 'M2': return accessor(new MyGame_Example2_Monster()); + default: return null; + } +} +export function unionListToAnyUniqueAliases(type, accessor, index) { + switch (AnyUniqueAliases[type]) { + case 'NONE': return null; + case 'M': return accessor(index, new Monster()); + case 'TS': return accessor(index, new TestSimpleTableWithEnum()); + case 'M2': return accessor(index, new MyGame_Example2_Monster()); + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.ts b/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.ts new file mode 100644 index 00000000000..ae85ea00b92 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any-unique-aliases.ts @@ -0,0 +1,42 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Monster, MonsterT } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; + + +export enum AnyUniqueAliases { + NONE = 0, + M = 1, + TS = 2, + M2 = 3 +} + +export function unionToAnyUniqueAliases( + type: AnyUniqueAliases, + accessor: (obj:Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum) => Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null +): Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null { + switch(AnyUniqueAliases[type]) { + case 'NONE': return null; + case 'M': return accessor(new Monster())! as Monster; + case 'TS': return accessor(new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum; + case 'M2': return accessor(new MyGame_Example2_Monster())! as MyGame_Example2_Monster; + default: return null; + } +} + +export function unionListToAnyUniqueAliases( + type: AnyUniqueAliases, + accessor: (index: number, obj:Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum) => Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null, + index: number +): Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null { + switch(AnyUniqueAliases[type]) { + case 'NONE': return null; + case 'M': return accessor(index, new Monster())! as Monster; + case 'TS': return accessor(index, new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum; + case 'M2': return accessor(index, new MyGame_Example2_Monster())! as MyGame_Example2_Monster; + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/any.d.ts new file mode 100644 index 00000000000..6d3e84c9cba --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any.d.ts @@ -0,0 +1,11 @@ +import { Monster as MyGame_Example2_Monster } from '../../my-game/example2/monster.js'; +import { Monster } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum } from '../../my-game/example/test-simple-table-with-enum.js'; +export declare enum Any { + NONE = 0, + Monster = 1, + TestSimpleTableWithEnum = 2, + MyGame_Example2_Monster = 3 +} +export declare function unionToAny(type: Any, accessor: (obj: Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum) => Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null): Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null; +export declare function unionListToAny(type: Any, accessor: (index: number, obj: Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum) => Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null, index: number): Monster | MyGame_Example2_Monster | TestSimpleTableWithEnum | null; diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any.js b/third_party/flatbuffers/tests/ts/my-game/example/any.js new file mode 100644 index 00000000000..ef2c3e8ae9b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any.js @@ -0,0 +1,30 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import { Monster as MyGame_Example2_Monster } from '../../my-game/example2/monster.js'; +import { Monster } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum } from '../../my-game/example/test-simple-table-with-enum.js'; +export var Any; +(function (Any) { + Any[Any["NONE"] = 0] = "NONE"; + Any[Any["Monster"] = 1] = "Monster"; + Any[Any["TestSimpleTableWithEnum"] = 2] = "TestSimpleTableWithEnum"; + Any[Any["MyGame_Example2_Monster"] = 3] = "MyGame_Example2_Monster"; +})(Any || (Any = {})); +export function unionToAny(type, accessor) { + switch (Any[type]) { + case 'NONE': return null; + case 'Monster': return accessor(new Monster()); + case 'TestSimpleTableWithEnum': return accessor(new TestSimpleTableWithEnum()); + case 'MyGame_Example2_Monster': return accessor(new MyGame_Example2_Monster()); + default: return null; + } +} +export function unionListToAny(type, accessor, index) { + switch (Any[type]) { + case 'NONE': return null; + case 'Monster': return accessor(index, new Monster()); + case 'TestSimpleTableWithEnum': return accessor(index, new TestSimpleTableWithEnum()); + case 'MyGame_Example2_Monster': return accessor(index, new MyGame_Example2_Monster()); + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/any.ts b/third_party/flatbuffers/tests/ts/my-game/example/any.ts new file mode 100644 index 00000000000..5e484fa0afa --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/any.ts @@ -0,0 +1,42 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Monster, MonsterT } from '../../my-game/example/monster.js'; +import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; + + +export enum Any { + NONE = 0, + Monster = 1, + TestSimpleTableWithEnum = 2, + MyGame_Example2_Monster = 3 +} + +export function unionToAny( + type: Any, + accessor: (obj:Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum) => Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null +): Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null { + switch(Any[type]) { + case 'NONE': return null; + case 'Monster': return accessor(new Monster())! as Monster; + case 'TestSimpleTableWithEnum': return accessor(new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum; + case 'MyGame_Example2_Monster': return accessor(new MyGame_Example2_Monster())! as MyGame_Example2_Monster; + default: return null; + } +} + +export function unionListToAny( + type: Any, + accessor: (index: number, obj:Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum) => Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null, + index: number +): Monster|MyGame_Example2_Monster|TestSimpleTableWithEnum|null { + switch(Any[type]) { + case 'NONE': return null; + case 'Monster': return accessor(index, new Monster())! as Monster; + case 'TestSimpleTableWithEnum': return accessor(index, new TestSimpleTableWithEnum())! as TestSimpleTableWithEnum; + case 'MyGame_Example2_Monster': return accessor(index, new MyGame_Example2_Monster())! as MyGame_Example2_Monster; + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/color.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/color.d.ts new file mode 100644 index 00000000000..79906f4b1e7 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/color.d.ts @@ -0,0 +1,15 @@ +/** + * Composite components of Monster color. + */ +export declare enum Color { + Red = 1, + /** + * \brief color Green + * Green is bit_flag with value (1u << 1) + */ + Green = 2, + /** + * \brief color Blue (1u << 3) + */ + Blue = 8 +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/color.js b/third_party/flatbuffers/tests/ts/my-game/example/color.js new file mode 100644 index 00000000000..5f2f1fd53b4 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/color.js @@ -0,0 +1,18 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +/** + * Composite components of Monster color. + */ +export var Color; +(function (Color) { + Color[Color["Red"] = 1] = "Red"; + /** + * \brief color Green + * Green is bit_flag with value (1u << 1) + */ + Color[Color["Green"] = 2] = "Green"; + /** + * \brief color Blue (1u << 3) + */ + Color[Color["Blue"] = 8] = "Blue"; +})(Color || (Color = {})); diff --git a/third_party/flatbuffers/tests/ts/my-game/example/color.ts b/third_party/flatbuffers/tests/ts/my-game/example/color.ts new file mode 100644 index 00000000000..a494515d59a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/color.ts @@ -0,0 +1,21 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +/** + * Composite components of Monster color. + */ +export enum Color { + Red = 1, + + /** + * \brief color Green + * Green is bit_flag with value (1u << 1) + */ + Green = 2, + + /** + * \brief color Blue (1u << 3) + */ + Blue = 8 +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/long-enum.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/long-enum.d.ts new file mode 100644 index 00000000000..72e656f14ae --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/long-enum.d.ts @@ -0,0 +1,5 @@ +export declare enum LongEnum { + LongOne = "2", + LongTwo = "4", + LongBig = "1099511627776" +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/long-enum.js b/third_party/flatbuffers/tests/ts/my-game/example/long-enum.js new file mode 100644 index 00000000000..10030720482 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/long-enum.js @@ -0,0 +1,8 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var LongEnum; +(function (LongEnum) { + LongEnum["LongOne"] = "2"; + LongEnum["LongTwo"] = "4"; + LongEnum["LongBig"] = "1099511627776"; +})(LongEnum || (LongEnum = {})); diff --git a/third_party/flatbuffers/tests/ts/my-game/example/long-enum.ts b/third_party/flatbuffers/tests/ts/my-game/example/long-enum.ts new file mode 100644 index 00000000000..07b1369e31e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/long-enum.ts @@ -0,0 +1,9 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum LongEnum { + LongOne = '2', + LongTwo = '4', + LongBig = '1099511627776' +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/monster.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/monster.d.ts new file mode 100644 index 00000000000..86488391cbb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/monster.d.ts @@ -0,0 +1,325 @@ +import * as flatbuffers from 'flatbuffers'; +import { MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Ability, AbilityT } from '../../my-game/example/ability.js'; +import { Any } from '../../my-game/example/any.js'; +import { AnyAmbiguousAliases } from '../../my-game/example/any-ambiguous-aliases.js'; +import { AnyUniqueAliases } from '../../my-game/example/any-unique-aliases.js'; +import { Color } from '../../my-game/example/color.js'; +import { Race } from '../../my-game/example/race.js'; +import { Referrable, ReferrableT } from '../../my-game/example/referrable.js'; +import { Stat, StatT } from '../../my-game/example/stat.js'; +import { Test, TestT } from '../../my-game/example/test.js'; +import { TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; +import { Vec3, Vec3T } from '../../my-game/example/vec3.js'; +import { InParentNamespace, InParentNamespaceT } from '../../my-game/in-parent-namespace.js'; +/** + * an example documentation comment: "monster object" + */ +export declare class Monster implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Monster; + static getRootAsMonster(bb: flatbuffers.ByteBuffer, obj?: Monster): Monster; + static getSizePrefixedRootAsMonster(bb: flatbuffers.ByteBuffer, obj?: Monster): Monster; + static bufferHasIdentifier(bb: flatbuffers.ByteBuffer): boolean; + pos(obj?: Vec3): Vec3 | null; + mana(): number; + mutate_mana(value: number): boolean; + hp(): number; + mutate_hp(value: number): boolean; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + inventory(index: number): number | null; + inventoryLength(): number; + inventoryArray(): Uint8Array | null; + color(): Color; + mutate_color(value: Color): boolean; + testType(): Any; + test(obj: any): any | null; + test4(index: number, obj?: Test): Test | null; + test4Length(): number; + testarrayofstring(index: number): string; + testarrayofstring(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + testarrayofstringLength(): number; + /** + * an example documentation comment: this will end up in the generated code + * multiline too + */ + testarrayoftables(index: number, obj?: Monster): Monster | null; + testarrayoftablesLength(): number; + enemy(obj?: Monster): Monster | null; + testnestedflatbuffer(index: number): number | null; + testnestedflatbufferLength(): number; + testnestedflatbufferArray(): Uint8Array | null; + testempty(obj?: Stat): Stat | null; + testbool(): boolean; + mutate_testbool(value: boolean): boolean; + testhashs32Fnv1(): number; + mutate_testhashs32_fnv1(value: number): boolean; + testhashu32Fnv1(): number; + mutate_testhashu32_fnv1(value: number): boolean; + testhashs64Fnv1(): bigint; + mutate_testhashs64_fnv1(value: bigint): boolean; + testhashu64Fnv1(): bigint; + mutate_testhashu64_fnv1(value: bigint): boolean; + testhashs32Fnv1a(): number; + mutate_testhashs32_fnv1a(value: number): boolean; + testhashu32Fnv1a(): number; + mutate_testhashu32_fnv1a(value: number): boolean; + testhashs64Fnv1a(): bigint; + mutate_testhashs64_fnv1a(value: bigint): boolean; + testhashu64Fnv1a(): bigint; + mutate_testhashu64_fnv1a(value: bigint): boolean; + testarrayofbools(index: number): boolean | null; + testarrayofboolsLength(): number; + testarrayofboolsArray(): Int8Array | null; + testf(): number; + mutate_testf(value: number): boolean; + testf2(): number; + mutate_testf2(value: number): boolean; + testf3(): number; + mutate_testf3(value: number): boolean; + testarrayofstring2(index: number): string; + testarrayofstring2(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + testarrayofstring2Length(): number; + testarrayofsortedstruct(index: number, obj?: Ability): Ability | null; + testarrayofsortedstructLength(): number; + flex(index: number): number | null; + flexLength(): number; + flexArray(): Uint8Array | null; + test5(index: number, obj?: Test): Test | null; + test5Length(): number; + vectorOfLongs(index: number): bigint | null; + vectorOfLongsLength(): number; + vectorOfDoubles(index: number): number | null; + vectorOfDoublesLength(): number; + vectorOfDoublesArray(): Float64Array | null; + parentNamespaceTest(obj?: InParentNamespace): InParentNamespace | null; + vectorOfReferrables(index: number, obj?: Referrable): Referrable | null; + vectorOfReferrablesLength(): number; + singleWeakReference(): bigint; + mutate_single_weak_reference(value: bigint): boolean; + vectorOfWeakReferences(index: number): bigint | null; + vectorOfWeakReferencesLength(): number; + vectorOfStrongReferrables(index: number, obj?: Referrable): Referrable | null; + vectorOfStrongReferrablesLength(): number; + coOwningReference(): bigint; + mutate_co_owning_reference(value: bigint): boolean; + vectorOfCoOwningReferences(index: number): bigint | null; + vectorOfCoOwningReferencesLength(): number; + nonOwningReference(): bigint; + mutate_non_owning_reference(value: bigint): boolean; + vectorOfNonOwningReferences(index: number): bigint | null; + vectorOfNonOwningReferencesLength(): number; + anyUniqueType(): AnyUniqueAliases; + anyUnique(obj: any): any | null; + anyAmbiguousType(): AnyAmbiguousAliases; + anyAmbiguous(obj: any): any | null; + vectorOfEnums(index: number): Color | null; + vectorOfEnumsLength(): number; + vectorOfEnumsArray(): Uint8Array | null; + signedEnum(): Race; + mutate_signed_enum(value: Race): boolean; + testrequirednestedflatbuffer(index: number): number | null; + testrequirednestedflatbufferLength(): number; + testrequirednestedflatbufferArray(): Uint8Array | null; + scalarKeySortedTables(index: number, obj?: Stat): Stat | null; + scalarKeySortedTablesLength(): number; + nativeInline(obj?: Test): Test | null; + longEnumNonEnumDefault(): bigint; + mutate_long_enum_non_enum_default(value: bigint): boolean; + longEnumNormalDefault(): bigint; + mutate_long_enum_normal_default(value: bigint): boolean; + nanDefault(): number; + mutate_nan_default(value: number): boolean; + infDefault(): number; + mutate_inf_default(value: number): boolean; + positiveInfDefault(): number; + mutate_positive_inf_default(value: number): boolean; + infinityDefault(): number; + mutate_infinity_default(value: number): boolean; + positiveInfinityDefault(): number; + mutate_positive_infinity_default(value: number): boolean; + negativeInfDefault(): number; + mutate_negative_inf_default(value: number): boolean; + negativeInfinityDefault(): number; + mutate_negative_infinity_default(value: number): boolean; + doubleInfDefault(): number; + mutate_double_inf_default(value: number): boolean; + static getFullyQualifiedName(): string; + static startMonster(builder: flatbuffers.Builder): void; + static addPos(builder: flatbuffers.Builder, posOffset: flatbuffers.Offset): void; + static addMana(builder: flatbuffers.Builder, mana: number): void; + static addHp(builder: flatbuffers.Builder, hp: number): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addInventory(builder: flatbuffers.Builder, inventoryOffset: flatbuffers.Offset): void; + static createInventoryVector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startInventoryVector(builder: flatbuffers.Builder, numElems: number): void; + static addColor(builder: flatbuffers.Builder, color: Color): void; + static addTestType(builder: flatbuffers.Builder, testType: Any): void; + static addTest(builder: flatbuffers.Builder, testOffset: flatbuffers.Offset): void; + static addTest4(builder: flatbuffers.Builder, test4Offset: flatbuffers.Offset): void; + static startTest4Vector(builder: flatbuffers.Builder, numElems: number): void; + static addTestarrayofstring(builder: flatbuffers.Builder, testarrayofstringOffset: flatbuffers.Offset): void; + static createTestarrayofstringVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startTestarrayofstringVector(builder: flatbuffers.Builder, numElems: number): void; + static addTestarrayoftables(builder: flatbuffers.Builder, testarrayoftablesOffset: flatbuffers.Offset): void; + static createTestarrayoftablesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startTestarrayoftablesVector(builder: flatbuffers.Builder, numElems: number): void; + static addEnemy(builder: flatbuffers.Builder, enemyOffset: flatbuffers.Offset): void; + static addTestnestedflatbuffer(builder: flatbuffers.Builder, testnestedflatbufferOffset: flatbuffers.Offset): void; + static createTestnestedflatbufferVector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startTestnestedflatbufferVector(builder: flatbuffers.Builder, numElems: number): void; + static addTestempty(builder: flatbuffers.Builder, testemptyOffset: flatbuffers.Offset): void; + static addTestbool(builder: flatbuffers.Builder, testbool: boolean): void; + static addTesthashs32Fnv1(builder: flatbuffers.Builder, testhashs32Fnv1: number): void; + static addTesthashu32Fnv1(builder: flatbuffers.Builder, testhashu32Fnv1: number): void; + static addTesthashs64Fnv1(builder: flatbuffers.Builder, testhashs64Fnv1: bigint): void; + static addTesthashu64Fnv1(builder: flatbuffers.Builder, testhashu64Fnv1: bigint): void; + static addTesthashs32Fnv1a(builder: flatbuffers.Builder, testhashs32Fnv1a: number): void; + static addTesthashu32Fnv1a(builder: flatbuffers.Builder, testhashu32Fnv1a: number): void; + static addTesthashs64Fnv1a(builder: flatbuffers.Builder, testhashs64Fnv1a: bigint): void; + static addTesthashu64Fnv1a(builder: flatbuffers.Builder, testhashu64Fnv1a: bigint): void; + static addTestarrayofbools(builder: flatbuffers.Builder, testarrayofboolsOffset: flatbuffers.Offset): void; + static createTestarrayofboolsVector(builder: flatbuffers.Builder, data: boolean[]): flatbuffers.Offset; + static startTestarrayofboolsVector(builder: flatbuffers.Builder, numElems: number): void; + static addTestf(builder: flatbuffers.Builder, testf: number): void; + static addTestf2(builder: flatbuffers.Builder, testf2: number): void; + static addTestf3(builder: flatbuffers.Builder, testf3: number): void; + static addTestarrayofstring2(builder: flatbuffers.Builder, testarrayofstring2Offset: flatbuffers.Offset): void; + static createTestarrayofstring2Vector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startTestarrayofstring2Vector(builder: flatbuffers.Builder, numElems: number): void; + static addTestarrayofsortedstruct(builder: flatbuffers.Builder, testarrayofsortedstructOffset: flatbuffers.Offset): void; + static startTestarrayofsortedstructVector(builder: flatbuffers.Builder, numElems: number): void; + static addFlex(builder: flatbuffers.Builder, flexOffset: flatbuffers.Offset): void; + static createFlexVector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startFlexVector(builder: flatbuffers.Builder, numElems: number): void; + static addTest5(builder: flatbuffers.Builder, test5Offset: flatbuffers.Offset): void; + static startTest5Vector(builder: flatbuffers.Builder, numElems: number): void; + static addVectorOfLongs(builder: flatbuffers.Builder, vectorOfLongsOffset: flatbuffers.Offset): void; + static createVectorOfLongsVector(builder: flatbuffers.Builder, data: bigint[]): flatbuffers.Offset; + static startVectorOfLongsVector(builder: flatbuffers.Builder, numElems: number): void; + static addVectorOfDoubles(builder: flatbuffers.Builder, vectorOfDoublesOffset: flatbuffers.Offset): void; + static createVectorOfDoublesVector(builder: flatbuffers.Builder, data: number[] | Float64Array): flatbuffers.Offset; + /** + * @deprecated This Uint8Array overload will be removed in the future. + */ + static createVectorOfDoublesVector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startVectorOfDoublesVector(builder: flatbuffers.Builder, numElems: number): void; + static addParentNamespaceTest(builder: flatbuffers.Builder, parentNamespaceTestOffset: flatbuffers.Offset): void; + static addVectorOfReferrables(builder: flatbuffers.Builder, vectorOfReferrablesOffset: flatbuffers.Offset): void; + static createVectorOfReferrablesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startVectorOfReferrablesVector(builder: flatbuffers.Builder, numElems: number): void; + static addSingleWeakReference(builder: flatbuffers.Builder, singleWeakReference: bigint): void; + static addVectorOfWeakReferences(builder: flatbuffers.Builder, vectorOfWeakReferencesOffset: flatbuffers.Offset): void; + static createVectorOfWeakReferencesVector(builder: flatbuffers.Builder, data: bigint[]): flatbuffers.Offset; + static startVectorOfWeakReferencesVector(builder: flatbuffers.Builder, numElems: number): void; + static addVectorOfStrongReferrables(builder: flatbuffers.Builder, vectorOfStrongReferrablesOffset: flatbuffers.Offset): void; + static createVectorOfStrongReferrablesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startVectorOfStrongReferrablesVector(builder: flatbuffers.Builder, numElems: number): void; + static addCoOwningReference(builder: flatbuffers.Builder, coOwningReference: bigint): void; + static addVectorOfCoOwningReferences(builder: flatbuffers.Builder, vectorOfCoOwningReferencesOffset: flatbuffers.Offset): void; + static createVectorOfCoOwningReferencesVector(builder: flatbuffers.Builder, data: bigint[]): flatbuffers.Offset; + static startVectorOfCoOwningReferencesVector(builder: flatbuffers.Builder, numElems: number): void; + static addNonOwningReference(builder: flatbuffers.Builder, nonOwningReference: bigint): void; + static addVectorOfNonOwningReferences(builder: flatbuffers.Builder, vectorOfNonOwningReferencesOffset: flatbuffers.Offset): void; + static createVectorOfNonOwningReferencesVector(builder: flatbuffers.Builder, data: bigint[]): flatbuffers.Offset; + static startVectorOfNonOwningReferencesVector(builder: flatbuffers.Builder, numElems: number): void; + static addAnyUniqueType(builder: flatbuffers.Builder, anyUniqueType: AnyUniqueAliases): void; + static addAnyUnique(builder: flatbuffers.Builder, anyUniqueOffset: flatbuffers.Offset): void; + static addAnyAmbiguousType(builder: flatbuffers.Builder, anyAmbiguousType: AnyAmbiguousAliases): void; + static addAnyAmbiguous(builder: flatbuffers.Builder, anyAmbiguousOffset: flatbuffers.Offset): void; + static addVectorOfEnums(builder: flatbuffers.Builder, vectorOfEnumsOffset: flatbuffers.Offset): void; + static createVectorOfEnumsVector(builder: flatbuffers.Builder, data: Color[]): flatbuffers.Offset; + static startVectorOfEnumsVector(builder: flatbuffers.Builder, numElems: number): void; + static addSignedEnum(builder: flatbuffers.Builder, signedEnum: Race): void; + static addTestrequirednestedflatbuffer(builder: flatbuffers.Builder, testrequirednestedflatbufferOffset: flatbuffers.Offset): void; + static createTestrequirednestedflatbufferVector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startTestrequirednestedflatbufferVector(builder: flatbuffers.Builder, numElems: number): void; + static addScalarKeySortedTables(builder: flatbuffers.Builder, scalarKeySortedTablesOffset: flatbuffers.Offset): void; + static createScalarKeySortedTablesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startScalarKeySortedTablesVector(builder: flatbuffers.Builder, numElems: number): void; + static addNativeInline(builder: flatbuffers.Builder, nativeInlineOffset: flatbuffers.Offset): void; + static addLongEnumNonEnumDefault(builder: flatbuffers.Builder, longEnumNonEnumDefault: bigint): void; + static addLongEnumNormalDefault(builder: flatbuffers.Builder, longEnumNormalDefault: bigint): void; + static addNanDefault(builder: flatbuffers.Builder, nanDefault: number): void; + static addInfDefault(builder: flatbuffers.Builder, infDefault: number): void; + static addPositiveInfDefault(builder: flatbuffers.Builder, positiveInfDefault: number): void; + static addInfinityDefault(builder: flatbuffers.Builder, infinityDefault: number): void; + static addPositiveInfinityDefault(builder: flatbuffers.Builder, positiveInfinityDefault: number): void; + static addNegativeInfDefault(builder: flatbuffers.Builder, negativeInfDefault: number): void; + static addNegativeInfinityDefault(builder: flatbuffers.Builder, negativeInfinityDefault: number): void; + static addDoubleInfDefault(builder: flatbuffers.Builder, doubleInfDefault: number): void; + static endMonster(builder: flatbuffers.Builder): flatbuffers.Offset; + static finishMonsterBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static finishSizePrefixedMonsterBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): Monster; + unpack(): MonsterT; + unpackTo(_o: MonsterT): void; +} +export declare class MonsterT implements flatbuffers.IGeneratedObject { + pos: Vec3T | null; + mana: number; + hp: number; + name: string | Uint8Array | null; + inventory: (number)[]; + color: Color; + testType: Any; + test: MonsterT | MyGame_Example2_MonsterT | TestSimpleTableWithEnumT | null; + test4: (TestT)[]; + testarrayofstring: (string)[]; + testarrayoftables: (MonsterT)[]; + enemy: MonsterT | null; + testnestedflatbuffer: (number)[]; + testempty: StatT | null; + testbool: boolean; + testhashs32Fnv1: number; + testhashu32Fnv1: number; + testhashs64Fnv1: bigint; + testhashu64Fnv1: bigint; + testhashs32Fnv1a: number; + testhashu32Fnv1a: number; + testhashs64Fnv1a: bigint; + testhashu64Fnv1a: bigint; + testarrayofbools: (boolean)[]; + testf: number; + testf2: number; + testf3: number; + testarrayofstring2: (string)[]; + testarrayofsortedstruct: (AbilityT)[]; + flex: (number)[]; + test5: (TestT)[]; + vectorOfLongs: (bigint)[]; + vectorOfDoubles: (number)[]; + parentNamespaceTest: InParentNamespaceT | null; + vectorOfReferrables: (ReferrableT)[]; + singleWeakReference: bigint; + vectorOfWeakReferences: (bigint)[]; + vectorOfStrongReferrables: (ReferrableT)[]; + coOwningReference: bigint; + vectorOfCoOwningReferences: (bigint)[]; + nonOwningReference: bigint; + vectorOfNonOwningReferences: (bigint)[]; + anyUniqueType: AnyUniqueAliases; + anyUnique: MonsterT | MyGame_Example2_MonsterT | TestSimpleTableWithEnumT | null; + anyAmbiguousType: AnyAmbiguousAliases; + anyAmbiguous: MonsterT | null; + vectorOfEnums: (Color)[]; + signedEnum: Race; + testrequirednestedflatbuffer: (number)[]; + scalarKeySortedTables: (StatT)[]; + nativeInline: TestT | null; + longEnumNonEnumDefault: bigint; + longEnumNormalDefault: bigint; + nanDefault: number; + infDefault: number; + positiveInfDefault: number; + infinityDefault: number; + positiveInfinityDefault: number; + negativeInfDefault: number; + negativeInfinityDefault: number; + doubleInfDefault: number; + constructor(pos?: Vec3T | null, mana?: number, hp?: number, name?: string | Uint8Array | null, inventory?: (number)[], color?: Color, testType?: Any, test?: MonsterT | MyGame_Example2_MonsterT | TestSimpleTableWithEnumT | null, test4?: (TestT)[], testarrayofstring?: (string)[], testarrayoftables?: (MonsterT)[], enemy?: MonsterT | null, testnestedflatbuffer?: (number)[], testempty?: StatT | null, testbool?: boolean, testhashs32Fnv1?: number, testhashu32Fnv1?: number, testhashs64Fnv1?: bigint, testhashu64Fnv1?: bigint, testhashs32Fnv1a?: number, testhashu32Fnv1a?: number, testhashs64Fnv1a?: bigint, testhashu64Fnv1a?: bigint, testarrayofbools?: (boolean)[], testf?: number, testf2?: number, testf3?: number, testarrayofstring2?: (string)[], testarrayofsortedstruct?: (AbilityT)[], flex?: (number)[], test5?: (TestT)[], vectorOfLongs?: (bigint)[], vectorOfDoubles?: (number)[], parentNamespaceTest?: InParentNamespaceT | null, vectorOfReferrables?: (ReferrableT)[], singleWeakReference?: bigint, vectorOfWeakReferences?: (bigint)[], vectorOfStrongReferrables?: (ReferrableT)[], coOwningReference?: bigint, vectorOfCoOwningReferences?: (bigint)[], nonOwningReference?: bigint, vectorOfNonOwningReferences?: (bigint)[], anyUniqueType?: AnyUniqueAliases, anyUnique?: MonsterT | MyGame_Example2_MonsterT | TestSimpleTableWithEnumT | null, anyAmbiguousType?: AnyAmbiguousAliases, anyAmbiguous?: MonsterT | null, vectorOfEnums?: (Color)[], signedEnum?: Race, testrequirednestedflatbuffer?: (number)[], scalarKeySortedTables?: (StatT)[], nativeInline?: TestT | null, longEnumNonEnumDefault?: bigint, longEnumNormalDefault?: bigint, nanDefault?: number, infDefault?: number, positiveInfDefault?: number, infinityDefault?: number, positiveInfinityDefault?: number, negativeInfDefault?: number, negativeInfinityDefault?: number, doubleInfDefault?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/monster.js b/third_party/flatbuffers/tests/ts/my-game/example/monster.js new file mode 100644 index 00000000000..11a6604b2b5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/monster.js @@ -0,0 +1,1270 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { Ability } from '../../my-game/example/ability.js'; +import { Any, unionToAny } from '../../my-game/example/any.js'; +import { AnyAmbiguousAliases, unionToAnyAmbiguousAliases } from '../../my-game/example/any-ambiguous-aliases.js'; +import { AnyUniqueAliases, unionToAnyUniqueAliases } from '../../my-game/example/any-unique-aliases.js'; +import { Color } from '../../my-game/example/color.js'; +import { Race } from '../../my-game/example/race.js'; +import { Referrable } from '../../my-game/example/referrable.js'; +import { Stat } from '../../my-game/example/stat.js'; +import { Test } from '../../my-game/example/test.js'; +import { Vec3 } from '../../my-game/example/vec3.js'; +import { InParentNamespace } from '../../my-game/in-parent-namespace.js'; +/** + * an example documentation comment: "monster object" + */ +export class Monster { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMonster(bb, obj) { + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMonster(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier('MONS'); + } + pos(obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new Vec3()).__init(this.bb_pos + offset, this.bb) : null; + } + mana() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 150; + } + mutate_mana(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt16(this.bb_pos + offset, value); + return true; + } + hp() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 100; + } + mutate_hp(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt16(this.bb_pos + offset, value); + return true; + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + inventory(index) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + inventoryLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + inventoryArray() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + color() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Color.Blue; + } + mutate_color(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeUint8(this.bb_pos + offset, value); + return true; + } + testType() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Any.NONE; + } + test(obj) { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + test4(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? (obj || new Test()).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null; + } + test4Length() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testarrayofstring(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + testarrayofstringLength() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + /** + * an example documentation comment: this will end up in the generated code + * multiline too + */ + testarrayoftables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? (obj || new Monster()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + testarrayoftablesLength() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + enemy(obj) { + const offset = this.bb.__offset(this.bb_pos, 28); + return offset ? (obj || new Monster()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + testnestedflatbuffer(index) { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + testnestedflatbufferLength() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testnestedflatbufferArray() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + testempty(obj) { + const offset = this.bb.__offset(this.bb_pos, 32); + return offset ? (obj || new Stat()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + testbool() { + const offset = this.bb.__offset(this.bb_pos, 34); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_testbool(value) { + const offset = this.bb.__offset(this.bb_pos, 34); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + testhashs32Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 36); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_testhashs32_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 36); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + testhashu32Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 38); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_testhashu32_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 38); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + testhashs64Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 40); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + mutate_testhashs64_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 40); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + testhashu64Fnv1() { + const offset = this.bb.__offset(this.bb_pos, 42); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_testhashu64_fnv1(value) { + const offset = this.bb.__offset(this.bb_pos, 42); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + testhashs32Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 44); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_testhashs32_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 44); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + testhashu32Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 46); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_testhashu32_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 46); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + testhashs64Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 48); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + mutate_testhashs64_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 48); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + testhashu64Fnv1a() { + const offset = this.bb.__offset(this.bb_pos, 50); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_testhashu64_fnv1a(value) { + const offset = this.bb.__offset(this.bb_pos, 50); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + testarrayofbools(index) { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? !!this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : false; + } + testarrayofboolsLength() { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testarrayofboolsArray() { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + testf() { + const offset = this.bb.__offset(this.bb_pos, 54); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.14159; + } + mutate_testf(value) { + const offset = this.bb.__offset(this.bb_pos, 54); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + testf2() { + const offset = this.bb.__offset(this.bb_pos, 56); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 3.0; + } + mutate_testf2(value) { + const offset = this.bb.__offset(this.bb_pos, 56); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + testf3() { + const offset = this.bb.__offset(this.bb_pos, 58); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; + } + mutate_testf3(value) { + const offset = this.bb.__offset(this.bb_pos, 58); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + testarrayofstring2(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 60); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + testarrayofstring2Length() { + const offset = this.bb.__offset(this.bb_pos, 60); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testarrayofsortedstruct(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 62); + return offset ? (obj || new Ability()).__init(this.bb.__vector(this.bb_pos + offset) + index * 8, this.bb) : null; + } + testarrayofsortedstructLength() { + const offset = this.bb.__offset(this.bb_pos, 62); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + flex(index) { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + flexLength() { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + flexArray() { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + test5(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 66); + return offset ? (obj || new Test()).__init(this.bb.__vector(this.bb_pos + offset) + index * 4, this.bb) : null; + } + test5Length() { + const offset = this.bb.__offset(this.bb_pos, 66); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfLongs(index) { + const offset = this.bb.__offset(this.bb_pos, 68); + return offset ? this.bb.readInt64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfLongsLength() { + const offset = this.bb.__offset(this.bb_pos, 68); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfDoubles(index) { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; + } + vectorOfDoublesLength() { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfDoublesArray() { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + parentNamespaceTest(obj) { + const offset = this.bb.__offset(this.bb_pos, 72); + return offset ? (obj || new InParentNamespace()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + vectorOfReferrables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 74); + return offset ? (obj || new Referrable()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + vectorOfReferrablesLength() { + const offset = this.bb.__offset(this.bb_pos, 74); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + singleWeakReference() { + const offset = this.bb.__offset(this.bb_pos, 76); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_single_weak_reference(value) { + const offset = this.bb.__offset(this.bb_pos, 76); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + vectorOfWeakReferences(index) { + const offset = this.bb.__offset(this.bb_pos, 78); + return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfWeakReferencesLength() { + const offset = this.bb.__offset(this.bb_pos, 78); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfStrongReferrables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 80); + return offset ? (obj || new Referrable()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + vectorOfStrongReferrablesLength() { + const offset = this.bb.__offset(this.bb_pos, 80); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + coOwningReference() { + const offset = this.bb.__offset(this.bb_pos, 82); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_co_owning_reference(value) { + const offset = this.bb.__offset(this.bb_pos, 82); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + vectorOfCoOwningReferences(index) { + const offset = this.bb.__offset(this.bb_pos, 84); + return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfCoOwningReferencesLength() { + const offset = this.bb.__offset(this.bb_pos, 84); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + nonOwningReference() { + const offset = this.bb.__offset(this.bb_pos, 86); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_non_owning_reference(value) { + const offset = this.bb.__offset(this.bb_pos, 86); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + vectorOfNonOwningReferences(index) { + const offset = this.bb.__offset(this.bb_pos, 88); + return offset ? this.bb.readUint64(this.bb.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); + } + vectorOfNonOwningReferencesLength() { + const offset = this.bb.__offset(this.bb_pos, 88); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + anyUniqueType() { + const offset = this.bb.__offset(this.bb_pos, 90); + return offset ? this.bb.readUint8(this.bb_pos + offset) : AnyUniqueAliases.NONE; + } + anyUnique(obj) { + const offset = this.bb.__offset(this.bb_pos, 92); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + anyAmbiguousType() { + const offset = this.bb.__offset(this.bb_pos, 94); + return offset ? this.bb.readUint8(this.bb_pos + offset) : AnyAmbiguousAliases.NONE; + } + anyAmbiguous(obj) { + const offset = this.bb.__offset(this.bb_pos, 96); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + vectorOfEnums(index) { + const offset = this.bb.__offset(this.bb_pos, 98); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + vectorOfEnumsLength() { + const offset = this.bb.__offset(this.bb_pos, 98); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vectorOfEnumsArray() { + const offset = this.bb.__offset(this.bb_pos, 98); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + signedEnum() { + const offset = this.bb.__offset(this.bb_pos, 100); + return offset ? this.bb.readInt8(this.bb_pos + offset) : Race.None; + } + mutate_signed_enum(value) { + const offset = this.bb.__offset(this.bb_pos, 100); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + testrequirednestedflatbuffer(index) { + const offset = this.bb.__offset(this.bb_pos, 102); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + testrequirednestedflatbufferLength() { + const offset = this.bb.__offset(this.bb_pos, 102); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testrequirednestedflatbufferArray() { + const offset = this.bb.__offset(this.bb_pos, 102); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + scalarKeySortedTables(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 104); + return offset ? (obj || new Stat()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + scalarKeySortedTablesLength() { + const offset = this.bb.__offset(this.bb_pos, 104); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + nativeInline(obj) { + const offset = this.bb.__offset(this.bb_pos, 106); + return offset ? (obj || new Test()).__init(this.bb_pos + offset, this.bb) : null; + } + longEnumNonEnumDefault() { + const offset = this.bb.__offset(this.bb_pos, 108); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_long_enum_non_enum_default(value) { + const offset = this.bb.__offset(this.bb_pos, 108); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + longEnumNormalDefault() { + const offset = this.bb.__offset(this.bb_pos, 110); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('2'); + } + mutate_long_enum_normal_default(value) { + const offset = this.bb.__offset(this.bb_pos, 110); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + nanDefault() { + const offset = this.bb.__offset(this.bb_pos, 112); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : NaN; + } + mutate_nan_default(value) { + const offset = this.bb.__offset(this.bb_pos, 112); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + infDefault() { + const offset = this.bb.__offset(this.bb_pos, 114); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 114); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + positiveInfDefault() { + const offset = this.bb.__offset(this.bb_pos, 116); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_positive_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 116); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + infinityDefault() { + const offset = this.bb.__offset(this.bb_pos, 118); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_infinity_default(value) { + const offset = this.bb.__offset(this.bb_pos, 118); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + positiveInfinityDefault() { + const offset = this.bb.__offset(this.bb_pos, 120); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : Infinity; + } + mutate_positive_infinity_default(value) { + const offset = this.bb.__offset(this.bb_pos, 120); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + negativeInfDefault() { + const offset = this.bb.__offset(this.bb_pos, 122); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : -Infinity; + } + mutate_negative_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 122); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + negativeInfinityDefault() { + const offset = this.bb.__offset(this.bb_pos, 124); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : -Infinity; + } + mutate_negative_infinity_default(value) { + const offset = this.bb.__offset(this.bb_pos, 124); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + doubleInfDefault() { + const offset = this.bb.__offset(this.bb_pos, 126); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : Infinity; + } + mutate_double_inf_default(value) { + const offset = this.bb.__offset(this.bb_pos, 126); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.Example.Monster'; + } + static startMonster(builder) { + builder.startObject(62); + } + static addPos(builder, posOffset) { + builder.addFieldStruct(0, posOffset, 0); + } + static addMana(builder, mana) { + builder.addFieldInt16(1, mana, 150); + } + static addHp(builder, hp) { + builder.addFieldInt16(2, hp, 100); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(3, nameOffset, 0); + } + static addInventory(builder, inventoryOffset) { + builder.addFieldOffset(5, inventoryOffset, 0); + } + static createInventoryVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startInventoryVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addColor(builder, color) { + builder.addFieldInt8(6, color, Color.Blue); + } + static addTestType(builder, testType) { + builder.addFieldInt8(7, testType, Any.NONE); + } + static addTest(builder, testOffset) { + builder.addFieldOffset(8, testOffset, 0); + } + static addTest4(builder, test4Offset) { + builder.addFieldOffset(9, test4Offset, 0); + } + static startTest4Vector(builder, numElems) { + builder.startVector(4, numElems, 2); + } + static addTestarrayofstring(builder, testarrayofstringOffset) { + builder.addFieldOffset(10, testarrayofstringOffset, 0); + } + static createTestarrayofstringVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestarrayofstringVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addTestarrayoftables(builder, testarrayoftablesOffset) { + builder.addFieldOffset(11, testarrayoftablesOffset, 0); + } + static createTestarrayoftablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestarrayoftablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addEnemy(builder, enemyOffset) { + builder.addFieldOffset(12, enemyOffset, 0); + } + static addTestnestedflatbuffer(builder, testnestedflatbufferOffset) { + builder.addFieldOffset(13, testnestedflatbufferOffset, 0); + } + static createTestnestedflatbufferVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startTestnestedflatbufferVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addTestempty(builder, testemptyOffset) { + builder.addFieldOffset(14, testemptyOffset, 0); + } + static addTestbool(builder, testbool) { + builder.addFieldInt8(15, +testbool, +false); + } + static addTesthashs32Fnv1(builder, testhashs32Fnv1) { + builder.addFieldInt32(16, testhashs32Fnv1, 0); + } + static addTesthashu32Fnv1(builder, testhashu32Fnv1) { + builder.addFieldInt32(17, testhashu32Fnv1, 0); + } + static addTesthashs64Fnv1(builder, testhashs64Fnv1) { + builder.addFieldInt64(18, testhashs64Fnv1, BigInt('0')); + } + static addTesthashu64Fnv1(builder, testhashu64Fnv1) { + builder.addFieldInt64(19, testhashu64Fnv1, BigInt('0')); + } + static addTesthashs32Fnv1a(builder, testhashs32Fnv1a) { + builder.addFieldInt32(20, testhashs32Fnv1a, 0); + } + static addTesthashu32Fnv1a(builder, testhashu32Fnv1a) { + builder.addFieldInt32(21, testhashu32Fnv1a, 0); + } + static addTesthashs64Fnv1a(builder, testhashs64Fnv1a) { + builder.addFieldInt64(22, testhashs64Fnv1a, BigInt('0')); + } + static addTesthashu64Fnv1a(builder, testhashu64Fnv1a) { + builder.addFieldInt64(23, testhashu64Fnv1a, BigInt('0')); + } + static addTestarrayofbools(builder, testarrayofboolsOffset) { + builder.addFieldOffset(24, testarrayofboolsOffset, 0); + } + static createTestarrayofboolsVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(+data[i]); + } + return builder.endVector(); + } + static startTestarrayofboolsVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addTestf(builder, testf) { + builder.addFieldFloat32(25, testf, 3.14159); + } + static addTestf2(builder, testf2) { + builder.addFieldFloat32(26, testf2, 3.0); + } + static addTestf3(builder, testf3) { + builder.addFieldFloat32(27, testf3, 0.0); + } + static addTestarrayofstring2(builder, testarrayofstring2Offset) { + builder.addFieldOffset(28, testarrayofstring2Offset, 0); + } + static createTestarrayofstring2Vector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestarrayofstring2Vector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addTestarrayofsortedstruct(builder, testarrayofsortedstructOffset) { + builder.addFieldOffset(29, testarrayofsortedstructOffset, 0); + } + static startTestarrayofsortedstructVector(builder, numElems) { + builder.startVector(8, numElems, 4); + } + static addFlex(builder, flexOffset) { + builder.addFieldOffset(30, flexOffset, 0); + } + static createFlexVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startFlexVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addTest5(builder, test5Offset) { + builder.addFieldOffset(31, test5Offset, 0); + } + static startTest5Vector(builder, numElems) { + builder.startVector(4, numElems, 2); + } + static addVectorOfLongs(builder, vectorOfLongsOffset) { + builder.addFieldOffset(32, vectorOfLongsOffset, 0); + } + static createVectorOfLongsVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfLongsVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addVectorOfDoubles(builder, vectorOfDoublesOffset) { + builder.addFieldOffset(33, vectorOfDoublesOffset, 0); + } + static createVectorOfDoublesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addFloat64(data[i]); + } + return builder.endVector(); + } + static startVectorOfDoublesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addParentNamespaceTest(builder, parentNamespaceTestOffset) { + builder.addFieldOffset(34, parentNamespaceTestOffset, 0); + } + static addVectorOfReferrables(builder, vectorOfReferrablesOffset) { + builder.addFieldOffset(35, vectorOfReferrablesOffset, 0); + } + static createVectorOfReferrablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startVectorOfReferrablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addSingleWeakReference(builder, singleWeakReference) { + builder.addFieldInt64(36, singleWeakReference, BigInt('0')); + } + static addVectorOfWeakReferences(builder, vectorOfWeakReferencesOffset) { + builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0); + } + static createVectorOfWeakReferencesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfWeakReferencesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addVectorOfStrongReferrables(builder, vectorOfStrongReferrablesOffset) { + builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0); + } + static createVectorOfStrongReferrablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startVectorOfStrongReferrablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addCoOwningReference(builder, coOwningReference) { + builder.addFieldInt64(39, coOwningReference, BigInt('0')); + } + static addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferencesOffset) { + builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0); + } + static createVectorOfCoOwningReferencesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfCoOwningReferencesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addNonOwningReference(builder, nonOwningReference) { + builder.addFieldInt64(41, nonOwningReference, BigInt('0')); + } + static addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferencesOffset) { + builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0); + } + static createVectorOfNonOwningReferencesVector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]); + } + return builder.endVector(); + } + static startVectorOfNonOwningReferencesVector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static addAnyUniqueType(builder, anyUniqueType) { + builder.addFieldInt8(43, anyUniqueType, AnyUniqueAliases.NONE); + } + static addAnyUnique(builder, anyUniqueOffset) { + builder.addFieldOffset(44, anyUniqueOffset, 0); + } + static addAnyAmbiguousType(builder, anyAmbiguousType) { + builder.addFieldInt8(45, anyAmbiguousType, AnyAmbiguousAliases.NONE); + } + static addAnyAmbiguous(builder, anyAmbiguousOffset) { + builder.addFieldOffset(46, anyAmbiguousOffset, 0); + } + static addVectorOfEnums(builder, vectorOfEnumsOffset) { + builder.addFieldOffset(47, vectorOfEnumsOffset, 0); + } + static createVectorOfEnumsVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startVectorOfEnumsVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addSignedEnum(builder, signedEnum) { + builder.addFieldInt8(48, signedEnum, Race.None); + } + static addTestrequirednestedflatbuffer(builder, testrequirednestedflatbufferOffset) { + builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0); + } + static createTestrequirednestedflatbufferVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startTestrequirednestedflatbufferVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addScalarKeySortedTables(builder, scalarKeySortedTablesOffset) { + builder.addFieldOffset(50, scalarKeySortedTablesOffset, 0); + } + static createScalarKeySortedTablesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startScalarKeySortedTablesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addNativeInline(builder, nativeInlineOffset) { + builder.addFieldStruct(51, nativeInlineOffset, 0); + } + static addLongEnumNonEnumDefault(builder, longEnumNonEnumDefault) { + builder.addFieldInt64(52, longEnumNonEnumDefault, BigInt('0')); + } + static addLongEnumNormalDefault(builder, longEnumNormalDefault) { + builder.addFieldInt64(53, longEnumNormalDefault, BigInt('2')); + } + static addNanDefault(builder, nanDefault) { + builder.addFieldFloat32(54, nanDefault, NaN); + } + static addInfDefault(builder, infDefault) { + builder.addFieldFloat32(55, infDefault, Infinity); + } + static addPositiveInfDefault(builder, positiveInfDefault) { + builder.addFieldFloat32(56, positiveInfDefault, Infinity); + } + static addInfinityDefault(builder, infinityDefault) { + builder.addFieldFloat32(57, infinityDefault, Infinity); + } + static addPositiveInfinityDefault(builder, positiveInfinityDefault) { + builder.addFieldFloat32(58, positiveInfinityDefault, Infinity); + } + static addNegativeInfDefault(builder, negativeInfDefault) { + builder.addFieldFloat32(59, negativeInfDefault, -Infinity); + } + static addNegativeInfinityDefault(builder, negativeInfinityDefault) { + builder.addFieldFloat32(60, negativeInfinityDefault, -Infinity); + } + static addDoubleInfDefault(builder, doubleInfDefault) { + builder.addFieldFloat64(61, doubleInfDefault, Infinity); + } + static endMonster(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 10); // name + return offset; + } + static finishMonsterBuffer(builder, offset) { + builder.finish(offset, 'MONS'); + } + static finishSizePrefixedMonsterBuffer(builder, offset) { + builder.finish(offset, 'MONS', true); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new MonsterT((this.pos() !== null ? this.pos().unpack() : null), this.mana(), this.hp(), this.name(), this.bb.createScalarList(this.inventory.bind(this), this.inventoryLength()), this.color(), this.testType(), (() => { + const temp = unionToAny(this.testType(), this.test.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.bb.createObjList(this.test4.bind(this), this.test4Length()), this.bb.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()), this.bb.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()), (this.enemy() !== null ? this.enemy().unpack() : null), this.bb.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()), (this.testempty() !== null ? this.testempty().unpack() : null), this.testbool(), this.testhashs32Fnv1(), this.testhashu32Fnv1(), this.testhashs64Fnv1(), this.testhashu64Fnv1(), this.testhashs32Fnv1a(), this.testhashu32Fnv1a(), this.testhashs64Fnv1a(), this.testhashu64Fnv1a(), this.bb.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()), this.testf(), this.testf2(), this.testf3(), this.bb.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()), this.bb.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()), this.bb.createScalarList(this.flex.bind(this), this.flexLength()), this.bb.createObjList(this.test5.bind(this), this.test5Length()), this.bb.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()), this.bb.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()), (this.parentNamespaceTest() !== null ? this.parentNamespaceTest().unpack() : null), this.bb.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()), this.singleWeakReference(), this.bb.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()), this.bb.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()), this.coOwningReference(), this.bb.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()), this.nonOwningReference(), this.bb.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()), this.anyUniqueType(), (() => { + const temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.anyAmbiguousType(), (() => { + const temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.bb.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()), this.signedEnum(), this.bb.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()), this.bb.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()), (this.nativeInline() !== null ? this.nativeInline().unpack() : null), this.longEnumNonEnumDefault(), this.longEnumNormalDefault(), this.nanDefault(), this.infDefault(), this.positiveInfDefault(), this.infinityDefault(), this.positiveInfinityDefault(), this.negativeInfDefault(), this.negativeInfinityDefault(), this.doubleInfDefault()); + } + unpackTo(_o) { + _o.pos = (this.pos() !== null ? this.pos().unpack() : null); + _o.mana = this.mana(); + _o.hp = this.hp(); + _o.name = this.name(); + _o.inventory = this.bb.createScalarList(this.inventory.bind(this), this.inventoryLength()); + _o.color = this.color(); + _o.testType = this.testType(); + _o.test = (() => { + const temp = unionToAny(this.testType(), this.test.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.test4 = this.bb.createObjList(this.test4.bind(this), this.test4Length()); + _o.testarrayofstring = this.bb.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()); + _o.testarrayoftables = this.bb.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()); + _o.enemy = (this.enemy() !== null ? this.enemy().unpack() : null); + _o.testnestedflatbuffer = this.bb.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()); + _o.testempty = (this.testempty() !== null ? this.testempty().unpack() : null); + _o.testbool = this.testbool(); + _o.testhashs32Fnv1 = this.testhashs32Fnv1(); + _o.testhashu32Fnv1 = this.testhashu32Fnv1(); + _o.testhashs64Fnv1 = this.testhashs64Fnv1(); + _o.testhashu64Fnv1 = this.testhashu64Fnv1(); + _o.testhashs32Fnv1a = this.testhashs32Fnv1a(); + _o.testhashu32Fnv1a = this.testhashu32Fnv1a(); + _o.testhashs64Fnv1a = this.testhashs64Fnv1a(); + _o.testhashu64Fnv1a = this.testhashu64Fnv1a(); + _o.testarrayofbools = this.bb.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()); + _o.testf = this.testf(); + _o.testf2 = this.testf2(); + _o.testf3 = this.testf3(); + _o.testarrayofstring2 = this.bb.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()); + _o.testarrayofsortedstruct = this.bb.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()); + _o.flex = this.bb.createScalarList(this.flex.bind(this), this.flexLength()); + _o.test5 = this.bb.createObjList(this.test5.bind(this), this.test5Length()); + _o.vectorOfLongs = this.bb.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()); + _o.vectorOfDoubles = this.bb.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()); + _o.parentNamespaceTest = (this.parentNamespaceTest() !== null ? this.parentNamespaceTest().unpack() : null); + _o.vectorOfReferrables = this.bb.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()); + _o.singleWeakReference = this.singleWeakReference(); + _o.vectorOfWeakReferences = this.bb.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()); + _o.vectorOfStrongReferrables = this.bb.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()); + _o.coOwningReference = this.coOwningReference(); + _o.vectorOfCoOwningReferences = this.bb.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()); + _o.nonOwningReference = this.nonOwningReference(); + _o.vectorOfNonOwningReferences = this.bb.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()); + _o.anyUniqueType = this.anyUniqueType(); + _o.anyUnique = (() => { + const temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.anyAmbiguousType = this.anyAmbiguousType(); + _o.anyAmbiguous = (() => { + const temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.vectorOfEnums = this.bb.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()); + _o.signedEnum = this.signedEnum(); + _o.testrequirednestedflatbuffer = this.bb.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()); + _o.scalarKeySortedTables = this.bb.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()); + _o.nativeInline = (this.nativeInline() !== null ? this.nativeInline().unpack() : null); + _o.longEnumNonEnumDefault = this.longEnumNonEnumDefault(); + _o.longEnumNormalDefault = this.longEnumNormalDefault(); + _o.nanDefault = this.nanDefault(); + _o.infDefault = this.infDefault(); + _o.positiveInfDefault = this.positiveInfDefault(); + _o.infinityDefault = this.infinityDefault(); + _o.positiveInfinityDefault = this.positiveInfinityDefault(); + _o.negativeInfDefault = this.negativeInfDefault(); + _o.negativeInfinityDefault = this.negativeInfinityDefault(); + _o.doubleInfDefault = this.doubleInfDefault(); + } +} +export class MonsterT { + constructor(pos = null, mana = 150, hp = 100, name = null, inventory = [], color = Color.Blue, testType = Any.NONE, test = null, test4 = [], testarrayofstring = [], testarrayoftables = [], enemy = null, testnestedflatbuffer = [], testempty = null, testbool = false, testhashs32Fnv1 = 0, testhashu32Fnv1 = 0, testhashs64Fnv1 = BigInt('0'), testhashu64Fnv1 = BigInt('0'), testhashs32Fnv1a = 0, testhashu32Fnv1a = 0, testhashs64Fnv1a = BigInt('0'), testhashu64Fnv1a = BigInt('0'), testarrayofbools = [], testf = 3.14159, testf2 = 3.0, testf3 = 0.0, testarrayofstring2 = [], testarrayofsortedstruct = [], flex = [], test5 = [], vectorOfLongs = [], vectorOfDoubles = [], parentNamespaceTest = null, vectorOfReferrables = [], singleWeakReference = BigInt('0'), vectorOfWeakReferences = [], vectorOfStrongReferrables = [], coOwningReference = BigInt('0'), vectorOfCoOwningReferences = [], nonOwningReference = BigInt('0'), vectorOfNonOwningReferences = [], anyUniqueType = AnyUniqueAliases.NONE, anyUnique = null, anyAmbiguousType = AnyAmbiguousAliases.NONE, anyAmbiguous = null, vectorOfEnums = [], signedEnum = Race.None, testrequirednestedflatbuffer = [], scalarKeySortedTables = [], nativeInline = null, longEnumNonEnumDefault = BigInt('0'), longEnumNormalDefault = BigInt('2'), nanDefault = NaN, infDefault = Infinity, positiveInfDefault = Infinity, infinityDefault = Infinity, positiveInfinityDefault = Infinity, negativeInfDefault = -Infinity, negativeInfinityDefault = -Infinity, doubleInfDefault = Infinity) { + this.pos = pos; + this.mana = mana; + this.hp = hp; + this.name = name; + this.inventory = inventory; + this.color = color; + this.testType = testType; + this.test = test; + this.test4 = test4; + this.testarrayofstring = testarrayofstring; + this.testarrayoftables = testarrayoftables; + this.enemy = enemy; + this.testnestedflatbuffer = testnestedflatbuffer; + this.testempty = testempty; + this.testbool = testbool; + this.testhashs32Fnv1 = testhashs32Fnv1; + this.testhashu32Fnv1 = testhashu32Fnv1; + this.testhashs64Fnv1 = testhashs64Fnv1; + this.testhashu64Fnv1 = testhashu64Fnv1; + this.testhashs32Fnv1a = testhashs32Fnv1a; + this.testhashu32Fnv1a = testhashu32Fnv1a; + this.testhashs64Fnv1a = testhashs64Fnv1a; + this.testhashu64Fnv1a = testhashu64Fnv1a; + this.testarrayofbools = testarrayofbools; + this.testf = testf; + this.testf2 = testf2; + this.testf3 = testf3; + this.testarrayofstring2 = testarrayofstring2; + this.testarrayofsortedstruct = testarrayofsortedstruct; + this.flex = flex; + this.test5 = test5; + this.vectorOfLongs = vectorOfLongs; + this.vectorOfDoubles = vectorOfDoubles; + this.parentNamespaceTest = parentNamespaceTest; + this.vectorOfReferrables = vectorOfReferrables; + this.singleWeakReference = singleWeakReference; + this.vectorOfWeakReferences = vectorOfWeakReferences; + this.vectorOfStrongReferrables = vectorOfStrongReferrables; + this.coOwningReference = coOwningReference; + this.vectorOfCoOwningReferences = vectorOfCoOwningReferences; + this.nonOwningReference = nonOwningReference; + this.vectorOfNonOwningReferences = vectorOfNonOwningReferences; + this.anyUniqueType = anyUniqueType; + this.anyUnique = anyUnique; + this.anyAmbiguousType = anyAmbiguousType; + this.anyAmbiguous = anyAmbiguous; + this.vectorOfEnums = vectorOfEnums; + this.signedEnum = signedEnum; + this.testrequirednestedflatbuffer = testrequirednestedflatbuffer; + this.scalarKeySortedTables = scalarKeySortedTables; + this.nativeInline = nativeInline; + this.longEnumNonEnumDefault = longEnumNonEnumDefault; + this.longEnumNormalDefault = longEnumNormalDefault; + this.nanDefault = nanDefault; + this.infDefault = infDefault; + this.positiveInfDefault = positiveInfDefault; + this.infinityDefault = infinityDefault; + this.positiveInfinityDefault = positiveInfinityDefault; + this.negativeInfDefault = negativeInfDefault; + this.negativeInfinityDefault = negativeInfinityDefault; + this.doubleInfDefault = doubleInfDefault; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const inventory = Monster.createInventoryVector(builder, this.inventory); + const test = builder.createObjectOffset(this.test); + const test4 = builder.createStructOffsetList(this.test4, Monster.startTest4Vector); + const testarrayofstring = Monster.createTestarrayofstringVector(builder, builder.createObjectOffsetList(this.testarrayofstring)); + const testarrayoftables = Monster.createTestarrayoftablesVector(builder, builder.createObjectOffsetList(this.testarrayoftables)); + const enemy = (this.enemy !== null ? this.enemy.pack(builder) : 0); + const testnestedflatbuffer = Monster.createTestnestedflatbufferVector(builder, this.testnestedflatbuffer); + const testempty = (this.testempty !== null ? this.testempty.pack(builder) : 0); + const testarrayofbools = Monster.createTestarrayofboolsVector(builder, this.testarrayofbools); + const testarrayofstring2 = Monster.createTestarrayofstring2Vector(builder, builder.createObjectOffsetList(this.testarrayofstring2)); + const testarrayofsortedstruct = builder.createStructOffsetList(this.testarrayofsortedstruct, Monster.startTestarrayofsortedstructVector); + const flex = Monster.createFlexVector(builder, this.flex); + const test5 = builder.createStructOffsetList(this.test5, Monster.startTest5Vector); + const vectorOfLongs = Monster.createVectorOfLongsVector(builder, this.vectorOfLongs); + const vectorOfDoubles = Monster.createVectorOfDoublesVector(builder, this.vectorOfDoubles); + const parentNamespaceTest = (this.parentNamespaceTest !== null ? this.parentNamespaceTest.pack(builder) : 0); + const vectorOfReferrables = Monster.createVectorOfReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfReferrables)); + const vectorOfWeakReferences = Monster.createVectorOfWeakReferencesVector(builder, this.vectorOfWeakReferences); + const vectorOfStrongReferrables = Monster.createVectorOfStrongReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfStrongReferrables)); + const vectorOfCoOwningReferences = Monster.createVectorOfCoOwningReferencesVector(builder, this.vectorOfCoOwningReferences); + const vectorOfNonOwningReferences = Monster.createVectorOfNonOwningReferencesVector(builder, this.vectorOfNonOwningReferences); + const anyUnique = builder.createObjectOffset(this.anyUnique); + const anyAmbiguous = builder.createObjectOffset(this.anyAmbiguous); + const vectorOfEnums = Monster.createVectorOfEnumsVector(builder, this.vectorOfEnums); + const testrequirednestedflatbuffer = Monster.createTestrequirednestedflatbufferVector(builder, this.testrequirednestedflatbuffer); + const scalarKeySortedTables = Monster.createScalarKeySortedTablesVector(builder, builder.createObjectOffsetList(this.scalarKeySortedTables)); + Monster.startMonster(builder); + Monster.addPos(builder, (this.pos !== null ? this.pos.pack(builder) : 0)); + Monster.addMana(builder, this.mana); + Monster.addHp(builder, this.hp); + Monster.addName(builder, name); + Monster.addInventory(builder, inventory); + Monster.addColor(builder, this.color); + Monster.addTestType(builder, this.testType); + Monster.addTest(builder, test); + Monster.addTest4(builder, test4); + Monster.addTestarrayofstring(builder, testarrayofstring); + Monster.addTestarrayoftables(builder, testarrayoftables); + Monster.addEnemy(builder, enemy); + Monster.addTestnestedflatbuffer(builder, testnestedflatbuffer); + Monster.addTestempty(builder, testempty); + Monster.addTestbool(builder, this.testbool); + Monster.addTesthashs32Fnv1(builder, this.testhashs32Fnv1); + Monster.addTesthashu32Fnv1(builder, this.testhashu32Fnv1); + Monster.addTesthashs64Fnv1(builder, this.testhashs64Fnv1); + Monster.addTesthashu64Fnv1(builder, this.testhashu64Fnv1); + Monster.addTesthashs32Fnv1a(builder, this.testhashs32Fnv1a); + Monster.addTesthashu32Fnv1a(builder, this.testhashu32Fnv1a); + Monster.addTesthashs64Fnv1a(builder, this.testhashs64Fnv1a); + Monster.addTesthashu64Fnv1a(builder, this.testhashu64Fnv1a); + Monster.addTestarrayofbools(builder, testarrayofbools); + Monster.addTestf(builder, this.testf); + Monster.addTestf2(builder, this.testf2); + Monster.addTestf3(builder, this.testf3); + Monster.addTestarrayofstring2(builder, testarrayofstring2); + Monster.addTestarrayofsortedstruct(builder, testarrayofsortedstruct); + Monster.addFlex(builder, flex); + Monster.addTest5(builder, test5); + Monster.addVectorOfLongs(builder, vectorOfLongs); + Monster.addVectorOfDoubles(builder, vectorOfDoubles); + Monster.addParentNamespaceTest(builder, parentNamespaceTest); + Monster.addVectorOfReferrables(builder, vectorOfReferrables); + Monster.addSingleWeakReference(builder, this.singleWeakReference); + Monster.addVectorOfWeakReferences(builder, vectorOfWeakReferences); + Monster.addVectorOfStrongReferrables(builder, vectorOfStrongReferrables); + Monster.addCoOwningReference(builder, this.coOwningReference); + Monster.addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences); + Monster.addNonOwningReference(builder, this.nonOwningReference); + Monster.addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences); + Monster.addAnyUniqueType(builder, this.anyUniqueType); + Monster.addAnyUnique(builder, anyUnique); + Monster.addAnyAmbiguousType(builder, this.anyAmbiguousType); + Monster.addAnyAmbiguous(builder, anyAmbiguous); + Monster.addVectorOfEnums(builder, vectorOfEnums); + Monster.addSignedEnum(builder, this.signedEnum); + Monster.addTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer); + Monster.addScalarKeySortedTables(builder, scalarKeySortedTables); + Monster.addNativeInline(builder, (this.nativeInline !== null ? this.nativeInline.pack(builder) : 0)); + Monster.addLongEnumNonEnumDefault(builder, this.longEnumNonEnumDefault); + Monster.addLongEnumNormalDefault(builder, this.longEnumNormalDefault); + Monster.addNanDefault(builder, this.nanDefault); + Monster.addInfDefault(builder, this.infDefault); + Monster.addPositiveInfDefault(builder, this.positiveInfDefault); + Monster.addInfinityDefault(builder, this.infinityDefault); + Monster.addPositiveInfinityDefault(builder, this.positiveInfinityDefault); + Monster.addNegativeInfDefault(builder, this.negativeInfDefault); + Monster.addNegativeInfinityDefault(builder, this.negativeInfinityDefault); + Monster.addDoubleInfDefault(builder, this.doubleInfDefault); + return Monster.endMonster(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/monster.ts b/third_party/flatbuffers/tests/ts/my-game/example/monster.ts new file mode 100644 index 00000000000..c94e3061476 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/monster.ts @@ -0,0 +1,1628 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Monster as MyGame_Example2_Monster, MonsterT as MyGame_Example2_MonsterT } from '../../my-game/example2/monster.js'; +import { Ability, AbilityT } from '../../my-game/example/ability.js'; +import { Any, unionToAny, unionListToAny } from '../../my-game/example/any.js'; +import { AnyAmbiguousAliases, unionToAnyAmbiguousAliases, unionListToAnyAmbiguousAliases } from '../../my-game/example/any-ambiguous-aliases.js'; +import { AnyUniqueAliases, unionToAnyUniqueAliases, unionListToAnyUniqueAliases } from '../../my-game/example/any-unique-aliases.js'; +import { Color } from '../../my-game/example/color.js'; +import { Race } from '../../my-game/example/race.js'; +import { Referrable, ReferrableT } from '../../my-game/example/referrable.js'; +import { Stat, StatT } from '../../my-game/example/stat.js'; +import { Test, TestT } from '../../my-game/example/test.js'; +import { TestSimpleTableWithEnum, TestSimpleTableWithEnumT } from '../../my-game/example/test-simple-table-with-enum.js'; +import { Vec3, Vec3T } from '../../my-game/example/vec3.js'; +import { InParentNamespace, InParentNamespaceT } from '../../my-game/in-parent-namespace.js'; + + +/** + * an example documentation comment: "monster object" + */ +export class Monster implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Monster { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster { + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean { + return bb.__has_identifier('MONS'); +} + +pos(obj?:Vec3):Vec3|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? (obj || new Vec3()).__init(this.bb_pos + offset, this.bb!) : null; +} + +mana():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 150; +} + +mutate_mana(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt16(this.bb_pos + offset, value); + return true; +} + +hp():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 100; +} + +mutate_hp(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt16(this.bb_pos + offset, value); + return true; +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +inventory(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +inventoryLength():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +inventoryArray():Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +color():Color { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : Color.Blue; +} + +mutate_color(value:Color):boolean { + const offset = this.bb!.__offset(this.bb_pos, 16); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint8(this.bb_pos + offset, value); + return true; +} + +testType():Any { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : Any.NONE; +} + +test(obj:any):any|null { + const offset = this.bb!.__offset(this.bb_pos, 20); + return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null; +} + +test4(index: number, obj?:Test):Test|null { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? (obj || new Test()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null; +} + +test4Length():number { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +testarrayofstring(index: number):string +testarrayofstring(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +testarrayofstring(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +testarrayofstringLength():number { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +/** + * an example documentation comment: this will end up in the generated code + * multiline too + */ +testarrayoftables(index: number, obj?:Monster):Monster|null { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? (obj || new Monster()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +testarrayoftablesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +enemy(obj?:Monster):Monster|null { + const offset = this.bb!.__offset(this.bb_pos, 28); + return offset ? (obj || new Monster()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +testnestedflatbuffer(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 30); + return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +testnestedflatbufferLength():number { + const offset = this.bb!.__offset(this.bb_pos, 30); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +testnestedflatbufferArray():Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 30); + return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +testempty(obj?:Stat):Stat|null { + const offset = this.bb!.__offset(this.bb_pos, 32); + return offset ? (obj || new Stat()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +testbool():boolean { + const offset = this.bb!.__offset(this.bb_pos, 34); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_testbool(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 34); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +testhashs32Fnv1():number { + const offset = this.bb!.__offset(this.bb_pos, 36); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_testhashs32_fnv1(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 36); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +testhashu32Fnv1():number { + const offset = this.bb!.__offset(this.bb_pos, 38); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; +} + +mutate_testhashu32_fnv1(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 38); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint32(this.bb_pos + offset, value); + return true; +} + +testhashs64Fnv1():bigint { + const offset = this.bb!.__offset(this.bb_pos, 40); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_testhashs64_fnv1(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 40); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt64(this.bb_pos + offset, value); + return true; +} + +testhashu64Fnv1():bigint { + const offset = this.bb!.__offset(this.bb_pos, 42); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_testhashu64_fnv1(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 42); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +testhashs32Fnv1a():number { + const offset = this.bb!.__offset(this.bb_pos, 44); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_testhashs32_fnv1a(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 44); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +testhashu32Fnv1a():number { + const offset = this.bb!.__offset(this.bb_pos, 46); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; +} + +mutate_testhashu32_fnv1a(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 46); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint32(this.bb_pos + offset, value); + return true; +} + +testhashs64Fnv1a():bigint { + const offset = this.bb!.__offset(this.bb_pos, 48); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_testhashs64_fnv1a(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 48); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt64(this.bb_pos + offset, value); + return true; +} + +testhashu64Fnv1a():bigint { + const offset = this.bb!.__offset(this.bb_pos, 50); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_testhashu64_fnv1a(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 50); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +testarrayofbools(index: number):boolean|null { + const offset = this.bb!.__offset(this.bb_pos, 52); + return offset ? !!this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : false; +} + +testarrayofboolsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 52); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +testarrayofboolsArray():Int8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 52); + return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +testf():number { + const offset = this.bb!.__offset(this.bb_pos, 54); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.14159; +} + +mutate_testf(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 54); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +testf2():number { + const offset = this.bb!.__offset(this.bb_pos, 56); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 3.0; +} + +mutate_testf2(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 56); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +testf3():number { + const offset = this.bb!.__offset(this.bb_pos, 58); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0; +} + +mutate_testf3(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 58); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +testarrayofstring2(index: number):string +testarrayofstring2(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +testarrayofstring2(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 60); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +testarrayofstring2Length():number { + const offset = this.bb!.__offset(this.bb_pos, 60); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +testarrayofsortedstruct(index: number, obj?:Ability):Ability|null { + const offset = this.bb!.__offset(this.bb_pos, 62); + return offset ? (obj || new Ability()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 8, this.bb!) : null; +} + +testarrayofsortedstructLength():number { + const offset = this.bb!.__offset(this.bb_pos, 62); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +flex(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 64); + return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +flexLength():number { + const offset = this.bb!.__offset(this.bb_pos, 64); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +flexArray():Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 64); + return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +test5(index: number, obj?:Test):Test|null { + const offset = this.bb!.__offset(this.bb_pos, 66); + return offset ? (obj || new Test()).__init(this.bb!.__vector(this.bb_pos + offset) + index * 4, this.bb!) : null; +} + +test5Length():number { + const offset = this.bb!.__offset(this.bb_pos, 66); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +vectorOfLongs(index: number):bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 68); + return offset ? this.bb!.readInt64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); +} + +vectorOfLongsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 68); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +vectorOfDoubles(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 70); + return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0; +} + +vectorOfDoublesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 70); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +vectorOfDoublesArray():Float64Array|null { + const offset = this.bb!.__offset(this.bb_pos, 70); + return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +parentNamespaceTest(obj?:InParentNamespace):InParentNamespace|null { + const offset = this.bb!.__offset(this.bb_pos, 72); + return offset ? (obj || new InParentNamespace()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +vectorOfReferrables(index: number, obj?:Referrable):Referrable|null { + const offset = this.bb!.__offset(this.bb_pos, 74); + return offset ? (obj || new Referrable()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +vectorOfReferrablesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 74); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +singleWeakReference():bigint { + const offset = this.bb!.__offset(this.bb_pos, 76); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_single_weak_reference(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 76); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +vectorOfWeakReferences(index: number):bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 78); + return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); +} + +vectorOfWeakReferencesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 78); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +vectorOfStrongReferrables(index: number, obj?:Referrable):Referrable|null { + const offset = this.bb!.__offset(this.bb_pos, 80); + return offset ? (obj || new Referrable()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +vectorOfStrongReferrablesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 80); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +coOwningReference():bigint { + const offset = this.bb!.__offset(this.bb_pos, 82); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_co_owning_reference(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 82); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +vectorOfCoOwningReferences(index: number):bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 84); + return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); +} + +vectorOfCoOwningReferencesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 84); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +nonOwningReference():bigint { + const offset = this.bb!.__offset(this.bb_pos, 86); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_non_owning_reference(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 86); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +vectorOfNonOwningReferences(index: number):bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 88); + return offset ? this.bb!.readUint64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : BigInt(0); +} + +vectorOfNonOwningReferencesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 88); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +anyUniqueType():AnyUniqueAliases { + const offset = this.bb!.__offset(this.bb_pos, 90); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : AnyUniqueAliases.NONE; +} + +anyUnique(obj:any):any|null { + const offset = this.bb!.__offset(this.bb_pos, 92); + return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null; +} + +anyAmbiguousType():AnyAmbiguousAliases { + const offset = this.bb!.__offset(this.bb_pos, 94); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : AnyAmbiguousAliases.NONE; +} + +anyAmbiguous(obj:any):any|null { + const offset = this.bb!.__offset(this.bb_pos, 96); + return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null; +} + +vectorOfEnums(index: number):Color|null { + const offset = this.bb!.__offset(this.bb_pos, 98); + return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +vectorOfEnumsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 98); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +vectorOfEnumsArray():Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 98); + return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +signedEnum():Race { + const offset = this.bb!.__offset(this.bb_pos, 100); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : Race.None; +} + +mutate_signed_enum(value:Race):boolean { + const offset = this.bb!.__offset(this.bb_pos, 100); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, value); + return true; +} + +testrequirednestedflatbuffer(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 102); + return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +testrequirednestedflatbufferLength():number { + const offset = this.bb!.__offset(this.bb_pos, 102); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +testrequirednestedflatbufferArray():Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 102); + return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +scalarKeySortedTables(index: number, obj?:Stat):Stat|null { + const offset = this.bb!.__offset(this.bb_pos, 104); + return offset ? (obj || new Stat()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +scalarKeySortedTablesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 104); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +nativeInline(obj?:Test):Test|null { + const offset = this.bb!.__offset(this.bb_pos, 106); + return offset ? (obj || new Test()).__init(this.bb_pos + offset, this.bb!) : null; +} + +longEnumNonEnumDefault():bigint { + const offset = this.bb!.__offset(this.bb_pos, 108); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_long_enum_non_enum_default(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 108); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +longEnumNormalDefault():bigint { + const offset = this.bb!.__offset(this.bb_pos, 110); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('2'); +} + +mutate_long_enum_normal_default(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 110); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +nanDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 112); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : NaN; +} + +mutate_nan_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 112); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +infDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 114); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : Infinity; +} + +mutate_inf_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 114); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +positiveInfDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 116); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : Infinity; +} + +mutate_positive_inf_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 116); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +infinityDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 118); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : Infinity; +} + +mutate_infinity_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 118); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +positiveInfinityDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 120); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : Infinity; +} + +mutate_positive_infinity_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 120); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +negativeInfDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 122); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : -Infinity; +} + +mutate_negative_inf_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 122); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +negativeInfinityDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 124); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : -Infinity; +} + +mutate_negative_infinity_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 124); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +doubleInfDefault():number { + const offset = this.bb!.__offset(this.bb_pos, 126); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : Infinity; +} + +mutate_double_inf_default(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 126); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat64(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.Monster'; +} + +static startMonster(builder:flatbuffers.Builder) { + builder.startObject(62); +} + +static addPos(builder:flatbuffers.Builder, posOffset:flatbuffers.Offset) { + builder.addFieldStruct(0, posOffset, 0); +} + +static addMana(builder:flatbuffers.Builder, mana:number) { + builder.addFieldInt16(1, mana, 150); +} + +static addHp(builder:flatbuffers.Builder, hp:number) { + builder.addFieldInt16(2, hp, 100); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, nameOffset, 0); +} + +static addInventory(builder:flatbuffers.Builder, inventoryOffset:flatbuffers.Offset) { + builder.addFieldOffset(5, inventoryOffset, 0); +} + +static createInventoryVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startInventoryVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addColor(builder:flatbuffers.Builder, color:Color) { + builder.addFieldInt8(6, color, Color.Blue); +} + +static addTestType(builder:flatbuffers.Builder, testType:Any) { + builder.addFieldInt8(7, testType, Any.NONE); +} + +static addTest(builder:flatbuffers.Builder, testOffset:flatbuffers.Offset) { + builder.addFieldOffset(8, testOffset, 0); +} + +static addTest4(builder:flatbuffers.Builder, test4Offset:flatbuffers.Offset) { + builder.addFieldOffset(9, test4Offset, 0); +} + +static startTest4Vector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 2); +} + +static addTestarrayofstring(builder:flatbuffers.Builder, testarrayofstringOffset:flatbuffers.Offset) { + builder.addFieldOffset(10, testarrayofstringOffset, 0); +} + +static createTestarrayofstringVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startTestarrayofstringVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addTestarrayoftables(builder:flatbuffers.Builder, testarrayoftablesOffset:flatbuffers.Offset) { + builder.addFieldOffset(11, testarrayoftablesOffset, 0); +} + +static createTestarrayoftablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startTestarrayoftablesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addEnemy(builder:flatbuffers.Builder, enemyOffset:flatbuffers.Offset) { + builder.addFieldOffset(12, enemyOffset, 0); +} + +static addTestnestedflatbuffer(builder:flatbuffers.Builder, testnestedflatbufferOffset:flatbuffers.Offset) { + builder.addFieldOffset(13, testnestedflatbufferOffset, 0); +} + +static createTestnestedflatbufferVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startTestnestedflatbufferVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addTestempty(builder:flatbuffers.Builder, testemptyOffset:flatbuffers.Offset) { + builder.addFieldOffset(14, testemptyOffset, 0); +} + +static addTestbool(builder:flatbuffers.Builder, testbool:boolean) { + builder.addFieldInt8(15, +testbool, +false); +} + +static addTesthashs32Fnv1(builder:flatbuffers.Builder, testhashs32Fnv1:number) { + builder.addFieldInt32(16, testhashs32Fnv1, 0); +} + +static addTesthashu32Fnv1(builder:flatbuffers.Builder, testhashu32Fnv1:number) { + builder.addFieldInt32(17, testhashu32Fnv1, 0); +} + +static addTesthashs64Fnv1(builder:flatbuffers.Builder, testhashs64Fnv1:bigint) { + builder.addFieldInt64(18, testhashs64Fnv1, BigInt('0')); +} + +static addTesthashu64Fnv1(builder:flatbuffers.Builder, testhashu64Fnv1:bigint) { + builder.addFieldInt64(19, testhashu64Fnv1, BigInt('0')); +} + +static addTesthashs32Fnv1a(builder:flatbuffers.Builder, testhashs32Fnv1a:number) { + builder.addFieldInt32(20, testhashs32Fnv1a, 0); +} + +static addTesthashu32Fnv1a(builder:flatbuffers.Builder, testhashu32Fnv1a:number) { + builder.addFieldInt32(21, testhashu32Fnv1a, 0); +} + +static addTesthashs64Fnv1a(builder:flatbuffers.Builder, testhashs64Fnv1a:bigint) { + builder.addFieldInt64(22, testhashs64Fnv1a, BigInt('0')); +} + +static addTesthashu64Fnv1a(builder:flatbuffers.Builder, testhashu64Fnv1a:bigint) { + builder.addFieldInt64(23, testhashu64Fnv1a, BigInt('0')); +} + +static addTestarrayofbools(builder:flatbuffers.Builder, testarrayofboolsOffset:flatbuffers.Offset) { + builder.addFieldOffset(24, testarrayofboolsOffset, 0); +} + +static createTestarrayofboolsVector(builder:flatbuffers.Builder, data:boolean[]):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(+data[i]!); + } + return builder.endVector(); +} + +static startTestarrayofboolsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addTestf(builder:flatbuffers.Builder, testf:number) { + builder.addFieldFloat32(25, testf, 3.14159); +} + +static addTestf2(builder:flatbuffers.Builder, testf2:number) { + builder.addFieldFloat32(26, testf2, 3.0); +} + +static addTestf3(builder:flatbuffers.Builder, testf3:number) { + builder.addFieldFloat32(27, testf3, 0.0); +} + +static addTestarrayofstring2(builder:flatbuffers.Builder, testarrayofstring2Offset:flatbuffers.Offset) { + builder.addFieldOffset(28, testarrayofstring2Offset, 0); +} + +static createTestarrayofstring2Vector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startTestarrayofstring2Vector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addTestarrayofsortedstruct(builder:flatbuffers.Builder, testarrayofsortedstructOffset:flatbuffers.Offset) { + builder.addFieldOffset(29, testarrayofsortedstructOffset, 0); +} + +static startTestarrayofsortedstructVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 4); +} + +static addFlex(builder:flatbuffers.Builder, flexOffset:flatbuffers.Offset) { + builder.addFieldOffset(30, flexOffset, 0); +} + +static createFlexVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startFlexVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addTest5(builder:flatbuffers.Builder, test5Offset:flatbuffers.Offset) { + builder.addFieldOffset(31, test5Offset, 0); +} + +static startTest5Vector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 2); +} + +static addVectorOfLongs(builder:flatbuffers.Builder, vectorOfLongsOffset:flatbuffers.Offset) { + builder.addFieldOffset(32, vectorOfLongsOffset, 0); +} + +static createVectorOfLongsVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfLongsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 8); +} + +static addVectorOfDoubles(builder:flatbuffers.Builder, vectorOfDoublesOffset:flatbuffers.Offset) { + builder.addFieldOffset(33, vectorOfDoublesOffset, 0); +} + +static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset; +/** + * @deprecated This Uint8Array overload will be removed in the future. + */ +static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; +static createVectorOfDoublesVector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addFloat64(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfDoublesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 8); +} + +static addParentNamespaceTest(builder:flatbuffers.Builder, parentNamespaceTestOffset:flatbuffers.Offset) { + builder.addFieldOffset(34, parentNamespaceTestOffset, 0); +} + +static addVectorOfReferrables(builder:flatbuffers.Builder, vectorOfReferrablesOffset:flatbuffers.Offset) { + builder.addFieldOffset(35, vectorOfReferrablesOffset, 0); +} + +static createVectorOfReferrablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfReferrablesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addSingleWeakReference(builder:flatbuffers.Builder, singleWeakReference:bigint) { + builder.addFieldInt64(36, singleWeakReference, BigInt('0')); +} + +static addVectorOfWeakReferences(builder:flatbuffers.Builder, vectorOfWeakReferencesOffset:flatbuffers.Offset) { + builder.addFieldOffset(37, vectorOfWeakReferencesOffset, 0); +} + +static createVectorOfWeakReferencesVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfWeakReferencesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 8); +} + +static addVectorOfStrongReferrables(builder:flatbuffers.Builder, vectorOfStrongReferrablesOffset:flatbuffers.Offset) { + builder.addFieldOffset(38, vectorOfStrongReferrablesOffset, 0); +} + +static createVectorOfStrongReferrablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfStrongReferrablesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addCoOwningReference(builder:flatbuffers.Builder, coOwningReference:bigint) { + builder.addFieldInt64(39, coOwningReference, BigInt('0')); +} + +static addVectorOfCoOwningReferences(builder:flatbuffers.Builder, vectorOfCoOwningReferencesOffset:flatbuffers.Offset) { + builder.addFieldOffset(40, vectorOfCoOwningReferencesOffset, 0); +} + +static createVectorOfCoOwningReferencesVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfCoOwningReferencesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 8); +} + +static addNonOwningReference(builder:flatbuffers.Builder, nonOwningReference:bigint) { + builder.addFieldInt64(41, nonOwningReference, BigInt('0')); +} + +static addVectorOfNonOwningReferences(builder:flatbuffers.Builder, vectorOfNonOwningReferencesOffset:flatbuffers.Offset) { + builder.addFieldOffset(42, vectorOfNonOwningReferencesOffset, 0); +} + +static createVectorOfNonOwningReferencesVector(builder:flatbuffers.Builder, data:bigint[]):flatbuffers.Offset { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt64(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfNonOwningReferencesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 8); +} + +static addAnyUniqueType(builder:flatbuffers.Builder, anyUniqueType:AnyUniqueAliases) { + builder.addFieldInt8(43, anyUniqueType, AnyUniqueAliases.NONE); +} + +static addAnyUnique(builder:flatbuffers.Builder, anyUniqueOffset:flatbuffers.Offset) { + builder.addFieldOffset(44, anyUniqueOffset, 0); +} + +static addAnyAmbiguousType(builder:flatbuffers.Builder, anyAmbiguousType:AnyAmbiguousAliases) { + builder.addFieldInt8(45, anyAmbiguousType, AnyAmbiguousAliases.NONE); +} + +static addAnyAmbiguous(builder:flatbuffers.Builder, anyAmbiguousOffset:flatbuffers.Offset) { + builder.addFieldOffset(46, anyAmbiguousOffset, 0); +} + +static addVectorOfEnums(builder:flatbuffers.Builder, vectorOfEnumsOffset:flatbuffers.Offset) { + builder.addFieldOffset(47, vectorOfEnumsOffset, 0); +} + +static createVectorOfEnumsVector(builder:flatbuffers.Builder, data:Color[]):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startVectorOfEnumsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addSignedEnum(builder:flatbuffers.Builder, signedEnum:Race) { + builder.addFieldInt8(48, signedEnum, Race.None); +} + +static addTestrequirednestedflatbuffer(builder:flatbuffers.Builder, testrequirednestedflatbufferOffset:flatbuffers.Offset) { + builder.addFieldOffset(49, testrequirednestedflatbufferOffset, 0); +} + +static createTestrequirednestedflatbufferVector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startTestrequirednestedflatbufferVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addScalarKeySortedTables(builder:flatbuffers.Builder, scalarKeySortedTablesOffset:flatbuffers.Offset) { + builder.addFieldOffset(50, scalarKeySortedTablesOffset, 0); +} + +static createScalarKeySortedTablesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startScalarKeySortedTablesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addNativeInline(builder:flatbuffers.Builder, nativeInlineOffset:flatbuffers.Offset) { + builder.addFieldStruct(51, nativeInlineOffset, 0); +} + +static addLongEnumNonEnumDefault(builder:flatbuffers.Builder, longEnumNonEnumDefault:bigint) { + builder.addFieldInt64(52, longEnumNonEnumDefault, BigInt('0')); +} + +static addLongEnumNormalDefault(builder:flatbuffers.Builder, longEnumNormalDefault:bigint) { + builder.addFieldInt64(53, longEnumNormalDefault, BigInt('2')); +} + +static addNanDefault(builder:flatbuffers.Builder, nanDefault:number) { + builder.addFieldFloat32(54, nanDefault, NaN); +} + +static addInfDefault(builder:flatbuffers.Builder, infDefault:number) { + builder.addFieldFloat32(55, infDefault, Infinity); +} + +static addPositiveInfDefault(builder:flatbuffers.Builder, positiveInfDefault:number) { + builder.addFieldFloat32(56, positiveInfDefault, Infinity); +} + +static addInfinityDefault(builder:flatbuffers.Builder, infinityDefault:number) { + builder.addFieldFloat32(57, infinityDefault, Infinity); +} + +static addPositiveInfinityDefault(builder:flatbuffers.Builder, positiveInfinityDefault:number) { + builder.addFieldFloat32(58, positiveInfinityDefault, Infinity); +} + +static addNegativeInfDefault(builder:flatbuffers.Builder, negativeInfDefault:number) { + builder.addFieldFloat32(59, negativeInfDefault, -Infinity); +} + +static addNegativeInfinityDefault(builder:flatbuffers.Builder, negativeInfinityDefault:number) { + builder.addFieldFloat32(60, negativeInfinityDefault, -Infinity); +} + +static addDoubleInfDefault(builder:flatbuffers.Builder, doubleInfDefault:number) { + builder.addFieldFloat64(61, doubleInfDefault, Infinity); +} + +static endMonster(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 10) // name + return offset; +} + +static finishMonsterBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'MONS'); +} + +static finishSizePrefixedMonsterBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'MONS', true); +} + + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):Monster { + return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): MonsterT { + return new MonsterT( + (this.pos() !== null ? this.pos()!.unpack() : null), + this.mana(), + this.hp(), + this.name(), + this.bb!.createScalarList(this.inventory.bind(this), this.inventoryLength()), + this.color(), + this.testType(), + (() => { + const temp = unionToAny(this.testType(), this.test.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(), + this.bb!.createObjList(this.test4.bind(this), this.test4Length()), + this.bb!.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()), + this.bb!.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()), + (this.enemy() !== null ? this.enemy()!.unpack() : null), + this.bb!.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()), + (this.testempty() !== null ? this.testempty()!.unpack() : null), + this.testbool(), + this.testhashs32Fnv1(), + this.testhashu32Fnv1(), + this.testhashs64Fnv1(), + this.testhashu64Fnv1(), + this.testhashs32Fnv1a(), + this.testhashu32Fnv1a(), + this.testhashs64Fnv1a(), + this.testhashu64Fnv1a(), + this.bb!.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()), + this.testf(), + this.testf2(), + this.testf3(), + this.bb!.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()), + this.bb!.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()), + this.bb!.createScalarList(this.flex.bind(this), this.flexLength()), + this.bb!.createObjList(this.test5.bind(this), this.test5Length()), + this.bb!.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()), + this.bb!.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()), + (this.parentNamespaceTest() !== null ? this.parentNamespaceTest()!.unpack() : null), + this.bb!.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()), + this.singleWeakReference(), + this.bb!.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()), + this.bb!.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()), + this.coOwningReference(), + this.bb!.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()), + this.nonOwningReference(), + this.bb!.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()), + this.anyUniqueType(), + (() => { + const temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(), + this.anyAmbiguousType(), + (() => { + const temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(), + this.bb!.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()), + this.signedEnum(), + this.bb!.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()), + this.bb!.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()), + (this.nativeInline() !== null ? this.nativeInline()!.unpack() : null), + this.longEnumNonEnumDefault(), + this.longEnumNormalDefault(), + this.nanDefault(), + this.infDefault(), + this.positiveInfDefault(), + this.infinityDefault(), + this.positiveInfinityDefault(), + this.negativeInfDefault(), + this.negativeInfinityDefault(), + this.doubleInfDefault() + ); +} + + +unpackTo(_o: MonsterT): void { + _o.pos = (this.pos() !== null ? this.pos()!.unpack() : null); + _o.mana = this.mana(); + _o.hp = this.hp(); + _o.name = this.name(); + _o.inventory = this.bb!.createScalarList(this.inventory.bind(this), this.inventoryLength()); + _o.color = this.color(); + _o.testType = this.testType(); + _o.test = (() => { + const temp = unionToAny(this.testType(), this.test.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(); + _o.test4 = this.bb!.createObjList(this.test4.bind(this), this.test4Length()); + _o.testarrayofstring = this.bb!.createScalarList(this.testarrayofstring.bind(this), this.testarrayofstringLength()); + _o.testarrayoftables = this.bb!.createObjList(this.testarrayoftables.bind(this), this.testarrayoftablesLength()); + _o.enemy = (this.enemy() !== null ? this.enemy()!.unpack() : null); + _o.testnestedflatbuffer = this.bb!.createScalarList(this.testnestedflatbuffer.bind(this), this.testnestedflatbufferLength()); + _o.testempty = (this.testempty() !== null ? this.testempty()!.unpack() : null); + _o.testbool = this.testbool(); + _o.testhashs32Fnv1 = this.testhashs32Fnv1(); + _o.testhashu32Fnv1 = this.testhashu32Fnv1(); + _o.testhashs64Fnv1 = this.testhashs64Fnv1(); + _o.testhashu64Fnv1 = this.testhashu64Fnv1(); + _o.testhashs32Fnv1a = this.testhashs32Fnv1a(); + _o.testhashu32Fnv1a = this.testhashu32Fnv1a(); + _o.testhashs64Fnv1a = this.testhashs64Fnv1a(); + _o.testhashu64Fnv1a = this.testhashu64Fnv1a(); + _o.testarrayofbools = this.bb!.createScalarList(this.testarrayofbools.bind(this), this.testarrayofboolsLength()); + _o.testf = this.testf(); + _o.testf2 = this.testf2(); + _o.testf3 = this.testf3(); + _o.testarrayofstring2 = this.bb!.createScalarList(this.testarrayofstring2.bind(this), this.testarrayofstring2Length()); + _o.testarrayofsortedstruct = this.bb!.createObjList(this.testarrayofsortedstruct.bind(this), this.testarrayofsortedstructLength()); + _o.flex = this.bb!.createScalarList(this.flex.bind(this), this.flexLength()); + _o.test5 = this.bb!.createObjList(this.test5.bind(this), this.test5Length()); + _o.vectorOfLongs = this.bb!.createScalarList(this.vectorOfLongs.bind(this), this.vectorOfLongsLength()); + _o.vectorOfDoubles = this.bb!.createScalarList(this.vectorOfDoubles.bind(this), this.vectorOfDoublesLength()); + _o.parentNamespaceTest = (this.parentNamespaceTest() !== null ? this.parentNamespaceTest()!.unpack() : null); + _o.vectorOfReferrables = this.bb!.createObjList(this.vectorOfReferrables.bind(this), this.vectorOfReferrablesLength()); + _o.singleWeakReference = this.singleWeakReference(); + _o.vectorOfWeakReferences = this.bb!.createScalarList(this.vectorOfWeakReferences.bind(this), this.vectorOfWeakReferencesLength()); + _o.vectorOfStrongReferrables = this.bb!.createObjList(this.vectorOfStrongReferrables.bind(this), this.vectorOfStrongReferrablesLength()); + _o.coOwningReference = this.coOwningReference(); + _o.vectorOfCoOwningReferences = this.bb!.createScalarList(this.vectorOfCoOwningReferences.bind(this), this.vectorOfCoOwningReferencesLength()); + _o.nonOwningReference = this.nonOwningReference(); + _o.vectorOfNonOwningReferences = this.bb!.createScalarList(this.vectorOfNonOwningReferences.bind(this), this.vectorOfNonOwningReferencesLength()); + _o.anyUniqueType = this.anyUniqueType(); + _o.anyUnique = (() => { + const temp = unionToAnyUniqueAliases(this.anyUniqueType(), this.anyUnique.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(); + _o.anyAmbiguousType = this.anyAmbiguousType(); + _o.anyAmbiguous = (() => { + const temp = unionToAnyAmbiguousAliases(this.anyAmbiguousType(), this.anyAmbiguous.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(); + _o.vectorOfEnums = this.bb!.createScalarList(this.vectorOfEnums.bind(this), this.vectorOfEnumsLength()); + _o.signedEnum = this.signedEnum(); + _o.testrequirednestedflatbuffer = this.bb!.createScalarList(this.testrequirednestedflatbuffer.bind(this), this.testrequirednestedflatbufferLength()); + _o.scalarKeySortedTables = this.bb!.createObjList(this.scalarKeySortedTables.bind(this), this.scalarKeySortedTablesLength()); + _o.nativeInline = (this.nativeInline() !== null ? this.nativeInline()!.unpack() : null); + _o.longEnumNonEnumDefault = this.longEnumNonEnumDefault(); + _o.longEnumNormalDefault = this.longEnumNormalDefault(); + _o.nanDefault = this.nanDefault(); + _o.infDefault = this.infDefault(); + _o.positiveInfDefault = this.positiveInfDefault(); + _o.infinityDefault = this.infinityDefault(); + _o.positiveInfinityDefault = this.positiveInfinityDefault(); + _o.negativeInfDefault = this.negativeInfDefault(); + _o.negativeInfinityDefault = this.negativeInfinityDefault(); + _o.doubleInfDefault = this.doubleInfDefault(); +} +} + +export class MonsterT implements flatbuffers.IGeneratedObject { +constructor( + public pos: Vec3T|null = null, + public mana: number = 150, + public hp: number = 100, + public name: string|Uint8Array|null = null, + public inventory: (number)[] = [], + public color: Color = Color.Blue, + public testType: Any = Any.NONE, + public test: MonsterT|MyGame_Example2_MonsterT|TestSimpleTableWithEnumT|null = null, + public test4: (TestT)[] = [], + public testarrayofstring: (string)[] = [], + public testarrayoftables: (MonsterT)[] = [], + public enemy: MonsterT|null = null, + public testnestedflatbuffer: (number)[] = [], + public testempty: StatT|null = null, + public testbool: boolean = false, + public testhashs32Fnv1: number = 0, + public testhashu32Fnv1: number = 0, + public testhashs64Fnv1: bigint = BigInt('0'), + public testhashu64Fnv1: bigint = BigInt('0'), + public testhashs32Fnv1a: number = 0, + public testhashu32Fnv1a: number = 0, + public testhashs64Fnv1a: bigint = BigInt('0'), + public testhashu64Fnv1a: bigint = BigInt('0'), + public testarrayofbools: (boolean)[] = [], + public testf: number = 3.14159, + public testf2: number = 3.0, + public testf3: number = 0.0, + public testarrayofstring2: (string)[] = [], + public testarrayofsortedstruct: (AbilityT)[] = [], + public flex: (number)[] = [], + public test5: (TestT)[] = [], + public vectorOfLongs: (bigint)[] = [], + public vectorOfDoubles: (number)[] = [], + public parentNamespaceTest: InParentNamespaceT|null = null, + public vectorOfReferrables: (ReferrableT)[] = [], + public singleWeakReference: bigint = BigInt('0'), + public vectorOfWeakReferences: (bigint)[] = [], + public vectorOfStrongReferrables: (ReferrableT)[] = [], + public coOwningReference: bigint = BigInt('0'), + public vectorOfCoOwningReferences: (bigint)[] = [], + public nonOwningReference: bigint = BigInt('0'), + public vectorOfNonOwningReferences: (bigint)[] = [], + public anyUniqueType: AnyUniqueAliases = AnyUniqueAliases.NONE, + public anyUnique: MonsterT|MyGame_Example2_MonsterT|TestSimpleTableWithEnumT|null = null, + public anyAmbiguousType: AnyAmbiguousAliases = AnyAmbiguousAliases.NONE, + public anyAmbiguous: MonsterT|null = null, + public vectorOfEnums: (Color)[] = [], + public signedEnum: Race = Race.None, + public testrequirednestedflatbuffer: (number)[] = [], + public scalarKeySortedTables: (StatT)[] = [], + public nativeInline: TestT|null = null, + public longEnumNonEnumDefault: bigint = BigInt('0'), + public longEnumNormalDefault: bigint = BigInt('2'), + public nanDefault: number = NaN, + public infDefault: number = Infinity, + public positiveInfDefault: number = Infinity, + public infinityDefault: number = Infinity, + public positiveInfinityDefault: number = Infinity, + public negativeInfDefault: number = -Infinity, + public negativeInfinityDefault: number = -Infinity, + public doubleInfDefault: number = Infinity +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const inventory = Monster.createInventoryVector(builder, this.inventory); + const test = builder.createObjectOffset(this.test); + const test4 = builder.createStructOffsetList(this.test4, Monster.startTest4Vector); + const testarrayofstring = Monster.createTestarrayofstringVector(builder, builder.createObjectOffsetList(this.testarrayofstring)); + const testarrayoftables = Monster.createTestarrayoftablesVector(builder, builder.createObjectOffsetList(this.testarrayoftables)); + const enemy = (this.enemy !== null ? this.enemy!.pack(builder) : 0); + const testnestedflatbuffer = Monster.createTestnestedflatbufferVector(builder, this.testnestedflatbuffer); + const testempty = (this.testempty !== null ? this.testempty!.pack(builder) : 0); + const testarrayofbools = Monster.createTestarrayofboolsVector(builder, this.testarrayofbools); + const testarrayofstring2 = Monster.createTestarrayofstring2Vector(builder, builder.createObjectOffsetList(this.testarrayofstring2)); + const testarrayofsortedstruct = builder.createStructOffsetList(this.testarrayofsortedstruct, Monster.startTestarrayofsortedstructVector); + const flex = Monster.createFlexVector(builder, this.flex); + const test5 = builder.createStructOffsetList(this.test5, Monster.startTest5Vector); + const vectorOfLongs = Monster.createVectorOfLongsVector(builder, this.vectorOfLongs); + const vectorOfDoubles = Monster.createVectorOfDoublesVector(builder, this.vectorOfDoubles); + const parentNamespaceTest = (this.parentNamespaceTest !== null ? this.parentNamespaceTest!.pack(builder) : 0); + const vectorOfReferrables = Monster.createVectorOfReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfReferrables)); + const vectorOfWeakReferences = Monster.createVectorOfWeakReferencesVector(builder, this.vectorOfWeakReferences); + const vectorOfStrongReferrables = Monster.createVectorOfStrongReferrablesVector(builder, builder.createObjectOffsetList(this.vectorOfStrongReferrables)); + const vectorOfCoOwningReferences = Monster.createVectorOfCoOwningReferencesVector(builder, this.vectorOfCoOwningReferences); + const vectorOfNonOwningReferences = Monster.createVectorOfNonOwningReferencesVector(builder, this.vectorOfNonOwningReferences); + const anyUnique = builder.createObjectOffset(this.anyUnique); + const anyAmbiguous = builder.createObjectOffset(this.anyAmbiguous); + const vectorOfEnums = Monster.createVectorOfEnumsVector(builder, this.vectorOfEnums); + const testrequirednestedflatbuffer = Monster.createTestrequirednestedflatbufferVector(builder, this.testrequirednestedflatbuffer); + const scalarKeySortedTables = Monster.createScalarKeySortedTablesVector(builder, builder.createObjectOffsetList(this.scalarKeySortedTables)); + + Monster.startMonster(builder); + Monster.addPos(builder, (this.pos !== null ? this.pos!.pack(builder) : 0)); + Monster.addMana(builder, this.mana); + Monster.addHp(builder, this.hp); + Monster.addName(builder, name); + Monster.addInventory(builder, inventory); + Monster.addColor(builder, this.color); + Monster.addTestType(builder, this.testType); + Monster.addTest(builder, test); + Monster.addTest4(builder, test4); + Monster.addTestarrayofstring(builder, testarrayofstring); + Monster.addTestarrayoftables(builder, testarrayoftables); + Monster.addEnemy(builder, enemy); + Monster.addTestnestedflatbuffer(builder, testnestedflatbuffer); + Monster.addTestempty(builder, testempty); + Monster.addTestbool(builder, this.testbool); + Monster.addTesthashs32Fnv1(builder, this.testhashs32Fnv1); + Monster.addTesthashu32Fnv1(builder, this.testhashu32Fnv1); + Monster.addTesthashs64Fnv1(builder, this.testhashs64Fnv1); + Monster.addTesthashu64Fnv1(builder, this.testhashu64Fnv1); + Monster.addTesthashs32Fnv1a(builder, this.testhashs32Fnv1a); + Monster.addTesthashu32Fnv1a(builder, this.testhashu32Fnv1a); + Monster.addTesthashs64Fnv1a(builder, this.testhashs64Fnv1a); + Monster.addTesthashu64Fnv1a(builder, this.testhashu64Fnv1a); + Monster.addTestarrayofbools(builder, testarrayofbools); + Monster.addTestf(builder, this.testf); + Monster.addTestf2(builder, this.testf2); + Monster.addTestf3(builder, this.testf3); + Monster.addTestarrayofstring2(builder, testarrayofstring2); + Monster.addTestarrayofsortedstruct(builder, testarrayofsortedstruct); + Monster.addFlex(builder, flex); + Monster.addTest5(builder, test5); + Monster.addVectorOfLongs(builder, vectorOfLongs); + Monster.addVectorOfDoubles(builder, vectorOfDoubles); + Monster.addParentNamespaceTest(builder, parentNamespaceTest); + Monster.addVectorOfReferrables(builder, vectorOfReferrables); + Monster.addSingleWeakReference(builder, this.singleWeakReference); + Monster.addVectorOfWeakReferences(builder, vectorOfWeakReferences); + Monster.addVectorOfStrongReferrables(builder, vectorOfStrongReferrables); + Monster.addCoOwningReference(builder, this.coOwningReference); + Monster.addVectorOfCoOwningReferences(builder, vectorOfCoOwningReferences); + Monster.addNonOwningReference(builder, this.nonOwningReference); + Monster.addVectorOfNonOwningReferences(builder, vectorOfNonOwningReferences); + Monster.addAnyUniqueType(builder, this.anyUniqueType); + Monster.addAnyUnique(builder, anyUnique); + Monster.addAnyAmbiguousType(builder, this.anyAmbiguousType); + Monster.addAnyAmbiguous(builder, anyAmbiguous); + Monster.addVectorOfEnums(builder, vectorOfEnums); + Monster.addSignedEnum(builder, this.signedEnum); + Monster.addTestrequirednestedflatbuffer(builder, testrequirednestedflatbuffer); + Monster.addScalarKeySortedTables(builder, scalarKeySortedTables); + Monster.addNativeInline(builder, (this.nativeInline !== null ? this.nativeInline!.pack(builder) : 0)); + Monster.addLongEnumNonEnumDefault(builder, this.longEnumNonEnumDefault); + Monster.addLongEnumNormalDefault(builder, this.longEnumNormalDefault); + Monster.addNanDefault(builder, this.nanDefault); + Monster.addInfDefault(builder, this.infDefault); + Monster.addPositiveInfDefault(builder, this.positiveInfDefault); + Monster.addInfinityDefault(builder, this.infinityDefault); + Monster.addPositiveInfinityDefault(builder, this.positiveInfinityDefault); + Monster.addNegativeInfDefault(builder, this.negativeInfDefault); + Monster.addNegativeInfinityDefault(builder, this.negativeInfinityDefault); + Monster.addDoubleInfDefault(builder, this.doubleInfDefault); + + return Monster.endMonster(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/race.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/race.d.ts new file mode 100644 index 00000000000..393807db471 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/race.d.ts @@ -0,0 +1,6 @@ +export declare enum Race { + None = -1, + Human = 0, + Dwarf = 1, + Elf = 2 +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/race.js b/third_party/flatbuffers/tests/ts/my-game/example/race.js new file mode 100644 index 00000000000..26f54c5152b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/race.js @@ -0,0 +1,9 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var Race; +(function (Race) { + Race[Race["None"] = -1] = "None"; + Race[Race["Human"] = 0] = "Human"; + Race[Race["Dwarf"] = 1] = "Dwarf"; + Race[Race["Elf"] = 2] = "Elf"; +})(Race || (Race = {})); diff --git a/third_party/flatbuffers/tests/ts/my-game/example/race.ts b/third_party/flatbuffers/tests/ts/my-game/example/race.ts new file mode 100644 index 00000000000..ef009e5498e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/race.ts @@ -0,0 +1,10 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum Race { + None = -1, + Human = 0, + Dwarf = 1, + Elf = 2 +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/referrable.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/referrable.d.ts new file mode 100644 index 00000000000..e1967fd8830 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/referrable.d.ts @@ -0,0 +1,24 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Referrable implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Referrable; + static getRootAsReferrable(bb: flatbuffers.ByteBuffer, obj?: Referrable): Referrable; + static getSizePrefixedRootAsReferrable(bb: flatbuffers.ByteBuffer, obj?: Referrable): Referrable; + id(): bigint; + mutate_id(value: bigint): boolean; + static getFullyQualifiedName(): string; + static startReferrable(builder: flatbuffers.Builder): void; + static addId(builder: flatbuffers.Builder, id: bigint): void; + static endReferrable(builder: flatbuffers.Builder): flatbuffers.Offset; + static createReferrable(builder: flatbuffers.Builder, id: bigint): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): Referrable; + unpack(): ReferrableT; + unpackTo(_o: ReferrableT): void; +} +export declare class ReferrableT implements flatbuffers.IGeneratedObject { + id: bigint; + constructor(id?: bigint); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/referrable.js b/third_party/flatbuffers/tests/ts/my-game/example/referrable.js new file mode 100644 index 00000000000..e37d9b7c362 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/referrable.js @@ -0,0 +1,71 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class Referrable { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsReferrable(bb, obj) { + return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsReferrable(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + id() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_id(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.Example.Referrable'; + } + static startReferrable(builder) { + builder.startObject(1); + } + static addId(builder, id) { + builder.addFieldInt64(0, id, BigInt('0')); + } + static endReferrable(builder) { + const offset = builder.endObject(); + return offset; + } + static createReferrable(builder, id) { + Referrable.startReferrable(builder); + Referrable.addId(builder, id); + return Referrable.endReferrable(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return Referrable.getRootAsReferrable(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new ReferrableT(this.id()); + } + unpackTo(_o) { + _o.id = this.id(); + } +} +export class ReferrableT { + constructor(id = BigInt('0')) { + this.id = id; + } + pack(builder) { + return Referrable.createReferrable(builder, this.id); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/referrable.ts b/third_party/flatbuffers/tests/ts/my-game/example/referrable.ts new file mode 100644 index 00000000000..02d8cb1b531 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/referrable.ts @@ -0,0 +1,97 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Referrable implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Referrable { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsReferrable(bb:flatbuffers.ByteBuffer, obj?:Referrable):Referrable { + return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsReferrable(bb:flatbuffers.ByteBuffer, obj?:Referrable):Referrable { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Referrable()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +id():bigint { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_id(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.Referrable'; +} + +static startReferrable(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addId(builder:flatbuffers.Builder, id:bigint) { + builder.addFieldInt64(0, id, BigInt('0')); +} + +static endReferrable(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createReferrable(builder:flatbuffers.Builder, id:bigint):flatbuffers.Offset { + Referrable.startReferrable(builder); + Referrable.addId(builder, id); + return Referrable.endReferrable(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):Referrable { + return Referrable.getRootAsReferrable(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): ReferrableT { + return new ReferrableT( + this.id() + ); +} + + +unpackTo(_o: ReferrableT): void { + _o.id = this.id(); +} +} + +export class ReferrableT implements flatbuffers.IGeneratedObject { +constructor( + public id: bigint = BigInt('0') +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Referrable.createReferrable(builder, + this.id + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/stat.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/stat.d.ts new file mode 100644 index 00000000000..9ccb1aa48e0 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/stat.d.ts @@ -0,0 +1,32 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Stat implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Stat; + static getRootAsStat(bb: flatbuffers.ByteBuffer, obj?: Stat): Stat; + static getSizePrefixedRootAsStat(bb: flatbuffers.ByteBuffer, obj?: Stat): Stat; + id(): string | null; + id(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + val(): bigint; + mutate_val(value: bigint): boolean; + count(): number; + mutate_count(value: number): boolean; + static getFullyQualifiedName(): string; + static startStat(builder: flatbuffers.Builder): void; + static addId(builder: flatbuffers.Builder, idOffset: flatbuffers.Offset): void; + static addVal(builder: flatbuffers.Builder, val: bigint): void; + static addCount(builder: flatbuffers.Builder, count: number): void; + static endStat(builder: flatbuffers.Builder): flatbuffers.Offset; + static createStat(builder: flatbuffers.Builder, idOffset: flatbuffers.Offset, val: bigint, count: number): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): Stat; + unpack(): StatT; + unpackTo(_o: StatT): void; +} +export declare class StatT implements flatbuffers.IGeneratedObject { + id: string | Uint8Array | null; + val: bigint; + count: number; + constructor(id?: string | Uint8Array | null, val?: bigint, count?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/stat.js b/third_party/flatbuffers/tests/ts/my-game/example/stat.js new file mode 100644 index 00000000000..8c168690333 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/stat.js @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class Stat { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsStat(bb, obj) { + return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsStat(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + id(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + val() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + mutate_val(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + count() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_count(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.Example.Stat'; + } + static startStat(builder) { + builder.startObject(3); + } + static addId(builder, idOffset) { + builder.addFieldOffset(0, idOffset, 0); + } + static addVal(builder, val) { + builder.addFieldInt64(1, val, BigInt('0')); + } + static addCount(builder, count) { + builder.addFieldInt16(2, count, 0); + } + static endStat(builder) { + const offset = builder.endObject(); + return offset; + } + static createStat(builder, idOffset, val, count) { + Stat.startStat(builder); + Stat.addId(builder, idOffset); + Stat.addVal(builder, val); + Stat.addCount(builder, count); + return Stat.endStat(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new StatT(this.id(), this.val(), this.count()); + } + unpackTo(_o) { + _o.id = this.id(); + _o.val = this.val(); + _o.count = this.count(); + } +} +export class StatT { + constructor(id = null, val = BigInt('0'), count = 0) { + this.id = id; + this.val = val; + this.count = count; + } + pack(builder) { + const id = (this.id !== null ? builder.createString(this.id) : 0); + return Stat.createStat(builder, id, this.val, this.count); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/stat.ts b/third_party/flatbuffers/tests/ts/my-game/example/stat.ts new file mode 100644 index 00000000000..00b8845f6a2 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/stat.ts @@ -0,0 +1,140 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Stat implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Stat { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsStat(bb:flatbuffers.ByteBuffer, obj?:Stat):Stat { + return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsStat(bb:flatbuffers.ByteBuffer, obj?:Stat):Stat { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Stat()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +id():string|null +id(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +id(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +val():bigint { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_val(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt64(this.bb_pos + offset, value); + return true; +} + +count():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +mutate_count(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint16(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.Stat'; +} + +static startStat(builder:flatbuffers.Builder) { + builder.startObject(3); +} + +static addId(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, idOffset, 0); +} + +static addVal(builder:flatbuffers.Builder, val:bigint) { + builder.addFieldInt64(1, val, BigInt('0')); +} + +static addCount(builder:flatbuffers.Builder, count:number) { + builder.addFieldInt16(2, count, 0); +} + +static endStat(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createStat(builder:flatbuffers.Builder, idOffset:flatbuffers.Offset, val:bigint, count:number):flatbuffers.Offset { + Stat.startStat(builder); + Stat.addId(builder, idOffset); + Stat.addVal(builder, val); + Stat.addCount(builder, count); + return Stat.endStat(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):Stat { + return Stat.getRootAsStat(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): StatT { + return new StatT( + this.id(), + this.val(), + this.count() + ); +} + + +unpackTo(_o: StatT): void { + _o.id = this.id(); + _o.val = this.val(); + _o.count = this.count(); +} +} + +export class StatT implements flatbuffers.IGeneratedObject { +constructor( + public id: string|Uint8Array|null = null, + public val: bigint = BigInt('0'), + public count: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const id = (this.id !== null ? builder.createString(this.id!) : 0); + + return Stat.createStat(builder, + id, + this.val, + this.count + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.d.ts new file mode 100644 index 00000000000..bd676b7c7c5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.d.ts @@ -0,0 +1,18 @@ +import * as flatbuffers from 'flatbuffers'; +import { StructOfStructs, StructOfStructsT } from '../../my-game/example/struct-of-structs.js'; +export declare class StructOfStructsOfStructs implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): StructOfStructsOfStructs; + a(obj?: StructOfStructs): StructOfStructs | null; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createStructOfStructsOfStructs(builder: flatbuffers.Builder, a_a_id: number, a_a_distance: number, a_b_a: number, a_b_b: number, a_c_id: number, a_c_distance: number): flatbuffers.Offset; + unpack(): StructOfStructsOfStructsT; + unpackTo(_o: StructOfStructsOfStructsT): void; +} +export declare class StructOfStructsOfStructsT implements flatbuffers.IGeneratedObject { + a: StructOfStructsT | null; + constructor(a?: StructOfStructsT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.js b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.js new file mode 100644 index 00000000000..0fc45ae160f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.js @@ -0,0 +1,51 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import { StructOfStructs } from '../../my-game/example/struct-of-structs.js'; +export class StructOfStructsOfStructs { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a(obj) { + return (obj || new StructOfStructs()).__init(this.bb_pos, this.bb); + } + static getFullyQualifiedName() { + return 'MyGame.Example.StructOfStructsOfStructs'; + } + static sizeOf() { + return 20; + } + static createStructOfStructsOfStructs(builder, a_a_id, a_a_distance, a_b_a, a_b_b, a_c_id, a_c_distance) { + builder.prep(4, 20); + builder.prep(4, 20); + builder.prep(4, 8); + builder.writeInt32(a_c_distance); + builder.writeInt32(a_c_id); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(a_b_b); + builder.writeInt16(a_b_a); + builder.prep(4, 8); + builder.writeInt32(a_a_distance); + builder.writeInt32(a_a_id); + return builder.offset(); + } + unpack() { + return new StructOfStructsOfStructsT((this.a() !== null ? this.a().unpack() : null)); + } + unpackTo(_o) { + _o.a = (this.a() !== null ? this.a().unpack() : null); + } +} +export class StructOfStructsOfStructsT { + constructor(a = null) { + this.a = a; + } + pack(builder) { + return StructOfStructsOfStructs.createStructOfStructsOfStructs(builder, (this.a?.a?.id ?? 0), (this.a?.a?.distance ?? 0), (this.a?.b?.a ?? 0), (this.a?.b?.b ?? 0), (this.a?.c?.id ?? 0), (this.a?.c?.distance ?? 0)); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.ts b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.ts new file mode 100644 index 00000000000..05bc63d528b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs-of-structs.ts @@ -0,0 +1,76 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { StructOfStructs, StructOfStructsT } from '../../my-game/example/struct-of-structs.js'; + + +export class StructOfStructsOfStructs implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):StructOfStructsOfStructs { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a(obj?:StructOfStructs):StructOfStructs|null { + return (obj || new StructOfStructs()).__init(this.bb_pos, this.bb!); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.StructOfStructsOfStructs'; +} + +static sizeOf():number { + return 20; +} + +static createStructOfStructsOfStructs(builder:flatbuffers.Builder, a_a_id: number, a_a_distance: number, a_b_a: number, a_b_b: number, a_c_id: number, a_c_distance: number):flatbuffers.Offset { + builder.prep(4, 20); + builder.prep(4, 20); + builder.prep(4, 8); + builder.writeInt32(a_c_distance); + builder.writeInt32(a_c_id); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(a_b_b); + builder.writeInt16(a_b_a); + builder.prep(4, 8); + builder.writeInt32(a_a_distance); + builder.writeInt32(a_a_id); + return builder.offset(); +} + + +unpack(): StructOfStructsOfStructsT { + return new StructOfStructsOfStructsT( + (this.a() !== null ? this.a()!.unpack() : null) + ); +} + + +unpackTo(_o: StructOfStructsOfStructsT): void { + _o.a = (this.a() !== null ? this.a()!.unpack() : null); +} +} + +export class StructOfStructsOfStructsT implements flatbuffers.IGeneratedObject { +constructor( + public a: StructOfStructsT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return StructOfStructsOfStructs.createStructOfStructsOfStructs(builder, + (this.a?.a?.id ?? 0), + (this.a?.a?.distance ?? 0), + (this.a?.b?.a ?? 0), + (this.a?.b?.b ?? 0), + (this.a?.c?.id ?? 0), + (this.a?.c?.distance ?? 0) + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.d.ts new file mode 100644 index 00000000000..cb299c4d2cc --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.d.ts @@ -0,0 +1,23 @@ +import * as flatbuffers from 'flatbuffers'; +import { Ability, AbilityT } from '../../my-game/example/ability.js'; +import { Test, TestT } from '../../my-game/example/test.js'; +export declare class StructOfStructs implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): StructOfStructs; + a(obj?: Ability): Ability | null; + b(obj?: Test): Test | null; + c(obj?: Ability): Ability | null; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createStructOfStructs(builder: flatbuffers.Builder, a_id: number, a_distance: number, b_a: number, b_b: number, c_id: number, c_distance: number): flatbuffers.Offset; + unpack(): StructOfStructsT; + unpackTo(_o: StructOfStructsT): void; +} +export declare class StructOfStructsT implements flatbuffers.IGeneratedObject { + a: AbilityT | null; + b: TestT | null; + c: AbilityT | null; + constructor(a?: AbilityT | null, b?: TestT | null, c?: AbilityT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.js b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.js new file mode 100644 index 00000000000..1f41f85a8b0 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.js @@ -0,0 +1,61 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import { Ability } from '../../my-game/example/ability.js'; +import { Test } from '../../my-game/example/test.js'; +export class StructOfStructs { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a(obj) { + return (obj || new Ability()).__init(this.bb_pos, this.bb); + } + b(obj) { + return (obj || new Test()).__init(this.bb_pos + 8, this.bb); + } + c(obj) { + return (obj || new Ability()).__init(this.bb_pos + 12, this.bb); + } + static getFullyQualifiedName() { + return 'MyGame.Example.StructOfStructs'; + } + static sizeOf() { + return 20; + } + static createStructOfStructs(builder, a_id, a_distance, b_a, b_b, c_id, c_distance) { + builder.prep(4, 20); + builder.prep(4, 8); + builder.writeInt32(c_distance); + builder.writeInt32(c_id); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(b_b); + builder.writeInt16(b_a); + builder.prep(4, 8); + builder.writeInt32(a_distance); + builder.writeInt32(a_id); + return builder.offset(); + } + unpack() { + return new StructOfStructsT((this.a() !== null ? this.a().unpack() : null), (this.b() !== null ? this.b().unpack() : null), (this.c() !== null ? this.c().unpack() : null)); + } + unpackTo(_o) { + _o.a = (this.a() !== null ? this.a().unpack() : null); + _o.b = (this.b() !== null ? this.b().unpack() : null); + _o.c = (this.c() !== null ? this.c().unpack() : null); + } +} +export class StructOfStructsT { + constructor(a = null, b = null, c = null) { + this.a = a; + this.b = b; + this.c = c; + } + pack(builder) { + return StructOfStructs.createStructOfStructs(builder, (this.a?.id ?? 0), (this.a?.distance ?? 0), (this.b?.a ?? 0), (this.b?.b ?? 0), (this.c?.id ?? 0), (this.c?.distance ?? 0)); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.ts b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.ts new file mode 100644 index 00000000000..e1fd746c050 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/struct-of-structs.ts @@ -0,0 +1,90 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Ability, AbilityT } from '../../my-game/example/ability.js'; +import { Test, TestT } from '../../my-game/example/test.js'; + + +export class StructOfStructs implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):StructOfStructs { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a(obj?:Ability):Ability|null { + return (obj || new Ability()).__init(this.bb_pos, this.bb!); +} + +b(obj?:Test):Test|null { + return (obj || new Test()).__init(this.bb_pos + 8, this.bb!); +} + +c(obj?:Ability):Ability|null { + return (obj || new Ability()).__init(this.bb_pos + 12, this.bb!); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.StructOfStructs'; +} + +static sizeOf():number { + return 20; +} + +static createStructOfStructs(builder:flatbuffers.Builder, a_id: number, a_distance: number, b_a: number, b_b: number, c_id: number, c_distance: number):flatbuffers.Offset { + builder.prep(4, 20); + builder.prep(4, 8); + builder.writeInt32(c_distance); + builder.writeInt32(c_id); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(b_b); + builder.writeInt16(b_a); + builder.prep(4, 8); + builder.writeInt32(a_distance); + builder.writeInt32(a_id); + return builder.offset(); +} + + +unpack(): StructOfStructsT { + return new StructOfStructsT( + (this.a() !== null ? this.a()!.unpack() : null), + (this.b() !== null ? this.b()!.unpack() : null), + (this.c() !== null ? this.c()!.unpack() : null) + ); +} + + +unpackTo(_o: StructOfStructsT): void { + _o.a = (this.a() !== null ? this.a()!.unpack() : null); + _o.b = (this.b() !== null ? this.b()!.unpack() : null); + _o.c = (this.c() !== null ? this.c()!.unpack() : null); +} +} + +export class StructOfStructsT implements flatbuffers.IGeneratedObject { +constructor( + public a: AbilityT|null = null, + public b: TestT|null = null, + public c: AbilityT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return StructOfStructs.createStructOfStructs(builder, + (this.a?.id ?? 0), + (this.a?.distance ?? 0), + (this.b?.a ?? 0), + (this.b?.b ?? 0), + (this.c?.id ?? 0), + (this.c?.distance ?? 0) + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.d.ts new file mode 100644 index 00000000000..7a3f6905c3e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.d.ts @@ -0,0 +1,25 @@ +import * as flatbuffers from 'flatbuffers'; +import { Color } from '../../my-game/example/color.js'; +export declare class TestSimpleTableWithEnum implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): TestSimpleTableWithEnum; + static getRootAsTestSimpleTableWithEnum(bb: flatbuffers.ByteBuffer, obj?: TestSimpleTableWithEnum): TestSimpleTableWithEnum; + static getSizePrefixedRootAsTestSimpleTableWithEnum(bb: flatbuffers.ByteBuffer, obj?: TestSimpleTableWithEnum): TestSimpleTableWithEnum; + color(): Color; + mutate_color(value: Color): boolean; + static getFullyQualifiedName(): string; + static startTestSimpleTableWithEnum(builder: flatbuffers.Builder): void; + static addColor(builder: flatbuffers.Builder, color: Color): void; + static endTestSimpleTableWithEnum(builder: flatbuffers.Builder): flatbuffers.Offset; + static createTestSimpleTableWithEnum(builder: flatbuffers.Builder, color: Color): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): TestSimpleTableWithEnum; + unpack(): TestSimpleTableWithEnumT; + unpackTo(_o: TestSimpleTableWithEnumT): void; +} +export declare class TestSimpleTableWithEnumT implements flatbuffers.IGeneratedObject { + color: Color; + constructor(color?: Color); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.js b/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.js new file mode 100644 index 00000000000..b4e0cfb3160 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.js @@ -0,0 +1,72 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { Color } from '../../my-game/example/color.js'; +export class TestSimpleTableWithEnum { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTestSimpleTableWithEnum(bb, obj) { + return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTestSimpleTableWithEnum(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + color() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Color.Green; + } + mutate_color(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeUint8(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.Example.TestSimpleTableWithEnum'; + } + static startTestSimpleTableWithEnum(builder) { + builder.startObject(1); + } + static addColor(builder, color) { + builder.addFieldInt8(0, color, Color.Green); + } + static endTestSimpleTableWithEnum(builder) { + const offset = builder.endObject(); + return offset; + } + static createTestSimpleTableWithEnum(builder, color) { + TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder); + TestSimpleTableWithEnum.addColor(builder, color); + return TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new TestSimpleTableWithEnumT(this.color()); + } + unpackTo(_o) { + _o.color = this.color(); + } +} +export class TestSimpleTableWithEnumT { + constructor(color = Color.Green) { + this.color = color; + } + pack(builder) { + return TestSimpleTableWithEnum.createTestSimpleTableWithEnum(builder, this.color); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.ts b/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.ts new file mode 100644 index 00000000000..ef6fa5d8348 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/test-simple-table-with-enum.ts @@ -0,0 +1,98 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Color } from '../../my-game/example/color.js'; + + +export class TestSimpleTableWithEnum implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):TestSimpleTableWithEnum { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsTestSimpleTableWithEnum(bb:flatbuffers.ByteBuffer, obj?:TestSimpleTableWithEnum):TestSimpleTableWithEnum { + return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsTestSimpleTableWithEnum(bb:flatbuffers.ByteBuffer, obj?:TestSimpleTableWithEnum):TestSimpleTableWithEnum { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TestSimpleTableWithEnum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +color():Color { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : Color.Green; +} + +mutate_color(value:Color):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint8(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.TestSimpleTableWithEnum'; +} + +static startTestSimpleTableWithEnum(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addColor(builder:flatbuffers.Builder, color:Color) { + builder.addFieldInt8(0, color, Color.Green); +} + +static endTestSimpleTableWithEnum(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createTestSimpleTableWithEnum(builder:flatbuffers.Builder, color:Color):flatbuffers.Offset { + TestSimpleTableWithEnum.startTestSimpleTableWithEnum(builder); + TestSimpleTableWithEnum.addColor(builder, color); + return TestSimpleTableWithEnum.endTestSimpleTableWithEnum(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):TestSimpleTableWithEnum { + return TestSimpleTableWithEnum.getRootAsTestSimpleTableWithEnum(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): TestSimpleTableWithEnumT { + return new TestSimpleTableWithEnumT( + this.color() + ); +} + + +unpackTo(_o: TestSimpleTableWithEnumT): void { + _o.color = this.color(); +} +} + +export class TestSimpleTableWithEnumT implements flatbuffers.IGeneratedObject { +constructor( + public color: Color = Color.Green +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return TestSimpleTableWithEnum.createTestSimpleTableWithEnum(builder, + this.color + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/test.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/test.d.ts new file mode 100644 index 00000000000..98764dcf7ba --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/test.d.ts @@ -0,0 +1,21 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Test implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Test; + a(): number; + mutate_a(value: number): boolean; + b(): number; + mutate_b(value: number): boolean; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createTest(builder: flatbuffers.Builder, a: number, b: number): flatbuffers.Offset; + unpack(): TestT; + unpackTo(_o: TestT): void; +} +export declare class TestT implements flatbuffers.IGeneratedObject { + a: number; + b: number; + constructor(a?: number, b?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/test.js b/third_party/flatbuffers/tests/ts/my-game/example/test.js new file mode 100644 index 00000000000..ba6ebfb7af6 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/test.js @@ -0,0 +1,55 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class Test { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return this.bb.readInt16(this.bb_pos); + } + mutate_a(value) { + this.bb.writeInt16(this.bb_pos + 0, value); + return true; + } + b() { + return this.bb.readInt8(this.bb_pos + 2); + } + mutate_b(value) { + this.bb.writeInt8(this.bb_pos + 2, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.Example.Test'; + } + static sizeOf() { + return 4; + } + static createTest(builder, a, b) { + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(b); + builder.writeInt16(a); + return builder.offset(); + } + unpack() { + return new TestT(this.a(), this.b()); + } + unpackTo(_o) { + _o.a = this.a(); + _o.b = this.b(); + } +} +export class TestT { + constructor(a = 0, b = 0) { + this.a = a; + this.b = b; + } + pack(builder) { + return Test.createTest(builder, this.a, this.b); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/test.ts b/third_party/flatbuffers/tests/ts/my-game/example/test.ts new file mode 100644 index 00000000000..db9263cfe65 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/test.ts @@ -0,0 +1,80 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Test implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Test { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a():number { + return this.bb!.readInt16(this.bb_pos); +} + +mutate_a(value:number):boolean { + this.bb!.writeInt16(this.bb_pos + 0, value); + return true; +} + +b():number { + return this.bb!.readInt8(this.bb_pos + 2); +} + +mutate_b(value:number):boolean { + this.bb!.writeInt8(this.bb_pos + 2, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.Test'; +} + +static sizeOf():number { + return 4; +} + +static createTest(builder:flatbuffers.Builder, a: number, b: number):flatbuffers.Offset { + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(b); + builder.writeInt16(a); + return builder.offset(); +} + + +unpack(): TestT { + return new TestT( + this.a(), + this.b() + ); +} + + +unpackTo(_o: TestT): void { + _o.a = this.a(); + _o.b = this.b(); +} +} + +export class TestT implements flatbuffers.IGeneratedObject { +constructor( + public a: number = 0, + public b: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Test.createTest(builder, + this.a, + this.b + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.d.ts new file mode 100644 index 00000000000..b552add17df --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.d.ts @@ -0,0 +1,82 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class TypeAliases implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): TypeAliases; + static getRootAsTypeAliases(bb: flatbuffers.ByteBuffer, obj?: TypeAliases): TypeAliases; + static getSizePrefixedRootAsTypeAliases(bb: flatbuffers.ByteBuffer, obj?: TypeAliases): TypeAliases; + i8(): number; + mutate_i8(value: number): boolean; + u8(): number; + mutate_u8(value: number): boolean; + i16(): number; + mutate_i16(value: number): boolean; + u16(): number; + mutate_u16(value: number): boolean; + i32(): number; + mutate_i32(value: number): boolean; + u32(): number; + mutate_u32(value: number): boolean; + i64(): bigint; + mutate_i64(value: bigint): boolean; + u64(): bigint; + mutate_u64(value: bigint): boolean; + f32(): number; + mutate_f32(value: number): boolean; + f64(): number; + mutate_f64(value: number): boolean; + v8(index: number): number | null; + v8Length(): number; + v8Array(): Int8Array | null; + vf64(index: number): number | null; + vf64Length(): number; + vf64Array(): Float64Array | null; + static getFullyQualifiedName(): string; + static startTypeAliases(builder: flatbuffers.Builder): void; + static addI8(builder: flatbuffers.Builder, i8: number): void; + static addU8(builder: flatbuffers.Builder, u8: number): void; + static addI16(builder: flatbuffers.Builder, i16: number): void; + static addU16(builder: flatbuffers.Builder, u16: number): void; + static addI32(builder: flatbuffers.Builder, i32: number): void; + static addU32(builder: flatbuffers.Builder, u32: number): void; + static addI64(builder: flatbuffers.Builder, i64: bigint): void; + static addU64(builder: flatbuffers.Builder, u64: bigint): void; + static addF32(builder: flatbuffers.Builder, f32: number): void; + static addF64(builder: flatbuffers.Builder, f64: number): void; + static addV8(builder: flatbuffers.Builder, v8Offset: flatbuffers.Offset): void; + static createV8Vector(builder: flatbuffers.Builder, data: number[] | Int8Array): flatbuffers.Offset; + /** + * @deprecated This Uint8Array overload will be removed in the future. + */ + static createV8Vector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startV8Vector(builder: flatbuffers.Builder, numElems: number): void; + static addVf64(builder: flatbuffers.Builder, vf64Offset: flatbuffers.Offset): void; + static createVf64Vector(builder: flatbuffers.Builder, data: number[] | Float64Array): flatbuffers.Offset; + /** + * @deprecated This Uint8Array overload will be removed in the future. + */ + static createVf64Vector(builder: flatbuffers.Builder, data: number[] | Uint8Array): flatbuffers.Offset; + static startVf64Vector(builder: flatbuffers.Builder, numElems: number): void; + static endTypeAliases(builder: flatbuffers.Builder): flatbuffers.Offset; + static createTypeAliases(builder: flatbuffers.Builder, i8: number, u8: number, i16: number, u16: number, i32: number, u32: number, i64: bigint, u64: bigint, f32: number, f64: number, v8Offset: flatbuffers.Offset, vf64Offset: flatbuffers.Offset): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): TypeAliases; + unpack(): TypeAliasesT; + unpackTo(_o: TypeAliasesT): void; +} +export declare class TypeAliasesT implements flatbuffers.IGeneratedObject { + i8: number; + u8: number; + i16: number; + u16: number; + i32: number; + u32: number; + i64: bigint; + u64: bigint; + f32: number; + f64: number; + v8: (number)[]; + vf64: (number)[]; + constructor(i8?: number, u8?: number, i16?: number, u16?: number, i32?: number, u32?: number, i64?: bigint, u64?: bigint, f32?: number, f64?: number, v8?: (number)[], vf64?: (number)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.js b/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.js new file mode 100644 index 00000000000..81f32772bd7 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.js @@ -0,0 +1,291 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class TypeAliases { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTypeAliases(bb, obj) { + return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTypeAliases(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + i8() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : 0; + } + mutate_i8(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + u8() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readUint8(this.bb_pos + offset) : 0; + } + mutate_u8(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeUint8(this.bb_pos + offset, value); + return true; + } + i16() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 0; + } + mutate_i16(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt16(this.bb_pos + offset, value); + return true; + } + u16() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_u16(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + i32() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_i32(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + u32() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_u32(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + i64() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + mutate_i64(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + u64() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_u64(value) { + const offset = this.bb.__offset(this.bb_pos, 18); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + f32() { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; + } + mutate_f32(value) { + const offset = this.bb.__offset(this.bb_pos, 20); + if (offset === 0) { + return false; + } + this.bb.writeFloat32(this.bb_pos + offset, value); + return true; + } + f64() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0; + } + mutate_f64(value) { + const offset = this.bb.__offset(this.bb_pos, 22); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + v8(index) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.readInt8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + v8Length() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + v8Array() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? new Int8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + vf64(index) { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.readFloat64(this.bb.__vector(this.bb_pos + offset) + index * 8) : 0; + } + vf64Length() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + vf64Array() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? new Float64Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + static getFullyQualifiedName() { + return 'MyGame.Example.TypeAliases'; + } + static startTypeAliases(builder) { + builder.startObject(12); + } + static addI8(builder, i8) { + builder.addFieldInt8(0, i8, 0); + } + static addU8(builder, u8) { + builder.addFieldInt8(1, u8, 0); + } + static addI16(builder, i16) { + builder.addFieldInt16(2, i16, 0); + } + static addU16(builder, u16) { + builder.addFieldInt16(3, u16, 0); + } + static addI32(builder, i32) { + builder.addFieldInt32(4, i32, 0); + } + static addU32(builder, u32) { + builder.addFieldInt32(5, u32, 0); + } + static addI64(builder, i64) { + builder.addFieldInt64(6, i64, BigInt('0')); + } + static addU64(builder, u64) { + builder.addFieldInt64(7, u64, BigInt('0')); + } + static addF32(builder, f32) { + builder.addFieldFloat32(8, f32, 0.0); + } + static addF64(builder, f64) { + builder.addFieldFloat64(9, f64, 0.0); + } + static addV8(builder, v8Offset) { + builder.addFieldOffset(10, v8Offset, 0); + } + static createV8Vector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startV8Vector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addVf64(builder, vf64Offset) { + builder.addFieldOffset(11, vf64Offset, 0); + } + static createVf64Vector(builder, data) { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addFloat64(data[i]); + } + return builder.endVector(); + } + static startVf64Vector(builder, numElems) { + builder.startVector(8, numElems, 8); + } + static endTypeAliases(builder) { + const offset = builder.endObject(); + return offset; + } + static createTypeAliases(builder, i8, u8, i16, u16, i32, u32, i64, u64, f32, f64, v8Offset, vf64Offset) { + TypeAliases.startTypeAliases(builder); + TypeAliases.addI8(builder, i8); + TypeAliases.addU8(builder, u8); + TypeAliases.addI16(builder, i16); + TypeAliases.addU16(builder, u16); + TypeAliases.addI32(builder, i32); + TypeAliases.addU32(builder, u32); + TypeAliases.addI64(builder, i64); + TypeAliases.addU64(builder, u64); + TypeAliases.addF32(builder, f32); + TypeAliases.addF64(builder, f64); + TypeAliases.addV8(builder, v8Offset); + TypeAliases.addVf64(builder, vf64Offset); + return TypeAliases.endTypeAliases(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return TypeAliases.getRootAsTypeAliases(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new TypeAliasesT(this.i8(), this.u8(), this.i16(), this.u16(), this.i32(), this.u32(), this.i64(), this.u64(), this.f32(), this.f64(), this.bb.createScalarList(this.v8.bind(this), this.v8Length()), this.bb.createScalarList(this.vf64.bind(this), this.vf64Length())); + } + unpackTo(_o) { + _o.i8 = this.i8(); + _o.u8 = this.u8(); + _o.i16 = this.i16(); + _o.u16 = this.u16(); + _o.i32 = this.i32(); + _o.u32 = this.u32(); + _o.i64 = this.i64(); + _o.u64 = this.u64(); + _o.f32 = this.f32(); + _o.f64 = this.f64(); + _o.v8 = this.bb.createScalarList(this.v8.bind(this), this.v8Length()); + _o.vf64 = this.bb.createScalarList(this.vf64.bind(this), this.vf64Length()); + } +} +export class TypeAliasesT { + constructor(i8 = 0, u8 = 0, i16 = 0, u16 = 0, i32 = 0, u32 = 0, i64 = BigInt('0'), u64 = BigInt('0'), f32 = 0.0, f64 = 0.0, v8 = [], vf64 = []) { + this.i8 = i8; + this.u8 = u8; + this.i16 = i16; + this.u16 = u16; + this.i32 = i32; + this.u32 = u32; + this.i64 = i64; + this.u64 = u64; + this.f32 = f32; + this.f64 = f64; + this.v8 = v8; + this.vf64 = vf64; + } + pack(builder) { + const v8 = TypeAliases.createV8Vector(builder, this.v8); + const vf64 = TypeAliases.createVf64Vector(builder, this.vf64); + return TypeAliases.createTypeAliases(builder, this.i8, this.u8, this.i16, this.u16, this.i32, this.u32, this.i64, this.u64, this.f32, this.f64, v8, vf64); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.ts b/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.ts new file mode 100644 index 00000000000..9f0ed0b265b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/type-aliases.ts @@ -0,0 +1,407 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class TypeAliases implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):TypeAliases { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsTypeAliases(bb:flatbuffers.ByteBuffer, obj?:TypeAliases):TypeAliases { + return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsTypeAliases(bb:flatbuffers.ByteBuffer, obj?:TypeAliases):TypeAliases { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TypeAliases()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +i8():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0; +} + +mutate_i8(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, value); + return true; +} + +u8():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0; +} + +mutate_u8(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint8(this.bb_pos + offset, value); + return true; +} + +i16():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0; +} + +mutate_i16(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt16(this.bb_pos + offset, value); + return true; +} + +u16():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +mutate_u16(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 10); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint16(this.bb_pos + offset, value); + return true; +} + +i32():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_i32(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 12); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +u32():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; +} + +mutate_u32(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 14); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint32(this.bb_pos + offset, value); + return true; +} + +i64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_i64(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 16); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt64(this.bb_pos + offset, value); + return true; +} + +u64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_u64(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 18); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +f32():number { + const offset = this.bb!.__offset(this.bb_pos, 20); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0; +} + +mutate_f32(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 20); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat32(this.bb_pos + offset, value); + return true; +} + +f64():number { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0; +} + +mutate_f64(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 22); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat64(this.bb_pos + offset, value); + return true; +} + +v8(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.readInt8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +v8Length():number { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +v8Array():Int8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? new Int8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +vf64(index: number):number|null { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? this.bb!.readFloat64(this.bb!.__vector(this.bb_pos + offset) + index * 8) : 0; +} + +vf64Length():number { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +vf64Array():Float64Array|null { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? new Float64Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.TypeAliases'; +} + +static startTypeAliases(builder:flatbuffers.Builder) { + builder.startObject(12); +} + +static addI8(builder:flatbuffers.Builder, i8:number) { + builder.addFieldInt8(0, i8, 0); +} + +static addU8(builder:flatbuffers.Builder, u8:number) { + builder.addFieldInt8(1, u8, 0); +} + +static addI16(builder:flatbuffers.Builder, i16:number) { + builder.addFieldInt16(2, i16, 0); +} + +static addU16(builder:flatbuffers.Builder, u16:number) { + builder.addFieldInt16(3, u16, 0); +} + +static addI32(builder:flatbuffers.Builder, i32:number) { + builder.addFieldInt32(4, i32, 0); +} + +static addU32(builder:flatbuffers.Builder, u32:number) { + builder.addFieldInt32(5, u32, 0); +} + +static addI64(builder:flatbuffers.Builder, i64:bigint) { + builder.addFieldInt64(6, i64, BigInt('0')); +} + +static addU64(builder:flatbuffers.Builder, u64:bigint) { + builder.addFieldInt64(7, u64, BigInt('0')); +} + +static addF32(builder:flatbuffers.Builder, f32:number) { + builder.addFieldFloat32(8, f32, 0.0); +} + +static addF64(builder:flatbuffers.Builder, f64:number) { + builder.addFieldFloat64(9, f64, 0.0); +} + +static addV8(builder:flatbuffers.Builder, v8Offset:flatbuffers.Offset) { + builder.addFieldOffset(10, v8Offset, 0); +} + +static createV8Vector(builder:flatbuffers.Builder, data:number[]|Int8Array):flatbuffers.Offset; +/** + * @deprecated This Uint8Array overload will be removed in the future. + */ +static createV8Vector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; +static createV8Vector(builder:flatbuffers.Builder, data:number[]|Int8Array|Uint8Array):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startV8Vector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addVf64(builder:flatbuffers.Builder, vf64Offset:flatbuffers.Offset) { + builder.addFieldOffset(11, vf64Offset, 0); +} + +static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Float64Array):flatbuffers.Offset; +/** + * @deprecated This Uint8Array overload will be removed in the future. + */ +static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Uint8Array):flatbuffers.Offset; +static createVf64Vector(builder:flatbuffers.Builder, data:number[]|Float64Array|Uint8Array):flatbuffers.Offset { + builder.startVector(8, data.length, 8); + for (let i = data.length - 1; i >= 0; i--) { + builder.addFloat64(data[i]!); + } + return builder.endVector(); +} + +static startVf64Vector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(8, numElems, 8); +} + +static endTypeAliases(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createTypeAliases(builder:flatbuffers.Builder, i8:number, u8:number, i16:number, u16:number, i32:number, u32:number, i64:bigint, u64:bigint, f32:number, f64:number, v8Offset:flatbuffers.Offset, vf64Offset:flatbuffers.Offset):flatbuffers.Offset { + TypeAliases.startTypeAliases(builder); + TypeAliases.addI8(builder, i8); + TypeAliases.addU8(builder, u8); + TypeAliases.addI16(builder, i16); + TypeAliases.addU16(builder, u16); + TypeAliases.addI32(builder, i32); + TypeAliases.addU32(builder, u32); + TypeAliases.addI64(builder, i64); + TypeAliases.addU64(builder, u64); + TypeAliases.addF32(builder, f32); + TypeAliases.addF64(builder, f64); + TypeAliases.addV8(builder, v8Offset); + TypeAliases.addVf64(builder, vf64Offset); + return TypeAliases.endTypeAliases(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):TypeAliases { + return TypeAliases.getRootAsTypeAliases(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): TypeAliasesT { + return new TypeAliasesT( + this.i8(), + this.u8(), + this.i16(), + this.u16(), + this.i32(), + this.u32(), + this.i64(), + this.u64(), + this.f32(), + this.f64(), + this.bb!.createScalarList(this.v8.bind(this), this.v8Length()), + this.bb!.createScalarList(this.vf64.bind(this), this.vf64Length()) + ); +} + + +unpackTo(_o: TypeAliasesT): void { + _o.i8 = this.i8(); + _o.u8 = this.u8(); + _o.i16 = this.i16(); + _o.u16 = this.u16(); + _o.i32 = this.i32(); + _o.u32 = this.u32(); + _o.i64 = this.i64(); + _o.u64 = this.u64(); + _o.f32 = this.f32(); + _o.f64 = this.f64(); + _o.v8 = this.bb!.createScalarList(this.v8.bind(this), this.v8Length()); + _o.vf64 = this.bb!.createScalarList(this.vf64.bind(this), this.vf64Length()); +} +} + +export class TypeAliasesT implements flatbuffers.IGeneratedObject { +constructor( + public i8: number = 0, + public u8: number = 0, + public i16: number = 0, + public u16: number = 0, + public i32: number = 0, + public u32: number = 0, + public i64: bigint = BigInt('0'), + public u64: bigint = BigInt('0'), + public f32: number = 0.0, + public f64: number = 0.0, + public v8: (number)[] = [], + public vf64: (number)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const v8 = TypeAliases.createV8Vector(builder, this.v8); + const vf64 = TypeAliases.createVf64Vector(builder, this.vf64); + + return TypeAliases.createTypeAliases(builder, + this.i8, + this.u8, + this.i16, + this.u16, + this.i32, + this.u32, + this.i64, + this.u64, + this.f32, + this.f64, + v8, + vf64 + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/vec3.d.ts b/third_party/flatbuffers/tests/ts/my-game/example/vec3.d.ts new file mode 100644 index 00000000000..c5a6be285c7 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/vec3.d.ts @@ -0,0 +1,34 @@ +import * as flatbuffers from 'flatbuffers'; +import { Color } from '../../my-game/example/color.js'; +import { Test, TestT } from '../../my-game/example/test.js'; +export declare class Vec3 implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Vec3; + x(): number; + mutate_x(value: number): boolean; + y(): number; + mutate_y(value: number): boolean; + z(): number; + mutate_z(value: number): boolean; + test1(): number; + mutate_test1(value: number): boolean; + test2(): Color; + mutate_test2(value: Color): boolean; + test3(obj?: Test): Test | null; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createVec3(builder: flatbuffers.Builder, x: number, y: number, z: number, test1: number, test2: Color, test3_a: number, test3_b: number): flatbuffers.Offset; + unpack(): Vec3T; + unpackTo(_o: Vec3T): void; +} +export declare class Vec3T implements flatbuffers.IGeneratedObject { + x: number; + y: number; + z: number; + test1: number; + test2: Color; + test3: TestT | null; + constructor(x?: number, y?: number, z?: number, test1?: number, test2?: Color, test3?: TestT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/vec3.js b/third_party/flatbuffers/tests/ts/my-game/example/vec3.js new file mode 100644 index 00000000000..cd5b03461b8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/vec3.js @@ -0,0 +1,98 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import { Color } from '../../my-game/example/color.js'; +import { Test } from '../../my-game/example/test.js'; +export class Vec3 { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + x() { + return this.bb.readFloat32(this.bb_pos); + } + mutate_x(value) { + this.bb.writeFloat32(this.bb_pos + 0, value); + return true; + } + y() { + return this.bb.readFloat32(this.bb_pos + 4); + } + mutate_y(value) { + this.bb.writeFloat32(this.bb_pos + 4, value); + return true; + } + z() { + return this.bb.readFloat32(this.bb_pos + 8); + } + mutate_z(value) { + this.bb.writeFloat32(this.bb_pos + 8, value); + return true; + } + test1() { + return this.bb.readFloat64(this.bb_pos + 16); + } + mutate_test1(value) { + this.bb.writeFloat64(this.bb_pos + 16, value); + return true; + } + test2() { + return this.bb.readUint8(this.bb_pos + 24); + } + mutate_test2(value) { + this.bb.writeUint8(this.bb_pos + 24, value); + return true; + } + test3(obj) { + return (obj || new Test()).__init(this.bb_pos + 26, this.bb); + } + static getFullyQualifiedName() { + return 'MyGame.Example.Vec3'; + } + static sizeOf() { + return 32; + } + static createVec3(builder, x, y, z, test1, test2, test3_a, test3_b) { + builder.prep(8, 32); + builder.pad(2); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(test3_b); + builder.writeInt16(test3_a); + builder.pad(1); + builder.writeInt8(test2); + builder.writeFloat64(test1); + builder.pad(4); + builder.writeFloat32(z); + builder.writeFloat32(y); + builder.writeFloat32(x); + return builder.offset(); + } + unpack() { + return new Vec3T(this.x(), this.y(), this.z(), this.test1(), this.test2(), (this.test3() !== null ? this.test3().unpack() : null)); + } + unpackTo(_o) { + _o.x = this.x(); + _o.y = this.y(); + _o.z = this.z(); + _o.test1 = this.test1(); + _o.test2 = this.test2(); + _o.test3 = (this.test3() !== null ? this.test3().unpack() : null); + } +} +export class Vec3T { + constructor(x = 0.0, y = 0.0, z = 0.0, test1 = 0.0, test2 = Color.Red, test3 = null) { + this.x = x; + this.y = y; + this.z = z; + this.test1 = test1; + this.test2 = test2; + this.test3 = test3; + } + pack(builder) { + return Vec3.createVec3(builder, this.x, this.y, this.z, this.test1, this.test2, (this.test3?.a ?? 0), (this.test3?.b ?? 0)); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example/vec3.ts b/third_party/flatbuffers/tests/ts/my-game/example/vec3.ts new file mode 100644 index 00000000000..88c0dbf72d1 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example/vec3.ts @@ -0,0 +1,139 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Color } from '../../my-game/example/color.js'; +import { Test, TestT } from '../../my-game/example/test.js'; + + +export class Vec3 implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Vec3 { + this.bb_pos = i; + this.bb = bb; + return this; +} + +x():number { + return this.bb!.readFloat32(this.bb_pos); +} + +mutate_x(value:number):boolean { + this.bb!.writeFloat32(this.bb_pos + 0, value); + return true; +} + +y():number { + return this.bb!.readFloat32(this.bb_pos + 4); +} + +mutate_y(value:number):boolean { + this.bb!.writeFloat32(this.bb_pos + 4, value); + return true; +} + +z():number { + return this.bb!.readFloat32(this.bb_pos + 8); +} + +mutate_z(value:number):boolean { + this.bb!.writeFloat32(this.bb_pos + 8, value); + return true; +} + +test1():number { + return this.bb!.readFloat64(this.bb_pos + 16); +} + +mutate_test1(value:number):boolean { + this.bb!.writeFloat64(this.bb_pos + 16, value); + return true; +} + +test2():Color { + return this.bb!.readUint8(this.bb_pos + 24); +} + +mutate_test2(value:Color):boolean { + this.bb!.writeUint8(this.bb_pos + 24, value); + return true; +} + +test3(obj?:Test):Test|null { + return (obj || new Test()).__init(this.bb_pos + 26, this.bb!); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example.Vec3'; +} + +static sizeOf():number { + return 32; +} + +static createVec3(builder:flatbuffers.Builder, x: number, y: number, z: number, test1: number, test2: Color, test3_a: number, test3_b: number):flatbuffers.Offset { + builder.prep(8, 32); + builder.pad(2); + builder.prep(2, 4); + builder.pad(1); + builder.writeInt8(test3_b); + builder.writeInt16(test3_a); + builder.pad(1); + builder.writeInt8(test2); + builder.writeFloat64(test1); + builder.pad(4); + builder.writeFloat32(z); + builder.writeFloat32(y); + builder.writeFloat32(x); + return builder.offset(); +} + + +unpack(): Vec3T { + return new Vec3T( + this.x(), + this.y(), + this.z(), + this.test1(), + this.test2(), + (this.test3() !== null ? this.test3()!.unpack() : null) + ); +} + + +unpackTo(_o: Vec3T): void { + _o.x = this.x(); + _o.y = this.y(); + _o.z = this.z(); + _o.test1 = this.test1(); + _o.test2 = this.test2(); + _o.test3 = (this.test3() !== null ? this.test3()!.unpack() : null); +} +} + +export class Vec3T implements flatbuffers.IGeneratedObject { +constructor( + public x: number = 0.0, + public y: number = 0.0, + public z: number = 0.0, + public test1: number = 0.0, + public test2: Color = Color.Red, + public test3: TestT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Vec3.createVec3(builder, + this.x, + this.y, + this.z, + this.test1, + this.test2, + (this.test3?.a ?? 0), + (this.test3?.b ?? 0) + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example2.d.ts b/third_party/flatbuffers/tests/ts/my-game/example2.d.ts new file mode 100644 index 00000000000..4aebab9710c --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example2.d.ts @@ -0,0 +1 @@ +export { Monster, MonsterT } from './example2/monster.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example2.js b/third_party/flatbuffers/tests/ts/my-game/example2.js new file mode 100644 index 00000000000..2c599c5df5b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example2.js @@ -0,0 +1,3 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { Monster, MonsterT } from './example2/monster.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example2.ts b/third_party/flatbuffers/tests/ts/my-game/example2.ts new file mode 100644 index 00000000000..5028bba20fd --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example2.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Monster, MonsterT } from './example2/monster.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/example2/monster.d.ts b/third_party/flatbuffers/tests/ts/my-game/example2/monster.d.ts new file mode 100644 index 00000000000..9da773b7d42 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example2/monster.d.ts @@ -0,0 +1,20 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Monster implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Monster; + static getRootAsMonster(bb: flatbuffers.ByteBuffer, obj?: Monster): Monster; + static getSizePrefixedRootAsMonster(bb: flatbuffers.ByteBuffer, obj?: Monster): Monster; + static getFullyQualifiedName(): string; + static startMonster(builder: flatbuffers.Builder): void; + static endMonster(builder: flatbuffers.Builder): flatbuffers.Offset; + static createMonster(builder: flatbuffers.Builder): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): Monster; + unpack(): MonsterT; + unpackTo(_o: MonsterT): void; +} +export declare class MonsterT implements flatbuffers.IGeneratedObject { + constructor(); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example2/monster.js b/third_party/flatbuffers/tests/ts/my-game/example2/monster.js new file mode 100644 index 00000000000..56d215f942b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example2/monster.js @@ -0,0 +1,51 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class Monster { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMonster(bb, obj) { + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMonster(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getFullyQualifiedName() { + return 'MyGame.Example2.Monster'; + } + static startMonster(builder) { + builder.startObject(0); + } + static endMonster(builder) { + const offset = builder.endObject(); + return offset; + } + static createMonster(builder) { + Monster.startMonster(builder); + return Monster.endMonster(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new MonsterT(); + } + unpackTo(_o) { } +} +export class MonsterT { + constructor() { } + pack(builder) { + return Monster.createMonster(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/example2/monster.ts b/third_party/flatbuffers/tests/ts/my-game/example2/monster.ts new file mode 100644 index 00000000000..39bf68d9ea2 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/example2/monster.ts @@ -0,0 +1,68 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Monster implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Monster { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster { + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsMonster(bb:flatbuffers.ByteBuffer, obj?:Monster):Monster { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Monster()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getFullyQualifiedName():string { + return 'MyGame.Example2.Monster'; +} + +static startMonster(builder:flatbuffers.Builder) { + builder.startObject(0); +} + +static endMonster(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createMonster(builder:flatbuffers.Builder):flatbuffers.Offset { + Monster.startMonster(builder); + return Monster.endMonster(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):Monster { + return Monster.getRootAsMonster(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): MonsterT { + return new MonsterT(); +} + + +unpackTo(_o: MonsterT): void {} +} + +export class MonsterT implements flatbuffers.IGeneratedObject { +constructor(){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Monster.createMonster(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.d.ts b/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.d.ts new file mode 100644 index 00000000000..07dc15659af --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.d.ts @@ -0,0 +1,20 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class InParentNamespace implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): InParentNamespace; + static getRootAsInParentNamespace(bb: flatbuffers.ByteBuffer, obj?: InParentNamespace): InParentNamespace; + static getSizePrefixedRootAsInParentNamespace(bb: flatbuffers.ByteBuffer, obj?: InParentNamespace): InParentNamespace; + static getFullyQualifiedName(): string; + static startInParentNamespace(builder: flatbuffers.Builder): void; + static endInParentNamespace(builder: flatbuffers.Builder): flatbuffers.Offset; + static createInParentNamespace(builder: flatbuffers.Builder): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): InParentNamespace; + unpack(): InParentNamespaceT; + unpackTo(_o: InParentNamespaceT): void; +} +export declare class InParentNamespaceT implements flatbuffers.IGeneratedObject { + constructor(); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.js b/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.js new file mode 100644 index 00000000000..197d271e870 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.js @@ -0,0 +1,51 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class InParentNamespace { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsInParentNamespace(bb, obj) { + return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsInParentNamespace(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getFullyQualifiedName() { + return 'MyGame.InParentNamespace'; + } + static startInParentNamespace(builder) { + builder.startObject(0); + } + static endInParentNamespace(builder) { + const offset = builder.endObject(); + return offset; + } + static createInParentNamespace(builder) { + InParentNamespace.startInParentNamespace(builder); + return InParentNamespace.endInParentNamespace(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return InParentNamespace.getRootAsInParentNamespace(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new InParentNamespaceT(); + } + unpackTo(_o) { } +} +export class InParentNamespaceT { + constructor() { } + pack(builder) { + return InParentNamespace.createInParentNamespace(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.ts b/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.ts new file mode 100644 index 00000000000..02f18e1ae87 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/in-parent-namespace.ts @@ -0,0 +1,68 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class InParentNamespace implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):InParentNamespace { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsInParentNamespace(bb:flatbuffers.ByteBuffer, obj?:InParentNamespace):InParentNamespace { + return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsInParentNamespace(bb:flatbuffers.ByteBuffer, obj?:InParentNamespace):InParentNamespace { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new InParentNamespace()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getFullyQualifiedName():string { + return 'MyGame.InParentNamespace'; +} + +static startInParentNamespace(builder:flatbuffers.Builder) { + builder.startObject(0); +} + +static endInParentNamespace(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createInParentNamespace(builder:flatbuffers.Builder):flatbuffers.Offset { + InParentNamespace.startInParentNamespace(builder); + return InParentNamespace.endInParentNamespace(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):InParentNamespace { + return InParentNamespace.getRootAsInParentNamespace(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): InParentNamespaceT { + return new InParentNamespaceT(); +} + + +unpackTo(_o: InParentNamespaceT): void {} +} + +export class InParentNamespaceT implements flatbuffers.IGeneratedObject { +constructor(){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return InParentNamespace.createInParentNamespace(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space.d.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space.d.ts new file mode 100644 index 00000000000..3152eff5d33 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space.d.ts @@ -0,0 +1,3 @@ +export { FromInclude } from './other-name-space/from-include.js'; +export { TableB, TableBT } from './other-name-space/table-b.js'; +export { Unused, UnusedT } from './other-name-space/unused.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space.js b/third_party/flatbuffers/tests/ts/my-game/other-name-space.js new file mode 100644 index 00000000000..6b80bdba64d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space.js @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { FromInclude } from './other-name-space/from-include.js'; +export { TableB, TableBT } from './other-name-space/table-b.js'; +export { Unused, UnusedT } from './other-name-space/unused.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space.ts new file mode 100644 index 00000000000..b8ddf753160 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space.ts @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { FromInclude } from './other-name-space/from-include.js'; +export { TableB, TableBT } from './other-name-space/table-b.js'; +export { Unused, UnusedT } from './other-name-space/unused.js'; diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.d.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.d.ts new file mode 100644 index 00000000000..dc12fa4b68f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.d.ts @@ -0,0 +1,3 @@ +export declare enum FromInclude { + IncludeVal = "0" +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.js b/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.js new file mode 100644 index 00000000000..e9d4e43a645 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.js @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var FromInclude; +(function (FromInclude) { + FromInclude["IncludeVal"] = "0"; +})(FromInclude || (FromInclude = {})); diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.ts new file mode 100644 index 00000000000..86305f24894 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/from-include.ts @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum FromInclude { + IncludeVal = '0' +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.d.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.d.ts new file mode 100644 index 00000000000..d4e1bcfc580 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.d.ts @@ -0,0 +1,24 @@ +import * as flatbuffers from 'flatbuffers'; +import { TableA, TableAT } from '../../table-a.js'; +export declare class TableB implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): TableB; + static getRootAsTableB(bb: flatbuffers.ByteBuffer, obj?: TableB): TableB; + static getSizePrefixedRootAsTableB(bb: flatbuffers.ByteBuffer, obj?: TableB): TableB; + a(obj?: TableA): TableA | null; + static getFullyQualifiedName(): string; + static startTableB(builder: flatbuffers.Builder): void; + static addA(builder: flatbuffers.Builder, aOffset: flatbuffers.Offset): void; + static endTableB(builder: flatbuffers.Builder): flatbuffers.Offset; + static createTableB(builder: flatbuffers.Builder, aOffset: flatbuffers.Offset): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): TableB; + unpack(): TableBT; + unpackTo(_o: TableBT): void; +} +export declare class TableBT implements flatbuffers.IGeneratedObject { + a: TableAT | null; + constructor(a?: TableAT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.js b/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.js new file mode 100644 index 00000000000..74b170c88d5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.js @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { TableA } from '../../table-a.js'; +export class TableB { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTableB(bb, obj) { + return (obj || new TableB()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTableB(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TableB()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + a(obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new TableA()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + static getFullyQualifiedName() { + return 'MyGame.OtherNameSpace.TableB'; + } + static startTableB(builder) { + builder.startObject(1); + } + static addA(builder, aOffset) { + builder.addFieldOffset(0, aOffset, 0); + } + static endTableB(builder) { + const offset = builder.endObject(); + return offset; + } + static createTableB(builder, aOffset) { + TableB.startTableB(builder); + TableB.addA(builder, aOffset); + return TableB.endTableB(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return TableB.getRootAsTableB(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new TableBT((this.a() !== null ? this.a().unpack() : null)); + } + unpackTo(_o) { + _o.a = (this.a() !== null ? this.a().unpack() : null); + } +} +export class TableBT { + constructor(a = null) { + this.a = a; + } + pack(builder) { + const a = (this.a !== null ? this.a.pack(builder) : 0); + return TableB.createTableB(builder, a); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.ts new file mode 100644 index 00000000000..264a7c44302 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/table-b.ts @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { TableA, TableAT } from '../../table-a.js'; + + +export class TableB implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):TableB { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsTableB(bb:flatbuffers.ByteBuffer, obj?:TableB):TableB { + return (obj || new TableB()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsTableB(bb:flatbuffers.ByteBuffer, obj?:TableB):TableB { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TableB()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +a(obj?:TableA):TableA|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? (obj || new TableA()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +static getFullyQualifiedName():string { + return 'MyGame.OtherNameSpace.TableB'; +} + +static startTableB(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addA(builder:flatbuffers.Builder, aOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, aOffset, 0); +} + +static endTableB(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createTableB(builder:flatbuffers.Builder, aOffset:flatbuffers.Offset):flatbuffers.Offset { + TableB.startTableB(builder); + TableB.addA(builder, aOffset); + return TableB.endTableB(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):TableB { + return TableB.getRootAsTableB(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): TableBT { + return new TableBT( + (this.a() !== null ? this.a()!.unpack() : null) + ); +} + + +unpackTo(_o: TableBT): void { + _o.a = (this.a() !== null ? this.a()!.unpack() : null); +} +} + +export class TableBT implements flatbuffers.IGeneratedObject { +constructor( + public a: TableAT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const a = (this.a !== null ? this.a!.pack(builder) : 0); + + return TableB.createTableB(builder, + a + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.d.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.d.ts new file mode 100644 index 00000000000..6d929f24b37 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.d.ts @@ -0,0 +1,18 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Unused implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Unused; + a(): number; + mutate_a(value: number): boolean; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createUnused(builder: flatbuffers.Builder, a: number): flatbuffers.Offset; + unpack(): UnusedT; + unpackTo(_o: UnusedT): void; +} +export declare class UnusedT implements flatbuffers.IGeneratedObject { + a: number; + constructor(a?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.js b/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.js new file mode 100644 index 00000000000..0b42918d1ea --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.js @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class Unused { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + a() { + return this.bb.readInt32(this.bb_pos); + } + mutate_a(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return 'MyGame.OtherNameSpace.Unused'; + } + static sizeOf() { + return 4; + } + static createUnused(builder, a) { + builder.prep(4, 4); + builder.writeInt32(a); + return builder.offset(); + } + unpack() { + return new UnusedT(this.a()); + } + unpackTo(_o) { + _o.a = this.a(); + } +} +export class UnusedT { + constructor(a = 0) { + this.a = a; + } + pack(builder) { + return Unused.createUnused(builder, this.a); + } +} diff --git a/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.ts b/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.ts new file mode 100644 index 00000000000..6c22d1e2e16 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/my-game/other-name-space/unused.ts @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Unused implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Unused { + this.bb_pos = i; + this.bb = bb; + return this; +} + +a():number { + return this.bb!.readInt32(this.bb_pos); +} + +mutate_a(value:number):boolean { + this.bb!.writeInt32(this.bb_pos + 0, value); + return true; +} + +static getFullyQualifiedName():string { + return 'MyGame.OtherNameSpace.Unused'; +} + +static sizeOf():number { + return 4; +} + +static createUnused(builder:flatbuffers.Builder, a: number):flatbuffers.Offset { + builder.prep(4, 4); + builder.writeInt32(a); + return builder.offset(); +} + + +unpack(): UnusedT { + return new UnusedT( + this.a() + ); +} + + +unpackTo(_o: UnusedT): void { + _o.a = this.a(); +} +} + +export class UnusedT implements flatbuffers.IGeneratedObject { +constructor( + public a: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Unused.createUnused(builder, + this.a + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.d.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.d.ts new file mode 100644 index 00000000000..40a0ac6fea9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.d.ts @@ -0,0 +1,2 @@ +export { OptionalByte } from './optional-scalars/optional-byte'; +export { ScalarStuff } from './optional-scalars/scalar-stuff'; diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.js b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.js new file mode 100644 index 00000000000..05aee5bf292 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.js @@ -0,0 +1,4 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { OptionalByte } from './optional-scalars/optional-byte'; +export { ScalarStuff } from './optional-scalars/scalar-stuff'; diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.ts new file mode 100644 index 00000000000..8fef7025af8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars.ts @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { OptionalByte } from './optional-scalars/optional-byte'; +export { ScalarStuff } from './optional-scalars/scalar-stuff'; diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.d.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.d.ts new file mode 100644 index 00000000000..fc5b5fecd73 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.d.ts @@ -0,0 +1,5 @@ +export declare enum OptionalByte { + None = 0, + One = 1, + Two = 2 +} diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.js b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.js new file mode 100644 index 00000000000..e669367e121 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.js @@ -0,0 +1,8 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var OptionalByte; +(function (OptionalByte) { + OptionalByte[OptionalByte["None"] = 0] = "None"; + OptionalByte[OptionalByte["One"] = 1] = "One"; + OptionalByte[OptionalByte["Two"] = 2] = "Two"; +})(OptionalByte || (OptionalByte = {})); diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.ts new file mode 100644 index 00000000000..9bb66a9bc14 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/optional-byte.ts @@ -0,0 +1,9 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum OptionalByte { + None = 0, + One = 1, + Two = 2 +} diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.d.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.d.ts new file mode 100644 index 00000000000..c8e01a30561 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.d.ts @@ -0,0 +1,88 @@ +import * as flatbuffers from 'flatbuffers'; +import { OptionalByte } from '../optional-scalars/optional-byte'; +export declare class ScalarStuff { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): ScalarStuff; + static getRootAsScalarStuff(bb: flatbuffers.ByteBuffer, obj?: ScalarStuff): ScalarStuff; + static getSizePrefixedRootAsScalarStuff(bb: flatbuffers.ByteBuffer, obj?: ScalarStuff): ScalarStuff; + static bufferHasIdentifier(bb: flatbuffers.ByteBuffer): boolean; + justI8(): number; + maybeI8(): number | null; + defaultI8(): number; + justU8(): number; + maybeU8(): number | null; + defaultU8(): number; + justI16(): number; + maybeI16(): number | null; + defaultI16(): number; + justU16(): number; + maybeU16(): number | null; + defaultU16(): number; + justI32(): number; + maybeI32(): number | null; + defaultI32(): number; + justU32(): number; + maybeU32(): number | null; + defaultU32(): number; + justI64(): bigint; + maybeI64(): bigint | null; + defaultI64(): bigint; + justU64(): bigint; + maybeU64(): bigint | null; + defaultU64(): bigint; + justF32(): number; + maybeF32(): number | null; + defaultF32(): number; + justF64(): number; + maybeF64(): number | null; + defaultF64(): number; + justBool(): boolean; + maybeBool(): boolean | null; + defaultBool(): boolean; + justEnum(): OptionalByte; + maybeEnum(): OptionalByte | null; + defaultEnum(): OptionalByte; + static getFullyQualifiedName(): string; + static startScalarStuff(builder: flatbuffers.Builder): void; + static addJustI8(builder: flatbuffers.Builder, justI8: number): void; + static addMaybeI8(builder: flatbuffers.Builder, maybeI8: number): void; + static addDefaultI8(builder: flatbuffers.Builder, defaultI8: number): void; + static addJustU8(builder: flatbuffers.Builder, justU8: number): void; + static addMaybeU8(builder: flatbuffers.Builder, maybeU8: number): void; + static addDefaultU8(builder: flatbuffers.Builder, defaultU8: number): void; + static addJustI16(builder: flatbuffers.Builder, justI16: number): void; + static addMaybeI16(builder: flatbuffers.Builder, maybeI16: number): void; + static addDefaultI16(builder: flatbuffers.Builder, defaultI16: number): void; + static addJustU16(builder: flatbuffers.Builder, justU16: number): void; + static addMaybeU16(builder: flatbuffers.Builder, maybeU16: number): void; + static addDefaultU16(builder: flatbuffers.Builder, defaultU16: number): void; + static addJustI32(builder: flatbuffers.Builder, justI32: number): void; + static addMaybeI32(builder: flatbuffers.Builder, maybeI32: number): void; + static addDefaultI32(builder: flatbuffers.Builder, defaultI32: number): void; + static addJustU32(builder: flatbuffers.Builder, justU32: number): void; + static addMaybeU32(builder: flatbuffers.Builder, maybeU32: number): void; + static addDefaultU32(builder: flatbuffers.Builder, defaultU32: number): void; + static addJustI64(builder: flatbuffers.Builder, justI64: bigint): void; + static addMaybeI64(builder: flatbuffers.Builder, maybeI64: bigint): void; + static addDefaultI64(builder: flatbuffers.Builder, defaultI64: bigint): void; + static addJustU64(builder: flatbuffers.Builder, justU64: bigint): void; + static addMaybeU64(builder: flatbuffers.Builder, maybeU64: bigint): void; + static addDefaultU64(builder: flatbuffers.Builder, defaultU64: bigint): void; + static addJustF32(builder: flatbuffers.Builder, justF32: number): void; + static addMaybeF32(builder: flatbuffers.Builder, maybeF32: number): void; + static addDefaultF32(builder: flatbuffers.Builder, defaultF32: number): void; + static addJustF64(builder: flatbuffers.Builder, justF64: number): void; + static addMaybeF64(builder: flatbuffers.Builder, maybeF64: number): void; + static addDefaultF64(builder: flatbuffers.Builder, defaultF64: number): void; + static addJustBool(builder: flatbuffers.Builder, justBool: boolean): void; + static addMaybeBool(builder: flatbuffers.Builder, maybeBool: boolean): void; + static addDefaultBool(builder: flatbuffers.Builder, defaultBool: boolean): void; + static addJustEnum(builder: flatbuffers.Builder, justEnum: OptionalByte): void; + static addMaybeEnum(builder: flatbuffers.Builder, maybeEnum: OptionalByte): void; + static addDefaultEnum(builder: flatbuffers.Builder, defaultEnum: OptionalByte): void; + static endScalarStuff(builder: flatbuffers.Builder): flatbuffers.Offset; + static finishScalarStuffBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static finishSizePrefixedScalarStuffBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static createScalarStuff(builder: flatbuffers.Builder, justI8: number, maybeI8: number | null, defaultI8: number, justU8: number, maybeU8: number | null, defaultU8: number, justI16: number, maybeI16: number | null, defaultI16: number, justU16: number, maybeU16: number | null, defaultU16: number, justI32: number, maybeI32: number | null, defaultI32: number, justU32: number, maybeU32: number | null, defaultU32: number, justI64: bigint, maybeI64: bigint | null, defaultI64: bigint, justU64: bigint, maybeU64: bigint | null, defaultU64: bigint, justF32: number, maybeF32: number | null, defaultF32: number, justF64: number, maybeF64: number | null, defaultF64: number, justBool: boolean, maybeBool: boolean | null, defaultBool: boolean, justEnum: OptionalByte, maybeEnum: OptionalByte | null, defaultEnum: OptionalByte): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.js b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.js new file mode 100644 index 00000000000..5a175ec1a02 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.js @@ -0,0 +1,345 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { OptionalByte } from '../optional-scalars/optional-byte'; +export class ScalarStuff { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsScalarStuff(bb, obj) { + return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsScalarStuff(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier('NULL'); + } + justI8() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : 0; + } + maybeI8() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt8(this.bb_pos + offset) : null; + } + defaultI8() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt8(this.bb_pos + offset) : 42; + } + justU8() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint8(this.bb_pos + offset) : 0; + } + maybeU8() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readUint8(this.bb_pos + offset) : null; + } + defaultU8() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint8(this.bb_pos + offset) : 42; + } + justI16() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 0; + } + maybeI16() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.readInt16(this.bb_pos + offset) : null; + } + defaultI16() { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? this.bb.readInt16(this.bb_pos + offset) : 42; + } + justU16() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + maybeU16() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.readUint16(this.bb_pos + offset) : null; + } + defaultU16() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 42; + } + justI32() { + const offset = this.bb.__offset(this.bb_pos, 28); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + maybeI32() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? this.bb.readInt32(this.bb_pos + offset) : null; + } + defaultI32() { + const offset = this.bb.__offset(this.bb_pos, 32); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 42; + } + justU32() { + const offset = this.bb.__offset(this.bb_pos, 34); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + maybeU32() { + const offset = this.bb.__offset(this.bb_pos, 36); + return offset ? this.bb.readUint32(this.bb_pos + offset) : null; + } + defaultU32() { + const offset = this.bb.__offset(this.bb_pos, 38); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 42; + } + justI64() { + const offset = this.bb.__offset(this.bb_pos, 40); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + maybeI64() { + const offset = this.bb.__offset(this.bb_pos, 42); + return offset ? this.bb.readInt64(this.bb_pos + offset) : null; + } + defaultI64() { + const offset = this.bb.__offset(this.bb_pos, 44); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('42'); + } + justU64() { + const offset = this.bb.__offset(this.bb_pos, 46); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + maybeU64() { + const offset = this.bb.__offset(this.bb_pos, 48); + return offset ? this.bb.readUint64(this.bb_pos + offset) : null; + } + defaultU64() { + const offset = this.bb.__offset(this.bb_pos, 50); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('42'); + } + justF32() { + const offset = this.bb.__offset(this.bb_pos, 52); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 0.0; + } + maybeF32() { + const offset = this.bb.__offset(this.bb_pos, 54); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : null; + } + defaultF32() { + const offset = this.bb.__offset(this.bb_pos, 56); + return offset ? this.bb.readFloat32(this.bb_pos + offset) : 42.0; + } + justF64() { + const offset = this.bb.__offset(this.bb_pos, 58); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0; + } + maybeF64() { + const offset = this.bb.__offset(this.bb_pos, 60); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : null; + } + defaultF64() { + const offset = this.bb.__offset(this.bb_pos, 62); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 42.0; + } + justBool() { + const offset = this.bb.__offset(this.bb_pos, 64); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + maybeBool() { + const offset = this.bb.__offset(this.bb_pos, 66); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : null; + } + defaultBool() { + const offset = this.bb.__offset(this.bb_pos, 68); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : true; + } + justEnum() { + const offset = this.bb.__offset(this.bb_pos, 70); + return offset ? this.bb.readInt8(this.bb_pos + offset) : OptionalByte.None; + } + maybeEnum() { + const offset = this.bb.__offset(this.bb_pos, 72); + return offset ? this.bb.readInt8(this.bb_pos + offset) : null; + } + defaultEnum() { + const offset = this.bb.__offset(this.bb_pos, 74); + return offset ? this.bb.readInt8(this.bb_pos + offset) : OptionalByte.One; + } + static getFullyQualifiedName() { + return 'optional_scalars.ScalarStuff'; + } + static startScalarStuff(builder) { + builder.startObject(36); + } + static addJustI8(builder, justI8) { + builder.addFieldInt8(0, justI8, 0); + } + static addMaybeI8(builder, maybeI8) { + builder.addFieldInt8(1, maybeI8, null); + } + static addDefaultI8(builder, defaultI8) { + builder.addFieldInt8(2, defaultI8, 42); + } + static addJustU8(builder, justU8) { + builder.addFieldInt8(3, justU8, 0); + } + static addMaybeU8(builder, maybeU8) { + builder.addFieldInt8(4, maybeU8, null); + } + static addDefaultU8(builder, defaultU8) { + builder.addFieldInt8(5, defaultU8, 42); + } + static addJustI16(builder, justI16) { + builder.addFieldInt16(6, justI16, 0); + } + static addMaybeI16(builder, maybeI16) { + builder.addFieldInt16(7, maybeI16, null); + } + static addDefaultI16(builder, defaultI16) { + builder.addFieldInt16(8, defaultI16, 42); + } + static addJustU16(builder, justU16) { + builder.addFieldInt16(9, justU16, 0); + } + static addMaybeU16(builder, maybeU16) { + builder.addFieldInt16(10, maybeU16, null); + } + static addDefaultU16(builder, defaultU16) { + builder.addFieldInt16(11, defaultU16, 42); + } + static addJustI32(builder, justI32) { + builder.addFieldInt32(12, justI32, 0); + } + static addMaybeI32(builder, maybeI32) { + builder.addFieldInt32(13, maybeI32, null); + } + static addDefaultI32(builder, defaultI32) { + builder.addFieldInt32(14, defaultI32, 42); + } + static addJustU32(builder, justU32) { + builder.addFieldInt32(15, justU32, 0); + } + static addMaybeU32(builder, maybeU32) { + builder.addFieldInt32(16, maybeU32, null); + } + static addDefaultU32(builder, defaultU32) { + builder.addFieldInt32(17, defaultU32, 42); + } + static addJustI64(builder, justI64) { + builder.addFieldInt64(18, justI64, BigInt('0')); + } + static addMaybeI64(builder, maybeI64) { + builder.addFieldInt64(19, maybeI64, null); + } + static addDefaultI64(builder, defaultI64) { + builder.addFieldInt64(20, defaultI64, BigInt('42')); + } + static addJustU64(builder, justU64) { + builder.addFieldInt64(21, justU64, BigInt('0')); + } + static addMaybeU64(builder, maybeU64) { + builder.addFieldInt64(22, maybeU64, null); + } + static addDefaultU64(builder, defaultU64) { + builder.addFieldInt64(23, defaultU64, BigInt('42')); + } + static addJustF32(builder, justF32) { + builder.addFieldFloat32(24, justF32, 0.0); + } + static addMaybeF32(builder, maybeF32) { + builder.addFieldFloat32(25, maybeF32, null); + } + static addDefaultF32(builder, defaultF32) { + builder.addFieldFloat32(26, defaultF32, 42.0); + } + static addJustF64(builder, justF64) { + builder.addFieldFloat64(27, justF64, 0.0); + } + static addMaybeF64(builder, maybeF64) { + builder.addFieldFloat64(28, maybeF64, null); + } + static addDefaultF64(builder, defaultF64) { + builder.addFieldFloat64(29, defaultF64, 42.0); + } + static addJustBool(builder, justBool) { + builder.addFieldInt8(30, +justBool, +false); + } + static addMaybeBool(builder, maybeBool) { + builder.addFieldInt8(31, +maybeBool, null); + } + static addDefaultBool(builder, defaultBool) { + builder.addFieldInt8(32, +defaultBool, +true); + } + static addJustEnum(builder, justEnum) { + builder.addFieldInt8(33, justEnum, OptionalByte.None); + } + static addMaybeEnum(builder, maybeEnum) { + builder.addFieldInt8(34, maybeEnum, null); + } + static addDefaultEnum(builder, defaultEnum) { + builder.addFieldInt8(35, defaultEnum, OptionalByte.One); + } + static endScalarStuff(builder) { + const offset = builder.endObject(); + return offset; + } + static finishScalarStuffBuffer(builder, offset) { + builder.finish(offset, 'NULL'); + } + static finishSizePrefixedScalarStuffBuffer(builder, offset) { + builder.finish(offset, 'NULL', true); + } + static createScalarStuff(builder, justI8, maybeI8, defaultI8, justU8, maybeU8, defaultU8, justI16, maybeI16, defaultI16, justU16, maybeU16, defaultU16, justI32, maybeI32, defaultI32, justU32, maybeU32, defaultU32, justI64, maybeI64, defaultI64, justU64, maybeU64, defaultU64, justF32, maybeF32, defaultF32, justF64, maybeF64, defaultF64, justBool, maybeBool, defaultBool, justEnum, maybeEnum, defaultEnum) { + ScalarStuff.startScalarStuff(builder); + ScalarStuff.addJustI8(builder, justI8); + if (maybeI8 !== null) + ScalarStuff.addMaybeI8(builder, maybeI8); + ScalarStuff.addDefaultI8(builder, defaultI8); + ScalarStuff.addJustU8(builder, justU8); + if (maybeU8 !== null) + ScalarStuff.addMaybeU8(builder, maybeU8); + ScalarStuff.addDefaultU8(builder, defaultU8); + ScalarStuff.addJustI16(builder, justI16); + if (maybeI16 !== null) + ScalarStuff.addMaybeI16(builder, maybeI16); + ScalarStuff.addDefaultI16(builder, defaultI16); + ScalarStuff.addJustU16(builder, justU16); + if (maybeU16 !== null) + ScalarStuff.addMaybeU16(builder, maybeU16); + ScalarStuff.addDefaultU16(builder, defaultU16); + ScalarStuff.addJustI32(builder, justI32); + if (maybeI32 !== null) + ScalarStuff.addMaybeI32(builder, maybeI32); + ScalarStuff.addDefaultI32(builder, defaultI32); + ScalarStuff.addJustU32(builder, justU32); + if (maybeU32 !== null) + ScalarStuff.addMaybeU32(builder, maybeU32); + ScalarStuff.addDefaultU32(builder, defaultU32); + ScalarStuff.addJustI64(builder, justI64); + if (maybeI64 !== null) + ScalarStuff.addMaybeI64(builder, maybeI64); + ScalarStuff.addDefaultI64(builder, defaultI64); + ScalarStuff.addJustU64(builder, justU64); + if (maybeU64 !== null) + ScalarStuff.addMaybeU64(builder, maybeU64); + ScalarStuff.addDefaultU64(builder, defaultU64); + ScalarStuff.addJustF32(builder, justF32); + if (maybeF32 !== null) + ScalarStuff.addMaybeF32(builder, maybeF32); + ScalarStuff.addDefaultF32(builder, defaultF32); + ScalarStuff.addJustF64(builder, justF64); + if (maybeF64 !== null) + ScalarStuff.addMaybeF64(builder, maybeF64); + ScalarStuff.addDefaultF64(builder, defaultF64); + ScalarStuff.addJustBool(builder, justBool); + if (maybeBool !== null) + ScalarStuff.addMaybeBool(builder, maybeBool); + ScalarStuff.addDefaultBool(builder, defaultBool); + ScalarStuff.addJustEnum(builder, justEnum); + if (maybeEnum !== null) + ScalarStuff.addMaybeEnum(builder, maybeEnum); + ScalarStuff.addDefaultEnum(builder, defaultEnum); + return ScalarStuff.endScalarStuff(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.ts new file mode 100644 index 00000000000..5416ab22711 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional-scalars/scalar-stuff.ts @@ -0,0 +1,429 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { OptionalByte } from '../optional-scalars/optional-byte'; + + +export class ScalarStuff { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):ScalarStuff { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff { + return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean { + return bb.__has_identifier('NULL'); +} + +justI8():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0; +} + +maybeI8():number|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : null; +} + +defaultI8():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : 42; +} + +justU8():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0; +} + +maybeU8():number|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : null; +} + +defaultU8():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : 42; +} + +justI16():number { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0; +} + +maybeI16():number|null { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : null; +} + +defaultI16():number { + const offset = this.bb!.__offset(this.bb_pos, 20); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 42; +} + +justU16():number { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +maybeU16():number|null { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : null; +} + +defaultU16():number { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 42; +} + +justI32():number { + const offset = this.bb!.__offset(this.bb_pos, 28); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +maybeI32():number|null { + const offset = this.bb!.__offset(this.bb_pos, 30); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : null; +} + +defaultI32():number { + const offset = this.bb!.__offset(this.bb_pos, 32); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 42; +} + +justU32():number { + const offset = this.bb!.__offset(this.bb_pos, 34); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; +} + +maybeU32():number|null { + const offset = this.bb!.__offset(this.bb_pos, 36); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : null; +} + +defaultU32():number { + const offset = this.bb!.__offset(this.bb_pos, 38); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 42; +} + +justI64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 40); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +maybeI64():bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 42); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : null; +} + +defaultI64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 44); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('42'); +} + +justU64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 46); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +maybeU64():bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 48); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : null; +} + +defaultU64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 50); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('42'); +} + +justF32():number { + const offset = this.bb!.__offset(this.bb_pos, 52); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0; +} + +maybeF32():number|null { + const offset = this.bb!.__offset(this.bb_pos, 54); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : null; +} + +defaultF32():number { + const offset = this.bb!.__offset(this.bb_pos, 56); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 42.0; +} + +justF64():number { + const offset = this.bb!.__offset(this.bb_pos, 58); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0; +} + +maybeF64():number|null { + const offset = this.bb!.__offset(this.bb_pos, 60); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : null; +} + +defaultF64():number { + const offset = this.bb!.__offset(this.bb_pos, 62); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 42.0; +} + +justBool():boolean { + const offset = this.bb!.__offset(this.bb_pos, 64); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +maybeBool():boolean|null { + const offset = this.bb!.__offset(this.bb_pos, 66); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : null; +} + +defaultBool():boolean { + const offset = this.bb!.__offset(this.bb_pos, 68); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : true; +} + +justEnum():OptionalByte { + const offset = this.bb!.__offset(this.bb_pos, 70); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.None; +} + +maybeEnum():OptionalByte|null { + const offset = this.bb!.__offset(this.bb_pos, 72); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : null; +} + +defaultEnum():OptionalByte { + const offset = this.bb!.__offset(this.bb_pos, 74); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.One; +} + +static getFullyQualifiedName():string { + return 'optional_scalars.ScalarStuff'; +} + +static startScalarStuff(builder:flatbuffers.Builder) { + builder.startObject(36); +} + +static addJustI8(builder:flatbuffers.Builder, justI8:number) { + builder.addFieldInt8(0, justI8, 0); +} + +static addMaybeI8(builder:flatbuffers.Builder, maybeI8:number) { + builder.addFieldInt8(1, maybeI8, null); +} + +static addDefaultI8(builder:flatbuffers.Builder, defaultI8:number) { + builder.addFieldInt8(2, defaultI8, 42); +} + +static addJustU8(builder:flatbuffers.Builder, justU8:number) { + builder.addFieldInt8(3, justU8, 0); +} + +static addMaybeU8(builder:flatbuffers.Builder, maybeU8:number) { + builder.addFieldInt8(4, maybeU8, null); +} + +static addDefaultU8(builder:flatbuffers.Builder, defaultU8:number) { + builder.addFieldInt8(5, defaultU8, 42); +} + +static addJustI16(builder:flatbuffers.Builder, justI16:number) { + builder.addFieldInt16(6, justI16, 0); +} + +static addMaybeI16(builder:flatbuffers.Builder, maybeI16:number) { + builder.addFieldInt16(7, maybeI16, null); +} + +static addDefaultI16(builder:flatbuffers.Builder, defaultI16:number) { + builder.addFieldInt16(8, defaultI16, 42); +} + +static addJustU16(builder:flatbuffers.Builder, justU16:number) { + builder.addFieldInt16(9, justU16, 0); +} + +static addMaybeU16(builder:flatbuffers.Builder, maybeU16:number) { + builder.addFieldInt16(10, maybeU16, null); +} + +static addDefaultU16(builder:flatbuffers.Builder, defaultU16:number) { + builder.addFieldInt16(11, defaultU16, 42); +} + +static addJustI32(builder:flatbuffers.Builder, justI32:number) { + builder.addFieldInt32(12, justI32, 0); +} + +static addMaybeI32(builder:flatbuffers.Builder, maybeI32:number) { + builder.addFieldInt32(13, maybeI32, null); +} + +static addDefaultI32(builder:flatbuffers.Builder, defaultI32:number) { + builder.addFieldInt32(14, defaultI32, 42); +} + +static addJustU32(builder:flatbuffers.Builder, justU32:number) { + builder.addFieldInt32(15, justU32, 0); +} + +static addMaybeU32(builder:flatbuffers.Builder, maybeU32:number) { + builder.addFieldInt32(16, maybeU32, null); +} + +static addDefaultU32(builder:flatbuffers.Builder, defaultU32:number) { + builder.addFieldInt32(17, defaultU32, 42); +} + +static addJustI64(builder:flatbuffers.Builder, justI64:bigint) { + builder.addFieldInt64(18, justI64, BigInt('0')); +} + +static addMaybeI64(builder:flatbuffers.Builder, maybeI64:bigint) { + builder.addFieldInt64(19, maybeI64, null); +} + +static addDefaultI64(builder:flatbuffers.Builder, defaultI64:bigint) { + builder.addFieldInt64(20, defaultI64, BigInt('42')); +} + +static addJustU64(builder:flatbuffers.Builder, justU64:bigint) { + builder.addFieldInt64(21, justU64, BigInt('0')); +} + +static addMaybeU64(builder:flatbuffers.Builder, maybeU64:bigint) { + builder.addFieldInt64(22, maybeU64, null); +} + +static addDefaultU64(builder:flatbuffers.Builder, defaultU64:bigint) { + builder.addFieldInt64(23, defaultU64, BigInt('42')); +} + +static addJustF32(builder:flatbuffers.Builder, justF32:number) { + builder.addFieldFloat32(24, justF32, 0.0); +} + +static addMaybeF32(builder:flatbuffers.Builder, maybeF32:number) { + builder.addFieldFloat32(25, maybeF32, null); +} + +static addDefaultF32(builder:flatbuffers.Builder, defaultF32:number) { + builder.addFieldFloat32(26, defaultF32, 42.0); +} + +static addJustF64(builder:flatbuffers.Builder, justF64:number) { + builder.addFieldFloat64(27, justF64, 0.0); +} + +static addMaybeF64(builder:flatbuffers.Builder, maybeF64:number) { + builder.addFieldFloat64(28, maybeF64, null); +} + +static addDefaultF64(builder:flatbuffers.Builder, defaultF64:number) { + builder.addFieldFloat64(29, defaultF64, 42.0); +} + +static addJustBool(builder:flatbuffers.Builder, justBool:boolean) { + builder.addFieldInt8(30, +justBool, +false); +} + +static addMaybeBool(builder:flatbuffers.Builder, maybeBool:boolean) { + builder.addFieldInt8(31, +maybeBool, null); +} + +static addDefaultBool(builder:flatbuffers.Builder, defaultBool:boolean) { + builder.addFieldInt8(32, +defaultBool, +true); +} + +static addJustEnum(builder:flatbuffers.Builder, justEnum:OptionalByte) { + builder.addFieldInt8(33, justEnum, OptionalByte.None); +} + +static addMaybeEnum(builder:flatbuffers.Builder, maybeEnum:OptionalByte) { + builder.addFieldInt8(34, maybeEnum, null); +} + +static addDefaultEnum(builder:flatbuffers.Builder, defaultEnum:OptionalByte) { + builder.addFieldInt8(35, defaultEnum, OptionalByte.One); +} + +static endScalarStuff(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static finishScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'NULL'); +} + +static finishSizePrefixedScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'NULL', true); +} + +static createScalarStuff(builder:flatbuffers.Builder, justI8:number, maybeI8:number|null, defaultI8:number, justU8:number, maybeU8:number|null, defaultU8:number, justI16:number, maybeI16:number|null, defaultI16:number, justU16:number, maybeU16:number|null, defaultU16:number, justI32:number, maybeI32:number|null, defaultI32:number, justU32:number, maybeU32:number|null, defaultU32:number, justI64:bigint, maybeI64:bigint|null, defaultI64:bigint, justU64:bigint, maybeU64:bigint|null, defaultU64:bigint, justF32:number, maybeF32:number|null, defaultF32:number, justF64:number, maybeF64:number|null, defaultF64:number, justBool:boolean, maybeBool:boolean|null, defaultBool:boolean, justEnum:OptionalByte, maybeEnum:OptionalByte|null, defaultEnum:OptionalByte):flatbuffers.Offset { + ScalarStuff.startScalarStuff(builder); + ScalarStuff.addJustI8(builder, justI8); + if (maybeI8 !== null) + ScalarStuff.addMaybeI8(builder, maybeI8); + ScalarStuff.addDefaultI8(builder, defaultI8); + ScalarStuff.addJustU8(builder, justU8); + if (maybeU8 !== null) + ScalarStuff.addMaybeU8(builder, maybeU8); + ScalarStuff.addDefaultU8(builder, defaultU8); + ScalarStuff.addJustI16(builder, justI16); + if (maybeI16 !== null) + ScalarStuff.addMaybeI16(builder, maybeI16); + ScalarStuff.addDefaultI16(builder, defaultI16); + ScalarStuff.addJustU16(builder, justU16); + if (maybeU16 !== null) + ScalarStuff.addMaybeU16(builder, maybeU16); + ScalarStuff.addDefaultU16(builder, defaultU16); + ScalarStuff.addJustI32(builder, justI32); + if (maybeI32 !== null) + ScalarStuff.addMaybeI32(builder, maybeI32); + ScalarStuff.addDefaultI32(builder, defaultI32); + ScalarStuff.addJustU32(builder, justU32); + if (maybeU32 !== null) + ScalarStuff.addMaybeU32(builder, maybeU32); + ScalarStuff.addDefaultU32(builder, defaultU32); + ScalarStuff.addJustI64(builder, justI64); + if (maybeI64 !== null) + ScalarStuff.addMaybeI64(builder, maybeI64); + ScalarStuff.addDefaultI64(builder, defaultI64); + ScalarStuff.addJustU64(builder, justU64); + if (maybeU64 !== null) + ScalarStuff.addMaybeU64(builder, maybeU64); + ScalarStuff.addDefaultU64(builder, defaultU64); + ScalarStuff.addJustF32(builder, justF32); + if (maybeF32 !== null) + ScalarStuff.addMaybeF32(builder, maybeF32); + ScalarStuff.addDefaultF32(builder, defaultF32); + ScalarStuff.addJustF64(builder, justF64); + if (maybeF64 !== null) + ScalarStuff.addMaybeF64(builder, maybeF64); + ScalarStuff.addDefaultF64(builder, defaultF64); + ScalarStuff.addJustBool(builder, justBool); + if (maybeBool !== null) + ScalarStuff.addMaybeBool(builder, maybeBool); + ScalarStuff.addDefaultBool(builder, defaultBool); + ScalarStuff.addJustEnum(builder, justEnum); + if (maybeEnum !== null) + ScalarStuff.addMaybeEnum(builder, maybeEnum); + ScalarStuff.addDefaultEnum(builder, defaultEnum); + return ScalarStuff.endScalarStuff(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.d.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.d.ts new file mode 100644 index 00000000000..de14740c35c --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.d.ts @@ -0,0 +1 @@ +export * as optional_scalars from './optional-scalars.js'; diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.js b/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.js new file mode 100644 index 00000000000..d519b38fa48 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.js @@ -0,0 +1,3 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import * as optional_scalars_1 from './optional-scalars.js'; +export { optional_scalars_1 as optional_scalars }; diff --git a/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.ts b/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.ts new file mode 100644 index 00000000000..3805ab68c83 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/no_import_ext/optional_scalars.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export * as optional_scalars from './optional-scalars.js'; diff --git a/third_party/flatbuffers/tests/ts/optional-scalars.ts b/third_party/flatbuffers/tests/ts/optional-scalars.ts new file mode 100644 index 00000000000..5ee90df78ff --- /dev/null +++ b/third_party/flatbuffers/tests/ts/optional-scalars.ts @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { OptionalByte } from './optional-scalars/optional-byte.js'; +export { ScalarStuff } from './optional-scalars/scalar-stuff.js'; diff --git a/third_party/flatbuffers/tests/ts/optional-scalars/optional-byte.ts b/third_party/flatbuffers/tests/ts/optional-scalars/optional-byte.ts new file mode 100644 index 00000000000..9bb66a9bc14 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/optional-scalars/optional-byte.ts @@ -0,0 +1,9 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum OptionalByte { + None = 0, + One = 1, + Two = 2 +} diff --git a/third_party/flatbuffers/tests/ts/optional-scalars/scalar-stuff.ts b/third_party/flatbuffers/tests/ts/optional-scalars/scalar-stuff.ts new file mode 100644 index 00000000000..e76088bce38 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/optional-scalars/scalar-stuff.ts @@ -0,0 +1,429 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { OptionalByte } from '../optional-scalars/optional-byte.js'; + + +export class ScalarStuff { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):ScalarStuff { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff { + return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsScalarStuff(bb:flatbuffers.ByteBuffer, obj?:ScalarStuff):ScalarStuff { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new ScalarStuff()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean { + return bb.__has_identifier('NULL'); +} + +justI8():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : 0; +} + +maybeI8():number|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : null; +} + +defaultI8():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : 42; +} + +justU8():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : 0; +} + +maybeU8():number|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : null; +} + +defaultU8():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : 42; +} + +justI16():number { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 0; +} + +maybeI16():number|null { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : null; +} + +defaultI16():number { + const offset = this.bb!.__offset(this.bb_pos, 20); + return offset ? this.bb!.readInt16(this.bb_pos + offset) : 42; +} + +justU16():number { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +maybeU16():number|null { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : null; +} + +defaultU16():number { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 42; +} + +justI32():number { + const offset = this.bb!.__offset(this.bb_pos, 28); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +maybeI32():number|null { + const offset = this.bb!.__offset(this.bb_pos, 30); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : null; +} + +defaultI32():number { + const offset = this.bb!.__offset(this.bb_pos, 32); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 42; +} + +justU32():number { + const offset = this.bb!.__offset(this.bb_pos, 34); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; +} + +maybeU32():number|null { + const offset = this.bb!.__offset(this.bb_pos, 36); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : null; +} + +defaultU32():number { + const offset = this.bb!.__offset(this.bb_pos, 38); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 42; +} + +justI64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 40); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +maybeI64():bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 42); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : null; +} + +defaultI64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 44); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('42'); +} + +justU64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 46); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +maybeU64():bigint|null { + const offset = this.bb!.__offset(this.bb_pos, 48); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : null; +} + +defaultU64():bigint { + const offset = this.bb!.__offset(this.bb_pos, 50); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('42'); +} + +justF32():number { + const offset = this.bb!.__offset(this.bb_pos, 52); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 0.0; +} + +maybeF32():number|null { + const offset = this.bb!.__offset(this.bb_pos, 54); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : null; +} + +defaultF32():number { + const offset = this.bb!.__offset(this.bb_pos, 56); + return offset ? this.bb!.readFloat32(this.bb_pos + offset) : 42.0; +} + +justF64():number { + const offset = this.bb!.__offset(this.bb_pos, 58); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0; +} + +maybeF64():number|null { + const offset = this.bb!.__offset(this.bb_pos, 60); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : null; +} + +defaultF64():number { + const offset = this.bb!.__offset(this.bb_pos, 62); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 42.0; +} + +justBool():boolean { + const offset = this.bb!.__offset(this.bb_pos, 64); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +maybeBool():boolean|null { + const offset = this.bb!.__offset(this.bb_pos, 66); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : null; +} + +defaultBool():boolean { + const offset = this.bb!.__offset(this.bb_pos, 68); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : true; +} + +justEnum():OptionalByte { + const offset = this.bb!.__offset(this.bb_pos, 70); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.None; +} + +maybeEnum():OptionalByte|null { + const offset = this.bb!.__offset(this.bb_pos, 72); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : null; +} + +defaultEnum():OptionalByte { + const offset = this.bb!.__offset(this.bb_pos, 74); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : OptionalByte.One; +} + +static getFullyQualifiedName():string { + return 'optional_scalars.ScalarStuff'; +} + +static startScalarStuff(builder:flatbuffers.Builder) { + builder.startObject(36); +} + +static addJustI8(builder:flatbuffers.Builder, justI8:number) { + builder.addFieldInt8(0, justI8, 0); +} + +static addMaybeI8(builder:flatbuffers.Builder, maybeI8:number) { + builder.addFieldInt8(1, maybeI8, null); +} + +static addDefaultI8(builder:flatbuffers.Builder, defaultI8:number) { + builder.addFieldInt8(2, defaultI8, 42); +} + +static addJustU8(builder:flatbuffers.Builder, justU8:number) { + builder.addFieldInt8(3, justU8, 0); +} + +static addMaybeU8(builder:flatbuffers.Builder, maybeU8:number) { + builder.addFieldInt8(4, maybeU8, null); +} + +static addDefaultU8(builder:flatbuffers.Builder, defaultU8:number) { + builder.addFieldInt8(5, defaultU8, 42); +} + +static addJustI16(builder:flatbuffers.Builder, justI16:number) { + builder.addFieldInt16(6, justI16, 0); +} + +static addMaybeI16(builder:flatbuffers.Builder, maybeI16:number) { + builder.addFieldInt16(7, maybeI16, null); +} + +static addDefaultI16(builder:flatbuffers.Builder, defaultI16:number) { + builder.addFieldInt16(8, defaultI16, 42); +} + +static addJustU16(builder:flatbuffers.Builder, justU16:number) { + builder.addFieldInt16(9, justU16, 0); +} + +static addMaybeU16(builder:flatbuffers.Builder, maybeU16:number) { + builder.addFieldInt16(10, maybeU16, null); +} + +static addDefaultU16(builder:flatbuffers.Builder, defaultU16:number) { + builder.addFieldInt16(11, defaultU16, 42); +} + +static addJustI32(builder:flatbuffers.Builder, justI32:number) { + builder.addFieldInt32(12, justI32, 0); +} + +static addMaybeI32(builder:flatbuffers.Builder, maybeI32:number) { + builder.addFieldInt32(13, maybeI32, null); +} + +static addDefaultI32(builder:flatbuffers.Builder, defaultI32:number) { + builder.addFieldInt32(14, defaultI32, 42); +} + +static addJustU32(builder:flatbuffers.Builder, justU32:number) { + builder.addFieldInt32(15, justU32, 0); +} + +static addMaybeU32(builder:flatbuffers.Builder, maybeU32:number) { + builder.addFieldInt32(16, maybeU32, null); +} + +static addDefaultU32(builder:flatbuffers.Builder, defaultU32:number) { + builder.addFieldInt32(17, defaultU32, 42); +} + +static addJustI64(builder:flatbuffers.Builder, justI64:bigint) { + builder.addFieldInt64(18, justI64, BigInt('0')); +} + +static addMaybeI64(builder:flatbuffers.Builder, maybeI64:bigint) { + builder.addFieldInt64(19, maybeI64, null); +} + +static addDefaultI64(builder:flatbuffers.Builder, defaultI64:bigint) { + builder.addFieldInt64(20, defaultI64, BigInt('42')); +} + +static addJustU64(builder:flatbuffers.Builder, justU64:bigint) { + builder.addFieldInt64(21, justU64, BigInt('0')); +} + +static addMaybeU64(builder:flatbuffers.Builder, maybeU64:bigint) { + builder.addFieldInt64(22, maybeU64, null); +} + +static addDefaultU64(builder:flatbuffers.Builder, defaultU64:bigint) { + builder.addFieldInt64(23, defaultU64, BigInt('42')); +} + +static addJustF32(builder:flatbuffers.Builder, justF32:number) { + builder.addFieldFloat32(24, justF32, 0.0); +} + +static addMaybeF32(builder:flatbuffers.Builder, maybeF32:number) { + builder.addFieldFloat32(25, maybeF32, null); +} + +static addDefaultF32(builder:flatbuffers.Builder, defaultF32:number) { + builder.addFieldFloat32(26, defaultF32, 42.0); +} + +static addJustF64(builder:flatbuffers.Builder, justF64:number) { + builder.addFieldFloat64(27, justF64, 0.0); +} + +static addMaybeF64(builder:flatbuffers.Builder, maybeF64:number) { + builder.addFieldFloat64(28, maybeF64, null); +} + +static addDefaultF64(builder:flatbuffers.Builder, defaultF64:number) { + builder.addFieldFloat64(29, defaultF64, 42.0); +} + +static addJustBool(builder:flatbuffers.Builder, justBool:boolean) { + builder.addFieldInt8(30, +justBool, +false); +} + +static addMaybeBool(builder:flatbuffers.Builder, maybeBool:boolean) { + builder.addFieldInt8(31, +maybeBool, null); +} + +static addDefaultBool(builder:flatbuffers.Builder, defaultBool:boolean) { + builder.addFieldInt8(32, +defaultBool, +true); +} + +static addJustEnum(builder:flatbuffers.Builder, justEnum:OptionalByte) { + builder.addFieldInt8(33, justEnum, OptionalByte.None); +} + +static addMaybeEnum(builder:flatbuffers.Builder, maybeEnum:OptionalByte) { + builder.addFieldInt8(34, maybeEnum, null); +} + +static addDefaultEnum(builder:flatbuffers.Builder, defaultEnum:OptionalByte) { + builder.addFieldInt8(35, defaultEnum, OptionalByte.One); +} + +static endScalarStuff(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static finishScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'NULL'); +} + +static finishSizePrefixedScalarStuffBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'NULL', true); +} + +static createScalarStuff(builder:flatbuffers.Builder, justI8:number, maybeI8:number|null, defaultI8:number, justU8:number, maybeU8:number|null, defaultU8:number, justI16:number, maybeI16:number|null, defaultI16:number, justU16:number, maybeU16:number|null, defaultU16:number, justI32:number, maybeI32:number|null, defaultI32:number, justU32:number, maybeU32:number|null, defaultU32:number, justI64:bigint, maybeI64:bigint|null, defaultI64:bigint, justU64:bigint, maybeU64:bigint|null, defaultU64:bigint, justF32:number, maybeF32:number|null, defaultF32:number, justF64:number, maybeF64:number|null, defaultF64:number, justBool:boolean, maybeBool:boolean|null, defaultBool:boolean, justEnum:OptionalByte, maybeEnum:OptionalByte|null, defaultEnum:OptionalByte):flatbuffers.Offset { + ScalarStuff.startScalarStuff(builder); + ScalarStuff.addJustI8(builder, justI8); + if (maybeI8 !== null) + ScalarStuff.addMaybeI8(builder, maybeI8); + ScalarStuff.addDefaultI8(builder, defaultI8); + ScalarStuff.addJustU8(builder, justU8); + if (maybeU8 !== null) + ScalarStuff.addMaybeU8(builder, maybeU8); + ScalarStuff.addDefaultU8(builder, defaultU8); + ScalarStuff.addJustI16(builder, justI16); + if (maybeI16 !== null) + ScalarStuff.addMaybeI16(builder, maybeI16); + ScalarStuff.addDefaultI16(builder, defaultI16); + ScalarStuff.addJustU16(builder, justU16); + if (maybeU16 !== null) + ScalarStuff.addMaybeU16(builder, maybeU16); + ScalarStuff.addDefaultU16(builder, defaultU16); + ScalarStuff.addJustI32(builder, justI32); + if (maybeI32 !== null) + ScalarStuff.addMaybeI32(builder, maybeI32); + ScalarStuff.addDefaultI32(builder, defaultI32); + ScalarStuff.addJustU32(builder, justU32); + if (maybeU32 !== null) + ScalarStuff.addMaybeU32(builder, maybeU32); + ScalarStuff.addDefaultU32(builder, defaultU32); + ScalarStuff.addJustI64(builder, justI64); + if (maybeI64 !== null) + ScalarStuff.addMaybeI64(builder, maybeI64); + ScalarStuff.addDefaultI64(builder, defaultI64); + ScalarStuff.addJustU64(builder, justU64); + if (maybeU64 !== null) + ScalarStuff.addMaybeU64(builder, maybeU64); + ScalarStuff.addDefaultU64(builder, defaultU64); + ScalarStuff.addJustF32(builder, justF32); + if (maybeF32 !== null) + ScalarStuff.addMaybeF32(builder, maybeF32); + ScalarStuff.addDefaultF32(builder, defaultF32); + ScalarStuff.addJustF64(builder, justF64); + if (maybeF64 !== null) + ScalarStuff.addMaybeF64(builder, maybeF64); + ScalarStuff.addDefaultF64(builder, defaultF64); + ScalarStuff.addJustBool(builder, justBool); + if (maybeBool !== null) + ScalarStuff.addMaybeBool(builder, maybeBool); + ScalarStuff.addDefaultBool(builder, defaultBool); + ScalarStuff.addJustEnum(builder, justEnum); + if (maybeEnum !== null) + ScalarStuff.addMaybeEnum(builder, maybeEnum); + ScalarStuff.addDefaultEnum(builder, defaultEnum); + return ScalarStuff.endScalarStuff(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/optional_scalars.ts b/third_party/flatbuffers/tests/ts/optional_scalars.ts new file mode 100644 index 00000000000..3805ab68c83 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/optional_scalars.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export * as optional_scalars from './optional-scalars.js'; diff --git a/third_party/flatbuffers/tests/ts/package.json b/third_party/flatbuffers/tests/ts/package.json new file mode 100644 index 00000000000..1639cf831e3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "dependencies": { + "flatbuffers": "../../" + } +} diff --git a/third_party/flatbuffers/tests/ts/pnpm-lock.yaml b/third_party/flatbuffers/tests/ts/pnpm-lock.yaml new file mode 100644 index 00000000000..730e4d7b227 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/pnpm-lock.yaml @@ -0,0 +1,10 @@ +lockfileVersion: '6.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +dependencies: + flatbuffers: + specifier: ../../ + version: link:../.. diff --git a/third_party/flatbuffers/tests/ts/reflection.d.ts b/third_party/flatbuffers/tests/ts/reflection.d.ts new file mode 100644 index 00000000000..5e1f87694e8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection.d.ts @@ -0,0 +1,12 @@ +export { AdvancedFeatures } from './reflection/advanced-features.js'; +export { BaseType } from './reflection/base-type.js'; +export { Enum, EnumT } from './reflection/enum.js'; +export { EnumVal, EnumValT } from './reflection/enum-val.js'; +export { Field, FieldT } from './reflection/field.js'; +export { KeyValue, KeyValueT } from './reflection/key-value.js'; +export { Object_ } from './reflection/object.js'; +export { RPCCall, RPCCallT } from './reflection/rpccall.js'; +export { Schema, SchemaT } from './reflection/schema.js'; +export { SchemaFile, SchemaFileT } from './reflection/schema-file.js'; +export { Service, ServiceT } from './reflection/service.js'; +export { Type, TypeT } from './reflection/type.js'; diff --git a/third_party/flatbuffers/tests/ts/reflection.js b/third_party/flatbuffers/tests/ts/reflection.js new file mode 100644 index 00000000000..ac0705641c2 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection.js @@ -0,0 +1,14 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { AdvancedFeatures } from './reflection/advanced-features.js'; +export { BaseType } from './reflection/base-type.js'; +export { Enum, EnumT } from './reflection/enum.js'; +export { EnumVal, EnumValT } from './reflection/enum-val.js'; +export { Field, FieldT } from './reflection/field.js'; +export { KeyValue, KeyValueT } from './reflection/key-value.js'; +export { Object_ } from './reflection/object.js'; +export { RPCCall, RPCCallT } from './reflection/rpccall.js'; +export { Schema, SchemaT } from './reflection/schema.js'; +export { SchemaFile, SchemaFileT } from './reflection/schema-file.js'; +export { Service, ServiceT } from './reflection/service.js'; +export { Type, TypeT } from './reflection/type.js'; diff --git a/third_party/flatbuffers/tests/ts/reflection.ts b/third_party/flatbuffers/tests/ts/reflection.ts new file mode 100644 index 00000000000..a43d07d212d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection.ts @@ -0,0 +1,16 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { AdvancedFeatures } from './reflection/advanced-features.js'; +export { BaseType } from './reflection/base-type.js'; +export { Enum, EnumT } from './reflection/enum.js'; +export { EnumVal, EnumValT } from './reflection/enum-val.js'; +export { Field, FieldT } from './reflection/field.js'; +export { KeyValue, KeyValueT } from './reflection/key-value.js'; +export { Object_ } from './reflection/object.js'; +export { RPCCall, RPCCallT } from './reflection/rpccall.js'; +export { Schema, SchemaT } from './reflection/schema.js'; +export { SchemaFile, SchemaFileT } from './reflection/schema-file.js'; +export { Service, ServiceT } from './reflection/service.js'; +export { Type, TypeT } from './reflection/type.js'; diff --git a/third_party/flatbuffers/tests/ts/reflection/advanced-features.d.ts b/third_party/flatbuffers/tests/ts/reflection/advanced-features.d.ts new file mode 100644 index 00000000000..a51745e45e8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/advanced-features.d.ts @@ -0,0 +1,9 @@ +/** + * New schema language features that are not supported by old code generators. + */ +export declare enum AdvancedFeatures { + AdvancedArrayFeatures = "1", + AdvancedUnionFeatures = "2", + OptionalScalars = "4", + DefaultVectorsAndStrings = "8" +} diff --git a/third_party/flatbuffers/tests/ts/reflection/advanced-features.js b/third_party/flatbuffers/tests/ts/reflection/advanced-features.js new file mode 100644 index 00000000000..aeef1a78da3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/advanced-features.js @@ -0,0 +1,12 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +/** + * New schema language features that are not supported by old code generators. + */ +export var AdvancedFeatures; +(function (AdvancedFeatures) { + AdvancedFeatures["AdvancedArrayFeatures"] = "1"; + AdvancedFeatures["AdvancedUnionFeatures"] = "2"; + AdvancedFeatures["OptionalScalars"] = "4"; + AdvancedFeatures["DefaultVectorsAndStrings"] = "8"; +})(AdvancedFeatures || (AdvancedFeatures = {})); diff --git a/third_party/flatbuffers/tests/ts/reflection/advanced-features.ts b/third_party/flatbuffers/tests/ts/reflection/advanced-features.ts new file mode 100644 index 00000000000..f68b7e24df9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/advanced-features.ts @@ -0,0 +1,13 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +/** + * New schema language features that are not supported by old code generators. + */ +export enum AdvancedFeatures { + AdvancedArrayFeatures = '1', + AdvancedUnionFeatures = '2', + OptionalScalars = '4', + DefaultVectorsAndStrings = '8' +} diff --git a/third_party/flatbuffers/tests/ts/reflection/base-type.d.ts b/third_party/flatbuffers/tests/ts/reflection/base-type.d.ts new file mode 100644 index 00000000000..a4aea8bd17f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/base-type.d.ts @@ -0,0 +1,22 @@ +export declare enum BaseType { + None = 0, + UType = 1, + Bool = 2, + Byte = 3, + UByte = 4, + Short = 5, + UShort = 6, + Int = 7, + UInt = 8, + Long = 9, + ULong = 10, + Float = 11, + Double = 12, + String = 13, + Vector = 14, + Obj = 15, + Union = 16, + Array = 17, + Vector64 = 18, + MaxBaseType = 19 +} diff --git a/third_party/flatbuffers/tests/ts/reflection/base-type.js b/third_party/flatbuffers/tests/ts/reflection/base-type.js new file mode 100644 index 00000000000..957d9fdc472 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/base-type.js @@ -0,0 +1,25 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var BaseType; +(function (BaseType) { + BaseType[BaseType["None"] = 0] = "None"; + BaseType[BaseType["UType"] = 1] = "UType"; + BaseType[BaseType["Bool"] = 2] = "Bool"; + BaseType[BaseType["Byte"] = 3] = "Byte"; + BaseType[BaseType["UByte"] = 4] = "UByte"; + BaseType[BaseType["Short"] = 5] = "Short"; + BaseType[BaseType["UShort"] = 6] = "UShort"; + BaseType[BaseType["Int"] = 7] = "Int"; + BaseType[BaseType["UInt"] = 8] = "UInt"; + BaseType[BaseType["Long"] = 9] = "Long"; + BaseType[BaseType["ULong"] = 10] = "ULong"; + BaseType[BaseType["Float"] = 11] = "Float"; + BaseType[BaseType["Double"] = 12] = "Double"; + BaseType[BaseType["String"] = 13] = "String"; + BaseType[BaseType["Vector"] = 14] = "Vector"; + BaseType[BaseType["Obj"] = 15] = "Obj"; + BaseType[BaseType["Union"] = 16] = "Union"; + BaseType[BaseType["Array"] = 17] = "Array"; + BaseType[BaseType["Vector64"] = 18] = "Vector64"; + BaseType[BaseType["MaxBaseType"] = 19] = "MaxBaseType"; +})(BaseType || (BaseType = {})); diff --git a/third_party/flatbuffers/tests/ts/reflection/base-type.ts b/third_party/flatbuffers/tests/ts/reflection/base-type.ts new file mode 100644 index 00000000000..38ef9fa1cbb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/base-type.ts @@ -0,0 +1,26 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum BaseType { + None = 0, + UType = 1, + Bool = 2, + Byte = 3, + UByte = 4, + Short = 5, + UShort = 6, + Int = 7, + UInt = 8, + Long = 9, + ULong = 10, + Float = 11, + Double = 12, + String = 13, + Vector = 14, + Obj = 15, + Union = 16, + Array = 17, + Vector64 = 18, + MaxBaseType = 19 +} diff --git a/third_party/flatbuffers/tests/ts/reflection/enum-val.d.ts b/third_party/flatbuffers/tests/ts/reflection/enum-val.d.ts new file mode 100644 index 00000000000..ba436fffa20 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/enum-val.d.ts @@ -0,0 +1,43 @@ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Type, TypeT } from '../reflection/type.js'; +export declare class EnumVal implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): EnumVal; + static getRootAsEnumVal(bb: flatbuffers.ByteBuffer, obj?: EnumVal): EnumVal; + static getSizePrefixedRootAsEnumVal(bb: flatbuffers.ByteBuffer, obj?: EnumVal): EnumVal; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + value(): bigint; + mutate_value(value: bigint): boolean; + unionType(obj?: Type): Type | null; + documentation(index: number): string; + documentation(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + documentationLength(): number; + attributes(index: number, obj?: KeyValue): KeyValue | null; + attributesLength(): number; + static getFullyQualifiedName(): string; + static startEnumVal(builder: flatbuffers.Builder): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addValue(builder: flatbuffers.Builder, value: bigint): void; + static addUnionType(builder: flatbuffers.Builder, unionTypeOffset: flatbuffers.Offset): void; + static addDocumentation(builder: flatbuffers.Builder, documentationOffset: flatbuffers.Offset): void; + static createDocumentationVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startDocumentationVector(builder: flatbuffers.Builder, numElems: number): void; + static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset): void; + static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startAttributesVector(builder: flatbuffers.Builder, numElems: number): void; + static endEnumVal(builder: flatbuffers.Builder): flatbuffers.Offset; + unpack(): EnumValT; + unpackTo(_o: EnumValT): void; +} +export declare class EnumValT implements flatbuffers.IGeneratedObject { + name: string | Uint8Array | null; + value: bigint; + unionType: TypeT | null; + documentation: (string)[]; + attributes: (KeyValueT)[]; + constructor(name?: string | Uint8Array | null, value?: bigint, unionType?: TypeT | null, documentation?: (string)[], attributes?: (KeyValueT)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/enum-val.js b/third_party/flatbuffers/tests/ts/reflection/enum-val.js new file mode 100644 index 00000000000..c937455006f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/enum-val.js @@ -0,0 +1,137 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue } from '../reflection/key-value.js'; +import { Type } from '../reflection/type.js'; +export class EnumVal { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsEnumVal(bb, obj) { + return (obj || new EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsEnumVal(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + mutate_value(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + unionType(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return 'reflection.EnumVal'; + } + static startEnumVal(builder) { + builder.startObject(6); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addValue(builder, value) { + builder.addFieldInt64(1, value, BigInt('0')); + } + static addUnionType(builder, unionTypeOffset) { + builder.addFieldOffset(3, unionTypeOffset, 0); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(4, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(5, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endEnumVal(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // name + return offset; + } + unpack() { + return new EnumValT(this.name(), this.value(), (this.unionType() !== null ? this.unionType().unpack() : null), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.bb.createObjList(this.attributes.bind(this), this.attributesLength())); + } + unpackTo(_o) { + _o.name = this.name(); + _o.value = this.value(); + _o.unionType = (this.unionType() !== null ? this.unionType().unpack() : null); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + } +} +export class EnumValT { + constructor(name = null, value = BigInt('0'), unionType = null, documentation = [], attributes = []) { + this.name = name; + this.value = value; + this.unionType = unionType; + this.documentation = documentation; + this.attributes = attributes; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const unionType = (this.unionType !== null ? this.unionType.pack(builder) : 0); + const documentation = EnumVal.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const attributes = EnumVal.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + EnumVal.startEnumVal(builder); + EnumVal.addName(builder, name); + EnumVal.addValue(builder, this.value); + EnumVal.addUnionType(builder, unionType); + EnumVal.addDocumentation(builder, documentation); + EnumVal.addAttributes(builder, attributes); + return EnumVal.endEnumVal(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/enum-val.ts b/third_party/flatbuffers/tests/ts/reflection/enum-val.ts new file mode 100644 index 00000000000..49e4a214fe8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/enum-val.ts @@ -0,0 +1,183 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Type, TypeT } from '../reflection/type.js'; + + +export class EnumVal implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):EnumVal { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsEnumVal(bb:flatbuffers.ByteBuffer, obj?:EnumVal):EnumVal { + return (obj || new EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsEnumVal(bb:flatbuffers.ByteBuffer, obj?:EnumVal):EnumVal { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +value():bigint { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_value(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt64(this.bb_pos + offset, value); + return true; +} + +unionType(obj?:Type):Type|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +documentation(index: number):string +documentation(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +documentation(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +documentationLength():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +attributes(index: number, obj?:KeyValue):KeyValue|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +attributesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static getFullyQualifiedName():string { + return 'reflection.EnumVal'; +} + +static startEnumVal(builder:flatbuffers.Builder) { + builder.startObject(6); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, nameOffset, 0); +} + +static addValue(builder:flatbuffers.Builder, value:bigint) { + builder.addFieldInt64(1, value, BigInt('0')); +} + +static addUnionType(builder:flatbuffers.Builder, unionTypeOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, unionTypeOffset, 0); +} + +static addDocumentation(builder:flatbuffers.Builder, documentationOffset:flatbuffers.Offset) { + builder.addFieldOffset(4, documentationOffset, 0); +} + +static createDocumentationVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startDocumentationVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addAttributes(builder:flatbuffers.Builder, attributesOffset:flatbuffers.Offset) { + builder.addFieldOffset(5, attributesOffset, 0); +} + +static createAttributesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startAttributesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endEnumVal(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // name + return offset; +} + + +unpack(): EnumValT { + return new EnumValT( + this.name(), + this.value(), + (this.unionType() !== null ? this.unionType()!.unpack() : null), + this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()), + this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()) + ); +} + + +unpackTo(_o: EnumValT): void { + _o.name = this.name(); + _o.value = this.value(); + _o.unionType = (this.unionType() !== null ? this.unionType()!.unpack() : null); + _o.documentation = this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.attributes = this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()); +} +} + +export class EnumValT implements flatbuffers.IGeneratedObject { +constructor( + public name: string|Uint8Array|null = null, + public value: bigint = BigInt('0'), + public unionType: TypeT|null = null, + public documentation: (string)[] = [], + public attributes: (KeyValueT)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const unionType = (this.unionType !== null ? this.unionType!.pack(builder) : 0); + const documentation = EnumVal.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const attributes = EnumVal.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + + EnumVal.startEnumVal(builder); + EnumVal.addName(builder, name); + EnumVal.addValue(builder, this.value); + EnumVal.addUnionType(builder, unionType); + EnumVal.addDocumentation(builder, documentation); + EnumVal.addAttributes(builder, attributes); + + return EnumVal.endEnumVal(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/enum.d.ts b/third_party/flatbuffers/tests/ts/reflection/enum.d.ts new file mode 100644 index 00000000000..e4226bf5244 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/enum.d.ts @@ -0,0 +1,57 @@ +import * as flatbuffers from 'flatbuffers'; +import { EnumVal, EnumValT } from '../reflection/enum-val.js'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Type, TypeT } from '../reflection/type.js'; +export declare class Enum implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Enum; + static getRootAsEnum(bb: flatbuffers.ByteBuffer, obj?: Enum): Enum; + static getSizePrefixedRootAsEnum(bb: flatbuffers.ByteBuffer, obj?: Enum): Enum; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + values(index: number, obj?: EnumVal): EnumVal | null; + valuesLength(): number; + isUnion(): boolean; + mutate_is_union(value: boolean): boolean; + underlyingType(obj?: Type): Type | null; + attributes(index: number, obj?: KeyValue): KeyValue | null; + attributesLength(): number; + documentation(index: number): string; + documentation(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + documentationLength(): number; + /** + * File that this Enum is declared in. + */ + declarationFile(): string | null; + declarationFile(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + static getFullyQualifiedName(): string; + static startEnum(builder: flatbuffers.Builder): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addValues(builder: flatbuffers.Builder, valuesOffset: flatbuffers.Offset): void; + static createValuesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startValuesVector(builder: flatbuffers.Builder, numElems: number): void; + static addIsUnion(builder: flatbuffers.Builder, isUnion: boolean): void; + static addUnderlyingType(builder: flatbuffers.Builder, underlyingTypeOffset: flatbuffers.Offset): void; + static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset): void; + static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startAttributesVector(builder: flatbuffers.Builder, numElems: number): void; + static addDocumentation(builder: flatbuffers.Builder, documentationOffset: flatbuffers.Offset): void; + static createDocumentationVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startDocumentationVector(builder: flatbuffers.Builder, numElems: number): void; + static addDeclarationFile(builder: flatbuffers.Builder, declarationFileOffset: flatbuffers.Offset): void; + static endEnum(builder: flatbuffers.Builder): flatbuffers.Offset; + unpack(): EnumT; + unpackTo(_o: EnumT): void; +} +export declare class EnumT implements flatbuffers.IGeneratedObject { + name: string | Uint8Array | null; + values: (EnumValT)[]; + isUnion: boolean; + underlyingType: TypeT | null; + attributes: (KeyValueT)[]; + documentation: (string)[]; + declarationFile: string | Uint8Array | null; + constructor(name?: string | Uint8Array | null, values?: (EnumValT)[], isUnion?: boolean, underlyingType?: TypeT | null, attributes?: (KeyValueT)[], documentation?: (string)[], declarationFile?: string | Uint8Array | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/enum.js b/third_party/flatbuffers/tests/ts/reflection/enum.js new file mode 100644 index 00000000000..e2cb6460ad1 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/enum.js @@ -0,0 +1,176 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { EnumVal } from '../reflection/enum-val.js'; +import { KeyValue } from '../reflection/key-value.js'; +import { Type } from '../reflection/type.js'; +export class Enum { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsEnum(bb, obj) { + return (obj || new Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsEnum(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + values(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new EnumVal()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + valuesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + isUnion() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_is_union(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + underlyingType(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return 'reflection.Enum'; + } + static startEnum(builder) { + builder.startObject(7); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addValues(builder, valuesOffset) { + builder.addFieldOffset(1, valuesOffset, 0); + } + static createValuesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startValuesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addIsUnion(builder, isUnion) { + builder.addFieldInt8(2, +isUnion, +false); + } + static addUnderlyingType(builder, underlyingTypeOffset) { + builder.addFieldOffset(3, underlyingTypeOffset, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(4, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(5, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(6, declarationFileOffset, 0); + } + static endEnum(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // name + builder.requiredField(offset, 6); // values + builder.requiredField(offset, 10); // underlying_type + return offset; + } + unpack() { + return new EnumT(this.name(), this.bb.createObjList(this.values.bind(this), this.valuesLength()), this.isUnion(), (this.underlyingType() !== null ? this.underlyingType().unpack() : null), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.values = this.bb.createObjList(this.values.bind(this), this.valuesLength()); + _o.isUnion = this.isUnion(); + _o.underlyingType = (this.underlyingType() !== null ? this.underlyingType().unpack() : null); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +} +export class EnumT { + constructor(name = null, values = [], isUnion = false, underlyingType = null, attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.values = values; + this.isUnion = isUnion; + this.underlyingType = underlyingType; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const values = Enum.createValuesVector(builder, builder.createObjectOffsetList(this.values)); + const underlyingType = (this.underlyingType !== null ? this.underlyingType.pack(builder) : 0); + const attributes = Enum.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Enum.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = (this.declarationFile !== null ? builder.createString(this.declarationFile) : 0); + Enum.startEnum(builder); + Enum.addName(builder, name); + Enum.addValues(builder, values); + Enum.addIsUnion(builder, this.isUnion); + Enum.addUnderlyingType(builder, underlyingType); + Enum.addAttributes(builder, attributes); + Enum.addDocumentation(builder, documentation); + Enum.addDeclarationFile(builder, declarationFile); + return Enum.endEnum(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/enum.ts b/third_party/flatbuffers/tests/ts/reflection/enum.ts new file mode 100644 index 00000000000..88336a7a586 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/enum.ts @@ -0,0 +1,236 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { EnumVal, EnumValT } from '../reflection/enum-val.js'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Type, TypeT } from '../reflection/type.js'; + + +export class Enum implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Enum { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsEnum(bb:flatbuffers.ByteBuffer, obj?:Enum):Enum { + return (obj || new Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsEnum(bb:flatbuffers.ByteBuffer, obj?:Enum):Enum { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +values(index: number, obj?:EnumVal):EnumVal|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new EnumVal()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +valuesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +isUnion():boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_is_union(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +underlyingType(obj?:Type):Type|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +attributes(index: number, obj?:KeyValue):KeyValue|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? (obj || new KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +attributesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +documentation(index: number):string +documentation(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +documentation(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +documentationLength():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +/** + * File that this Enum is declared in. + */ +declarationFile():string|null +declarationFile(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +declarationFile(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'reflection.Enum'; +} + +static startEnum(builder:flatbuffers.Builder) { + builder.startObject(7); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, nameOffset, 0); +} + +static addValues(builder:flatbuffers.Builder, valuesOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, valuesOffset, 0); +} + +static createValuesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startValuesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addIsUnion(builder:flatbuffers.Builder, isUnion:boolean) { + builder.addFieldInt8(2, +isUnion, +false); +} + +static addUnderlyingType(builder:flatbuffers.Builder, underlyingTypeOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, underlyingTypeOffset, 0); +} + +static addAttributes(builder:flatbuffers.Builder, attributesOffset:flatbuffers.Offset) { + builder.addFieldOffset(4, attributesOffset, 0); +} + +static createAttributesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startAttributesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDocumentation(builder:flatbuffers.Builder, documentationOffset:flatbuffers.Offset) { + builder.addFieldOffset(5, documentationOffset, 0); +} + +static createDocumentationVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startDocumentationVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDeclarationFile(builder:flatbuffers.Builder, declarationFileOffset:flatbuffers.Offset) { + builder.addFieldOffset(6, declarationFileOffset, 0); +} + +static endEnum(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // name + builder.requiredField(offset, 6) // values + builder.requiredField(offset, 10) // underlying_type + return offset; +} + + +unpack(): EnumT { + return new EnumT( + this.name(), + this.bb!.createObjList(this.values.bind(this), this.valuesLength()), + this.isUnion(), + (this.underlyingType() !== null ? this.underlyingType()!.unpack() : null), + this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()), + this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()), + this.declarationFile() + ); +} + + +unpackTo(_o: EnumT): void { + _o.name = this.name(); + _o.values = this.bb!.createObjList(this.values.bind(this), this.valuesLength()); + _o.isUnion = this.isUnion(); + _o.underlyingType = (this.underlyingType() !== null ? this.underlyingType()!.unpack() : null); + _o.attributes = this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); +} +} + +export class EnumT implements flatbuffers.IGeneratedObject { +constructor( + public name: string|Uint8Array|null = null, + public values: (EnumValT)[] = [], + public isUnion: boolean = false, + public underlyingType: TypeT|null = null, + public attributes: (KeyValueT)[] = [], + public documentation: (string)[] = [], + public declarationFile: string|Uint8Array|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const values = Enum.createValuesVector(builder, builder.createObjectOffsetList(this.values)); + const underlyingType = (this.underlyingType !== null ? this.underlyingType!.pack(builder) : 0); + const attributes = Enum.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Enum.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = (this.declarationFile !== null ? builder.createString(this.declarationFile!) : 0); + + Enum.startEnum(builder); + Enum.addName(builder, name); + Enum.addValues(builder, values); + Enum.addIsUnion(builder, this.isUnion); + Enum.addUnderlyingType(builder, underlyingType); + Enum.addAttributes(builder, attributes); + Enum.addDocumentation(builder, documentation); + Enum.addDeclarationFile(builder, declarationFile); + + return Enum.endEnum(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/field.d.ts b/third_party/flatbuffers/tests/ts/reflection/field.d.ts new file mode 100644 index 00000000000..e4f4bf53904 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/field.d.ts @@ -0,0 +1,85 @@ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Type, TypeT } from '../reflection/type.js'; +export declare class Field implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Field; + static getRootAsField(bb: flatbuffers.ByteBuffer, obj?: Field): Field; + static getSizePrefixedRootAsField(bb: flatbuffers.ByteBuffer, obj?: Field): Field; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + type(obj?: Type): Type | null; + id(): number; + mutate_id(value: number): boolean; + offset(): number; + mutate_offset(value: number): boolean; + defaultInteger(): bigint; + mutate_default_integer(value: bigint): boolean; + defaultReal(): number; + mutate_default_real(value: number): boolean; + deprecated(): boolean; + mutate_deprecated(value: boolean): boolean; + required(): boolean; + mutate_required(value: boolean): boolean; + key(): boolean; + mutate_key(value: boolean): boolean; + attributes(index: number, obj?: KeyValue): KeyValue | null; + attributesLength(): number; + documentation(index: number): string; + documentation(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + documentationLength(): number; + optional(): boolean; + mutate_optional(value: boolean): boolean; + /** + * Number of padding octets to always add after this field. Structs only. + */ + padding(): number; + mutate_padding(value: number): boolean; + /** + * If the field uses 64-bit offsets. + */ + offset64(): boolean; + mutate_offset64(value: boolean): boolean; + static getFullyQualifiedName(): string; + static startField(builder: flatbuffers.Builder): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addType(builder: flatbuffers.Builder, typeOffset: flatbuffers.Offset): void; + static addId(builder: flatbuffers.Builder, id: number): void; + static addOffset(builder: flatbuffers.Builder, offset: number): void; + static addDefaultInteger(builder: flatbuffers.Builder, defaultInteger: bigint): void; + static addDefaultReal(builder: flatbuffers.Builder, defaultReal: number): void; + static addDeprecated(builder: flatbuffers.Builder, deprecated: boolean): void; + static addRequired(builder: flatbuffers.Builder, required: boolean): void; + static addKey(builder: flatbuffers.Builder, key: boolean): void; + static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset): void; + static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startAttributesVector(builder: flatbuffers.Builder, numElems: number): void; + static addDocumentation(builder: flatbuffers.Builder, documentationOffset: flatbuffers.Offset): void; + static createDocumentationVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startDocumentationVector(builder: flatbuffers.Builder, numElems: number): void; + static addOptional(builder: flatbuffers.Builder, optional: boolean): void; + static addPadding(builder: flatbuffers.Builder, padding: number): void; + static addOffset64(builder: flatbuffers.Builder, offset64: boolean): void; + static endField(builder: flatbuffers.Builder): flatbuffers.Offset; + unpack(): FieldT; + unpackTo(_o: FieldT): void; +} +export declare class FieldT implements flatbuffers.IGeneratedObject { + name: string | Uint8Array | null; + type: TypeT | null; + id: number; + offset: number; + defaultInteger: bigint; + defaultReal: number; + deprecated: boolean; + required: boolean; + key: boolean; + attributes: (KeyValueT)[]; + documentation: (string)[]; + optional: boolean; + padding: number; + offset64: boolean; + constructor(name?: string | Uint8Array | null, type?: TypeT | null, id?: number, offset?: number, defaultInteger?: bigint, defaultReal?: number, deprecated?: boolean, required?: boolean, key?: boolean, attributes?: (KeyValueT)[], documentation?: (string)[], optional?: boolean, padding?: number, offset64?: boolean); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/field.js b/third_party/flatbuffers/tests/ts/reflection/field.js new file mode 100644 index 00000000000..a8a8fd34733 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/field.js @@ -0,0 +1,306 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue } from '../reflection/key-value.js'; +import { Type } from '../reflection/type.js'; +export class Field { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsField(bb, obj) { + return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsField(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + type(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + id() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_id(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + offset() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_offset(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + defaultInteger() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt('0'); + } + mutate_default_integer(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + defaultReal() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0.0; + } + mutate_default_real(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + deprecated() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_deprecated(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + required() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_required(value) { + const offset = this.bb.__offset(this.bb_pos, 18); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + key() { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_key(value) { + const offset = this.bb.__offset(this.bb_pos, 20); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + optional() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_optional(value) { + const offset = this.bb.__offset(this.bb_pos, 26); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + /** + * Number of padding octets to always add after this field. Structs only. + */ + padding() { + const offset = this.bb.__offset(this.bb_pos, 28); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_padding(value) { + const offset = this.bb.__offset(this.bb_pos, 28); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + /** + * If the field uses 64-bit offsets. + */ + offset64() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_offset64(value) { + const offset = this.bb.__offset(this.bb_pos, 30); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + static getFullyQualifiedName() { + return 'reflection.Field'; + } + static startField(builder) { + builder.startObject(14); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addType(builder, typeOffset) { + builder.addFieldOffset(1, typeOffset, 0); + } + static addId(builder, id) { + builder.addFieldInt16(2, id, 0); + } + static addOffset(builder, offset) { + builder.addFieldInt16(3, offset, 0); + } + static addDefaultInteger(builder, defaultInteger) { + builder.addFieldInt64(4, defaultInteger, BigInt('0')); + } + static addDefaultReal(builder, defaultReal) { + builder.addFieldFloat64(5, defaultReal, 0.0); + } + static addDeprecated(builder, deprecated) { + builder.addFieldInt8(6, +deprecated, +false); + } + static addRequired(builder, required) { + builder.addFieldInt8(7, +required, +false); + } + static addKey(builder, key) { + builder.addFieldInt8(8, +key, +false); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(9, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(10, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addOptional(builder, optional) { + builder.addFieldInt8(11, +optional, +false); + } + static addPadding(builder, padding) { + builder.addFieldInt16(12, padding, 0); + } + static addOffset64(builder, offset64) { + builder.addFieldInt8(13, +offset64, +false); + } + static endField(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // name + builder.requiredField(offset, 6); // type + return offset; + } + unpack() { + return new FieldT(this.name(), (this.type() !== null ? this.type().unpack() : null), this.id(), this.offset(), this.defaultInteger(), this.defaultReal(), this.deprecated(), this.required(), this.key(), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.optional(), this.padding(), this.offset64()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.type = (this.type() !== null ? this.type().unpack() : null); + _o.id = this.id(); + _o.offset = this.offset(); + _o.defaultInteger = this.defaultInteger(); + _o.defaultReal = this.defaultReal(); + _o.deprecated = this.deprecated(); + _o.required = this.required(); + _o.key = this.key(); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.optional = this.optional(); + _o.padding = this.padding(); + _o.offset64 = this.offset64(); + } +} +export class FieldT { + constructor(name = null, type = null, id = 0, offset = 0, defaultInteger = BigInt('0'), defaultReal = 0.0, deprecated = false, required = false, key = false, attributes = [], documentation = [], optional = false, padding = 0, offset64 = false) { + this.name = name; + this.type = type; + this.id = id; + this.offset = offset; + this.defaultInteger = defaultInteger; + this.defaultReal = defaultReal; + this.deprecated = deprecated; + this.required = required; + this.key = key; + this.attributes = attributes; + this.documentation = documentation; + this.optional = optional; + this.padding = padding; + this.offset64 = offset64; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const type = (this.type !== null ? this.type.pack(builder) : 0); + const attributes = Field.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Field.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + Field.startField(builder); + Field.addName(builder, name); + Field.addType(builder, type); + Field.addId(builder, this.id); + Field.addOffset(builder, this.offset); + Field.addDefaultInteger(builder, this.defaultInteger); + Field.addDefaultReal(builder, this.defaultReal); + Field.addDeprecated(builder, this.deprecated); + Field.addRequired(builder, this.required); + Field.addKey(builder, this.key); + Field.addAttributes(builder, attributes); + Field.addDocumentation(builder, documentation); + Field.addOptional(builder, this.optional); + Field.addPadding(builder, this.padding); + Field.addOffset64(builder, this.offset64); + return Field.endField(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/field.ts b/third_party/flatbuffers/tests/ts/reflection/field.ts new file mode 100644 index 00000000000..75a2d342234 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/field.ts @@ -0,0 +1,406 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Type, TypeT } from '../reflection/type.js'; + + +export class Field implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Field { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsField(bb:flatbuffers.ByteBuffer, obj?:Field):Field { + return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsField(bb:flatbuffers.ByteBuffer, obj?:Field):Field { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +type(obj?:Type):Type|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new Type()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +id():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +mutate_id(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint16(this.bb_pos + offset, value); + return true; +} + +offset():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +mutate_offset(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 10); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint16(this.bb_pos + offset, value); + return true; +} + +defaultInteger():bigint { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readInt64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_default_integer(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 12); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt64(this.bb_pos + offset, value); + return true; +} + +defaultReal():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readFloat64(this.bb_pos + offset) : 0.0; +} + +mutate_default_real(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 14); + + if (offset === 0) { + return false; + } + + this.bb!.writeFloat64(this.bb_pos + offset, value); + return true; +} + +deprecated():boolean { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_deprecated(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 16); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +required():boolean { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_required(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 18); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +key():boolean { + const offset = this.bb!.__offset(this.bb_pos, 20); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_key(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 20); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +attributes(index: number, obj?:KeyValue):KeyValue|null { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? (obj || new KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +attributesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 22); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +documentation(index: number):string +documentation(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +documentation(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +documentationLength():number { + const offset = this.bb!.__offset(this.bb_pos, 24); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +optional():boolean { + const offset = this.bb!.__offset(this.bb_pos, 26); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_optional(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 26); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +/** + * Number of padding octets to always add after this field. Structs only. + */ +padding():number { + const offset = this.bb!.__offset(this.bb_pos, 28); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +mutate_padding(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 28); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint16(this.bb_pos + offset, value); + return true; +} + +/** + * If the field uses 64-bit offsets. + */ +offset64():boolean { + const offset = this.bb!.__offset(this.bb_pos, 30); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_offset64(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 30); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +static getFullyQualifiedName():string { + return 'reflection.Field'; +} + +static startField(builder:flatbuffers.Builder) { + builder.startObject(14); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, nameOffset, 0); +} + +static addType(builder:flatbuffers.Builder, typeOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, typeOffset, 0); +} + +static addId(builder:flatbuffers.Builder, id:number) { + builder.addFieldInt16(2, id, 0); +} + +static addOffset(builder:flatbuffers.Builder, offset:number) { + builder.addFieldInt16(3, offset, 0); +} + +static addDefaultInteger(builder:flatbuffers.Builder, defaultInteger:bigint) { + builder.addFieldInt64(4, defaultInteger, BigInt('0')); +} + +static addDefaultReal(builder:flatbuffers.Builder, defaultReal:number) { + builder.addFieldFloat64(5, defaultReal, 0.0); +} + +static addDeprecated(builder:flatbuffers.Builder, deprecated:boolean) { + builder.addFieldInt8(6, +deprecated, +false); +} + +static addRequired(builder:flatbuffers.Builder, required:boolean) { + builder.addFieldInt8(7, +required, +false); +} + +static addKey(builder:flatbuffers.Builder, key:boolean) { + builder.addFieldInt8(8, +key, +false); +} + +static addAttributes(builder:flatbuffers.Builder, attributesOffset:flatbuffers.Offset) { + builder.addFieldOffset(9, attributesOffset, 0); +} + +static createAttributesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startAttributesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDocumentation(builder:flatbuffers.Builder, documentationOffset:flatbuffers.Offset) { + builder.addFieldOffset(10, documentationOffset, 0); +} + +static createDocumentationVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startDocumentationVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addOptional(builder:flatbuffers.Builder, optional:boolean) { + builder.addFieldInt8(11, +optional, +false); +} + +static addPadding(builder:flatbuffers.Builder, padding:number) { + builder.addFieldInt16(12, padding, 0); +} + +static addOffset64(builder:flatbuffers.Builder, offset64:boolean) { + builder.addFieldInt8(13, +offset64, +false); +} + +static endField(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // name + builder.requiredField(offset, 6) // type + return offset; +} + + +unpack(): FieldT { + return new FieldT( + this.name(), + (this.type() !== null ? this.type()!.unpack() : null), + this.id(), + this.offset(), + this.defaultInteger(), + this.defaultReal(), + this.deprecated(), + this.required(), + this.key(), + this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()), + this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()), + this.optional(), + this.padding(), + this.offset64() + ); +} + + +unpackTo(_o: FieldT): void { + _o.name = this.name(); + _o.type = (this.type() !== null ? this.type()!.unpack() : null); + _o.id = this.id(); + _o.offset = this.offset(); + _o.defaultInteger = this.defaultInteger(); + _o.defaultReal = this.defaultReal(); + _o.deprecated = this.deprecated(); + _o.required = this.required(); + _o.key = this.key(); + _o.attributes = this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.optional = this.optional(); + _o.padding = this.padding(); + _o.offset64 = this.offset64(); +} +} + +export class FieldT implements flatbuffers.IGeneratedObject { +constructor( + public name: string|Uint8Array|null = null, + public type: TypeT|null = null, + public id: number = 0, + public offset: number = 0, + public defaultInteger: bigint = BigInt('0'), + public defaultReal: number = 0.0, + public deprecated: boolean = false, + public required: boolean = false, + public key: boolean = false, + public attributes: (KeyValueT)[] = [], + public documentation: (string)[] = [], + public optional: boolean = false, + public padding: number = 0, + public offset64: boolean = false +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const type = (this.type !== null ? this.type!.pack(builder) : 0); + const attributes = Field.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Field.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + + Field.startField(builder); + Field.addName(builder, name); + Field.addType(builder, type); + Field.addId(builder, this.id); + Field.addOffset(builder, this.offset); + Field.addDefaultInteger(builder, this.defaultInteger); + Field.addDefaultReal(builder, this.defaultReal); + Field.addDeprecated(builder, this.deprecated); + Field.addRequired(builder, this.required); + Field.addKey(builder, this.key); + Field.addAttributes(builder, attributes); + Field.addDocumentation(builder, documentation); + Field.addOptional(builder, this.optional); + Field.addPadding(builder, this.padding); + Field.addOffset64(builder, this.offset64); + + return Field.endField(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/key-value.d.ts b/third_party/flatbuffers/tests/ts/reflection/key-value.d.ts new file mode 100644 index 00000000000..23f5f1d442a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/key-value.d.ts @@ -0,0 +1,26 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class KeyValue implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): KeyValue; + static getRootAsKeyValue(bb: flatbuffers.ByteBuffer, obj?: KeyValue): KeyValue; + static getSizePrefixedRootAsKeyValue(bb: flatbuffers.ByteBuffer, obj?: KeyValue): KeyValue; + key(): string | null; + key(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + value(): string | null; + value(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + static getFullyQualifiedName(): string; + static startKeyValue(builder: flatbuffers.Builder): void; + static addKey(builder: flatbuffers.Builder, keyOffset: flatbuffers.Offset): void; + static addValue(builder: flatbuffers.Builder, valueOffset: flatbuffers.Offset): void; + static endKeyValue(builder: flatbuffers.Builder): flatbuffers.Offset; + static createKeyValue(builder: flatbuffers.Builder, keyOffset: flatbuffers.Offset, valueOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): KeyValueT; + unpackTo(_o: KeyValueT): void; +} +export declare class KeyValueT implements flatbuffers.IGeneratedObject { + key: string | Uint8Array | null; + value: string | Uint8Array | null; + constructor(key?: string | Uint8Array | null, value?: string | Uint8Array | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/key-value.js b/third_party/flatbuffers/tests/ts/reflection/key-value.js new file mode 100644 index 00000000000..289e9eaef9a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/key-value.js @@ -0,0 +1,70 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class KeyValue { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsKeyValue(bb, obj) { + return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsKeyValue(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + key(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return 'reflection.KeyValue'; + } + static startKeyValue(builder) { + builder.startObject(2); + } + static addKey(builder, keyOffset) { + builder.addFieldOffset(0, keyOffset, 0); + } + static addValue(builder, valueOffset) { + builder.addFieldOffset(1, valueOffset, 0); + } + static endKeyValue(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // key + return offset; + } + static createKeyValue(builder, keyOffset, valueOffset) { + KeyValue.startKeyValue(builder); + KeyValue.addKey(builder, keyOffset); + KeyValue.addValue(builder, valueOffset); + return KeyValue.endKeyValue(builder); + } + unpack() { + return new KeyValueT(this.key(), this.value()); + } + unpackTo(_o) { + _o.key = this.key(); + _o.value = this.value(); + } +} +export class KeyValueT { + constructor(key = null, value = null) { + this.key = key; + this.value = value; + } + pack(builder) { + const key = (this.key !== null ? builder.createString(this.key) : 0); + const value = (this.value !== null ? builder.createString(this.value) : 0); + return KeyValue.createKeyValue(builder, key, value); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/key-value.ts b/third_party/flatbuffers/tests/ts/reflection/key-value.ts new file mode 100644 index 00000000000..8d7fe045996 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/key-value.ts @@ -0,0 +1,100 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class KeyValue implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):KeyValue { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsKeyValue(bb:flatbuffers.ByteBuffer, obj?:KeyValue):KeyValue { + return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsKeyValue(bb:flatbuffers.ByteBuffer, obj?:KeyValue):KeyValue { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +key():string|null +key(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +key(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +value():string|null +value(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +value(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'reflection.KeyValue'; +} + +static startKeyValue(builder:flatbuffers.Builder) { + builder.startObject(2); +} + +static addKey(builder:flatbuffers.Builder, keyOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, keyOffset, 0); +} + +static addValue(builder:flatbuffers.Builder, valueOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, valueOffset, 0); +} + +static endKeyValue(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // key + return offset; +} + +static createKeyValue(builder:flatbuffers.Builder, keyOffset:flatbuffers.Offset, valueOffset:flatbuffers.Offset):flatbuffers.Offset { + KeyValue.startKeyValue(builder); + KeyValue.addKey(builder, keyOffset); + KeyValue.addValue(builder, valueOffset); + return KeyValue.endKeyValue(builder); +} + +unpack(): KeyValueT { + return new KeyValueT( + this.key(), + this.value() + ); +} + + +unpackTo(_o: KeyValueT): void { + _o.key = this.key(); + _o.value = this.value(); +} +} + +export class KeyValueT implements flatbuffers.IGeneratedObject { +constructor( + public key: string|Uint8Array|null = null, + public value: string|Uint8Array|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const key = (this.key !== null ? builder.createString(this.key!) : 0); + const value = (this.value !== null ? builder.createString(this.value!) : 0); + + return KeyValue.createKeyValue(builder, + key, + value + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/object.d.ts b/third_party/flatbuffers/tests/ts/reflection/object.d.ts new file mode 100644 index 00000000000..8f8c5400df8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/object.d.ts @@ -0,0 +1,62 @@ +import * as flatbuffers from 'flatbuffers'; +import { Field, FieldT } from '../reflection/field.js'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +export declare class Object_ implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Object_; + static getRootAsObject(bb: flatbuffers.ByteBuffer, obj?: Object_): Object_; + static getSizePrefixedRootAsObject(bb: flatbuffers.ByteBuffer, obj?: Object_): Object_; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + fields(index: number, obj?: Field): Field | null; + fieldsLength(): number; + isStruct(): boolean; + mutate_is_struct(value: boolean): boolean; + minalign(): number; + mutate_minalign(value: number): boolean; + bytesize(): number; + mutate_bytesize(value: number): boolean; + attributes(index: number, obj?: KeyValue): KeyValue | null; + attributesLength(): number; + documentation(index: number): string; + documentation(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + documentationLength(): number; + /** + * File that this Object is declared in. + */ + declarationFile(): string | null; + declarationFile(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + static getFullyQualifiedName(): string; + static startObject(builder: flatbuffers.Builder): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addFields(builder: flatbuffers.Builder, fieldsOffset: flatbuffers.Offset): void; + static createFieldsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startFieldsVector(builder: flatbuffers.Builder, numElems: number): void; + static addIsStruct(builder: flatbuffers.Builder, isStruct: boolean): void; + static addMinalign(builder: flatbuffers.Builder, minalign: number): void; + static addBytesize(builder: flatbuffers.Builder, bytesize: number): void; + static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset): void; + static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startAttributesVector(builder: flatbuffers.Builder, numElems: number): void; + static addDocumentation(builder: flatbuffers.Builder, documentationOffset: flatbuffers.Offset): void; + static createDocumentationVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startDocumentationVector(builder: flatbuffers.Builder, numElems: number): void; + static addDeclarationFile(builder: flatbuffers.Builder, declarationFileOffset: flatbuffers.Offset): void; + static endObject(builder: flatbuffers.Builder): flatbuffers.Offset; + static createObject(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset, fieldsOffset: flatbuffers.Offset, isStruct: boolean, minalign: number, bytesize: number, attributesOffset: flatbuffers.Offset, documentationOffset: flatbuffers.Offset, declarationFileOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): Object_T; + unpackTo(_o: Object_T): void; +} +export declare class Object_T implements flatbuffers.IGeneratedObject { + name: string | Uint8Array | null; + fields: (FieldT)[]; + isStruct: boolean; + minalign: number; + bytesize: number; + attributes: (KeyValueT)[]; + documentation: (string)[]; + declarationFile: string | Uint8Array | null; + constructor(name?: string | Uint8Array | null, fields?: (FieldT)[], isStruct?: boolean, minalign?: number, bytesize?: number, attributes?: (KeyValueT)[], documentation?: (string)[], declarationFile?: string | Uint8Array | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/object.js b/third_party/flatbuffers/tests/ts/reflection/object.js new file mode 100644 index 00000000000..bf1edf8cbfb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/object.js @@ -0,0 +1,202 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { Field } from '../reflection/field.js'; +import { KeyValue } from '../reflection/key-value.js'; +export class Object_ { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsObject(bb, obj) { + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsObject(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + fields(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Field()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + fieldsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + isStruct() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_is_struct(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + minalign() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_minalign(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + bytesize() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_bytesize(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return 'reflection.Object'; + } + static startObject(builder) { + builder.startObject(8); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addFields(builder, fieldsOffset) { + builder.addFieldOffset(1, fieldsOffset, 0); + } + static createFieldsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFieldsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addIsStruct(builder, isStruct) { + builder.addFieldInt8(2, +isStruct, +false); + } + static addMinalign(builder, minalign) { + builder.addFieldInt32(3, minalign, 0); + } + static addBytesize(builder, bytesize) { + builder.addFieldInt32(4, bytesize, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(5, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(6, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(7, declarationFileOffset, 0); + } + static endObject(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // name + builder.requiredField(offset, 6); // fields + return offset; + } + static createObject(builder, nameOffset, fieldsOffset, isStruct, minalign, bytesize, attributesOffset, documentationOffset, declarationFileOffset) { + Object_.startObject(builder); + Object_.addName(builder, nameOffset); + Object_.addFields(builder, fieldsOffset); + Object_.addIsStruct(builder, isStruct); + Object_.addMinalign(builder, minalign); + Object_.addBytesize(builder, bytesize); + Object_.addAttributes(builder, attributesOffset); + Object_.addDocumentation(builder, documentationOffset); + Object_.addDeclarationFile(builder, declarationFileOffset); + return Object_.endObject(builder); + } + unpack() { + return new Object_T(this.name(), this.bb.createObjList(this.fields.bind(this), this.fieldsLength()), this.isStruct(), this.minalign(), this.bytesize(), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.fields = this.bb.createObjList(this.fields.bind(this), this.fieldsLength()); + _o.isStruct = this.isStruct(); + _o.minalign = this.minalign(); + _o.bytesize = this.bytesize(); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +} +export class Object_T { + constructor(name = null, fields = [], isStruct = false, minalign = 0, bytesize = 0, attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.fields = fields; + this.isStruct = isStruct; + this.minalign = minalign; + this.bytesize = bytesize; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const fields = Object_.createFieldsVector(builder, builder.createObjectOffsetList(this.fields)); + const attributes = Object_.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Object_.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = (this.declarationFile !== null ? builder.createString(this.declarationFile) : 0); + return Object_.createObject(builder, name, fields, this.isStruct, this.minalign, this.bytesize, attributes, documentation, declarationFile); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/object.ts b/third_party/flatbuffers/tests/ts/reflection/object.ts new file mode 100644 index 00000000000..088b3300021 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/object.ts @@ -0,0 +1,279 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Field, FieldT } from '../reflection/field.js'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; + + +export class Object_ implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Object_ { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsObject(bb:flatbuffers.ByteBuffer, obj?:Object_):Object_ { + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsObject(bb:flatbuffers.ByteBuffer, obj?:Object_):Object_ { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +fields(index: number, obj?:Field):Field|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new Field()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +fieldsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +isStruct():boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_is_struct(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +minalign():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_minalign(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 10); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +bytesize():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_bytesize(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 12); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +attributes(index: number, obj?:KeyValue):KeyValue|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +attributesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +documentation(index: number):string +documentation(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +documentation(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +documentationLength():number { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +/** + * File that this Object is declared in. + */ +declarationFile():string|null +declarationFile(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +declarationFile(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'reflection.Object'; +} + +static startObject(builder:flatbuffers.Builder) { + builder.startObject(8); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, nameOffset, 0); +} + +static addFields(builder:flatbuffers.Builder, fieldsOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, fieldsOffset, 0); +} + +static createFieldsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startFieldsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addIsStruct(builder:flatbuffers.Builder, isStruct:boolean) { + builder.addFieldInt8(2, +isStruct, +false); +} + +static addMinalign(builder:flatbuffers.Builder, minalign:number) { + builder.addFieldInt32(3, minalign, 0); +} + +static addBytesize(builder:flatbuffers.Builder, bytesize:number) { + builder.addFieldInt32(4, bytesize, 0); +} + +static addAttributes(builder:flatbuffers.Builder, attributesOffset:flatbuffers.Offset) { + builder.addFieldOffset(5, attributesOffset, 0); +} + +static createAttributesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startAttributesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDocumentation(builder:flatbuffers.Builder, documentationOffset:flatbuffers.Offset) { + builder.addFieldOffset(6, documentationOffset, 0); +} + +static createDocumentationVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startDocumentationVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDeclarationFile(builder:flatbuffers.Builder, declarationFileOffset:flatbuffers.Offset) { + builder.addFieldOffset(7, declarationFileOffset, 0); +} + +static endObject(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // name + builder.requiredField(offset, 6) // fields + return offset; +} + +static createObject(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset, fieldsOffset:flatbuffers.Offset, isStruct:boolean, minalign:number, bytesize:number, attributesOffset:flatbuffers.Offset, documentationOffset:flatbuffers.Offset, declarationFileOffset:flatbuffers.Offset):flatbuffers.Offset { + Object_.startObject(builder); + Object_.addName(builder, nameOffset); + Object_.addFields(builder, fieldsOffset); + Object_.addIsStruct(builder, isStruct); + Object_.addMinalign(builder, minalign); + Object_.addBytesize(builder, bytesize); + Object_.addAttributes(builder, attributesOffset); + Object_.addDocumentation(builder, documentationOffset); + Object_.addDeclarationFile(builder, declarationFileOffset); + return Object_.endObject(builder); +} + +unpack(): Object_T { + return new Object_T( + this.name(), + this.bb!.createObjList(this.fields.bind(this), this.fieldsLength()), + this.isStruct(), + this.minalign(), + this.bytesize(), + this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()), + this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()), + this.declarationFile() + ); +} + + +unpackTo(_o: Object_T): void { + _o.name = this.name(); + _o.fields = this.bb!.createObjList(this.fields.bind(this), this.fieldsLength()); + _o.isStruct = this.isStruct(); + _o.minalign = this.minalign(); + _o.bytesize = this.bytesize(); + _o.attributes = this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); +} +} + +export class Object_T implements flatbuffers.IGeneratedObject { +constructor( + public name: string|Uint8Array|null = null, + public fields: (FieldT)[] = [], + public isStruct: boolean = false, + public minalign: number = 0, + public bytesize: number = 0, + public attributes: (KeyValueT)[] = [], + public documentation: (string)[] = [], + public declarationFile: string|Uint8Array|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const fields = Object_.createFieldsVector(builder, builder.createObjectOffsetList(this.fields)); + const attributes = Object_.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Object_.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = (this.declarationFile !== null ? builder.createString(this.declarationFile!) : 0); + + return Object_.createObject(builder, + name, + fields, + this.isStruct, + this.minalign, + this.bytesize, + attributes, + documentation, + declarationFile + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/rpccall.d.ts b/third_party/flatbuffers/tests/ts/reflection/rpccall.d.ts new file mode 100644 index 00000000000..e70ba917495 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/rpccall.d.ts @@ -0,0 +1,42 @@ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Object_, Object_T } from '../reflection/object.js'; +export declare class RPCCall implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): RPCCall; + static getRootAsRPCCall(bb: flatbuffers.ByteBuffer, obj?: RPCCall): RPCCall; + static getSizePrefixedRootAsRPCCall(bb: flatbuffers.ByteBuffer, obj?: RPCCall): RPCCall; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + request(obj?: Object_): Object_ | null; + response(obj?: Object_): Object_ | null; + attributes(index: number, obj?: KeyValue): KeyValue | null; + attributesLength(): number; + documentation(index: number): string; + documentation(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + documentationLength(): number; + static getFullyQualifiedName(): string; + static startRPCCall(builder: flatbuffers.Builder): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addRequest(builder: flatbuffers.Builder, requestOffset: flatbuffers.Offset): void; + static addResponse(builder: flatbuffers.Builder, responseOffset: flatbuffers.Offset): void; + static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset): void; + static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startAttributesVector(builder: flatbuffers.Builder, numElems: number): void; + static addDocumentation(builder: flatbuffers.Builder, documentationOffset: flatbuffers.Offset): void; + static createDocumentationVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startDocumentationVector(builder: flatbuffers.Builder, numElems: number): void; + static endRPCCall(builder: flatbuffers.Builder): flatbuffers.Offset; + unpack(): RPCCallT; + unpackTo(_o: RPCCallT): void; +} +export declare class RPCCallT implements flatbuffers.IGeneratedObject { + name: string | Uint8Array | null; + request: Object_T | null; + response: Object_T | null; + attributes: (KeyValueT)[]; + documentation: (string)[]; + constructor(name?: string | Uint8Array | null, request?: Object_T | null, response?: Object_T | null, attributes?: (KeyValueT)[], documentation?: (string)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/rpccall.js b/third_party/flatbuffers/tests/ts/reflection/rpccall.js new file mode 100644 index 00000000000..f7fa5743b11 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/rpccall.js @@ -0,0 +1,132 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue } from '../reflection/key-value.js'; +import { Object_ } from '../reflection/object.js'; +export class RPCCall { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsRPCCall(bb, obj) { + return (obj || new RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsRPCCall(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + request(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + response(obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return 'reflection.RPCCall'; + } + static startRPCCall(builder) { + builder.startObject(5); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addRequest(builder, requestOffset) { + builder.addFieldOffset(1, requestOffset, 0); + } + static addResponse(builder, responseOffset) { + builder.addFieldOffset(2, responseOffset, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(3, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(4, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endRPCCall(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // name + builder.requiredField(offset, 6); // request + builder.requiredField(offset, 8); // response + return offset; + } + unpack() { + return new RPCCallT(this.name(), (this.request() !== null ? this.request().unpack() : null), (this.response() !== null ? this.response().unpack() : null), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength())); + } + unpackTo(_o) { + _o.name = this.name(); + _o.request = (this.request() !== null ? this.request().unpack() : null); + _o.response = (this.response() !== null ? this.response().unpack() : null); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + } +} +export class RPCCallT { + constructor(name = null, request = null, response = null, attributes = [], documentation = []) { + this.name = name; + this.request = request; + this.response = response; + this.attributes = attributes; + this.documentation = documentation; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const request = (this.request !== null ? this.request.pack(builder) : 0); + const response = (this.response !== null ? this.response.pack(builder) : 0); + const attributes = RPCCall.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = RPCCall.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + RPCCall.startRPCCall(builder); + RPCCall.addName(builder, name); + RPCCall.addRequest(builder, request); + RPCCall.addResponse(builder, response); + RPCCall.addAttributes(builder, attributes); + RPCCall.addDocumentation(builder, documentation); + return RPCCall.endRPCCall(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/rpccall.ts b/third_party/flatbuffers/tests/ts/reflection/rpccall.ts new file mode 100644 index 00000000000..9202300426f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/rpccall.ts @@ -0,0 +1,175 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { Object_, Object_T } from '../reflection/object.js'; + + +export class RPCCall implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):RPCCall { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsRPCCall(bb:flatbuffers.ByteBuffer, obj?:RPCCall):RPCCall { + return (obj || new RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsRPCCall(bb:flatbuffers.ByteBuffer, obj?:RPCCall):RPCCall { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +request(obj?:Object_):Object_|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new Object_()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +response(obj?:Object_):Object_|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? (obj || new Object_()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +attributes(index: number, obj?:KeyValue):KeyValue|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? (obj || new KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +attributesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +documentation(index: number):string +documentation(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +documentation(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +documentationLength():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static getFullyQualifiedName():string { + return 'reflection.RPCCall'; +} + +static startRPCCall(builder:flatbuffers.Builder) { + builder.startObject(5); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, nameOffset, 0); +} + +static addRequest(builder:flatbuffers.Builder, requestOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, requestOffset, 0); +} + +static addResponse(builder:flatbuffers.Builder, responseOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, responseOffset, 0); +} + +static addAttributes(builder:flatbuffers.Builder, attributesOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, attributesOffset, 0); +} + +static createAttributesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startAttributesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDocumentation(builder:flatbuffers.Builder, documentationOffset:flatbuffers.Offset) { + builder.addFieldOffset(4, documentationOffset, 0); +} + +static createDocumentationVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startDocumentationVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endRPCCall(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // name + builder.requiredField(offset, 6) // request + builder.requiredField(offset, 8) // response + return offset; +} + + +unpack(): RPCCallT { + return new RPCCallT( + this.name(), + (this.request() !== null ? this.request()!.unpack() : null), + (this.response() !== null ? this.response()!.unpack() : null), + this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()), + this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()) + ); +} + + +unpackTo(_o: RPCCallT): void { + _o.name = this.name(); + _o.request = (this.request() !== null ? this.request()!.unpack() : null); + _o.response = (this.response() !== null ? this.response()!.unpack() : null); + _o.attributes = this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()); +} +} + +export class RPCCallT implements flatbuffers.IGeneratedObject { +constructor( + public name: string|Uint8Array|null = null, + public request: Object_T|null = null, + public response: Object_T|null = null, + public attributes: (KeyValueT)[] = [], + public documentation: (string)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const request = (this.request !== null ? this.request!.pack(builder) : 0); + const response = (this.response !== null ? this.response!.pack(builder) : 0); + const attributes = RPCCall.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = RPCCall.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + + RPCCall.startRPCCall(builder); + RPCCall.addName(builder, name); + RPCCall.addRequest(builder, request); + RPCCall.addResponse(builder, response); + RPCCall.addAttributes(builder, attributes); + RPCCall.addDocumentation(builder, documentation); + + return RPCCall.endRPCCall(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/schema-file.d.ts b/third_party/flatbuffers/tests/ts/reflection/schema-file.d.ts new file mode 100644 index 00000000000..18f943caa42 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/schema-file.d.ts @@ -0,0 +1,40 @@ +import * as flatbuffers from 'flatbuffers'; +/** + * File specific information. + * Symbols declared within a file may be recovered by iterating over all + * symbols and examining the `declaration_file` field. + */ +export declare class SchemaFile implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): SchemaFile; + static getRootAsSchemaFile(bb: flatbuffers.ByteBuffer, obj?: SchemaFile): SchemaFile; + static getSizePrefixedRootAsSchemaFile(bb: flatbuffers.ByteBuffer, obj?: SchemaFile): SchemaFile; + /** + * Filename, relative to project root. + */ + filename(): string | null; + filename(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + /** + * Names of included files, relative to project root. + */ + includedFilenames(index: number): string; + includedFilenames(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + includedFilenamesLength(): number; + static getFullyQualifiedName(): string; + static startSchemaFile(builder: flatbuffers.Builder): void; + static addFilename(builder: flatbuffers.Builder, filenameOffset: flatbuffers.Offset): void; + static addIncludedFilenames(builder: flatbuffers.Builder, includedFilenamesOffset: flatbuffers.Offset): void; + static createIncludedFilenamesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startIncludedFilenamesVector(builder: flatbuffers.Builder, numElems: number): void; + static endSchemaFile(builder: flatbuffers.Builder): flatbuffers.Offset; + static createSchemaFile(builder: flatbuffers.Builder, filenameOffset: flatbuffers.Offset, includedFilenamesOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): SchemaFileT; + unpackTo(_o: SchemaFileT): void; +} +export declare class SchemaFileT implements flatbuffers.IGeneratedObject { + filename: string | Uint8Array | null; + includedFilenames: (string)[]; + constructor(filename?: string | Uint8Array | null, includedFilenames?: (string)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/schema-file.js b/third_party/flatbuffers/tests/ts/reflection/schema-file.js new file mode 100644 index 00000000000..cb4cf49ef6c --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/schema-file.js @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +/** + * File specific information. + * Symbols declared within a file may be recovered by iterating over all + * symbols and examining the `declaration_file` field. + */ +export class SchemaFile { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchemaFile(bb, obj) { + return (obj || new SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchemaFile(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + filename(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + includedFilenames(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + includedFilenamesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return 'reflection.SchemaFile'; + } + static startSchemaFile(builder) { + builder.startObject(2); + } + static addFilename(builder, filenameOffset) { + builder.addFieldOffset(0, filenameOffset, 0); + } + static addIncludedFilenames(builder, includedFilenamesOffset) { + builder.addFieldOffset(1, includedFilenamesOffset, 0); + } + static createIncludedFilenamesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startIncludedFilenamesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endSchemaFile(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // filename + return offset; + } + static createSchemaFile(builder, filenameOffset, includedFilenamesOffset) { + SchemaFile.startSchemaFile(builder); + SchemaFile.addFilename(builder, filenameOffset); + SchemaFile.addIncludedFilenames(builder, includedFilenamesOffset); + return SchemaFile.endSchemaFile(builder); + } + unpack() { + return new SchemaFileT(this.filename(), this.bb.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength())); + } + unpackTo(_o) { + _o.filename = this.filename(); + _o.includedFilenames = this.bb.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength()); + } +} +export class SchemaFileT { + constructor(filename = null, includedFilenames = []) { + this.filename = filename; + this.includedFilenames = includedFilenames; + } + pack(builder) { + const filename = (this.filename !== null ? builder.createString(this.filename) : 0); + const includedFilenames = SchemaFile.createIncludedFilenamesVector(builder, builder.createObjectOffsetList(this.includedFilenames)); + return SchemaFile.createSchemaFile(builder, filename, includedFilenames); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/schema-file.ts b/third_party/flatbuffers/tests/ts/reflection/schema-file.ts new file mode 100644 index 00000000000..44544eb26ca --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/schema-file.ts @@ -0,0 +1,128 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +/** + * File specific information. + * Symbols declared within a file may be recovered by iterating over all + * symbols and examining the `declaration_file` field. + */ +export class SchemaFile implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):SchemaFile { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsSchemaFile(bb:flatbuffers.ByteBuffer, obj?:SchemaFile):SchemaFile { + return (obj || new SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsSchemaFile(bb:flatbuffers.ByteBuffer, obj?:SchemaFile):SchemaFile { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +/** + * Filename, relative to project root. + */ +filename():string|null +filename(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +filename(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +/** + * Names of included files, relative to project root. + */ +includedFilenames(index: number):string +includedFilenames(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +includedFilenames(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +includedFilenamesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static getFullyQualifiedName():string { + return 'reflection.SchemaFile'; +} + +static startSchemaFile(builder:flatbuffers.Builder) { + builder.startObject(2); +} + +static addFilename(builder:flatbuffers.Builder, filenameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, filenameOffset, 0); +} + +static addIncludedFilenames(builder:flatbuffers.Builder, includedFilenamesOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, includedFilenamesOffset, 0); +} + +static createIncludedFilenamesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startIncludedFilenamesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endSchemaFile(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // filename + return offset; +} + +static createSchemaFile(builder:flatbuffers.Builder, filenameOffset:flatbuffers.Offset, includedFilenamesOffset:flatbuffers.Offset):flatbuffers.Offset { + SchemaFile.startSchemaFile(builder); + SchemaFile.addFilename(builder, filenameOffset); + SchemaFile.addIncludedFilenames(builder, includedFilenamesOffset); + return SchemaFile.endSchemaFile(builder); +} + +unpack(): SchemaFileT { + return new SchemaFileT( + this.filename(), + this.bb!.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength()) + ); +} + + +unpackTo(_o: SchemaFileT): void { + _o.filename = this.filename(); + _o.includedFilenames = this.bb!.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength()); +} +} + +export class SchemaFileT implements flatbuffers.IGeneratedObject { +constructor( + public filename: string|Uint8Array|null = null, + public includedFilenames: (string)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const filename = (this.filename !== null ? builder.createString(this.filename!) : 0); + const includedFilenames = SchemaFile.createIncludedFilenamesVector(builder, builder.createObjectOffsetList(this.includedFilenames)); + + return SchemaFile.createSchemaFile(builder, + filename, + includedFilenames + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/schema.d.ts b/third_party/flatbuffers/tests/ts/reflection/schema.d.ts new file mode 100644 index 00000000000..40a38afa169 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/schema.d.ts @@ -0,0 +1,67 @@ +import * as flatbuffers from 'flatbuffers'; +import { Enum, EnumT } from '../reflection/enum.js'; +import { Object_, Object_T } from '../reflection/object.js'; +import { SchemaFile, SchemaFileT } from '../reflection/schema-file.js'; +import { Service, ServiceT } from '../reflection/service.js'; +export declare class Schema implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Schema; + static getRootAsSchema(bb: flatbuffers.ByteBuffer, obj?: Schema): Schema; + static getSizePrefixedRootAsSchema(bb: flatbuffers.ByteBuffer, obj?: Schema): Schema; + static bufferHasIdentifier(bb: flatbuffers.ByteBuffer): boolean; + objects(index: number, obj?: Object_): Object_ | null; + objectsLength(): number; + enums(index: number, obj?: Enum): Enum | null; + enumsLength(): number; + fileIdent(): string | null; + fileIdent(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + fileExt(): string | null; + fileExt(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + rootTable(obj?: Object_): Object_ | null; + services(index: number, obj?: Service): Service | null; + servicesLength(): number; + advancedFeatures(): bigint; + mutate_advanced_features(value: bigint): boolean; + /** + * All the files used in this compilation. Files are relative to where + * flatc was invoked. + */ + fbsFiles(index: number, obj?: SchemaFile): SchemaFile | null; + fbsFilesLength(): number; + static getFullyQualifiedName(): string; + static startSchema(builder: flatbuffers.Builder): void; + static addObjects(builder: flatbuffers.Builder, objectsOffset: flatbuffers.Offset): void; + static createObjectsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startObjectsVector(builder: flatbuffers.Builder, numElems: number): void; + static addEnums(builder: flatbuffers.Builder, enumsOffset: flatbuffers.Offset): void; + static createEnumsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startEnumsVector(builder: flatbuffers.Builder, numElems: number): void; + static addFileIdent(builder: flatbuffers.Builder, fileIdentOffset: flatbuffers.Offset): void; + static addFileExt(builder: flatbuffers.Builder, fileExtOffset: flatbuffers.Offset): void; + static addRootTable(builder: flatbuffers.Builder, rootTableOffset: flatbuffers.Offset): void; + static addServices(builder: flatbuffers.Builder, servicesOffset: flatbuffers.Offset): void; + static createServicesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startServicesVector(builder: flatbuffers.Builder, numElems: number): void; + static addAdvancedFeatures(builder: flatbuffers.Builder, advancedFeatures: bigint): void; + static addFbsFiles(builder: flatbuffers.Builder, fbsFilesOffset: flatbuffers.Offset): void; + static createFbsFilesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startFbsFilesVector(builder: flatbuffers.Builder, numElems: number): void; + static endSchema(builder: flatbuffers.Builder): flatbuffers.Offset; + static finishSchemaBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static finishSizePrefixedSchemaBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + unpack(): SchemaT; + unpackTo(_o: SchemaT): void; +} +export declare class SchemaT implements flatbuffers.IGeneratedObject { + objects: (Object_T)[]; + enums: (EnumT)[]; + fileIdent: string | Uint8Array | null; + fileExt: string | Uint8Array | null; + rootTable: Object_T | null; + services: (ServiceT)[]; + advancedFeatures: bigint; + fbsFiles: (SchemaFileT)[]; + constructor(objects?: (Object_T)[], enums?: (EnumT)[], fileIdent?: string | Uint8Array | null, fileExt?: string | Uint8Array | null, rootTable?: Object_T | null, services?: (ServiceT)[], advancedFeatures?: bigint, fbsFiles?: (SchemaFileT)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/schema.js b/third_party/flatbuffers/tests/ts/reflection/schema.js new file mode 100644 index 00000000000..ef474c556f8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/schema.js @@ -0,0 +1,214 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { Enum } from '../reflection/enum.js'; +import { Object_ } from '../reflection/object.js'; +import { SchemaFile } from '../reflection/schema-file.js'; +import { Service } from '../reflection/service.js'; +export class Schema { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchema(bb, obj) { + return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchema(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier('BFBS'); + } + objects(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + objectsLength() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + enums(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Enum()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + enumsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + fileIdent(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + fileExt(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + rootTable(obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + services(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new Service()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + servicesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + advancedFeatures() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt('0'); + } + mutate_advanced_features(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + /** + * All the files used in this compilation. Files are relative to where + * flatc was invoked. + */ + fbsFiles(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? (obj || new SchemaFile()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + fbsFilesLength() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return 'reflection.Schema'; + } + static startSchema(builder) { + builder.startObject(8); + } + static addObjects(builder, objectsOffset) { + builder.addFieldOffset(0, objectsOffset, 0); + } + static createObjectsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startObjectsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addEnums(builder, enumsOffset) { + builder.addFieldOffset(1, enumsOffset, 0); + } + static createEnumsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startEnumsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addFileIdent(builder, fileIdentOffset) { + builder.addFieldOffset(2, fileIdentOffset, 0); + } + static addFileExt(builder, fileExtOffset) { + builder.addFieldOffset(3, fileExtOffset, 0); + } + static addRootTable(builder, rootTableOffset) { + builder.addFieldOffset(4, rootTableOffset, 0); + } + static addServices(builder, servicesOffset) { + builder.addFieldOffset(5, servicesOffset, 0); + } + static createServicesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startServicesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAdvancedFeatures(builder, advancedFeatures) { + builder.addFieldInt64(6, advancedFeatures, BigInt('0')); + } + static addFbsFiles(builder, fbsFilesOffset) { + builder.addFieldOffset(7, fbsFilesOffset, 0); + } + static createFbsFilesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFbsFilesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endSchema(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // objects + builder.requiredField(offset, 6); // enums + return offset; + } + static finishSchemaBuffer(builder, offset) { + builder.finish(offset, 'BFBS'); + } + static finishSizePrefixedSchemaBuffer(builder, offset) { + builder.finish(offset, 'BFBS', true); + } + unpack() { + return new SchemaT(this.bb.createObjList(this.objects.bind(this), this.objectsLength()), this.bb.createObjList(this.enums.bind(this), this.enumsLength()), this.fileIdent(), this.fileExt(), (this.rootTable() !== null ? this.rootTable().unpack() : null), this.bb.createObjList(this.services.bind(this), this.servicesLength()), this.advancedFeatures(), this.bb.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength())); + } + unpackTo(_o) { + _o.objects = this.bb.createObjList(this.objects.bind(this), this.objectsLength()); + _o.enums = this.bb.createObjList(this.enums.bind(this), this.enumsLength()); + _o.fileIdent = this.fileIdent(); + _o.fileExt = this.fileExt(); + _o.rootTable = (this.rootTable() !== null ? this.rootTable().unpack() : null); + _o.services = this.bb.createObjList(this.services.bind(this), this.servicesLength()); + _o.advancedFeatures = this.advancedFeatures(); + _o.fbsFiles = this.bb.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength()); + } +} +export class SchemaT { + constructor(objects = [], enums = [], fileIdent = null, fileExt = null, rootTable = null, services = [], advancedFeatures = BigInt('0'), fbsFiles = []) { + this.objects = objects; + this.enums = enums; + this.fileIdent = fileIdent; + this.fileExt = fileExt; + this.rootTable = rootTable; + this.services = services; + this.advancedFeatures = advancedFeatures; + this.fbsFiles = fbsFiles; + } + pack(builder) { + const objects = Schema.createObjectsVector(builder, builder.createObjectOffsetList(this.objects)); + const enums = Schema.createEnumsVector(builder, builder.createObjectOffsetList(this.enums)); + const fileIdent = (this.fileIdent !== null ? builder.createString(this.fileIdent) : 0); + const fileExt = (this.fileExt !== null ? builder.createString(this.fileExt) : 0); + const rootTable = (this.rootTable !== null ? this.rootTable.pack(builder) : 0); + const services = Schema.createServicesVector(builder, builder.createObjectOffsetList(this.services)); + const fbsFiles = Schema.createFbsFilesVector(builder, builder.createObjectOffsetList(this.fbsFiles)); + Schema.startSchema(builder); + Schema.addObjects(builder, objects); + Schema.addEnums(builder, enums); + Schema.addFileIdent(builder, fileIdent); + Schema.addFileExt(builder, fileExt); + Schema.addRootTable(builder, rootTable); + Schema.addServices(builder, services); + Schema.addAdvancedFeatures(builder, this.advancedFeatures); + Schema.addFbsFiles(builder, fbsFiles); + return Schema.endSchema(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/schema.ts b/third_party/flatbuffers/tests/ts/reflection/schema.ts new file mode 100644 index 00000000000..53922de6225 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/schema.ts @@ -0,0 +1,278 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Enum, EnumT } from '../reflection/enum.js'; +import { Object_, Object_T } from '../reflection/object.js'; +import { SchemaFile, SchemaFileT } from '../reflection/schema-file.js'; +import { Service, ServiceT } from '../reflection/service.js'; + + +export class Schema implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Schema { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsSchema(bb:flatbuffers.ByteBuffer, obj?:Schema):Schema { + return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsSchema(bb:flatbuffers.ByteBuffer, obj?:Schema):Schema { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean { + return bb.__has_identifier('BFBS'); +} + +objects(index: number, obj?:Object_):Object_|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? (obj || new Object_()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +objectsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +enums(index: number, obj?:Enum):Enum|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new Enum()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +enumsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +fileIdent():string|null +fileIdent(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +fileIdent(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +fileExt():string|null +fileExt(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +fileExt(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +rootTable(obj?:Object_):Object_|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? (obj || new Object_()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +services(index: number, obj?:Service):Service|null { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? (obj || new Service()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +servicesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +advancedFeatures():bigint { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? this.bb!.readUint64(this.bb_pos + offset) : BigInt('0'); +} + +mutate_advanced_features(value:bigint):boolean { + const offset = this.bb!.__offset(this.bb_pos, 16); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint64(this.bb_pos + offset, value); + return true; +} + +/** + * All the files used in this compilation. Files are relative to where + * flatc was invoked. + */ +fbsFiles(index: number, obj?:SchemaFile):SchemaFile|null { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? (obj || new SchemaFile()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +fbsFilesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 18); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static getFullyQualifiedName():string { + return 'reflection.Schema'; +} + +static startSchema(builder:flatbuffers.Builder) { + builder.startObject(8); +} + +static addObjects(builder:flatbuffers.Builder, objectsOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, objectsOffset, 0); +} + +static createObjectsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startObjectsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addEnums(builder:flatbuffers.Builder, enumsOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, enumsOffset, 0); +} + +static createEnumsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startEnumsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addFileIdent(builder:flatbuffers.Builder, fileIdentOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, fileIdentOffset, 0); +} + +static addFileExt(builder:flatbuffers.Builder, fileExtOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, fileExtOffset, 0); +} + +static addRootTable(builder:flatbuffers.Builder, rootTableOffset:flatbuffers.Offset) { + builder.addFieldOffset(4, rootTableOffset, 0); +} + +static addServices(builder:flatbuffers.Builder, servicesOffset:flatbuffers.Offset) { + builder.addFieldOffset(5, servicesOffset, 0); +} + +static createServicesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startServicesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addAdvancedFeatures(builder:flatbuffers.Builder, advancedFeatures:bigint) { + builder.addFieldInt64(6, advancedFeatures, BigInt('0')); +} + +static addFbsFiles(builder:flatbuffers.Builder, fbsFilesOffset:flatbuffers.Offset) { + builder.addFieldOffset(7, fbsFilesOffset, 0); +} + +static createFbsFilesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startFbsFilesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endSchema(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // objects + builder.requiredField(offset, 6) // enums + return offset; +} + +static finishSchemaBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'BFBS'); +} + +static finishSizePrefixedSchemaBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'BFBS', true); +} + + +unpack(): SchemaT { + return new SchemaT( + this.bb!.createObjList(this.objects.bind(this), this.objectsLength()), + this.bb!.createObjList(this.enums.bind(this), this.enumsLength()), + this.fileIdent(), + this.fileExt(), + (this.rootTable() !== null ? this.rootTable()!.unpack() : null), + this.bb!.createObjList(this.services.bind(this), this.servicesLength()), + this.advancedFeatures(), + this.bb!.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength()) + ); +} + + +unpackTo(_o: SchemaT): void { + _o.objects = this.bb!.createObjList(this.objects.bind(this), this.objectsLength()); + _o.enums = this.bb!.createObjList(this.enums.bind(this), this.enumsLength()); + _o.fileIdent = this.fileIdent(); + _o.fileExt = this.fileExt(); + _o.rootTable = (this.rootTable() !== null ? this.rootTable()!.unpack() : null); + _o.services = this.bb!.createObjList(this.services.bind(this), this.servicesLength()); + _o.advancedFeatures = this.advancedFeatures(); + _o.fbsFiles = this.bb!.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength()); +} +} + +export class SchemaT implements flatbuffers.IGeneratedObject { +constructor( + public objects: (Object_T)[] = [], + public enums: (EnumT)[] = [], + public fileIdent: string|Uint8Array|null = null, + public fileExt: string|Uint8Array|null = null, + public rootTable: Object_T|null = null, + public services: (ServiceT)[] = [], + public advancedFeatures: bigint = BigInt('0'), + public fbsFiles: (SchemaFileT)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const objects = Schema.createObjectsVector(builder, builder.createObjectOffsetList(this.objects)); + const enums = Schema.createEnumsVector(builder, builder.createObjectOffsetList(this.enums)); + const fileIdent = (this.fileIdent !== null ? builder.createString(this.fileIdent!) : 0); + const fileExt = (this.fileExt !== null ? builder.createString(this.fileExt!) : 0); + const rootTable = (this.rootTable !== null ? this.rootTable!.pack(builder) : 0); + const services = Schema.createServicesVector(builder, builder.createObjectOffsetList(this.services)); + const fbsFiles = Schema.createFbsFilesVector(builder, builder.createObjectOffsetList(this.fbsFiles)); + + Schema.startSchema(builder); + Schema.addObjects(builder, objects); + Schema.addEnums(builder, enums); + Schema.addFileIdent(builder, fileIdent); + Schema.addFileExt(builder, fileExt); + Schema.addRootTable(builder, rootTable); + Schema.addServices(builder, services); + Schema.addAdvancedFeatures(builder, this.advancedFeatures); + Schema.addFbsFiles(builder, fbsFiles); + + return Schema.endSchema(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/service.d.ts b/third_party/flatbuffers/tests/ts/reflection/service.d.ts new file mode 100644 index 00000000000..6bea22bb6fb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/service.d.ts @@ -0,0 +1,50 @@ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { RPCCall, RPCCallT } from '../reflection/rpccall.js'; +export declare class Service implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Service; + static getRootAsService(bb: flatbuffers.ByteBuffer, obj?: Service): Service; + static getSizePrefixedRootAsService(bb: flatbuffers.ByteBuffer, obj?: Service): Service; + name(): string | null; + name(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + calls(index: number, obj?: RPCCall): RPCCall | null; + callsLength(): number; + attributes(index: number, obj?: KeyValue): KeyValue | null; + attributesLength(): number; + documentation(index: number): string; + documentation(index: number, optionalEncoding: flatbuffers.Encoding): string | Uint8Array; + documentationLength(): number; + /** + * File that this Service is declared in. + */ + declarationFile(): string | null; + declarationFile(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + static getFullyQualifiedName(): string; + static startService(builder: flatbuffers.Builder): void; + static addName(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset): void; + static addCalls(builder: flatbuffers.Builder, callsOffset: flatbuffers.Offset): void; + static createCallsVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startCallsVector(builder: flatbuffers.Builder, numElems: number): void; + static addAttributes(builder: flatbuffers.Builder, attributesOffset: flatbuffers.Offset): void; + static createAttributesVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startAttributesVector(builder: flatbuffers.Builder, numElems: number): void; + static addDocumentation(builder: flatbuffers.Builder, documentationOffset: flatbuffers.Offset): void; + static createDocumentationVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startDocumentationVector(builder: flatbuffers.Builder, numElems: number): void; + static addDeclarationFile(builder: flatbuffers.Builder, declarationFileOffset: flatbuffers.Offset): void; + static endService(builder: flatbuffers.Builder): flatbuffers.Offset; + static createService(builder: flatbuffers.Builder, nameOffset: flatbuffers.Offset, callsOffset: flatbuffers.Offset, attributesOffset: flatbuffers.Offset, documentationOffset: flatbuffers.Offset, declarationFileOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): ServiceT; + unpackTo(_o: ServiceT): void; +} +export declare class ServiceT implements flatbuffers.IGeneratedObject { + name: string | Uint8Array | null; + calls: (RPCCallT)[]; + attributes: (KeyValueT)[]; + documentation: (string)[]; + declarationFile: string | Uint8Array | null; + constructor(name?: string | Uint8Array | null, calls?: (RPCCallT)[], attributes?: (KeyValueT)[], documentation?: (string)[], declarationFile?: string | Uint8Array | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/service.js b/third_party/flatbuffers/tests/ts/reflection/service.js new file mode 100644 index 00000000000..0373c7d503b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/service.js @@ -0,0 +1,147 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { KeyValue } from '../reflection/key-value.js'; +import { RPCCall } from '../reflection/rpccall.js'; +export class Service { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsService(bb, obj) { + return (obj || new Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsService(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + calls(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new RPCCall()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + callsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return 'reflection.Service'; + } + static startService(builder) { + builder.startObject(5); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addCalls(builder, callsOffset) { + builder.addFieldOffset(1, callsOffset, 0); + } + static createCallsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCallsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(2, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(3, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(4, declarationFileOffset, 0); + } + static endService(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // name + return offset; + } + static createService(builder, nameOffset, callsOffset, attributesOffset, documentationOffset, declarationFileOffset) { + Service.startService(builder); + Service.addName(builder, nameOffset); + Service.addCalls(builder, callsOffset); + Service.addAttributes(builder, attributesOffset); + Service.addDocumentation(builder, documentationOffset); + Service.addDeclarationFile(builder, declarationFileOffset); + return Service.endService(builder); + } + unpack() { + return new ServiceT(this.name(), this.bb.createObjList(this.calls.bind(this), this.callsLength()), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.calls = this.bb.createObjList(this.calls.bind(this), this.callsLength()); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +} +export class ServiceT { + constructor(name = null, calls = [], attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.calls = calls; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = (this.name !== null ? builder.createString(this.name) : 0); + const calls = Service.createCallsVector(builder, builder.createObjectOffsetList(this.calls)); + const attributes = Service.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Service.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = (this.declarationFile !== null ? builder.createString(this.declarationFile) : 0); + return Service.createService(builder, name, calls, attributes, documentation, declarationFile); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/service.ts b/third_party/flatbuffers/tests/ts/reflection/service.ts new file mode 100644 index 00000000000..2c2c62ddce4 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/service.ts @@ -0,0 +1,203 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { KeyValue, KeyValueT } from '../reflection/key-value.js'; +import { RPCCall, RPCCallT } from '../reflection/rpccall.js'; + + +export class Service implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Service { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsService(bb:flatbuffers.ByteBuffer, obj?:Service):Service { + return (obj || new Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsService(bb:flatbuffers.ByteBuffer, obj?:Service):Service { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +name():string|null +name(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +name(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +calls(index: number, obj?:RPCCall):RPCCall|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? (obj || new RPCCall()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +callsLength():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +attributes(index: number, obj?:KeyValue):KeyValue|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? (obj || new KeyValue()).__init(this.bb!.__indirect(this.bb!.__vector(this.bb_pos + offset) + index * 4), this.bb!) : null; +} + +attributesLength():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +documentation(index: number):string +documentation(index: number,optionalEncoding:flatbuffers.Encoding):string|Uint8Array +documentation(index: number,optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__string(this.bb!.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; +} + +documentationLength():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +/** + * File that this Service is declared in. + */ +declarationFile():string|null +declarationFile(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +declarationFile(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'reflection.Service'; +} + +static startService(builder:flatbuffers.Builder) { + builder.startObject(5); +} + +static addName(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, nameOffset, 0); +} + +static addCalls(builder:flatbuffers.Builder, callsOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, callsOffset, 0); +} + +static createCallsVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startCallsVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addAttributes(builder:flatbuffers.Builder, attributesOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, attributesOffset, 0); +} + +static createAttributesVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startAttributesVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDocumentation(builder:flatbuffers.Builder, documentationOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, documentationOffset, 0); +} + +static createDocumentationVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startDocumentationVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addDeclarationFile(builder:flatbuffers.Builder, declarationFileOffset:flatbuffers.Offset) { + builder.addFieldOffset(4, declarationFileOffset, 0); +} + +static endService(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // name + return offset; +} + +static createService(builder:flatbuffers.Builder, nameOffset:flatbuffers.Offset, callsOffset:flatbuffers.Offset, attributesOffset:flatbuffers.Offset, documentationOffset:flatbuffers.Offset, declarationFileOffset:flatbuffers.Offset):flatbuffers.Offset { + Service.startService(builder); + Service.addName(builder, nameOffset); + Service.addCalls(builder, callsOffset); + Service.addAttributes(builder, attributesOffset); + Service.addDocumentation(builder, documentationOffset); + Service.addDeclarationFile(builder, declarationFileOffset); + return Service.endService(builder); +} + +unpack(): ServiceT { + return new ServiceT( + this.name(), + this.bb!.createObjList(this.calls.bind(this), this.callsLength()), + this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()), + this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()), + this.declarationFile() + ); +} + + +unpackTo(_o: ServiceT): void { + _o.name = this.name(); + _o.calls = this.bb!.createObjList(this.calls.bind(this), this.callsLength()); + _o.attributes = this.bb!.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb!.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); +} +} + +export class ServiceT implements flatbuffers.IGeneratedObject { +constructor( + public name: string|Uint8Array|null = null, + public calls: (RPCCallT)[] = [], + public attributes: (KeyValueT)[] = [], + public documentation: (string)[] = [], + public declarationFile: string|Uint8Array|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const name = (this.name !== null ? builder.createString(this.name!) : 0); + const calls = Service.createCallsVector(builder, builder.createObjectOffsetList(this.calls)); + const attributes = Service.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Service.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = (this.declarationFile !== null ? builder.createString(this.declarationFile!) : 0); + + return Service.createService(builder, + name, + calls, + attributes, + documentation, + declarationFile + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection/type.d.ts b/third_party/flatbuffers/tests/ts/reflection/type.d.ts new file mode 100644 index 00000000000..811732c6f47 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/type.d.ts @@ -0,0 +1,49 @@ +import * as flatbuffers from 'flatbuffers'; +import { BaseType } from '../reflection/base-type.js'; +export declare class Type implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Type; + static getRootAsType(bb: flatbuffers.ByteBuffer, obj?: Type): Type; + static getSizePrefixedRootAsType(bb: flatbuffers.ByteBuffer, obj?: Type): Type; + baseType(): BaseType; + mutate_base_type(value: BaseType): boolean; + element(): BaseType; + mutate_element(value: BaseType): boolean; + index(): number; + mutate_index(value: number): boolean; + fixedLength(): number; + mutate_fixed_length(value: number): boolean; + /** + * The size (octets) of the `base_type` field. + */ + baseSize(): number; + mutate_base_size(value: number): boolean; + /** + * The size (octets) of the `element` field, if present. + */ + elementSize(): number; + mutate_element_size(value: number): boolean; + static getFullyQualifiedName(): string; + static startType(builder: flatbuffers.Builder): void; + static addBaseType(builder: flatbuffers.Builder, baseType: BaseType): void; + static addElement(builder: flatbuffers.Builder, element: BaseType): void; + static addIndex(builder: flatbuffers.Builder, index: number): void; + static addFixedLength(builder: flatbuffers.Builder, fixedLength: number): void; + static addBaseSize(builder: flatbuffers.Builder, baseSize: number): void; + static addElementSize(builder: flatbuffers.Builder, elementSize: number): void; + static endType(builder: flatbuffers.Builder): flatbuffers.Offset; + static createType(builder: flatbuffers.Builder, baseType: BaseType, element: BaseType, index: number, fixedLength: number, baseSize: number, elementSize: number): flatbuffers.Offset; + unpack(): TypeT; + unpackTo(_o: TypeT): void; +} +export declare class TypeT implements flatbuffers.IGeneratedObject { + baseType: BaseType; + element: BaseType; + index: number; + fixedLength: number; + baseSize: number; + elementSize: number; + constructor(baseType?: BaseType, element?: BaseType, index?: number, fixedLength?: number, baseSize?: number, elementSize?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/reflection/type.js b/third_party/flatbuffers/tests/ts/reflection/type.js new file mode 100644 index 00000000000..fc5f0e0eaa9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/type.js @@ -0,0 +1,162 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { BaseType } from '../reflection/base-type.js'; +export class Type { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsType(bb, obj) { + return (obj || new Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsType(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + baseType() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BaseType.None; + } + mutate_base_type(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + element() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BaseType.None; + } + mutate_element(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + index() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb_pos + offset) : -1; + } + mutate_index(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + fixedLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_fixed_length(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + /** + * The size (octets) of the `base_type` field. + */ + baseSize() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 4; + } + mutate_base_size(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + /** + * The size (octets) of the `element` field, if present. + */ + elementSize() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_element_size(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'reflection.Type'; + } + static startType(builder) { + builder.startObject(6); + } + static addBaseType(builder, baseType) { + builder.addFieldInt8(0, baseType, BaseType.None); + } + static addElement(builder, element) { + builder.addFieldInt8(1, element, BaseType.None); + } + static addIndex(builder, index) { + builder.addFieldInt32(2, index, -1); + } + static addFixedLength(builder, fixedLength) { + builder.addFieldInt16(3, fixedLength, 0); + } + static addBaseSize(builder, baseSize) { + builder.addFieldInt32(4, baseSize, 4); + } + static addElementSize(builder, elementSize) { + builder.addFieldInt32(5, elementSize, 0); + } + static endType(builder) { + const offset = builder.endObject(); + return offset; + } + static createType(builder, baseType, element, index, fixedLength, baseSize, elementSize) { + Type.startType(builder); + Type.addBaseType(builder, baseType); + Type.addElement(builder, element); + Type.addIndex(builder, index); + Type.addFixedLength(builder, fixedLength); + Type.addBaseSize(builder, baseSize); + Type.addElementSize(builder, elementSize); + return Type.endType(builder); + } + unpack() { + return new TypeT(this.baseType(), this.element(), this.index(), this.fixedLength(), this.baseSize(), this.elementSize()); + } + unpackTo(_o) { + _o.baseType = this.baseType(); + _o.element = this.element(); + _o.index = this.index(); + _o.fixedLength = this.fixedLength(); + _o.baseSize = this.baseSize(); + _o.elementSize = this.elementSize(); + } +} +export class TypeT { + constructor(baseType = BaseType.None, element = BaseType.None, index = -1, fixedLength = 0, baseSize = 4, elementSize = 0) { + this.baseType = baseType; + this.element = element; + this.index = index; + this.fixedLength = fixedLength; + this.baseSize = baseSize; + this.elementSize = elementSize; + } + pack(builder) { + return Type.createType(builder, this.baseType, this.element, this.index, this.fixedLength, this.baseSize, this.elementSize); + } +} diff --git a/third_party/flatbuffers/tests/ts/reflection/type.ts b/third_party/flatbuffers/tests/ts/reflection/type.ts new file mode 100644 index 00000000000..c6dfb928f2d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection/type.ts @@ -0,0 +1,221 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { BaseType } from '../reflection/base-type.js'; + + +export class Type implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Type { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsType(bb:flatbuffers.ByteBuffer, obj?:Type):Type { + return (obj || new Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsType(bb:flatbuffers.ByteBuffer, obj?:Type):Type { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +baseType():BaseType { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : BaseType.None; +} + +mutate_base_type(value:BaseType):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, value); + return true; +} + +element():BaseType { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt8(this.bb_pos + offset) : BaseType.None; +} + +mutate_element(value:BaseType):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, value); + return true; +} + +index():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : -1; +} + +mutate_index(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +fixedLength():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readUint16(this.bb_pos + offset) : 0; +} + +mutate_fixed_length(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 10); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint16(this.bb_pos + offset, value); + return true; +} + +/** + * The size (octets) of the `base_type` field. + */ +baseSize():number { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 4; +} + +mutate_base_size(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 12); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint32(this.bb_pos + offset, value); + return true; +} + +/** + * The size (octets) of the `element` field, if present. + */ +elementSize():number { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readUint32(this.bb_pos + offset) : 0; +} + +mutate_element_size(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 14); + + if (offset === 0) { + return false; + } + + this.bb!.writeUint32(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'reflection.Type'; +} + +static startType(builder:flatbuffers.Builder) { + builder.startObject(6); +} + +static addBaseType(builder:flatbuffers.Builder, baseType:BaseType) { + builder.addFieldInt8(0, baseType, BaseType.None); +} + +static addElement(builder:flatbuffers.Builder, element:BaseType) { + builder.addFieldInt8(1, element, BaseType.None); +} + +static addIndex(builder:flatbuffers.Builder, index:number) { + builder.addFieldInt32(2, index, -1); +} + +static addFixedLength(builder:flatbuffers.Builder, fixedLength:number) { + builder.addFieldInt16(3, fixedLength, 0); +} + +static addBaseSize(builder:flatbuffers.Builder, baseSize:number) { + builder.addFieldInt32(4, baseSize, 4); +} + +static addElementSize(builder:flatbuffers.Builder, elementSize:number) { + builder.addFieldInt32(5, elementSize, 0); +} + +static endType(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createType(builder:flatbuffers.Builder, baseType:BaseType, element:BaseType, index:number, fixedLength:number, baseSize:number, elementSize:number):flatbuffers.Offset { + Type.startType(builder); + Type.addBaseType(builder, baseType); + Type.addElement(builder, element); + Type.addIndex(builder, index); + Type.addFixedLength(builder, fixedLength); + Type.addBaseSize(builder, baseSize); + Type.addElementSize(builder, elementSize); + return Type.endType(builder); +} + +unpack(): TypeT { + return new TypeT( + this.baseType(), + this.element(), + this.index(), + this.fixedLength(), + this.baseSize(), + this.elementSize() + ); +} + + +unpackTo(_o: TypeT): void { + _o.baseType = this.baseType(); + _o.element = this.element(); + _o.index = this.index(); + _o.fixedLength = this.fixedLength(); + _o.baseSize = this.baseSize(); + _o.elementSize = this.elementSize(); +} +} + +export class TypeT implements flatbuffers.IGeneratedObject { +constructor( + public baseType: BaseType = BaseType.None, + public element: BaseType = BaseType.None, + public index: number = -1, + public fixedLength: number = 0, + public baseSize: number = 4, + public elementSize: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Type.createType(builder, + this.baseType, + this.element, + this.index, + this.fixedLength, + this.baseSize, + this.elementSize + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/reflection_generated.cjs b/third_party/flatbuffers/tests/ts/reflection_generated.cjs new file mode 100644 index 00000000000..45a4a1e711d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/reflection_generated.cjs @@ -0,0 +1,1659 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// reflection.ts +var reflection_exports = {}; +__export(reflection_exports, { + AdvancedFeatures: () => AdvancedFeatures, + BaseType: () => BaseType, + Enum: () => Enum, + EnumVal: () => EnumVal, + Field: () => Field, + KeyValue: () => KeyValue, + Object_: () => Object_, + RPCCall: () => RPCCall, + Schema: () => Schema, + SchemaFile: () => SchemaFile, + Service: () => Service, + Type: () => Type +}); +module.exports = __toCommonJS(reflection_exports); + +// reflection/advanced-features.ts +var AdvancedFeatures = /* @__PURE__ */ ((AdvancedFeatures2) => { + AdvancedFeatures2["AdvancedArrayFeatures"] = "1"; + AdvancedFeatures2["AdvancedUnionFeatures"] = "2"; + AdvancedFeatures2["OptionalScalars"] = "4"; + AdvancedFeatures2["DefaultVectorsAndStrings"] = "8"; + return AdvancedFeatures2; +})(AdvancedFeatures || {}); + +// reflection/base-type.js +var BaseType; +(function(BaseType2) { + BaseType2[BaseType2["None"] = 0] = "None"; + BaseType2[BaseType2["UType"] = 1] = "UType"; + BaseType2[BaseType2["Bool"] = 2] = "Bool"; + BaseType2[BaseType2["Byte"] = 3] = "Byte"; + BaseType2[BaseType2["UByte"] = 4] = "UByte"; + BaseType2[BaseType2["Short"] = 5] = "Short"; + BaseType2[BaseType2["UShort"] = 6] = "UShort"; + BaseType2[BaseType2["Int"] = 7] = "Int"; + BaseType2[BaseType2["UInt"] = 8] = "UInt"; + BaseType2[BaseType2["Long"] = 9] = "Long"; + BaseType2[BaseType2["ULong"] = 10] = "ULong"; + BaseType2[BaseType2["Float"] = 11] = "Float"; + BaseType2[BaseType2["Double"] = 12] = "Double"; + BaseType2[BaseType2["String"] = 13] = "String"; + BaseType2[BaseType2["Vector"] = 14] = "Vector"; + BaseType2[BaseType2["Obj"] = 15] = "Obj"; + BaseType2[BaseType2["Union"] = 16] = "Union"; + BaseType2[BaseType2["Array"] = 17] = "Array"; + BaseType2[BaseType2["MaxBaseType"] = 18] = "MaxBaseType"; +})(BaseType = BaseType || (BaseType = {})); + +// reflection/enum.js +var flatbuffers4 = __toESM(require("flatbuffers"), 1); + +// reflection/enum-val.js +var flatbuffers3 = __toESM(require("flatbuffers"), 1); + +// reflection/key-value.js +var flatbuffers = __toESM(require("flatbuffers"), 1); +var KeyValue = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsKeyValue(bb, obj) { + return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsKeyValue(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + key(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection_KeyValue"; + } + static startKeyValue(builder) { + builder.startObject(2); + } + static addKey(builder, keyOffset) { + builder.addFieldOffset(0, keyOffset, 0); + } + static addValue(builder, valueOffset) { + builder.addFieldOffset(1, valueOffset, 0); + } + static endKeyValue(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + static createKeyValue(builder, keyOffset, valueOffset) { + KeyValue.startKeyValue(builder); + KeyValue.addKey(builder, keyOffset); + KeyValue.addValue(builder, valueOffset); + return KeyValue.endKeyValue(builder); + } + unpack() { + return new KeyValueT(this.key(), this.value()); + } + unpackTo(_o) { + _o.key = this.key(); + _o.value = this.value(); + } +}; +var KeyValueT = class { + constructor(key = null, value = null) { + this.key = key; + this.value = value; + } + pack(builder) { + const key = this.key !== null ? builder.createString(this.key) : 0; + const value = this.value !== null ? builder.createString(this.value) : 0; + return KeyValue.createKeyValue(builder, key, value); + } +}; + +// reflection/type.js +var flatbuffers2 = __toESM(require("flatbuffers"), 1); +var Type = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsType(bb, obj) { + return (obj || new Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsType(bb, obj) { + bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH); + return (obj || new Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + baseType() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BaseType.None; + } + mutate_base_type(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + element() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BaseType.None; + } + mutate_element(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + index() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb_pos + offset) : -1; + } + mutate_index(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + fixedLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_fixed_length(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + baseSize() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 4; + } + mutate_base_size(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + elementSize() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_element_size(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "reflection_Type"; + } + static startType(builder) { + builder.startObject(6); + } + static addBaseType(builder, baseType) { + builder.addFieldInt8(0, baseType, BaseType.None); + } + static addElement(builder, element) { + builder.addFieldInt8(1, element, BaseType.None); + } + static addIndex(builder, index) { + builder.addFieldInt32(2, index, -1); + } + static addFixedLength(builder, fixedLength) { + builder.addFieldInt16(3, fixedLength, 0); + } + static addBaseSize(builder, baseSize) { + builder.addFieldInt32(4, baseSize, 4); + } + static addElementSize(builder, elementSize) { + builder.addFieldInt32(5, elementSize, 0); + } + static endType(builder) { + const offset = builder.endObject(); + return offset; + } + static createType(builder, baseType, element, index, fixedLength, baseSize, elementSize) { + Type.startType(builder); + Type.addBaseType(builder, baseType); + Type.addElement(builder, element); + Type.addIndex(builder, index); + Type.addFixedLength(builder, fixedLength); + Type.addBaseSize(builder, baseSize); + Type.addElementSize(builder, elementSize); + return Type.endType(builder); + } + unpack() { + return new TypeT(this.baseType(), this.element(), this.index(), this.fixedLength(), this.baseSize(), this.elementSize()); + } + unpackTo(_o) { + _o.baseType = this.baseType(); + _o.element = this.element(); + _o.index = this.index(); + _o.fixedLength = this.fixedLength(); + _o.baseSize = this.baseSize(); + _o.elementSize = this.elementSize(); + } +}; +var TypeT = class { + constructor(baseType = BaseType.None, element = BaseType.None, index = -1, fixedLength = 0, baseSize = 4, elementSize = 0) { + this.baseType = baseType; + this.element = element; + this.index = index; + this.fixedLength = fixedLength; + this.baseSize = baseSize; + this.elementSize = elementSize; + } + pack(builder) { + return Type.createType(builder, this.baseType, this.element, this.index, this.fixedLength, this.baseSize, this.elementSize); + } +}; + +// reflection/enum-val.js +var EnumVal = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsEnumVal(bb, obj) { + return (obj || new EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsEnumVal(bb, obj) { + bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH); + return (obj || new EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_value(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + unionType(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection_EnumVal"; + } + static startEnumVal(builder) { + builder.startObject(6); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addValue(builder, value) { + builder.addFieldInt64(1, value, BigInt("0")); + } + static addUnionType(builder, unionTypeOffset) { + builder.addFieldOffset(3, unionTypeOffset, 0); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(4, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(5, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endEnumVal(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + unpack() { + return new EnumValT(this.name(), this.value(), this.unionType() !== null ? this.unionType().unpack() : null, this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.bb.createObjList(this.attributes.bind(this), this.attributesLength())); + } + unpackTo(_o) { + _o.name = this.name(); + _o.value = this.value(); + _o.unionType = this.unionType() !== null ? this.unionType().unpack() : null; + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + } +}; +var EnumValT = class { + constructor(name = null, value = BigInt("0"), unionType = null, documentation = [], attributes = []) { + this.name = name; + this.value = value; + this.unionType = unionType; + this.documentation = documentation; + this.attributes = attributes; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const unionType = this.unionType !== null ? this.unionType.pack(builder) : 0; + const documentation = EnumVal.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const attributes = EnumVal.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + EnumVal.startEnumVal(builder); + EnumVal.addName(builder, name); + EnumVal.addValue(builder, this.value); + EnumVal.addUnionType(builder, unionType); + EnumVal.addDocumentation(builder, documentation); + EnumVal.addAttributes(builder, attributes); + return EnumVal.endEnumVal(builder); + } +}; + +// reflection/enum.js +var Enum = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsEnum(bb, obj) { + return (obj || new Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsEnum(bb, obj) { + bb.setPosition(bb.position() + flatbuffers4.SIZE_PREFIX_LENGTH); + return (obj || new Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + values(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new EnumVal()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + valuesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + isUnion() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_is_union(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + underlyingType(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection_Enum"; + } + static startEnum(builder) { + builder.startObject(7); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addValues(builder, valuesOffset) { + builder.addFieldOffset(1, valuesOffset, 0); + } + static createValuesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startValuesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addIsUnion(builder, isUnion) { + builder.addFieldInt8(2, +isUnion, 0); + } + static addUnderlyingType(builder, underlyingTypeOffset) { + builder.addFieldOffset(3, underlyingTypeOffset, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(4, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(5, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(6, declarationFileOffset, 0); + } + static endEnum(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + builder.requiredField(offset, 10); + return offset; + } + unpack() { + return new EnumT(this.name(), this.bb.createObjList(this.values.bind(this), this.valuesLength()), this.isUnion(), this.underlyingType() !== null ? this.underlyingType().unpack() : null, this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.values = this.bb.createObjList(this.values.bind(this), this.valuesLength()); + _o.isUnion = this.isUnion(); + _o.underlyingType = this.underlyingType() !== null ? this.underlyingType().unpack() : null; + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +}; +var EnumT = class { + constructor(name = null, values = [], isUnion = false, underlyingType = null, attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.values = values; + this.isUnion = isUnion; + this.underlyingType = underlyingType; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const values = Enum.createValuesVector(builder, builder.createObjectOffsetList(this.values)); + const underlyingType = this.underlyingType !== null ? this.underlyingType.pack(builder) : 0; + const attributes = Enum.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Enum.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = this.declarationFile !== null ? builder.createString(this.declarationFile) : 0; + Enum.startEnum(builder); + Enum.addName(builder, name); + Enum.addValues(builder, values); + Enum.addIsUnion(builder, this.isUnion); + Enum.addUnderlyingType(builder, underlyingType); + Enum.addAttributes(builder, attributes); + Enum.addDocumentation(builder, documentation); + Enum.addDeclarationFile(builder, declarationFile); + return Enum.endEnum(builder); + } +}; + +// reflection/field.js +var flatbuffers5 = __toESM(require("flatbuffers"), 1); +var Field = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsField(bb, obj) { + return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsField(bb, obj) { + bb.setPosition(bb.position() + flatbuffers5.SIZE_PREFIX_LENGTH); + return (obj || new Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + type(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + id() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_id(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + offset() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_offset(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + defaultInteger() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_default_integer(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + defaultReal() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0; + } + mutate_default_real(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + deprecated() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_deprecated(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + required() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_required(value) { + const offset = this.bb.__offset(this.bb_pos, 18); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + key() { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_key(value) { + const offset = this.bb.__offset(this.bb_pos, 20); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + optional() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_optional(value) { + const offset = this.bb.__offset(this.bb_pos, 26); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + padding() { + const offset = this.bb.__offset(this.bb_pos, 28); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_padding(value) { + const offset = this.bb.__offset(this.bb_pos, 28); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "reflection_Field"; + } + static startField(builder) { + builder.startObject(13); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addType(builder, typeOffset) { + builder.addFieldOffset(1, typeOffset, 0); + } + static addId(builder, id) { + builder.addFieldInt16(2, id, 0); + } + static addOffset(builder, offset) { + builder.addFieldInt16(3, offset, 0); + } + static addDefaultInteger(builder, defaultInteger) { + builder.addFieldInt64(4, defaultInteger, BigInt("0")); + } + static addDefaultReal(builder, defaultReal) { + builder.addFieldFloat64(5, defaultReal, 0); + } + static addDeprecated(builder, deprecated) { + builder.addFieldInt8(6, +deprecated, 0); + } + static addRequired(builder, required) { + builder.addFieldInt8(7, +required, 0); + } + static addKey(builder, key) { + builder.addFieldInt8(8, +key, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(9, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(10, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addOptional(builder, optional) { + builder.addFieldInt8(11, +optional, 0); + } + static addPadding(builder, padding) { + builder.addFieldInt16(12, padding, 0); + } + static endField(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + return offset; + } + unpack() { + return new FieldT(this.name(), this.type() !== null ? this.type().unpack() : null, this.id(), this.offset(), this.defaultInteger(), this.defaultReal(), this.deprecated(), this.required(), this.key(), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.optional(), this.padding()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.type = this.type() !== null ? this.type().unpack() : null; + _o.id = this.id(); + _o.offset = this.offset(); + _o.defaultInteger = this.defaultInteger(); + _o.defaultReal = this.defaultReal(); + _o.deprecated = this.deprecated(); + _o.required = this.required(); + _o.key = this.key(); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.optional = this.optional(); + _o.padding = this.padding(); + } +}; +var FieldT = class { + constructor(name = null, type = null, id = 0, offset = 0, defaultInteger = BigInt("0"), defaultReal = 0, deprecated = false, required = false, key = false, attributes = [], documentation = [], optional = false, padding = 0) { + this.name = name; + this.type = type; + this.id = id; + this.offset = offset; + this.defaultInteger = defaultInteger; + this.defaultReal = defaultReal; + this.deprecated = deprecated; + this.required = required; + this.key = key; + this.attributes = attributes; + this.documentation = documentation; + this.optional = optional; + this.padding = padding; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const type = this.type !== null ? this.type.pack(builder) : 0; + const attributes = Field.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Field.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + Field.startField(builder); + Field.addName(builder, name); + Field.addType(builder, type); + Field.addId(builder, this.id); + Field.addOffset(builder, this.offset); + Field.addDefaultInteger(builder, this.defaultInteger); + Field.addDefaultReal(builder, this.defaultReal); + Field.addDeprecated(builder, this.deprecated); + Field.addRequired(builder, this.required); + Field.addKey(builder, this.key); + Field.addAttributes(builder, attributes); + Field.addDocumentation(builder, documentation); + Field.addOptional(builder, this.optional); + Field.addPadding(builder, this.padding); + return Field.endField(builder); + } +}; + +// reflection/object.js +var flatbuffers6 = __toESM(require("flatbuffers"), 1); +var Object_ = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsObject(bb, obj) { + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsObject(bb, obj) { + bb.setPosition(bb.position() + flatbuffers6.SIZE_PREFIX_LENGTH); + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + fields(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Field()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + fieldsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + isStruct() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_is_struct(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + minalign() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_minalign(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + bytesize() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_bytesize(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection_Object"; + } + static startObject(builder) { + builder.startObject(8); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addFields(builder, fieldsOffset) { + builder.addFieldOffset(1, fieldsOffset, 0); + } + static createFieldsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFieldsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addIsStruct(builder, isStruct) { + builder.addFieldInt8(2, +isStruct, 0); + } + static addMinalign(builder, minalign) { + builder.addFieldInt32(3, minalign, 0); + } + static addBytesize(builder, bytesize) { + builder.addFieldInt32(4, bytesize, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(5, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(6, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(7, declarationFileOffset, 0); + } + static endObject(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + return offset; + } + static createObject(builder, nameOffset, fieldsOffset, isStruct, minalign, bytesize, attributesOffset, documentationOffset, declarationFileOffset) { + Object_.startObject(builder); + Object_.addName(builder, nameOffset); + Object_.addFields(builder, fieldsOffset); + Object_.addIsStruct(builder, isStruct); + Object_.addMinalign(builder, minalign); + Object_.addBytesize(builder, bytesize); + Object_.addAttributes(builder, attributesOffset); + Object_.addDocumentation(builder, documentationOffset); + Object_.addDeclarationFile(builder, declarationFileOffset); + return Object_.endObject(builder); + } + unpack() { + return new Object_T(this.name(), this.bb.createObjList(this.fields.bind(this), this.fieldsLength()), this.isStruct(), this.minalign(), this.bytesize(), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.fields = this.bb.createObjList(this.fields.bind(this), this.fieldsLength()); + _o.isStruct = this.isStruct(); + _o.minalign = this.minalign(); + _o.bytesize = this.bytesize(); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +}; +var Object_T = class { + constructor(name = null, fields = [], isStruct = false, minalign = 0, bytesize = 0, attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.fields = fields; + this.isStruct = isStruct; + this.minalign = minalign; + this.bytesize = bytesize; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const fields = Object_.createFieldsVector(builder, builder.createObjectOffsetList(this.fields)); + const attributes = Object_.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Object_.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = this.declarationFile !== null ? builder.createString(this.declarationFile) : 0; + return Object_.createObject(builder, name, fields, this.isStruct, this.minalign, this.bytesize, attributes, documentation, declarationFile); + } +}; + +// reflection/rpccall.js +var flatbuffers7 = __toESM(require("flatbuffers"), 1); +var RPCCall = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsRPCCall(bb, obj) { + return (obj || new RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsRPCCall(bb, obj) { + bb.setPosition(bb.position() + flatbuffers7.SIZE_PREFIX_LENGTH); + return (obj || new RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + request(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + response(obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection_RPCCall"; + } + static startRPCCall(builder) { + builder.startObject(5); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addRequest(builder, requestOffset) { + builder.addFieldOffset(1, requestOffset, 0); + } + static addResponse(builder, responseOffset) { + builder.addFieldOffset(2, responseOffset, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(3, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(4, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endRPCCall(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + builder.requiredField(offset, 8); + return offset; + } + unpack() { + return new RPCCallT(this.name(), this.request() !== null ? this.request().unpack() : null, this.response() !== null ? this.response().unpack() : null, this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength())); + } + unpackTo(_o) { + _o.name = this.name(); + _o.request = this.request() !== null ? this.request().unpack() : null; + _o.response = this.response() !== null ? this.response().unpack() : null; + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + } +}; +var RPCCallT = class { + constructor(name = null, request = null, response = null, attributes = [], documentation = []) { + this.name = name; + this.request = request; + this.response = response; + this.attributes = attributes; + this.documentation = documentation; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const request = this.request !== null ? this.request.pack(builder) : 0; + const response = this.response !== null ? this.response.pack(builder) : 0; + const attributes = RPCCall.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = RPCCall.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + RPCCall.startRPCCall(builder); + RPCCall.addName(builder, name); + RPCCall.addRequest(builder, request); + RPCCall.addResponse(builder, response); + RPCCall.addAttributes(builder, attributes); + RPCCall.addDocumentation(builder, documentation); + return RPCCall.endRPCCall(builder); + } +}; + +// reflection/schema.js +var flatbuffers10 = __toESM(require("flatbuffers"), 1); + +// reflection/schema-file.js +var flatbuffers8 = __toESM(require("flatbuffers"), 1); +var SchemaFile = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchemaFile(bb, obj) { + return (obj || new SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchemaFile(bb, obj) { + bb.setPosition(bb.position() + flatbuffers8.SIZE_PREFIX_LENGTH); + return (obj || new SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + filename(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + includedFilenames(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + includedFilenamesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection_SchemaFile"; + } + static startSchemaFile(builder) { + builder.startObject(2); + } + static addFilename(builder, filenameOffset) { + builder.addFieldOffset(0, filenameOffset, 0); + } + static addIncludedFilenames(builder, includedFilenamesOffset) { + builder.addFieldOffset(1, includedFilenamesOffset, 0); + } + static createIncludedFilenamesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startIncludedFilenamesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endSchemaFile(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + static createSchemaFile(builder, filenameOffset, includedFilenamesOffset) { + SchemaFile.startSchemaFile(builder); + SchemaFile.addFilename(builder, filenameOffset); + SchemaFile.addIncludedFilenames(builder, includedFilenamesOffset); + return SchemaFile.endSchemaFile(builder); + } + unpack() { + return new SchemaFileT(this.filename(), this.bb.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength())); + } + unpackTo(_o) { + _o.filename = this.filename(); + _o.includedFilenames = this.bb.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength()); + } +}; +var SchemaFileT = class { + constructor(filename = null, includedFilenames = []) { + this.filename = filename; + this.includedFilenames = includedFilenames; + } + pack(builder) { + const filename = this.filename !== null ? builder.createString(this.filename) : 0; + const includedFilenames = SchemaFile.createIncludedFilenamesVector(builder, builder.createObjectOffsetList(this.includedFilenames)); + return SchemaFile.createSchemaFile(builder, filename, includedFilenames); + } +}; + +// reflection/service.js +var flatbuffers9 = __toESM(require("flatbuffers"), 1); +var Service = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsService(bb, obj) { + return (obj || new Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsService(bb, obj) { + bb.setPosition(bb.position() + flatbuffers9.SIZE_PREFIX_LENGTH); + return (obj || new Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + calls(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new RPCCall()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + callsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection_Service"; + } + static startService(builder) { + builder.startObject(5); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addCalls(builder, callsOffset) { + builder.addFieldOffset(1, callsOffset, 0); + } + static createCallsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCallsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(2, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(3, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(4, declarationFileOffset, 0); + } + static endService(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + static createService(builder, nameOffset, callsOffset, attributesOffset, documentationOffset, declarationFileOffset) { + Service.startService(builder); + Service.addName(builder, nameOffset); + Service.addCalls(builder, callsOffset); + Service.addAttributes(builder, attributesOffset); + Service.addDocumentation(builder, documentationOffset); + Service.addDeclarationFile(builder, declarationFileOffset); + return Service.endService(builder); + } + unpack() { + return new ServiceT(this.name(), this.bb.createObjList(this.calls.bind(this), this.callsLength()), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.calls = this.bb.createObjList(this.calls.bind(this), this.callsLength()); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +}; +var ServiceT = class { + constructor(name = null, calls = [], attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.calls = calls; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const calls = Service.createCallsVector(builder, builder.createObjectOffsetList(this.calls)); + const attributes = Service.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Service.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = this.declarationFile !== null ? builder.createString(this.declarationFile) : 0; + return Service.createService(builder, name, calls, attributes, documentation, declarationFile); + } +}; + +// reflection/schema.js +var Schema = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchema(bb, obj) { + return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchema(bb, obj) { + bb.setPosition(bb.position() + flatbuffers10.SIZE_PREFIX_LENGTH); + return (obj || new Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier("BFBS"); + } + objects(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + objectsLength() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + enums(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Enum()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + enumsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + fileIdent(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + fileExt(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + rootTable(obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + services(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new Service()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + servicesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + advancedFeatures() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_advanced_features(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + fbsFiles(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? (obj || new SchemaFile()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + fbsFilesLength() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection_Schema"; + } + static startSchema(builder) { + builder.startObject(8); + } + static addObjects(builder, objectsOffset) { + builder.addFieldOffset(0, objectsOffset, 0); + } + static createObjectsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startObjectsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addEnums(builder, enumsOffset) { + builder.addFieldOffset(1, enumsOffset, 0); + } + static createEnumsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startEnumsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addFileIdent(builder, fileIdentOffset) { + builder.addFieldOffset(2, fileIdentOffset, 0); + } + static addFileExt(builder, fileExtOffset) { + builder.addFieldOffset(3, fileExtOffset, 0); + } + static addRootTable(builder, rootTableOffset) { + builder.addFieldOffset(4, rootTableOffset, 0); + } + static addServices(builder, servicesOffset) { + builder.addFieldOffset(5, servicesOffset, 0); + } + static createServicesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startServicesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAdvancedFeatures(builder, advancedFeatures) { + builder.addFieldInt64(6, advancedFeatures, BigInt("0")); + } + static addFbsFiles(builder, fbsFilesOffset) { + builder.addFieldOffset(7, fbsFilesOffset, 0); + } + static createFbsFilesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFbsFilesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endSchema(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + return offset; + } + static finishSchemaBuffer(builder, offset) { + builder.finish(offset, "BFBS"); + } + static finishSizePrefixedSchemaBuffer(builder, offset) { + builder.finish(offset, "BFBS", true); + } + unpack() { + return new SchemaT(this.bb.createObjList(this.objects.bind(this), this.objectsLength()), this.bb.createObjList(this.enums.bind(this), this.enumsLength()), this.fileIdent(), this.fileExt(), this.rootTable() !== null ? this.rootTable().unpack() : null, this.bb.createObjList(this.services.bind(this), this.servicesLength()), this.advancedFeatures(), this.bb.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength())); + } + unpackTo(_o) { + _o.objects = this.bb.createObjList(this.objects.bind(this), this.objectsLength()); + _o.enums = this.bb.createObjList(this.enums.bind(this), this.enumsLength()); + _o.fileIdent = this.fileIdent(); + _o.fileExt = this.fileExt(); + _o.rootTable = this.rootTable() !== null ? this.rootTable().unpack() : null; + _o.services = this.bb.createObjList(this.services.bind(this), this.servicesLength()); + _o.advancedFeatures = this.advancedFeatures(); + _o.fbsFiles = this.bb.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength()); + } +}; +var SchemaT = class { + constructor(objects = [], enums = [], fileIdent = null, fileExt = null, rootTable = null, services = [], advancedFeatures = BigInt("0"), fbsFiles = []) { + this.objects = objects; + this.enums = enums; + this.fileIdent = fileIdent; + this.fileExt = fileExt; + this.rootTable = rootTable; + this.services = services; + this.advancedFeatures = advancedFeatures; + this.fbsFiles = fbsFiles; + } + pack(builder) { + const objects = Schema.createObjectsVector(builder, builder.createObjectOffsetList(this.objects)); + const enums = Schema.createEnumsVector(builder, builder.createObjectOffsetList(this.enums)); + const fileIdent = this.fileIdent !== null ? builder.createString(this.fileIdent) : 0; + const fileExt = this.fileExt !== null ? builder.createString(this.fileExt) : 0; + const rootTable = this.rootTable !== null ? this.rootTable.pack(builder) : 0; + const services = Schema.createServicesVector(builder, builder.createObjectOffsetList(this.services)); + const fbsFiles = Schema.createFbsFilesVector(builder, builder.createObjectOffsetList(this.fbsFiles)); + Schema.startSchema(builder); + Schema.addObjects(builder, objects); + Schema.addEnums(builder, enums); + Schema.addFileIdent(builder, fileIdent); + Schema.addFileExt(builder, fileExt); + Schema.addRootTable(builder, rootTable); + Schema.addServices(builder, services); + Schema.addAdvancedFeatures(builder, this.advancedFeatures); + Schema.addFbsFiles(builder, fbsFiles); + return Schema.endSchema(builder); + } +}; diff --git a/third_party/flatbuffers/tests/ts/required-strings/foo.js b/third_party/flatbuffers/tests/ts/required-strings/foo.js new file mode 100644 index 00000000000..774fcca1430 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/required-strings/foo.js @@ -0,0 +1,49 @@ +// automatically generated by the FlatBuffers compiler, do not modify +import * as flatbuffers from 'flatbuffers'; +export class Foo { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsFoo(bb, obj) { + return (obj || new Foo()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsFoo(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Foo()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + strA(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + strB(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static startFoo(builder) { + builder.startObject(2); + } + static addStrA(builder, strAOffset) { + builder.addFieldOffset(0, strAOffset, 0); + } + static addStrB(builder, strBOffset) { + builder.addFieldOffset(1, strBOffset, 0); + } + static endFoo(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); // str_a + builder.requiredField(offset, 6); // str_b + return offset; + } + static createFoo(builder, strAOffset, strBOffset) { + Foo.startFoo(builder); + Foo.addStrA(builder, strAOffset); + Foo.addStrB(builder, strBOffset); + return Foo.endFoo(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/required-strings/foo.ts b/third_party/flatbuffers/tests/ts/required-strings/foo.ts new file mode 100644 index 00000000000..8ae6666ce4a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/required-strings/foo.ts @@ -0,0 +1,62 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import * as flatbuffers from 'flatbuffers'; + +export class Foo { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Foo { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsFoo(bb:flatbuffers.ByteBuffer, obj?:Foo):Foo { + return (obj || new Foo()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsFoo(bb:flatbuffers.ByteBuffer, obj?:Foo):Foo { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Foo()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +strA():string|null +strA(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +strA(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +strB():string|null +strB(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +strB(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static startFoo(builder:flatbuffers.Builder) { + builder.startObject(2); +} + +static addStrA(builder:flatbuffers.Builder, strAOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, strAOffset, 0); +} + +static addStrB(builder:flatbuffers.Builder, strBOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, strBOffset, 0); +} + +static endFoo(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + builder.requiredField(offset, 4) // str_a + builder.requiredField(offset, 6) // str_b + return offset; +} + +static createFoo(builder:flatbuffers.Builder, strAOffset:flatbuffers.Offset, strBOffset:flatbuffers.Offset):flatbuffers.Offset { + Foo.startFoo(builder); + Foo.addStrA(builder, strAOffset); + Foo.addStrB(builder, strBOffset); + return Foo.endFoo(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/required_strings_generated.js b/third_party/flatbuffers/tests/ts/required_strings_generated.js new file mode 100644 index 00000000000..9f9cf01780f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/required_strings_generated.js @@ -0,0 +1,2 @@ +"use strict"; +// automatically generated by the FlatBuffers compiler, do not modify diff --git a/third_party/flatbuffers/tests/ts/required_strings_generated.ts b/third_party/flatbuffers/tests/ts/required_strings_generated.ts new file mode 100644 index 00000000000..b7d545f8dcb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/required_strings_generated.ts @@ -0,0 +1,2 @@ +// automatically generated by the FlatBuffers compiler, do not modify + diff --git a/third_party/flatbuffers/tests/ts/table-a.d.ts b/third_party/flatbuffers/tests/ts/table-a.d.ts new file mode 100644 index 00000000000..f6708354c3e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/table-a.d.ts @@ -0,0 +1,24 @@ +import * as flatbuffers from 'flatbuffers'; +import { TableB, TableBT } from './my-game/other-name-space/table-b.js'; +export declare class TableA implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): TableA; + static getRootAsTableA(bb: flatbuffers.ByteBuffer, obj?: TableA): TableA; + static getSizePrefixedRootAsTableA(bb: flatbuffers.ByteBuffer, obj?: TableA): TableA; + b(obj?: TableB): TableB | null; + static getFullyQualifiedName(): string; + static startTableA(builder: flatbuffers.Builder): void; + static addB(builder: flatbuffers.Builder, bOffset: flatbuffers.Offset): void; + static endTableA(builder: flatbuffers.Builder): flatbuffers.Offset; + static createTableA(builder: flatbuffers.Builder, bOffset: flatbuffers.Offset): flatbuffers.Offset; + serialize(): Uint8Array; + static deserialize(buffer: Uint8Array): TableA; + unpack(): TableAT; + unpackTo(_o: TableAT): void; +} +export declare class TableAT implements flatbuffers.IGeneratedObject { + b: TableBT | null; + constructor(b?: TableBT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/table-a.js b/third_party/flatbuffers/tests/ts/table-a.js new file mode 100644 index 00000000000..b3bff4ada42 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/table-a.js @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { TableB } from './my-game/other-name-space/table-b.js'; +export class TableA { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsTableA(bb, obj) { + return (obj || new TableA()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsTableA(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TableA()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + b(obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new TableB()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + static getFullyQualifiedName() { + return 'TableA'; + } + static startTableA(builder) { + builder.startObject(1); + } + static addB(builder, bOffset) { + builder.addFieldOffset(0, bOffset, 0); + } + static endTableA(builder) { + const offset = builder.endObject(); + return offset; + } + static createTableA(builder, bOffset) { + TableA.startTableA(builder); + TableA.addB(builder, bOffset); + return TableA.endTableA(builder); + } + serialize() { + return this.bb.bytes(); + } + static deserialize(buffer) { + return TableA.getRootAsTableA(new flatbuffers.ByteBuffer(buffer)); + } + unpack() { + return new TableAT((this.b() !== null ? this.b().unpack() : null)); + } + unpackTo(_o) { + _o.b = (this.b() !== null ? this.b().unpack() : null); + } +} +export class TableAT { + constructor(b = null) { + this.b = b; + } + pack(builder) { + const b = (this.b !== null ? this.b.pack(builder) : 0); + return TableA.createTableA(builder, b); + } +} diff --git a/third_party/flatbuffers/tests/ts/table-a.ts b/third_party/flatbuffers/tests/ts/table-a.ts new file mode 100644 index 00000000000..9d47ed5286f --- /dev/null +++ b/third_party/flatbuffers/tests/ts/table-a.ts @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { TableB, TableBT } from './my-game/other-name-space/table-b.js'; + + +export class TableA implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):TableA { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsTableA(bb:flatbuffers.ByteBuffer, obj?:TableA):TableA { + return (obj || new TableA()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsTableA(bb:flatbuffers.ByteBuffer, obj?:TableA):TableA { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new TableA()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +b(obj?:TableB):TableB|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? (obj || new TableB()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +static getFullyQualifiedName():string { + return 'TableA'; +} + +static startTableA(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addB(builder:flatbuffers.Builder, bOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, bOffset, 0); +} + +static endTableA(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createTableA(builder:flatbuffers.Builder, bOffset:flatbuffers.Offset):flatbuffers.Offset { + TableA.startTableA(builder); + TableA.addB(builder, bOffset); + return TableA.endTableA(builder); +} + +serialize():Uint8Array { + return this.bb!.bytes(); +} + +static deserialize(buffer: Uint8Array):TableA { + return TableA.getRootAsTableA(new flatbuffers.ByteBuffer(buffer)) +} + +unpack(): TableAT { + return new TableAT( + (this.b() !== null ? this.b()!.unpack() : null) + ); +} + + +unpackTo(_o: TableAT): void { + _o.b = (this.b() !== null ? this.b()!.unpack() : null); +} +} + +export class TableAT implements flatbuffers.IGeneratedObject { +constructor( + public b: TableBT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const b = (this.b !== null ? this.b!.pack(builder) : 0); + + return TableA.createTableA(builder, + b + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/test_dir/BUILD.bazel b/third_party/flatbuffers/tests/ts/test_dir/BUILD.bazel new file mode 100644 index 00000000000..fdd54ded39b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/test_dir/BUILD.bazel @@ -0,0 +1,26 @@ +load("@aspect_rules_js//js:defs.bzl", "js_test") +load("//:typescript.bzl", "flatbuffer_ts_library") + +flatbuffer_ts_library( + name = "typescript_transitive_ts_fbs", + srcs = ["typescript_transitive_include.fbs"], + visibility = ["//visibility:public"], +) + +flatbuffer_ts_library( + name = "include_ts_fbs", + srcs = ["typescript_include.fbs"], + visibility = ["//visibility:public"], + deps = [":typescript_transitive_ts_fbs"], +) + +js_test( + name = "import_test", + chdir = package_name(), + data = [ + "package.json", + ":include_ts_fbs", + "//tests/ts:node_modules/flatbuffers", + ], + entry_point = "import_test.js", +) diff --git a/third_party/flatbuffers/tests/ts/test_dir/import_test.js b/third_party/flatbuffers/tests/ts/test_dir/import_test.js new file mode 100644 index 00000000000..594b11e0ec7 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/test_dir/import_test.js @@ -0,0 +1,31 @@ +import assert from 'assert' +import * as flatbuffers from 'flatbuffers' + +import typescript_include from './typescript_include_generated.cjs' + +const foobar = typescript_include.foobar; + +function main() { + // Validate the enums. + assert.strictEqual(foobar.Abc.a, 0); + assert.strictEqual(foobar.class_.arguments_, 0); + + // Validate building a table. + var fbb = new flatbuffers.Builder(1); + var name = fbb.createString("Foo Bar"); + + foobar.Tab.startTab(fbb); + foobar.Tab.addAbc(fbb, foobar.Abc.a); + foobar.Tab.addArg(fbb, foobar.class_.arguments_); + foobar.Tab.addName(fbb, name); + var tab = foobar.Tab.endTab(fbb); + + fbb.finish(tab); + + // Call as a sanity check. Would be better to validate actual output here. + fbb.asUint8Array(); + + console.log('FlatBuffers Bazel Import test: completed successfully'); +} + +main(); diff --git a/third_party/flatbuffers/tests/ts/test_dir/package.json b/third_party/flatbuffers/tests/ts/test_dir/package.json new file mode 100644 index 00000000000..af3f206b37e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/test_dir/package.json @@ -0,0 +1,6 @@ +{ + "type": "module", + "dependencies": { + "flatbuffers": "../../../" + } +} diff --git a/third_party/flatbuffers/tests/ts/test_dir/typescript_include.fbs b/third_party/flatbuffers/tests/ts/test_dir/typescript_include.fbs new file mode 100644 index 00000000000..aa43fe38a6e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/test_dir/typescript_include.fbs @@ -0,0 +1,13 @@ +include 'typescript_transitive_include.fbs'; + +namespace foobar; + +enum class: int { + arguments, +} + +table Tab { + abc:Abc; + arg:class; + name:string; +} diff --git a/third_party/flatbuffers/tests/ts/test_dir/typescript_transitive_include.fbs b/third_party/flatbuffers/tests/ts/test_dir/typescript_transitive_include.fbs new file mode 100644 index 00000000000..80ccb07c4c3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/test_dir/typescript_transitive_include.fbs @@ -0,0 +1,5 @@ +namespace foobar; + +enum Abc: int { + a, +} diff --git a/third_party/flatbuffers/tests/ts/tsconfig.json b/third_party/flatbuffers/tests/ts/tsconfig.json new file mode 100644 index 00000000000..eb08992b427 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/tsconfig.json @@ -0,0 +1,20 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM"], + "module": "NodeNext", + "declaration": true, + "strict": true + }, + "include": [ + "monster_test.ts", + "typescript_keywords.ts", + "my-game/**/*.ts", + "typescript/**/*.ts", + "optional_scalars/**/*.ts", + "namespace_test/**/*.ts", + "union_vector/**/*.ts", + "arrays_test_complex/**/*.ts", + "union_underlying_type_test.ts" + ] +} diff --git a/third_party/flatbuffers/tests/ts/tsconfig.node.json b/third_party/flatbuffers/tests/ts/tsconfig.node.json new file mode 100644 index 00000000000..63cc8682740 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/tsconfig.node.json @@ -0,0 +1,12 @@ +{ + "compilerOptions": { + "target": "ES2020", + "lib": ["ES2020", "DOM"], + "moduleResolution": "node", + "declaration": true, + "strict": true + }, + "include": [ + "no_import_ext/**/*.ts" + ] +} diff --git a/third_party/flatbuffers/tests/ts/typescript.d.ts b/third_party/flatbuffers/tests/ts/typescript.d.ts new file mode 100644 index 00000000000..3c9fcbf2f04 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript.d.ts @@ -0,0 +1,2 @@ +export { Object_ } from './typescript/object.js'; +export { class_ } from './typescript/class.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript.js b/third_party/flatbuffers/tests/ts/typescript.js new file mode 100644 index 00000000000..aaa77b6f414 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript.js @@ -0,0 +1,4 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { Object_ } from './typescript/object.js'; +export { class_ } from './typescript/class.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript.ts b/third_party/flatbuffers/tests/ts/typescript.ts new file mode 100644 index 00000000000..da50d15393d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript.ts @@ -0,0 +1,6 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Object_ } from './typescript/object.js'; +export { class_ } from './typescript/class.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript/class.d.ts b/third_party/flatbuffers/tests/ts/typescript/class.d.ts new file mode 100644 index 00000000000..ff6c5422265 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript/class.d.ts @@ -0,0 +1,4 @@ +export declare enum class_ { + new_ = 0, + instanceof_ = 1 +} diff --git a/third_party/flatbuffers/tests/ts/typescript/class.js b/third_party/flatbuffers/tests/ts/typescript/class.js new file mode 100644 index 00000000000..2dba0365e82 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript/class.js @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export var class_; +(function (class_) { + class_[class_["new_"] = 0] = "new_"; + class_[class_["instanceof_"] = 1] = "instanceof_"; +})(class_ || (class_ = {})); diff --git a/third_party/flatbuffers/tests/ts/typescript/class.ts b/third_party/flatbuffers/tests/ts/typescript/class.ts new file mode 100644 index 00000000000..69b4a0ae6df --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript/class.ts @@ -0,0 +1,8 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export enum class_ { + new_ = 0, + instanceof_ = 1 +} diff --git a/third_party/flatbuffers/tests/ts/typescript/object.d.ts b/third_party/flatbuffers/tests/ts/typescript/object.d.ts new file mode 100644 index 00000000000..c8e8b75e8aa --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript/object.d.ts @@ -0,0 +1,48 @@ +import * as flatbuffers from 'flatbuffers'; +import { Abc } from '../foobar/abc.js'; +import { class_ as foobar_class_ } from '../foobar/class.js'; +import { Schema, SchemaT } from '../reflection/schema.js'; +import { class_ } from '../typescript/class.js'; +export declare class Object_ implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Object_; + static getRootAsObject(bb: flatbuffers.ByteBuffer, obj?: Object_): Object_; + static getSizePrefixedRootAsObject(bb: flatbuffers.ByteBuffer, obj?: Object_): Object_; + return_(): number; + mutate_return(value: number): boolean; + if_(): number; + mutate_if(value: number): boolean; + switch_(): number; + mutate_switch(value: number): boolean; + enum_(): class_; + mutate_enum(value: class_): boolean; + enum2(): foobar_class_; + mutate_enum2(value: foobar_class_): boolean; + enum3(): Abc; + mutate_enum3(value: Abc): boolean; + reflect(obj?: Schema): Schema | null; + static getFullyQualifiedName(): string; + static startObject(builder: flatbuffers.Builder): void; + static addReturn(builder: flatbuffers.Builder, return_: number): void; + static addIf(builder: flatbuffers.Builder, if_: number): void; + static addSwitch(builder: flatbuffers.Builder, switch_: number): void; + static addEnum(builder: flatbuffers.Builder, enum_: class_): void; + static addEnum2(builder: flatbuffers.Builder, enum2: foobar_class_): void; + static addEnum3(builder: flatbuffers.Builder, enum3: Abc): void; + static addReflect(builder: flatbuffers.Builder, reflectOffset: flatbuffers.Offset): void; + static endObject(builder: flatbuffers.Builder): flatbuffers.Offset; + unpack(): Object_T; + unpackTo(_o: Object_T): void; +} +export declare class Object_T implements flatbuffers.IGeneratedObject { + return_: number; + if_: number; + switch_: number; + enum_: class_; + enum2: foobar_class_; + enum3: Abc; + reflect: SchemaT | null; + constructor(return_?: number, if_?: number, switch_?: number, enum_?: class_, enum2?: foobar_class_, enum3?: Abc, reflect?: SchemaT | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/typescript/object.js b/third_party/flatbuffers/tests/ts/typescript/object.js new file mode 100644 index 00000000000..c8b97691867 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript/object.js @@ -0,0 +1,167 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { Abc } from '../foobar/abc.js'; +import { class_ as foobar_class_ } from '../foobar/class.js'; +import { Schema } from '../reflection/schema.js'; +import { class_ } from '../typescript/class.js'; +export class Object_ { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsObject(bb, obj) { + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsObject(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + return_() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_return(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + if_() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_if(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + switch_() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_switch(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + enum_() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt32(this.bb_pos + offset) : class_.new_; + } + mutate_enum(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + enum2() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : foobar_class_.arguments_; + } + mutate_enum2(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + enum3() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readInt32(this.bb_pos + offset) : Abc.a; + } + mutate_enum3(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + reflect(obj) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? (obj || new Schema()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + static getFullyQualifiedName() { + return 'typescript.Object'; + } + static startObject(builder) { + builder.startObject(7); + } + static addReturn(builder, return_) { + builder.addFieldInt32(0, return_, 0); + } + static addIf(builder, if_) { + builder.addFieldInt32(1, if_, 0); + } + static addSwitch(builder, switch_) { + builder.addFieldInt32(2, switch_, 0); + } + static addEnum(builder, enum_) { + builder.addFieldInt32(3, enum_, class_.new_); + } + static addEnum2(builder, enum2) { + builder.addFieldInt32(4, enum2, foobar_class_.arguments_); + } + static addEnum3(builder, enum3) { + builder.addFieldInt32(5, enum3, Abc.a); + } + static addReflect(builder, reflectOffset) { + builder.addFieldOffset(6, reflectOffset, 0); + } + static endObject(builder) { + const offset = builder.endObject(); + return offset; + } + unpack() { + return new Object_T(this.return_(), this.if_(), this.switch_(), this.enum_(), this.enum2(), this.enum3(), (this.reflect() !== null ? this.reflect().unpack() : null)); + } + unpackTo(_o) { + _o.return_ = this.return_(); + _o.if_ = this.if_(); + _o.switch_ = this.switch_(); + _o.enum_ = this.enum_(); + _o.enum2 = this.enum2(); + _o.enum3 = this.enum3(); + _o.reflect = (this.reflect() !== null ? this.reflect().unpack() : null); + } +} +export class Object_T { + constructor(return_ = 0, if_ = 0, switch_ = 0, enum_ = class_.new_, enum2 = foobar_class_.arguments_, enum3 = Abc.a, reflect = null) { + this.return_ = return_; + this.if_ = if_; + this.switch_ = switch_; + this.enum_ = enum_; + this.enum2 = enum2; + this.enum3 = enum3; + this.reflect = reflect; + } + pack(builder) { + const reflect = (this.reflect !== null ? this.reflect.pack(builder) : 0); + Object_.startObject(builder); + Object_.addReturn(builder, this.return_); + Object_.addIf(builder, this.if_); + Object_.addSwitch(builder, this.switch_); + Object_.addEnum(builder, this.enum_); + Object_.addEnum2(builder, this.enum2); + Object_.addEnum3(builder, this.enum3); + Object_.addReflect(builder, reflect); + return Object_.endObject(builder); + } +} diff --git a/third_party/flatbuffers/tests/ts/typescript/object.ts b/third_party/flatbuffers/tests/ts/typescript/object.ts new file mode 100644 index 00000000000..c7760d8f139 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript/object.ts @@ -0,0 +1,224 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Abc } from '../foobar/abc.js'; +import { class_ as foobar_class_ } from '../foobar/class.js'; +import { Schema, SchemaT } from '../reflection/schema.js'; +import { class_ } from '../typescript/class.js'; + + +export class Object_ implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Object_ { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsObject(bb:flatbuffers.ByteBuffer, obj?:Object_):Object_ { + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsObject(bb:flatbuffers.ByteBuffer, obj?:Object_):Object_ { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +return_():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_return(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +if_():number { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_if(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 6); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +switch_():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_switch(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 8); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +enum_():class_ { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : class_.new_; +} + +mutate_enum(value:class_):boolean { + const offset = this.bb!.__offset(this.bb_pos, 10); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +enum2():foobar_class_ { + const offset = this.bb!.__offset(this.bb_pos, 12); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : foobar_class_.arguments_; +} + +mutate_enum2(value:foobar_class_):boolean { + const offset = this.bb!.__offset(this.bb_pos, 12); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +enum3():Abc { + const offset = this.bb!.__offset(this.bb_pos, 14); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : Abc.a; +} + +mutate_enum3(value:Abc):boolean { + const offset = this.bb!.__offset(this.bb_pos, 14); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +reflect(obj?:Schema):Schema|null { + const offset = this.bb!.__offset(this.bb_pos, 16); + return offset ? (obj || new Schema()).__init(this.bb!.__indirect(this.bb_pos + offset), this.bb!) : null; +} + +static getFullyQualifiedName():string { + return 'typescript.Object'; +} + +static startObject(builder:flatbuffers.Builder) { + builder.startObject(7); +} + +static addReturn(builder:flatbuffers.Builder, return_:number) { + builder.addFieldInt32(0, return_, 0); +} + +static addIf(builder:flatbuffers.Builder, if_:number) { + builder.addFieldInt32(1, if_, 0); +} + +static addSwitch(builder:flatbuffers.Builder, switch_:number) { + builder.addFieldInt32(2, switch_, 0); +} + +static addEnum(builder:flatbuffers.Builder, enum_:class_) { + builder.addFieldInt32(3, enum_, class_.new_); +} + +static addEnum2(builder:flatbuffers.Builder, enum2:foobar_class_) { + builder.addFieldInt32(4, enum2, foobar_class_.arguments_); +} + +static addEnum3(builder:flatbuffers.Builder, enum3:Abc) { + builder.addFieldInt32(5, enum3, Abc.a); +} + +static addReflect(builder:flatbuffers.Builder, reflectOffset:flatbuffers.Offset) { + builder.addFieldOffset(6, reflectOffset, 0); +} + +static endObject(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + + +unpack(): Object_T { + return new Object_T( + this.return_(), + this.if_(), + this.switch_(), + this.enum_(), + this.enum2(), + this.enum3(), + (this.reflect() !== null ? this.reflect()!.unpack() : null) + ); +} + + +unpackTo(_o: Object_T): void { + _o.return_ = this.return_(); + _o.if_ = this.if_(); + _o.switch_ = this.switch_(); + _o.enum_ = this.enum_(); + _o.enum2 = this.enum2(); + _o.enum3 = this.enum3(); + _o.reflect = (this.reflect() !== null ? this.reflect()!.unpack() : null); +} +} + +export class Object_T implements flatbuffers.IGeneratedObject { +constructor( + public return_: number = 0, + public if_: number = 0, + public switch_: number = 0, + public enum_: class_ = class_.new_, + public enum2: foobar_class_ = foobar_class_.arguments_, + public enum3: Abc = Abc.a, + public reflect: SchemaT|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const reflect = (this.reflect !== null ? this.reflect!.pack(builder) : 0); + + Object_.startObject(builder); + Object_.addReturn(builder, this.return_); + Object_.addIf(builder, this.if_); + Object_.addSwitch(builder, this.switch_); + Object_.addEnum(builder, this.enum_); + Object_.addEnum2(builder, this.enum2); + Object_.addEnum3(builder, this.enum3); + Object_.addReflect(builder, reflect); + + return Object_.endObject(builder); +} +} diff --git a/third_party/flatbuffers/tests/ts/typescript_include.ts b/third_party/flatbuffers/tests/ts/typescript_include.ts new file mode 100644 index 00000000000..aabfb64fa2d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_include.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export * as foobar from './foobar.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript_include_generated.cjs b/third_party/flatbuffers/tests/ts/typescript_include_generated.cjs new file mode 100644 index 00000000000..a54eecfb4bf --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_include_generated.cjs @@ -0,0 +1,31 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// foobar.ts +var foobar_exports = {}; +__export(foobar_exports, { + Abc: () => Abc +}); +module.exports = __toCommonJS(foobar_exports); + +// foobar/abc.js +var Abc; +(function(Abc2) { + Abc2[Abc2["a"] = 0] = "a"; +})(Abc = Abc || (Abc = {})); diff --git a/third_party/flatbuffers/tests/ts/typescript_keywords.d.ts b/third_party/flatbuffers/tests/ts/typescript_keywords.d.ts new file mode 100644 index 00000000000..cd607f1f9fc --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_keywords.d.ts @@ -0,0 +1,3 @@ +export * as foobar from './foobar.js'; +export * as reflection from './reflection.js'; +export * as typescript from './typescript.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript_keywords.fbs b/third_party/flatbuffers/tests/ts/typescript_keywords.fbs new file mode 100644 index 00000000000..cdb96961d8b --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_keywords.fbs @@ -0,0 +1,21 @@ +include 'test_dir/typescript_include.fbs'; +include 'reflection/reflection.fbs'; + +// This file includes a variety of keywords meant to deliberately interfere +// with typescript keywords. +namespace typescript; + +enum class: int { + new, + instanceof, +} + +table Object { + return:int; + if:int; + switch:int; + enum:class; + enum2:foobar.class; + enum3:foobar.Abc; + reflect:reflection.Schema; +} diff --git a/third_party/flatbuffers/tests/ts/typescript_keywords.js b/third_party/flatbuffers/tests/ts/typescript_keywords.js new file mode 100644 index 00000000000..60b7e5751b1 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_keywords.js @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export * as foobar from './foobar.js'; +export * as reflection from './reflection.js'; +export * as typescript from './typescript.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript_keywords.ts b/third_party/flatbuffers/tests/ts/typescript_keywords.ts new file mode 100644 index 00000000000..77696e7a1c5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_keywords.ts @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export * as foobar from './foobar.js'; +export * as reflection from './reflection.js'; +export * as typescript from './typescript.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript_keywords_generated.cjs b/third_party/flatbuffers/tests/ts/typescript_keywords_generated.cjs new file mode 100644 index 00000000000..cc89f84c44a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_keywords_generated.cjs @@ -0,0 +1,1912 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// typescript_keywords.ts +var typescript_keywords_exports = {}; +__export(typescript_keywords_exports, { + foobar: () => foobar_exports, + reflection: () => reflection_exports, + typescript: () => typescript_exports +}); +module.exports = __toCommonJS(typescript_keywords_exports); + +// foobar.js +var foobar_exports = {}; +__export(foobar_exports, { + Abc: () => Abc +}); + +// foobar/abc.js +var Abc; +(function(Abc2) { + Abc2[Abc2["a"] = 0] = "a"; +})(Abc || (Abc = {})); + +// reflection.js +var reflection_exports = {}; +__export(reflection_exports, { + AdvancedFeatures: () => AdvancedFeatures, + BaseType: () => BaseType, + Enum: () => Enum, + EnumT: () => EnumT, + EnumVal: () => EnumVal, + EnumValT: () => EnumValT, + Field: () => Field, + FieldT: () => FieldT, + KeyValue: () => KeyValue, + KeyValueT: () => KeyValueT, + Object_: () => Object_, + RPCCall: () => RPCCall, + RPCCallT: () => RPCCallT, + Schema: () => Schema, + SchemaFile: () => SchemaFile, + SchemaFileT: () => SchemaFileT, + SchemaT: () => SchemaT, + Service: () => Service, + ServiceT: () => ServiceT, + Type: () => Type, + TypeT: () => TypeT +}); + +// reflection/advanced-features.js +var AdvancedFeatures; +(function(AdvancedFeatures2) { + AdvancedFeatures2["AdvancedArrayFeatures"] = "1"; + AdvancedFeatures2["AdvancedUnionFeatures"] = "2"; + AdvancedFeatures2["OptionalScalars"] = "4"; + AdvancedFeatures2["DefaultVectorsAndStrings"] = "8"; +})(AdvancedFeatures || (AdvancedFeatures = {})); + +// reflection/base-type.js +var BaseType; +(function(BaseType2) { + BaseType2[BaseType2["None"] = 0] = "None"; + BaseType2[BaseType2["UType"] = 1] = "UType"; + BaseType2[BaseType2["Bool"] = 2] = "Bool"; + BaseType2[BaseType2["Byte"] = 3] = "Byte"; + BaseType2[BaseType2["UByte"] = 4] = "UByte"; + BaseType2[BaseType2["Short"] = 5] = "Short"; + BaseType2[BaseType2["UShort"] = 6] = "UShort"; + BaseType2[BaseType2["Int"] = 7] = "Int"; + BaseType2[BaseType2["UInt"] = 8] = "UInt"; + BaseType2[BaseType2["Long"] = 9] = "Long"; + BaseType2[BaseType2["ULong"] = 10] = "ULong"; + BaseType2[BaseType2["Float"] = 11] = "Float"; + BaseType2[BaseType2["Double"] = 12] = "Double"; + BaseType2[BaseType2["String"] = 13] = "String"; + BaseType2[BaseType2["Vector"] = 14] = "Vector"; + BaseType2[BaseType2["Obj"] = 15] = "Obj"; + BaseType2[BaseType2["Union"] = 16] = "Union"; + BaseType2[BaseType2["Array"] = 17] = "Array"; + BaseType2[BaseType2["Vector64"] = 18] = "Vector64"; + BaseType2[BaseType2["MaxBaseType"] = 19] = "MaxBaseType"; +})(BaseType || (BaseType = {})); + +// reflection/enum.js +var flatbuffers4 = __toESM(require("flatbuffers"), 1); + +// reflection/enum-val.js +var flatbuffers3 = __toESM(require("flatbuffers"), 1); + +// reflection/key-value.js +var flatbuffers = __toESM(require("flatbuffers"), 1); +var KeyValue = class _KeyValue { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsKeyValue(bb, obj) { + return (obj || new _KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsKeyValue(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new _KeyValue()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + key(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection.KeyValue"; + } + static startKeyValue(builder) { + builder.startObject(2); + } + static addKey(builder, keyOffset) { + builder.addFieldOffset(0, keyOffset, 0); + } + static addValue(builder, valueOffset) { + builder.addFieldOffset(1, valueOffset, 0); + } + static endKeyValue(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + static createKeyValue(builder, keyOffset, valueOffset) { + _KeyValue.startKeyValue(builder); + _KeyValue.addKey(builder, keyOffset); + _KeyValue.addValue(builder, valueOffset); + return _KeyValue.endKeyValue(builder); + } + unpack() { + return new KeyValueT(this.key(), this.value()); + } + unpackTo(_o) { + _o.key = this.key(); + _o.value = this.value(); + } +}; +var KeyValueT = class { + constructor(key = null, value = null) { + this.key = key; + this.value = value; + } + pack(builder) { + const key = this.key !== null ? builder.createString(this.key) : 0; + const value = this.value !== null ? builder.createString(this.value) : 0; + return KeyValue.createKeyValue(builder, key, value); + } +}; + +// reflection/type.js +var flatbuffers2 = __toESM(require("flatbuffers"), 1); +var Type = class _Type { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsType(bb, obj) { + return (obj || new _Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsType(bb, obj) { + bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH); + return (obj || new _Type()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + baseType() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BaseType.None; + } + mutate_base_type(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + element() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt8(this.bb_pos + offset) : BaseType.None; + } + mutate_element(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, value); + return true; + } + index() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb_pos + offset) : -1; + } + mutate_index(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + fixedLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_fixed_length(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + /** + * The size (octets) of the `base_type` field. + */ + baseSize() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 4; + } + mutate_base_size(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + /** + * The size (octets) of the `element` field, if present. + */ + elementSize() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readUint32(this.bb_pos + offset) : 0; + } + mutate_element_size(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeUint32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "reflection.Type"; + } + static startType(builder) { + builder.startObject(6); + } + static addBaseType(builder, baseType) { + builder.addFieldInt8(0, baseType, BaseType.None); + } + static addElement(builder, element) { + builder.addFieldInt8(1, element, BaseType.None); + } + static addIndex(builder, index) { + builder.addFieldInt32(2, index, -1); + } + static addFixedLength(builder, fixedLength) { + builder.addFieldInt16(3, fixedLength, 0); + } + static addBaseSize(builder, baseSize) { + builder.addFieldInt32(4, baseSize, 4); + } + static addElementSize(builder, elementSize) { + builder.addFieldInt32(5, elementSize, 0); + } + static endType(builder) { + const offset = builder.endObject(); + return offset; + } + static createType(builder, baseType, element, index, fixedLength, baseSize, elementSize) { + _Type.startType(builder); + _Type.addBaseType(builder, baseType); + _Type.addElement(builder, element); + _Type.addIndex(builder, index); + _Type.addFixedLength(builder, fixedLength); + _Type.addBaseSize(builder, baseSize); + _Type.addElementSize(builder, elementSize); + return _Type.endType(builder); + } + unpack() { + return new TypeT(this.baseType(), this.element(), this.index(), this.fixedLength(), this.baseSize(), this.elementSize()); + } + unpackTo(_o) { + _o.baseType = this.baseType(); + _o.element = this.element(); + _o.index = this.index(); + _o.fixedLength = this.fixedLength(); + _o.baseSize = this.baseSize(); + _o.elementSize = this.elementSize(); + } +}; +var TypeT = class { + constructor(baseType = BaseType.None, element = BaseType.None, index = -1, fixedLength = 0, baseSize = 4, elementSize = 0) { + this.baseType = baseType; + this.element = element; + this.index = index; + this.fixedLength = fixedLength; + this.baseSize = baseSize; + this.elementSize = elementSize; + } + pack(builder) { + return Type.createType(builder, this.baseType, this.element, this.index, this.fixedLength, this.baseSize, this.elementSize); + } +}; + +// reflection/enum-val.js +var EnumVal = class _EnumVal { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsEnumVal(bb, obj) { + return (obj || new _EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsEnumVal(bb, obj) { + bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH); + return (obj || new _EnumVal()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + value() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_value(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + unionType(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection.EnumVal"; + } + static startEnumVal(builder) { + builder.startObject(6); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addValue(builder, value) { + builder.addFieldInt64(1, value, BigInt("0")); + } + static addUnionType(builder, unionTypeOffset) { + builder.addFieldOffset(3, unionTypeOffset, 0); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(4, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(5, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endEnumVal(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + unpack() { + return new EnumValT(this.name(), this.value(), this.unionType() !== null ? this.unionType().unpack() : null, this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.bb.createObjList(this.attributes.bind(this), this.attributesLength())); + } + unpackTo(_o) { + _o.name = this.name(); + _o.value = this.value(); + _o.unionType = this.unionType() !== null ? this.unionType().unpack() : null; + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + } +}; +var EnumValT = class { + constructor(name = null, value = BigInt("0"), unionType = null, documentation = [], attributes = []) { + this.name = name; + this.value = value; + this.unionType = unionType; + this.documentation = documentation; + this.attributes = attributes; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const unionType = this.unionType !== null ? this.unionType.pack(builder) : 0; + const documentation = EnumVal.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const attributes = EnumVal.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + EnumVal.startEnumVal(builder); + EnumVal.addName(builder, name); + EnumVal.addValue(builder, this.value); + EnumVal.addUnionType(builder, unionType); + EnumVal.addDocumentation(builder, documentation); + EnumVal.addAttributes(builder, attributes); + return EnumVal.endEnumVal(builder); + } +}; + +// reflection/enum.js +var Enum = class _Enum { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsEnum(bb, obj) { + return (obj || new _Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsEnum(bb, obj) { + bb.setPosition(bb.position() + flatbuffers4.SIZE_PREFIX_LENGTH); + return (obj || new _Enum()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + values(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new EnumVal()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + valuesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + isUnion() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_is_union(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + underlyingType(obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection.Enum"; + } + static startEnum(builder) { + builder.startObject(7); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addValues(builder, valuesOffset) { + builder.addFieldOffset(1, valuesOffset, 0); + } + static createValuesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startValuesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addIsUnion(builder, isUnion) { + builder.addFieldInt8(2, +isUnion, 0); + } + static addUnderlyingType(builder, underlyingTypeOffset) { + builder.addFieldOffset(3, underlyingTypeOffset, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(4, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(5, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(6, declarationFileOffset, 0); + } + static endEnum(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + builder.requiredField(offset, 10); + return offset; + } + unpack() { + return new EnumT(this.name(), this.bb.createObjList(this.values.bind(this), this.valuesLength()), this.isUnion(), this.underlyingType() !== null ? this.underlyingType().unpack() : null, this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.values = this.bb.createObjList(this.values.bind(this), this.valuesLength()); + _o.isUnion = this.isUnion(); + _o.underlyingType = this.underlyingType() !== null ? this.underlyingType().unpack() : null; + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +}; +var EnumT = class { + constructor(name = null, values = [], isUnion = false, underlyingType = null, attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.values = values; + this.isUnion = isUnion; + this.underlyingType = underlyingType; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const values = Enum.createValuesVector(builder, builder.createObjectOffsetList(this.values)); + const underlyingType = this.underlyingType !== null ? this.underlyingType.pack(builder) : 0; + const attributes = Enum.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Enum.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = this.declarationFile !== null ? builder.createString(this.declarationFile) : 0; + Enum.startEnum(builder); + Enum.addName(builder, name); + Enum.addValues(builder, values); + Enum.addIsUnion(builder, this.isUnion); + Enum.addUnderlyingType(builder, underlyingType); + Enum.addAttributes(builder, attributes); + Enum.addDocumentation(builder, documentation); + Enum.addDeclarationFile(builder, declarationFile); + return Enum.endEnum(builder); + } +}; + +// reflection/field.js +var flatbuffers5 = __toESM(require("flatbuffers"), 1); +var Field = class _Field { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsField(bb, obj) { + return (obj || new _Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsField(bb, obj) { + bb.setPosition(bb.position() + flatbuffers5.SIZE_PREFIX_LENGTH); + return (obj || new _Field()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + type(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Type()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + id() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_id(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + offset() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_offset(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + defaultInteger() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt64(this.bb_pos + offset) : BigInt("0"); + } + mutate_default_integer(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt64(this.bb_pos + offset, value); + return true; + } + defaultReal() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readFloat64(this.bb_pos + offset) : 0; + } + mutate_default_real(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeFloat64(this.bb_pos + offset, value); + return true; + } + deprecated() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_deprecated(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + required() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_required(value) { + const offset = this.bb.__offset(this.bb_pos, 18); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + key() { + const offset = this.bb.__offset(this.bb_pos, 20); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_key(value) { + const offset = this.bb.__offset(this.bb_pos, 20); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 22); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 24); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + optional() { + const offset = this.bb.__offset(this.bb_pos, 26); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_optional(value) { + const offset = this.bb.__offset(this.bb_pos, 26); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + /** + * Number of padding octets to always add after this field. Structs only. + */ + padding() { + const offset = this.bb.__offset(this.bb_pos, 28); + return offset ? this.bb.readUint16(this.bb_pos + offset) : 0; + } + mutate_padding(value) { + const offset = this.bb.__offset(this.bb_pos, 28); + if (offset === 0) { + return false; + } + this.bb.writeUint16(this.bb_pos + offset, value); + return true; + } + /** + * If the field uses 64-bit offsets. + */ + offset64() { + const offset = this.bb.__offset(this.bb_pos, 30); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_offset64(value) { + const offset = this.bb.__offset(this.bb_pos, 30); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + static getFullyQualifiedName() { + return "reflection.Field"; + } + static startField(builder) { + builder.startObject(14); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addType(builder, typeOffset) { + builder.addFieldOffset(1, typeOffset, 0); + } + static addId(builder, id) { + builder.addFieldInt16(2, id, 0); + } + static addOffset(builder, offset) { + builder.addFieldInt16(3, offset, 0); + } + static addDefaultInteger(builder, defaultInteger) { + builder.addFieldInt64(4, defaultInteger, BigInt("0")); + } + static addDefaultReal(builder, defaultReal) { + builder.addFieldFloat64(5, defaultReal, 0); + } + static addDeprecated(builder, deprecated) { + builder.addFieldInt8(6, +deprecated, 0); + } + static addRequired(builder, required) { + builder.addFieldInt8(7, +required, 0); + } + static addKey(builder, key) { + builder.addFieldInt8(8, +key, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(9, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(10, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addOptional(builder, optional) { + builder.addFieldInt8(11, +optional, 0); + } + static addPadding(builder, padding) { + builder.addFieldInt16(12, padding, 0); + } + static addOffset64(builder, offset64) { + builder.addFieldInt8(13, +offset64, 0); + } + static endField(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + return offset; + } + unpack() { + return new FieldT(this.name(), this.type() !== null ? this.type().unpack() : null, this.id(), this.offset(), this.defaultInteger(), this.defaultReal(), this.deprecated(), this.required(), this.key(), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.optional(), this.padding(), this.offset64()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.type = this.type() !== null ? this.type().unpack() : null; + _o.id = this.id(); + _o.offset = this.offset(); + _o.defaultInteger = this.defaultInteger(); + _o.defaultReal = this.defaultReal(); + _o.deprecated = this.deprecated(); + _o.required = this.required(); + _o.key = this.key(); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.optional = this.optional(); + _o.padding = this.padding(); + _o.offset64 = this.offset64(); + } +}; +var FieldT = class { + constructor(name = null, type = null, id = 0, offset = 0, defaultInteger = BigInt("0"), defaultReal = 0, deprecated = false, required = false, key = false, attributes = [], documentation = [], optional = false, padding = 0, offset64 = false) { + this.name = name; + this.type = type; + this.id = id; + this.offset = offset; + this.defaultInteger = defaultInteger; + this.defaultReal = defaultReal; + this.deprecated = deprecated; + this.required = required; + this.key = key; + this.attributes = attributes; + this.documentation = documentation; + this.optional = optional; + this.padding = padding; + this.offset64 = offset64; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const type = this.type !== null ? this.type.pack(builder) : 0; + const attributes = Field.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Field.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + Field.startField(builder); + Field.addName(builder, name); + Field.addType(builder, type); + Field.addId(builder, this.id); + Field.addOffset(builder, this.offset); + Field.addDefaultInteger(builder, this.defaultInteger); + Field.addDefaultReal(builder, this.defaultReal); + Field.addDeprecated(builder, this.deprecated); + Field.addRequired(builder, this.required); + Field.addKey(builder, this.key); + Field.addAttributes(builder, attributes); + Field.addDocumentation(builder, documentation); + Field.addOptional(builder, this.optional); + Field.addPadding(builder, this.padding); + Field.addOffset64(builder, this.offset64); + return Field.endField(builder); + } +}; + +// reflection/object.js +var flatbuffers6 = __toESM(require("flatbuffers"), 1); +var Object_ = class _Object_ { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsObject(bb, obj) { + return (obj || new _Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsObject(bb, obj) { + bb.setPosition(bb.position() + flatbuffers6.SIZE_PREFIX_LENGTH); + return (obj || new _Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + fields(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Field()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + fieldsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + isStruct() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_is_struct(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + minalign() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_minalign(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + bytesize() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_bytesize(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection.Object"; + } + static startObject(builder) { + builder.startObject(8); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addFields(builder, fieldsOffset) { + builder.addFieldOffset(1, fieldsOffset, 0); + } + static createFieldsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFieldsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addIsStruct(builder, isStruct) { + builder.addFieldInt8(2, +isStruct, 0); + } + static addMinalign(builder, minalign) { + builder.addFieldInt32(3, minalign, 0); + } + static addBytesize(builder, bytesize) { + builder.addFieldInt32(4, bytesize, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(5, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(6, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(7, declarationFileOffset, 0); + } + static endObject(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + return offset; + } + static createObject(builder, nameOffset, fieldsOffset, isStruct, minalign, bytesize, attributesOffset, documentationOffset, declarationFileOffset) { + _Object_.startObject(builder); + _Object_.addName(builder, nameOffset); + _Object_.addFields(builder, fieldsOffset); + _Object_.addIsStruct(builder, isStruct); + _Object_.addMinalign(builder, minalign); + _Object_.addBytesize(builder, bytesize); + _Object_.addAttributes(builder, attributesOffset); + _Object_.addDocumentation(builder, documentationOffset); + _Object_.addDeclarationFile(builder, declarationFileOffset); + return _Object_.endObject(builder); + } + unpack() { + return new Object_T(this.name(), this.bb.createObjList(this.fields.bind(this), this.fieldsLength()), this.isStruct(), this.minalign(), this.bytesize(), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.fields = this.bb.createObjList(this.fields.bind(this), this.fieldsLength()); + _o.isStruct = this.isStruct(); + _o.minalign = this.minalign(); + _o.bytesize = this.bytesize(); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +}; +var Object_T = class { + constructor(name = null, fields = [], isStruct = false, minalign = 0, bytesize = 0, attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.fields = fields; + this.isStruct = isStruct; + this.minalign = minalign; + this.bytesize = bytesize; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const fields = Object_.createFieldsVector(builder, builder.createObjectOffsetList(this.fields)); + const attributes = Object_.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Object_.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = this.declarationFile !== null ? builder.createString(this.declarationFile) : 0; + return Object_.createObject(builder, name, fields, this.isStruct, this.minalign, this.bytesize, attributes, documentation, declarationFile); + } +}; + +// reflection/rpccall.js +var flatbuffers7 = __toESM(require("flatbuffers"), 1); +var RPCCall = class _RPCCall { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsRPCCall(bb, obj) { + return (obj || new _RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsRPCCall(bb, obj) { + bb.setPosition(bb.position() + flatbuffers7.SIZE_PREFIX_LENGTH); + return (obj || new _RPCCall()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + request(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + response(obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection.RPCCall"; + } + static startRPCCall(builder) { + builder.startObject(5); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addRequest(builder, requestOffset) { + builder.addFieldOffset(1, requestOffset, 0); + } + static addResponse(builder, responseOffset) { + builder.addFieldOffset(2, responseOffset, 0); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(3, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(4, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endRPCCall(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + builder.requiredField(offset, 8); + return offset; + } + unpack() { + return new RPCCallT(this.name(), this.request() !== null ? this.request().unpack() : null, this.response() !== null ? this.response().unpack() : null, this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength())); + } + unpackTo(_o) { + _o.name = this.name(); + _o.request = this.request() !== null ? this.request().unpack() : null; + _o.response = this.response() !== null ? this.response().unpack() : null; + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + } +}; +var RPCCallT = class { + constructor(name = null, request = null, response = null, attributes = [], documentation = []) { + this.name = name; + this.request = request; + this.response = response; + this.attributes = attributes; + this.documentation = documentation; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const request = this.request !== null ? this.request.pack(builder) : 0; + const response = this.response !== null ? this.response.pack(builder) : 0; + const attributes = RPCCall.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = RPCCall.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + RPCCall.startRPCCall(builder); + RPCCall.addName(builder, name); + RPCCall.addRequest(builder, request); + RPCCall.addResponse(builder, response); + RPCCall.addAttributes(builder, attributes); + RPCCall.addDocumentation(builder, documentation); + return RPCCall.endRPCCall(builder); + } +}; + +// reflection/schema.js +var flatbuffers10 = __toESM(require("flatbuffers"), 1); + +// reflection/schema-file.js +var flatbuffers8 = __toESM(require("flatbuffers"), 1); +var SchemaFile = class _SchemaFile { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchemaFile(bb, obj) { + return (obj || new _SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchemaFile(bb, obj) { + bb.setPosition(bb.position() + flatbuffers8.SIZE_PREFIX_LENGTH); + return (obj || new _SchemaFile()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + filename(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + includedFilenames(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + includedFilenamesLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection.SchemaFile"; + } + static startSchemaFile(builder) { + builder.startObject(2); + } + static addFilename(builder, filenameOffset) { + builder.addFieldOffset(0, filenameOffset, 0); + } + static addIncludedFilenames(builder, includedFilenamesOffset) { + builder.addFieldOffset(1, includedFilenamesOffset, 0); + } + static createIncludedFilenamesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startIncludedFilenamesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endSchemaFile(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + static createSchemaFile(builder, filenameOffset, includedFilenamesOffset) { + _SchemaFile.startSchemaFile(builder); + _SchemaFile.addFilename(builder, filenameOffset); + _SchemaFile.addIncludedFilenames(builder, includedFilenamesOffset); + return _SchemaFile.endSchemaFile(builder); + } + unpack() { + return new SchemaFileT(this.filename(), this.bb.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength())); + } + unpackTo(_o) { + _o.filename = this.filename(); + _o.includedFilenames = this.bb.createScalarList(this.includedFilenames.bind(this), this.includedFilenamesLength()); + } +}; +var SchemaFileT = class { + constructor(filename = null, includedFilenames = []) { + this.filename = filename; + this.includedFilenames = includedFilenames; + } + pack(builder) { + const filename = this.filename !== null ? builder.createString(this.filename) : 0; + const includedFilenames = SchemaFile.createIncludedFilenamesVector(builder, builder.createObjectOffsetList(this.includedFilenames)); + return SchemaFile.createSchemaFile(builder, filename, includedFilenames); + } +}; + +// reflection/service.js +var flatbuffers9 = __toESM(require("flatbuffers"), 1); +var Service = class _Service { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsService(bb, obj) { + return (obj || new _Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsService(bb, obj) { + bb.setPosition(bb.position() + flatbuffers9.SIZE_PREFIX_LENGTH); + return (obj || new _Service()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + name(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + calls(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new RPCCall()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + callsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + attributes(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? (obj || new KeyValue()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + attributesLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + documentation(index, optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb.__vector(this.bb_pos + offset) + index * 4, optionalEncoding) : null; + } + documentationLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + declarationFile(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return "reflection.Service"; + } + static startService(builder) { + builder.startObject(5); + } + static addName(builder, nameOffset) { + builder.addFieldOffset(0, nameOffset, 0); + } + static addCalls(builder, callsOffset) { + builder.addFieldOffset(1, callsOffset, 0); + } + static createCallsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCallsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAttributes(builder, attributesOffset) { + builder.addFieldOffset(2, attributesOffset, 0); + } + static createAttributesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startAttributesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDocumentation(builder, documentationOffset) { + builder.addFieldOffset(3, documentationOffset, 0); + } + static createDocumentationVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startDocumentationVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addDeclarationFile(builder, declarationFileOffset) { + builder.addFieldOffset(4, declarationFileOffset, 0); + } + static endService(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + return offset; + } + static createService(builder, nameOffset, callsOffset, attributesOffset, documentationOffset, declarationFileOffset) { + _Service.startService(builder); + _Service.addName(builder, nameOffset); + _Service.addCalls(builder, callsOffset); + _Service.addAttributes(builder, attributesOffset); + _Service.addDocumentation(builder, documentationOffset); + _Service.addDeclarationFile(builder, declarationFileOffset); + return _Service.endService(builder); + } + unpack() { + return new ServiceT(this.name(), this.bb.createObjList(this.calls.bind(this), this.callsLength()), this.bb.createObjList(this.attributes.bind(this), this.attributesLength()), this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()), this.declarationFile()); + } + unpackTo(_o) { + _o.name = this.name(); + _o.calls = this.bb.createObjList(this.calls.bind(this), this.callsLength()); + _o.attributes = this.bb.createObjList(this.attributes.bind(this), this.attributesLength()); + _o.documentation = this.bb.createScalarList(this.documentation.bind(this), this.documentationLength()); + _o.declarationFile = this.declarationFile(); + } +}; +var ServiceT = class { + constructor(name = null, calls = [], attributes = [], documentation = [], declarationFile = null) { + this.name = name; + this.calls = calls; + this.attributes = attributes; + this.documentation = documentation; + this.declarationFile = declarationFile; + } + pack(builder) { + const name = this.name !== null ? builder.createString(this.name) : 0; + const calls = Service.createCallsVector(builder, builder.createObjectOffsetList(this.calls)); + const attributes = Service.createAttributesVector(builder, builder.createObjectOffsetList(this.attributes)); + const documentation = Service.createDocumentationVector(builder, builder.createObjectOffsetList(this.documentation)); + const declarationFile = this.declarationFile !== null ? builder.createString(this.declarationFile) : 0; + return Service.createService(builder, name, calls, attributes, documentation, declarationFile); + } +}; + +// reflection/schema.js +var Schema = class _Schema { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsSchema(bb, obj) { + return (obj || new _Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsSchema(bb, obj) { + bb.setPosition(bb.position() + flatbuffers10.SIZE_PREFIX_LENGTH); + return (obj || new _Schema()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier("BFBS"); + } + objects(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + objectsLength() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + enums(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? (obj || new Enum()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + enumsLength() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + fileIdent(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + fileExt(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + rootTable(obj) { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? (obj || new Object_()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + services(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? (obj || new Service()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + servicesLength() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + advancedFeatures() { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? this.bb.readUint64(this.bb_pos + offset) : BigInt("0"); + } + mutate_advanced_features(value) { + const offset = this.bb.__offset(this.bb_pos, 16); + if (offset === 0) { + return false; + } + this.bb.writeUint64(this.bb_pos + offset, value); + return true; + } + /** + * All the files used in this compilation. Files are relative to where + * flatc was invoked. + */ + fbsFiles(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? (obj || new SchemaFile()).__init(this.bb.__indirect(this.bb.__vector(this.bb_pos + offset) + index * 4), this.bb) : null; + } + fbsFilesLength() { + const offset = this.bb.__offset(this.bb_pos, 18); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "reflection.Schema"; + } + static startSchema(builder) { + builder.startObject(8); + } + static addObjects(builder, objectsOffset) { + builder.addFieldOffset(0, objectsOffset, 0); + } + static createObjectsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startObjectsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addEnums(builder, enumsOffset) { + builder.addFieldOffset(1, enumsOffset, 0); + } + static createEnumsVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startEnumsVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addFileIdent(builder, fileIdentOffset) { + builder.addFieldOffset(2, fileIdentOffset, 0); + } + static addFileExt(builder, fileExtOffset) { + builder.addFieldOffset(3, fileExtOffset, 0); + } + static addRootTable(builder, rootTableOffset) { + builder.addFieldOffset(4, rootTableOffset, 0); + } + static addServices(builder, servicesOffset) { + builder.addFieldOffset(5, servicesOffset, 0); + } + static createServicesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startServicesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addAdvancedFeatures(builder, advancedFeatures) { + builder.addFieldInt64(6, advancedFeatures, BigInt("0")); + } + static addFbsFiles(builder, fbsFilesOffset) { + builder.addFieldOffset(7, fbsFilesOffset, 0); + } + static createFbsFilesVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startFbsFilesVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endSchema(builder) { + const offset = builder.endObject(); + builder.requiredField(offset, 4); + builder.requiredField(offset, 6); + return offset; + } + static finishSchemaBuffer(builder, offset) { + builder.finish(offset, "BFBS"); + } + static finishSizePrefixedSchemaBuffer(builder, offset) { + builder.finish(offset, "BFBS", true); + } + unpack() { + return new SchemaT(this.bb.createObjList(this.objects.bind(this), this.objectsLength()), this.bb.createObjList(this.enums.bind(this), this.enumsLength()), this.fileIdent(), this.fileExt(), this.rootTable() !== null ? this.rootTable().unpack() : null, this.bb.createObjList(this.services.bind(this), this.servicesLength()), this.advancedFeatures(), this.bb.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength())); + } + unpackTo(_o) { + _o.objects = this.bb.createObjList(this.objects.bind(this), this.objectsLength()); + _o.enums = this.bb.createObjList(this.enums.bind(this), this.enumsLength()); + _o.fileIdent = this.fileIdent(); + _o.fileExt = this.fileExt(); + _o.rootTable = this.rootTable() !== null ? this.rootTable().unpack() : null; + _o.services = this.bb.createObjList(this.services.bind(this), this.servicesLength()); + _o.advancedFeatures = this.advancedFeatures(); + _o.fbsFiles = this.bb.createObjList(this.fbsFiles.bind(this), this.fbsFilesLength()); + } +}; +var SchemaT = class { + constructor(objects = [], enums = [], fileIdent = null, fileExt = null, rootTable = null, services = [], advancedFeatures = BigInt("0"), fbsFiles = []) { + this.objects = objects; + this.enums = enums; + this.fileIdent = fileIdent; + this.fileExt = fileExt; + this.rootTable = rootTable; + this.services = services; + this.advancedFeatures = advancedFeatures; + this.fbsFiles = fbsFiles; + } + pack(builder) { + const objects = Schema.createObjectsVector(builder, builder.createObjectOffsetList(this.objects)); + const enums = Schema.createEnumsVector(builder, builder.createObjectOffsetList(this.enums)); + const fileIdent = this.fileIdent !== null ? builder.createString(this.fileIdent) : 0; + const fileExt = this.fileExt !== null ? builder.createString(this.fileExt) : 0; + const rootTable = this.rootTable !== null ? this.rootTable.pack(builder) : 0; + const services = Schema.createServicesVector(builder, builder.createObjectOffsetList(this.services)); + const fbsFiles = Schema.createFbsFilesVector(builder, builder.createObjectOffsetList(this.fbsFiles)); + Schema.startSchema(builder); + Schema.addObjects(builder, objects); + Schema.addEnums(builder, enums); + Schema.addFileIdent(builder, fileIdent); + Schema.addFileExt(builder, fileExt); + Schema.addRootTable(builder, rootTable); + Schema.addServices(builder, services); + Schema.addAdvancedFeatures(builder, this.advancedFeatures); + Schema.addFbsFiles(builder, fbsFiles); + return Schema.endSchema(builder); + } +}; + +// typescript.js +var typescript_exports = {}; +__export(typescript_exports, { + Object_: () => Object_2, + class_: () => class_2 +}); + +// typescript/object.js +var flatbuffers11 = __toESM(require("flatbuffers"), 1); + +// foobar/class.js +var class_; +(function(class_3) { + class_3[class_3["arguments_"] = 0] = "arguments_"; +})(class_ || (class_ = {})); + +// typescript/class.js +var class_2; +(function(class_3) { + class_3[class_3["new_"] = 0] = "new_"; + class_3[class_3["instanceof_"] = 1] = "instanceof_"; +})(class_2 || (class_2 = {})); + +// typescript/object.js +var Object_2 = class _Object_ { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsObject(bb, obj) { + return (obj || new _Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsObject(bb, obj) { + bb.setPosition(bb.position() + flatbuffers11.SIZE_PREFIX_LENGTH); + return (obj || new _Object_()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + return_() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_return(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + if_() { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_if(value) { + const offset = this.bb.__offset(this.bb_pos, 6); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + switch_() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_switch(value) { + const offset = this.bb.__offset(this.bb_pos, 8); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + enum_() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.readInt32(this.bb_pos + offset) : class_2.new_; + } + mutate_enum(value) { + const offset = this.bb.__offset(this.bb_pos, 10); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + enum2() { + const offset = this.bb.__offset(this.bb_pos, 12); + return offset ? this.bb.readInt32(this.bb_pos + offset) : class_.arguments_; + } + mutate_enum2(value) { + const offset = this.bb.__offset(this.bb_pos, 12); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + enum3() { + const offset = this.bb.__offset(this.bb_pos, 14); + return offset ? this.bb.readInt32(this.bb_pos + offset) : Abc.a; + } + mutate_enum3(value) { + const offset = this.bb.__offset(this.bb_pos, 14); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + reflect(obj) { + const offset = this.bb.__offset(this.bb_pos, 16); + return offset ? (obj || new Schema()).__init(this.bb.__indirect(this.bb_pos + offset), this.bb) : null; + } + static getFullyQualifiedName() { + return "typescript.Object"; + } + static startObject(builder) { + builder.startObject(7); + } + static addReturn(builder, return_) { + builder.addFieldInt32(0, return_, 0); + } + static addIf(builder, if_) { + builder.addFieldInt32(1, if_, 0); + } + static addSwitch(builder, switch_) { + builder.addFieldInt32(2, switch_, 0); + } + static addEnum(builder, enum_) { + builder.addFieldInt32(3, enum_, class_2.new_); + } + static addEnum2(builder, enum2) { + builder.addFieldInt32(4, enum2, class_.arguments_); + } + static addEnum3(builder, enum3) { + builder.addFieldInt32(5, enum3, Abc.a); + } + static addReflect(builder, reflectOffset) { + builder.addFieldOffset(6, reflectOffset, 0); + } + static endObject(builder) { + const offset = builder.endObject(); + return offset; + } + unpack() { + return new Object_T2(this.return_(), this.if_(), this.switch_(), this.enum_(), this.enum2(), this.enum3(), this.reflect() !== null ? this.reflect().unpack() : null); + } + unpackTo(_o) { + _o.return_ = this.return_(); + _o.if_ = this.if_(); + _o.switch_ = this.switch_(); + _o.enum_ = this.enum_(); + _o.enum2 = this.enum2(); + _o.enum3 = this.enum3(); + _o.reflect = this.reflect() !== null ? this.reflect().unpack() : null; + } +}; +var Object_T2 = class { + constructor(return_ = 0, if_ = 0, switch_ = 0, enum_ = class_2.new_, enum2 = class_.arguments_, enum3 = Abc.a, reflect = null) { + this.return_ = return_; + this.if_ = if_; + this.switch_ = switch_; + this.enum_ = enum_; + this.enum2 = enum2; + this.enum3 = enum3; + this.reflect = reflect; + } + pack(builder) { + const reflect = this.reflect !== null ? this.reflect.pack(builder) : 0; + Object_2.startObject(builder); + Object_2.addReturn(builder, this.return_); + Object_2.addIf(builder, this.if_); + Object_2.addSwitch(builder, this.switch_); + Object_2.addEnum(builder, this.enum_); + Object_2.addEnum2(builder, this.enum2); + Object_2.addEnum3(builder, this.enum3); + Object_2.addReflect(builder, reflect); + return Object_2.endObject(builder); + } +}; diff --git a/third_party/flatbuffers/tests/ts/typescript_transitive_include.ts b/third_party/flatbuffers/tests/ts/typescript_transitive_include.ts new file mode 100644 index 00000000000..aabfb64fa2d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_transitive_include.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export * as foobar from './foobar.js'; diff --git a/third_party/flatbuffers/tests/ts/typescript_transitive_include_generated.cjs b/third_party/flatbuffers/tests/ts/typescript_transitive_include_generated.cjs new file mode 100644 index 00000000000..a54eecfb4bf --- /dev/null +++ b/third_party/flatbuffers/tests/ts/typescript_transitive_include_generated.cjs @@ -0,0 +1,31 @@ +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// foobar.ts +var foobar_exports = {}; +__export(foobar_exports, { + Abc: () => Abc +}); +module.exports = __toCommonJS(foobar_exports); + +// foobar/abc.js +var Abc; +(function(Abc2) { + Abc2[Abc2["a"] = 0] = "a"; +})(Abc = Abc || (Abc = {})); diff --git a/third_party/flatbuffers/tests/ts/unicode_test.mon b/third_party/flatbuffers/tests/ts/unicode_test.mon new file mode 100644 index 00000000000..14f5fb4d266 Binary files /dev/null and b/third_party/flatbuffers/tests/ts/unicode_test.mon differ diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type.d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type.d.ts new file mode 100644 index 00000000000..41a06b5a4b9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type.d.ts @@ -0,0 +1,5 @@ +export { A, AT } from './union-underlying-type/a.js'; +export { ABC } from './union-underlying-type/abc.js'; +export { B, BT } from './union-underlying-type/b.js'; +export { C, CT } from './union-underlying-type/c.js'; +export { D, DT } from './union-underlying-type/d.js'; diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type.js b/third_party/flatbuffers/tests/ts/union-underlying-type.js new file mode 100644 index 00000000000..5548134163a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type.js @@ -0,0 +1,7 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { A, AT } from './union-underlying-type/a.js'; +export { ABC } from './union-underlying-type/abc.js'; +export { B, BT } from './union-underlying-type/b.js'; +export { C, CT } from './union-underlying-type/c.js'; +export { D, DT } from './union-underlying-type/d.js'; diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type.ts b/third_party/flatbuffers/tests/ts/union-underlying-type.ts new file mode 100644 index 00000000000..df14f067f60 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type.ts @@ -0,0 +1,9 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { A, AT } from './union-underlying-type/a.js'; +export { ABC } from './union-underlying-type/abc.js'; +export { B, BT } from './union-underlying-type/b.js'; +export { C, CT } from './union-underlying-type/c.js'; +export { D, DT } from './union-underlying-type/d.js'; diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/a.d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/a.d.ts new file mode 100644 index 00000000000..79b07cc04d5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/a.d.ts @@ -0,0 +1,22 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class A implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): A; + static getRootAsA(bb: flatbuffers.ByteBuffer, obj?: A): A; + static getSizePrefixedRootAsA(bb: flatbuffers.ByteBuffer, obj?: A): A; + a(): number; + mutate_a(value: number): boolean; + static getFullyQualifiedName(): string; + static startA(builder: flatbuffers.Builder): void; + static addA(builder: flatbuffers.Builder, a: number): void; + static endA(builder: flatbuffers.Builder): flatbuffers.Offset; + static createA(builder: flatbuffers.Builder, a: number): flatbuffers.Offset; + unpack(): AT; + unpackTo(_o: AT): void; +} +export declare class AT implements flatbuffers.IGeneratedObject { + a: number; + constructor(a?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/a.js b/third_party/flatbuffers/tests/ts/union-underlying-type/a.js new file mode 100644 index 00000000000..72854573249 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/a.js @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class A { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsA(bb, obj) { + return (obj || new A()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsA(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new A()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + a() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_a(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'UnionUnderlyingType.A'; + } + static startA(builder) { + builder.startObject(1); + } + static addA(builder, a) { + builder.addFieldInt32(0, a, 0); + } + static endA(builder) { + const offset = builder.endObject(); + return offset; + } + static createA(builder, a) { + A.startA(builder); + A.addA(builder, a); + return A.endA(builder); + } + unpack() { + return new AT(this.a()); + } + unpackTo(_o) { + _o.a = this.a(); + } +} +export class AT { + constructor(a = 0) { + this.a = a; + } + pack(builder) { + return A.createA(builder, this.a); + } +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/a.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/a.ts new file mode 100644 index 00000000000..f0039a90cb6 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/a.ts @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class A implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):A { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsA(bb:flatbuffers.ByteBuffer, obj?:A):A { + return (obj || new A()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsA(bb:flatbuffers.ByteBuffer, obj?:A):A { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new A()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +a():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_a(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'UnionUnderlyingType.A'; +} + +static startA(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addA(builder:flatbuffers.Builder, a:number) { + builder.addFieldInt32(0, a, 0); +} + +static endA(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createA(builder:flatbuffers.Builder, a:number):flatbuffers.Offset { + A.startA(builder); + A.addA(builder, a); + return A.endA(builder); +} + +unpack(): AT { + return new AT( + this.a() + ); +} + + +unpackTo(_o: AT): void { + _o.a = this.a(); +} +} + +export class AT implements flatbuffers.IGeneratedObject { +constructor( + public a: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return A.createA(builder, + this.a + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/abc.d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/abc.d.ts new file mode 100644 index 00000000000..1ebd5fdb5d9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/abc.d.ts @@ -0,0 +1,11 @@ +import { A } from '../union-underlying-type/a.js'; +import { B } from '../union-underlying-type/b.js'; +import { C } from '../union-underlying-type/c.js'; +export declare enum ABC { + NONE = 0, + A = 555, + B = 666, + C = 777 +} +export declare function unionToAbc(type: ABC, accessor: (obj: A | B | C) => A | B | C | null): A | B | C | null; +export declare function unionListToAbc(type: ABC, accessor: (index: number, obj: A | B | C) => A | B | C | null, index: number): A | B | C | null; diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/abc.js b/third_party/flatbuffers/tests/ts/union-underlying-type/abc.js new file mode 100644 index 00000000000..a0434f1f936 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/abc.js @@ -0,0 +1,30 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import { A } from '../union-underlying-type/a.js'; +import { B } from '../union-underlying-type/b.js'; +import { C } from '../union-underlying-type/c.js'; +export var ABC; +(function (ABC) { + ABC[ABC["NONE"] = 0] = "NONE"; + ABC[ABC["A"] = 555] = "A"; + ABC[ABC["B"] = 666] = "B"; + ABC[ABC["C"] = 777] = "C"; +})(ABC || (ABC = {})); +export function unionToAbc(type, accessor) { + switch (ABC[type]) { + case 'NONE': return null; + case 'A': return accessor(new A()); + case 'B': return accessor(new B()); + case 'C': return accessor(new C()); + default: return null; + } +} +export function unionListToAbc(type, accessor, index) { + switch (ABC[type]) { + case 'NONE': return null; + case 'A': return accessor(index, new A()); + case 'B': return accessor(index, new B()); + case 'C': return accessor(index, new C()); + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/abc.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/abc.ts new file mode 100644 index 00000000000..0ef1a79b975 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/abc.ts @@ -0,0 +1,42 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import { A, AT } from '../union-underlying-type/a.js'; +import { B, BT } from '../union-underlying-type/b.js'; +import { C, CT } from '../union-underlying-type/c.js'; + + +export enum ABC { + NONE = 0, + A = 555, + B = 666, + C = 777 +} + +export function unionToAbc( + type: ABC, + accessor: (obj:A|B|C) => A|B|C|null +): A|B|C|null { + switch(ABC[type]) { + case 'NONE': return null; + case 'A': return accessor(new A())! as A; + case 'B': return accessor(new B())! as B; + case 'C': return accessor(new C())! as C; + default: return null; + } +} + +export function unionListToAbc( + type: ABC, + accessor: (index: number, obj:A|B|C) => A|B|C|null, + index: number +): A|B|C|null { + switch(ABC[type]) { + case 'NONE': return null; + case 'A': return accessor(index, new A())! as A; + case 'B': return accessor(index, new B())! as B; + case 'C': return accessor(index, new C())! as C; + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/b.d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/b.d.ts new file mode 100644 index 00000000000..ea8b84d0902 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/b.d.ts @@ -0,0 +1,22 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class B implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): B; + static getRootAsB(bb: flatbuffers.ByteBuffer, obj?: B): B; + static getSizePrefixedRootAsB(bb: flatbuffers.ByteBuffer, obj?: B): B; + b(): string | null; + b(optionalEncoding: flatbuffers.Encoding): string | Uint8Array | null; + static getFullyQualifiedName(): string; + static startB(builder: flatbuffers.Builder): void; + static addB(builder: flatbuffers.Builder, bOffset: flatbuffers.Offset): void; + static endB(builder: flatbuffers.Builder): flatbuffers.Offset; + static createB(builder: flatbuffers.Builder, bOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): BT; + unpackTo(_o: BT): void; +} +export declare class BT implements flatbuffers.IGeneratedObject { + b: string | Uint8Array | null; + constructor(b?: string | Uint8Array | null); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/b.js b/third_party/flatbuffers/tests/ts/union-underlying-type/b.js new file mode 100644 index 00000000000..85e67b224d2 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/b.js @@ -0,0 +1,58 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class B { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsB(bb, obj) { + return (obj || new B()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsB(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new B()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + b(optionalEncoding) { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.__string(this.bb_pos + offset, optionalEncoding) : null; + } + static getFullyQualifiedName() { + return 'UnionUnderlyingType.B'; + } + static startB(builder) { + builder.startObject(1); + } + static addB(builder, bOffset) { + builder.addFieldOffset(0, bOffset, 0); + } + static endB(builder) { + const offset = builder.endObject(); + return offset; + } + static createB(builder, bOffset) { + B.startB(builder); + B.addB(builder, bOffset); + return B.endB(builder); + } + unpack() { + return new BT(this.b()); + } + unpackTo(_o) { + _o.b = this.b(); + } +} +export class BT { + constructor(b = null) { + this.b = b; + } + pack(builder) { + const b = (this.b !== null ? builder.createString(this.b) : 0); + return B.createB(builder, b); + } +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/b.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/b.ts new file mode 100644 index 00000000000..3be0a545810 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/b.ts @@ -0,0 +1,82 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class B implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):B { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsB(bb:flatbuffers.ByteBuffer, obj?:B):B { + return (obj || new B()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsB(bb:flatbuffers.ByteBuffer, obj?:B):B { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new B()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +b():string|null +b(optionalEncoding:flatbuffers.Encoding):string|Uint8Array|null +b(optionalEncoding?:any):string|Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.__string(this.bb_pos + offset, optionalEncoding) : null; +} + +static getFullyQualifiedName():string { + return 'UnionUnderlyingType.B'; +} + +static startB(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addB(builder:flatbuffers.Builder, bOffset:flatbuffers.Offset) { + builder.addFieldOffset(0, bOffset, 0); +} + +static endB(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createB(builder:flatbuffers.Builder, bOffset:flatbuffers.Offset):flatbuffers.Offset { + B.startB(builder); + B.addB(builder, bOffset); + return B.endB(builder); +} + +unpack(): BT { + return new BT( + this.b() + ); +} + + +unpackTo(_o: BT): void { + _o.b = this.b(); +} +} + +export class BT implements flatbuffers.IGeneratedObject { +constructor( + public b: string|Uint8Array|null = null +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const b = (this.b !== null ? builder.createString(this.b!) : 0); + + return B.createB(builder, + b + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/c.d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/c.d.ts new file mode 100644 index 00000000000..08d990ffb55 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/c.d.ts @@ -0,0 +1,22 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class C implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): C; + static getRootAsC(bb: flatbuffers.ByteBuffer, obj?: C): C; + static getSizePrefixedRootAsC(bb: flatbuffers.ByteBuffer, obj?: C): C; + c(): boolean; + mutate_c(value: boolean): boolean; + static getFullyQualifiedName(): string; + static startC(builder: flatbuffers.Builder): void; + static addC(builder: flatbuffers.Builder, c: boolean): void; + static endC(builder: flatbuffers.Builder): flatbuffers.Offset; + static createC(builder: flatbuffers.Builder, c: boolean): flatbuffers.Offset; + unpack(): CT; + unpackTo(_o: CT): void; +} +export declare class CT implements flatbuffers.IGeneratedObject { + c: boolean; + constructor(c?: boolean); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/c.js b/third_party/flatbuffers/tests/ts/union-underlying-type/c.js new file mode 100644 index 00000000000..48c38b78fff --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/c.js @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class C { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsC(bb, obj) { + return (obj || new C()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsC(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new C()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + c() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? !!this.bb.readInt8(this.bb_pos + offset) : false; + } + mutate_c(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt8(this.bb_pos + offset, +value); + return true; + } + static getFullyQualifiedName() { + return 'UnionUnderlyingType.C'; + } + static startC(builder) { + builder.startObject(1); + } + static addC(builder, c) { + builder.addFieldInt8(0, +c, +false); + } + static endC(builder) { + const offset = builder.endObject(); + return offset; + } + static createC(builder, c) { + C.startC(builder); + C.addC(builder, c); + return C.endC(builder); + } + unpack() { + return new CT(this.c()); + } + unpackTo(_o) { + _o.c = this.c(); + } +} +export class CT { + constructor(c = false) { + this.c = c; + } + pack(builder) { + return C.createC(builder, this.c); + } +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/c.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/c.ts new file mode 100644 index 00000000000..782c0c503be --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/c.ts @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class C implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):C { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsC(bb:flatbuffers.ByteBuffer, obj?:C):C { + return (obj || new C()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsC(bb:flatbuffers.ByteBuffer, obj?:C):C { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new C()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +c():boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? !!this.bb!.readInt8(this.bb_pos + offset) : false; +} + +mutate_c(value:boolean):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt8(this.bb_pos + offset, +value); + return true; +} + +static getFullyQualifiedName():string { + return 'UnionUnderlyingType.C'; +} + +static startC(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addC(builder:flatbuffers.Builder, c:boolean) { + builder.addFieldInt8(0, +c, +false); +} + +static endC(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createC(builder:flatbuffers.Builder, c:boolean):flatbuffers.Offset { + C.startC(builder); + C.addC(builder, c); + return C.endC(builder); +} + +unpack(): CT { + return new CT( + this.c() + ); +} + + +unpackTo(_o: CT): void { + _o.c = this.c(); +} +} + +export class CT implements flatbuffers.IGeneratedObject { +constructor( + public c: boolean = false +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return C.createC(builder, + this.c + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/d.d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/d.d.ts new file mode 100644 index 00000000000..fcb5f65233a --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/d.d.ts @@ -0,0 +1,41 @@ +import * as flatbuffers from 'flatbuffers'; +import { AT } from '../union-underlying-type/a.js'; +import { ABC } from '../union-underlying-type/abc.js'; +import { BT } from '../union-underlying-type/b.js'; +import { CT } from '../union-underlying-type/c.js'; +export declare class D implements flatbuffers.IUnpackableObject
{ + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): D; + static getRootAsD(bb: flatbuffers.ByteBuffer, obj?: D): D; + static getSizePrefixedRootAsD(bb: flatbuffers.ByteBuffer, obj?: D): D; + testUnionType(): ABC; + testUnion(obj: any): any | null; + testVectorOfUnionType(index: number): ABC | null; + testVectorOfUnionTypeLength(): number; + testVectorOfUnionTypeArray(): Int32Array | null; + testVectorOfUnion(index: number, obj: any): any | null; + testVectorOfUnionLength(): number; + static getFullyQualifiedName(): string; + static startD(builder: flatbuffers.Builder): void; + static addTestUnionType(builder: flatbuffers.Builder, testUnionType: ABC): void; + static addTestUnion(builder: flatbuffers.Builder, testUnionOffset: flatbuffers.Offset): void; + static addTestVectorOfUnionType(builder: flatbuffers.Builder, testVectorOfUnionTypeOffset: flatbuffers.Offset): void; + static createTestVectorOfUnionTypeVector(builder: flatbuffers.Builder, data: ABC[]): flatbuffers.Offset; + static startTestVectorOfUnionTypeVector(builder: flatbuffers.Builder, numElems: number): void; + static addTestVectorOfUnion(builder: flatbuffers.Builder, testVectorOfUnionOffset: flatbuffers.Offset): void; + static createTestVectorOfUnionVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startTestVectorOfUnionVector(builder: flatbuffers.Builder, numElems: number): void; + static endD(builder: flatbuffers.Builder): flatbuffers.Offset; + static createD(builder: flatbuffers.Builder, testUnionType: ABC, testUnionOffset: flatbuffers.Offset, testVectorOfUnionTypeOffset: flatbuffers.Offset, testVectorOfUnionOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): DT; + unpackTo(_o: DT): void; +} +export declare class DT implements flatbuffers.IGeneratedObject { + testUnionType: ABC; + testUnion: AT | BT | CT | null; + testVectorOfUnionType: (ABC)[]; + testVectorOfUnion: (AT | BT | CT)[]; + constructor(testUnionType?: ABC, testUnion?: AT | BT | CT | null, testVectorOfUnionType?: (ABC)[], testVectorOfUnion?: (AT | BT | CT)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/d.js b/third_party/flatbuffers/tests/ts/union-underlying-type/d.js new file mode 100644 index 00000000000..da66e15c056 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/d.js @@ -0,0 +1,163 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { ABC, unionToAbc, unionListToAbc } from '../union-underlying-type/abc.js'; +export class D { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsD(bb, obj) { + return (obj || new D()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsD(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new D()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + testUnionType() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : ABC.NONE; + } + testUnion(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__union(obj, this.bb_pos + offset) : null; + } + testVectorOfUnionType(index) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readInt32(this.bb.__vector(this.bb_pos + offset) + index * 4) : 0; + } + testVectorOfUnionTypeLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + testVectorOfUnionTypeArray() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? new Int32Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + testVectorOfUnion(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__union(obj, this.bb.__vector(this.bb_pos + offset) + index * 4) : null; + } + testVectorOfUnionLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return 'UnionUnderlyingType.D'; + } + static startD(builder) { + builder.startObject(4); + } + static addTestUnionType(builder, testUnionType) { + builder.addFieldInt32(0, testUnionType, ABC.NONE); + } + static addTestUnion(builder, testUnionOffset) { + builder.addFieldOffset(1, testUnionOffset, 0); + } + static addTestVectorOfUnionType(builder, testVectorOfUnionTypeOffset) { + builder.addFieldOffset(2, testVectorOfUnionTypeOffset, 0); + } + static createTestVectorOfUnionTypeVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt32(data[i]); + } + return builder.endVector(); + } + static startTestVectorOfUnionTypeVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static addTestVectorOfUnion(builder, testVectorOfUnionOffset) { + builder.addFieldOffset(3, testVectorOfUnionOffset, 0); + } + static createTestVectorOfUnionVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startTestVectorOfUnionVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endD(builder) { + const offset = builder.endObject(); + return offset; + } + static createD(builder, testUnionType, testUnionOffset, testVectorOfUnionTypeOffset, testVectorOfUnionOffset) { + D.startD(builder); + D.addTestUnionType(builder, testUnionType); + D.addTestUnion(builder, testUnionOffset); + D.addTestVectorOfUnionType(builder, testVectorOfUnionTypeOffset); + D.addTestVectorOfUnion(builder, testVectorOfUnionOffset); + return D.endD(builder); + } + unpack() { + return new DT(this.testUnionType(), (() => { + const temp = unionToAbc(this.testUnionType(), this.testUnion.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(), this.bb.createScalarList(this.testVectorOfUnionType.bind(this), this.testVectorOfUnionTypeLength()), (() => { + const ret = []; + for (let targetEnumIndex = 0; targetEnumIndex < this.testVectorOfUnionTypeLength(); ++targetEnumIndex) { + const targetEnum = this.testVectorOfUnionType(targetEnumIndex); + if (targetEnum === null || ABC[targetEnum] === 'NONE') { + continue; + } + const temp = unionListToAbc(targetEnum, this.testVectorOfUnion.bind(this), targetEnumIndex); + if (temp === null) { + continue; + } + ret.push(temp.unpack()); + } + return ret; + })()); + } + unpackTo(_o) { + _o.testUnionType = this.testUnionType(); + _o.testUnion = (() => { + const temp = unionToAbc(this.testUnionType(), this.testUnion.bind(this)); + if (temp === null) { + return null; + } + return temp.unpack(); + })(); + _o.testVectorOfUnionType = this.bb.createScalarList(this.testVectorOfUnionType.bind(this), this.testVectorOfUnionTypeLength()); + _o.testVectorOfUnion = (() => { + const ret = []; + for (let targetEnumIndex = 0; targetEnumIndex < this.testVectorOfUnionTypeLength(); ++targetEnumIndex) { + const targetEnum = this.testVectorOfUnionType(targetEnumIndex); + if (targetEnum === null || ABC[targetEnum] === 'NONE') { + continue; + } + const temp = unionListToAbc(targetEnum, this.testVectorOfUnion.bind(this), targetEnumIndex); + if (temp === null) { + continue; + } + ret.push(temp.unpack()); + } + return ret; + })(); + } +} +export class DT { + constructor(testUnionType = ABC.NONE, testUnion = null, testVectorOfUnionType = [], testVectorOfUnion = []) { + this.testUnionType = testUnionType; + this.testUnion = testUnion; + this.testVectorOfUnionType = testVectorOfUnionType; + this.testVectorOfUnion = testVectorOfUnion; + } + pack(builder) { + const testUnion = builder.createObjectOffset(this.testUnion); + const testVectorOfUnionType = D.createTestVectorOfUnionTypeVector(builder, this.testVectorOfUnionType); + const testVectorOfUnion = D.createTestVectorOfUnionVector(builder, builder.createObjectOffsetList(this.testVectorOfUnion)); + return D.createD(builder, this.testUnionType, testUnion, testVectorOfUnionType, testVectorOfUnion); + } +} diff --git a/third_party/flatbuffers/tests/ts/union-underlying-type/d.ts b/third_party/flatbuffers/tests/ts/union-underlying-type/d.ts new file mode 100644 index 00000000000..c90e167d130 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union-underlying-type/d.ts @@ -0,0 +1,197 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { A, AT } from '../union-underlying-type/a.js'; +import { ABC, unionToAbc, unionListToAbc } from '../union-underlying-type/abc.js'; +import { B, BT } from '../union-underlying-type/b.js'; +import { C, CT } from '../union-underlying-type/c.js'; + + +export class D implements flatbuffers.IUnpackableObject
(new DT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void D::UnPackTo(DT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = test_union_type(); _o->test_union.type = _e; } + { auto _e = test_union(); if (_e) _o->test_union.value = UnionUnderlyingType::ABCUnion::UnPack(_e, test_union_type(), _resolver); } + { auto _e = test_vector_of_union_type(); if (_e) { _o->test_vector_of_union.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test_vector_of_union[_i].type = static_cast(_e->Get(_i)); } } else { _o->test_vector_of_union.resize(0); } } + { auto _e = test_vector_of_union(); if (_e) { _o->test_vector_of_union.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->test_vector_of_union[_i].value = UnionUnderlyingType::ABCUnion::UnPack(_e->Get(_i), test_vector_of_union_type()->GetEnum(_i), _resolver); } } else { _o->test_vector_of_union.resize(0); } } +} + +inline ::flatbuffers::Offset D::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const DT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateD(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateD(::flatbuffers::FlatBufferBuilder &_fbb, const DT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const DT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _test_union_type = _o->test_union.type; + auto _test_union = _o->test_union.Pack(_fbb); + auto _test_vector_of_union_type = _o->test_vector_of_union.size() ? _fbb.CreateVector(_o->test_vector_of_union.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->test_vector_of_union[i].type; }, &_va) : 0; + auto _test_vector_of_union = _o->test_vector_of_union.size() ? _fbb.CreateVector<::flatbuffers::Offset>(_o->test_vector_of_union.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->test_vector_of_union[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va) : 0; + return UnionUnderlyingType::CreateD( + _fbb, + _test_union_type, + _test_union, + _test_vector_of_union_type, + _test_vector_of_union); +} + +inline bool VerifyABC(::flatbuffers::Verifier &verifier, const void *obj, ABC type) { + switch (type) { + case ABC::NONE: { + return true; + } + case ABC::A: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case ABC::B: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case ABC::C: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyABCVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyABC( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *ABCUnion::UnPack(const void *obj, ABC type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case ABC::A: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case ABC::B: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case ABC::C: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset ABCUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case ABC::A: { + auto ptr = reinterpret_cast(value); + return CreateA(_fbb, ptr, _rehasher).Union(); + } + case ABC::B: { + auto ptr = reinterpret_cast(value); + return CreateB(_fbb, ptr, _rehasher).Union(); + } + case ABC::C: { + auto ptr = reinterpret_cast(value); + return CreateC(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline ABCUnion::ABCUnion(const ABCUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case ABC::A: { + value = new UnionUnderlyingType::AT(*reinterpret_cast(u.value)); + break; + } + case ABC::B: { + value = new UnionUnderlyingType::BT(*reinterpret_cast(u.value)); + break; + } + case ABC::C: { + value = new UnionUnderlyingType::CT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void ABCUnion::Reset() { + switch (type) { + case ABC::A: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case ABC::B: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case ABC::C: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = ABC::NONE; +} + +inline const ::flatbuffers::TypeTable *ABCTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + UnionUnderlyingType::ATypeTable, + UnionUnderlyingType::BTypeTable, + UnionUnderlyingType::CTypeTable + }; + static const int64_t values[] = { 0, 555, 666, 777 }; + static const char * const names[] = { + "NONE", + "A", + "B", + "C" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 4, type_codes, type_refs, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *ATypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "a" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *BTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_STRING, 0, -1 } + }; + static const char * const names[] = { + "b" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *CTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_BOOL, 0, -1 } + }; + static const char * const names[] = { + "c" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *DTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UTYPE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_UTYPE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + UnionUnderlyingType::ABCTypeTable + }; + static const char * const names[] = { + "test_union_type", + "test_union", + "test_vector_of_union_type", + "test_vector_of_union" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +} // namespace UnionUnderlyingType + +#endif // FLATBUFFERS_GENERATED_UNIONUNDERLYINGTYPETEST_UNIONUNDERLYINGTYPE_H_ diff --git a/third_party/flatbuffers/tests/union_value_collision.fbs b/third_party/flatbuffers/tests/union_value_collision.fbs new file mode 100644 index 00000000000..58162044695 --- /dev/null +++ b/third_party/flatbuffers/tests/union_value_collision.fbs @@ -0,0 +1,22 @@ +namespace union_value_collsion; + +table IntValue { + value:int; +} +table Collide { + collide: string (key); + value: string; +} + +union Value { IntValue } + +union Other { IntValue } + +// This table tests collsions of Unions and fields named value. +table Collision { + some_value : Value; + value : Other; + collide : [Collision]; +} + +root_type Collision; \ No newline at end of file diff --git a/third_party/flatbuffers/tests/union_value_collsion/union_value_collision_generated.cs b/third_party/flatbuffers/tests/union_value_collsion/union_value_collision_generated.cs new file mode 100644 index 00000000000..f4686997f31 --- /dev/null +++ b/third_party/flatbuffers/tests/union_value_collsion/union_value_collision_generated.cs @@ -0,0 +1,531 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace union_value_collsion +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Value : byte +{ + NONE = 0, + IntValue = 1, +}; + +public class ValueUnion { + public Value Type { get; set; } + public object Value_ { get; set; } + + public ValueUnion() { + this.Type = Value.NONE; + this.Value_ = null; + } + + public T As() where T : class { return this.Value_ as T; } + public union_value_collsion.IntValueT AsIntValue() { return this.As(); } + public static ValueUnion FromIntValue(union_value_collsion.IntValueT _intvalue) { return new ValueUnion{ Type = Value.IntValue, Value_ = _intvalue }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, ValueUnion _o) { + switch (_o.Type) { + default: return 0; + case Value.IntValue: return union_value_collsion.IntValue.Pack(builder, _o.AsIntValue()).Value; + } + } +} + +public class ValueUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(ValueUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as ValueUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, ValueUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value_); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as ValueUnion, serializer); + } + } + public ValueUnion ReadJson(Newtonsoft.Json.JsonReader reader, ValueUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case Value.IntValue: _o.Value_ = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class ValueVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((Value)typeId) + { + case Value.IntValue: + result = union_value_collsion.IntValueVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Other : byte +{ + NONE = 0, + IntValue = 1, +}; + +public class OtherUnion { + public Other Type { get; set; } + public object Value { get; set; } + + public OtherUnion() { + this.Type = Other.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public union_value_collsion.IntValueT AsIntValue() { return this.As(); } + public static OtherUnion FromIntValue(union_value_collsion.IntValueT _intvalue) { return new OtherUnion{ Type = Other.IntValue, Value = _intvalue }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, OtherUnion _o) { + switch (_o.Type) { + default: return 0; + case Other.IntValue: return union_value_collsion.IntValue.Pack(builder, _o.AsIntValue()).Value; + } + } +} + +public class OtherUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(OtherUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as OtherUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, OtherUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as OtherUnion, serializer); + } + } + public OtherUnion ReadJson(Newtonsoft.Json.JsonReader reader, OtherUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case Other.IntValue: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class OtherVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((Other)typeId) + { + case Other.IntValue: + result = union_value_collsion.IntValueVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + +public struct IntValue : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static IntValue GetRootAsIntValue(ByteBuffer _bb) { return GetRootAsIntValue(_bb, new IntValue()); } + public static IntValue GetRootAsIntValue(ByteBuffer _bb, IntValue obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public IntValue __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int Value { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + + public static Offset CreateIntValue(FlatBufferBuilder builder, + int value = 0) { + builder.StartTable(1); + IntValue.AddValue(builder, value); + return IntValue.EndIntValue(builder); + } + + public static void StartIntValue(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddValue(FlatBufferBuilder builder, int value) { builder.AddInt(0, value, 0); } + public static Offset EndIntValue(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public IntValueT UnPack() { + var _o = new IntValueT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(IntValueT _o) { + _o.Value = this.Value; + } + public static Offset Pack(FlatBufferBuilder builder, IntValueT _o) { + if (_o == null) return default(Offset); + return CreateIntValue( + builder, + _o.Value); + } +} + +public class IntValueT +{ + [Newtonsoft.Json.JsonProperty("value")] + public int Value { get; set; } + + public IntValueT() { + this.Value = 0; + } +} + + +static public class IntValueVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Value*/, 4 /*int*/, 4, false) + && verifier.VerifyTableEnd(tablePos); + } +} +public struct Collide : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Collide GetRootAsCollide(ByteBuffer _bb) { return GetRootAsCollide(_bb, new Collide()); } + public static Collide GetRootAsCollide(ByteBuffer _bb, Collide obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Collide __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public string Collide_ { get { int o = __p.__offset(4); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } } +#if ENABLE_SPAN_T + public Span GetCollideBytes() { return __p.__vector_as_span(4, 1); } +#else + public ArraySegment? GetCollideBytes() { return __p.__vector_as_arraysegment(4); } +#endif + public byte[] GetCollideArray() { return __p.__vector_as_array(4); } + public string Value { get { int o = __p.__offset(6); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } } +#if ENABLE_SPAN_T + public Span GetValueBytes() { return __p.__vector_as_span(6, 1); } +#else + public ArraySegment? GetValueBytes() { return __p.__vector_as_arraysegment(6); } +#endif + public byte[] GetValueArray() { return __p.__vector_as_array(6); } + + public static Offset CreateCollide(FlatBufferBuilder builder, + StringOffset collideOffset = default(StringOffset), + StringOffset valueOffset = default(StringOffset)) { + builder.StartTable(2); + Collide.AddValue(builder, valueOffset); + Collide.AddCollide(builder, collideOffset); + return Collide.EndCollide(builder); + } + + public static void StartCollide(FlatBufferBuilder builder) { builder.StartTable(2); } + public static void AddCollide(FlatBufferBuilder builder, StringOffset collideOffset) { builder.AddOffset(0, collideOffset.Value, 0); } + public static void AddValue(FlatBufferBuilder builder, StringOffset valueOffset) { builder.AddOffset(1, valueOffset.Value, 0); } + public static Offset EndCollide(FlatBufferBuilder builder) { + int o = builder.EndTable(); + builder.Required(o, 4); // collide + return new Offset(o); + } + + public static VectorOffset CreateSortedVectorOfCollide(FlatBufferBuilder builder, Offset[] offsets) { + Array.Sort(offsets, + (Offset o1, Offset o2) => + new Collide().__assign(builder.DataBuffer.Length - o1.Value, builder.DataBuffer).Collide_.CompareTo(new Collide().__assign(builder.DataBuffer.Length - o2.Value, builder.DataBuffer).Collide_)); + return builder.CreateVectorOfTables(offsets); + } + + public static Collide? __lookup_by_key(int vectorLocation, string key, ByteBuffer bb) { + Collide obj_ = new Collide(); + int span = bb.GetInt(vectorLocation - 4); + int start = 0; + while (span != 0) { + int middle = span / 2; + int tableOffset = Table.__indirect(vectorLocation + 4 * (start + middle), bb); + obj_.__assign(tableOffset, bb); + int comp = obj_.Collide_.CompareTo(key); + if (comp > 0) { + span = middle; + } else if (comp < 0) { + middle++; + start += middle; + span -= middle; + } else { + return obj_; + } + } + return null; + } + public CollideT UnPack() { + var _o = new CollideT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(CollideT _o) { + _o.Collide_ = this.Collide_; + _o.Value = this.Value; + } + public static Offset Pack(FlatBufferBuilder builder, CollideT _o) { + if (_o == null) return default(Offset); + var _collide = _o.Collide_ == null ? default(StringOffset) : builder.CreateString(_o.Collide_); + var _value = _o.Value == null ? default(StringOffset) : builder.CreateString(_o.Value); + return CreateCollide( + builder, + _collide, + _value); + } +} + +public class CollideT +{ + [Newtonsoft.Json.JsonProperty("collide")] + public string Collide_ { get; set; } + [Newtonsoft.Json.JsonProperty("value")] + public string Value { get; set; } + + public CollideT() { + this.Collide_ = null; + this.Value = null; + } +} + + +static public class CollideVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyString(tablePos, 4 /*Collide*/, true) + && verifier.VerifyString(tablePos, 6 /*Value*/, false) + && verifier.VerifyTableEnd(tablePos); + } +} +public struct Collision : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Collision GetRootAsCollision(ByteBuffer _bb) { return GetRootAsCollision(_bb, new Collision()); } + public static Collision GetRootAsCollision(ByteBuffer _bb, Collision obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool VerifyCollision(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("", false, CollisionVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Collision __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public union_value_collsion.Value SomeValueType { get { int o = __p.__offset(4); return o != 0 ? (union_value_collsion.Value)__p.bb.Get(o + __p.bb_pos) : union_value_collsion.Value.NONE; } } + public TTable? SomeValue() where TTable : struct, IFlatbufferObject { int o = __p.__offset(6); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public union_value_collsion.IntValue SomeValueAsIntValue() { return SomeValue().Value; } + public union_value_collsion.Other ValueType { get { int o = __p.__offset(8); return o != 0 ? (union_value_collsion.Other)__p.bb.Get(o + __p.bb_pos) : union_value_collsion.Other.NONE; } } + public TTable? Value() where TTable : struct, IFlatbufferObject { int o = __p.__offset(10); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public union_value_collsion.IntValue ValueAsIntValue() { return Value().Value; } + public union_value_collsion.Collision? Collide(int j) { int o = __p.__offset(12); return o != 0 ? (union_value_collsion.Collision?)(new union_value_collsion.Collision()).__assign(__p.__indirect(__p.__vector(o) + j * 4), __p.bb) : null; } + public int CollideLength { get { int o = __p.__offset(12); return o != 0 ? __p.__vector_len(o) : 0; } } + + public static Offset CreateCollision(FlatBufferBuilder builder, + union_value_collsion.Value some_value_type = union_value_collsion.Value.NONE, + int some_valueOffset = 0, + union_value_collsion.Other value_type = union_value_collsion.Other.NONE, + int valueOffset = 0, + VectorOffset collideOffset = default(VectorOffset)) { + builder.StartTable(5); + Collision.AddCollide(builder, collideOffset); + Collision.AddValue(builder, valueOffset); + Collision.AddSomeValue(builder, some_valueOffset); + Collision.AddValueType(builder, value_type); + Collision.AddSomeValueType(builder, some_value_type); + return Collision.EndCollision(builder); + } + + public static void StartCollision(FlatBufferBuilder builder) { builder.StartTable(5); } + public static void AddSomeValueType(FlatBufferBuilder builder, union_value_collsion.Value someValueType) { builder.AddByte(0, (byte)someValueType, 0); } + public static void AddSomeValue(FlatBufferBuilder builder, int someValueOffset) { builder.AddOffset(1, someValueOffset, 0); } + public static void AddValueType(FlatBufferBuilder builder, union_value_collsion.Other valueType) { builder.AddByte(2, (byte)valueType, 0); } + public static void AddValue(FlatBufferBuilder builder, int valueOffset) { builder.AddOffset(3, valueOffset, 0); } + public static void AddCollide(FlatBufferBuilder builder, VectorOffset collideOffset) { builder.AddOffset(4, collideOffset.Value, 0); } + public static VectorOffset CreateCollideVector(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i].Value); return builder.EndVector(); } + public static VectorOffset CreateCollideVectorBlock(FlatBufferBuilder builder, Offset[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateCollideVectorBlock(FlatBufferBuilder builder, ArraySegment> data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateCollideVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add>(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartCollideVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static Offset EndCollision(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishCollisionBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value); } + public static void FinishSizePrefixedCollisionBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value); } + public CollisionT UnPack() { + var _o = new CollisionT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(CollisionT _o) { + _o.SomeValue = new union_value_collsion.ValueUnion(); + _o.SomeValue.Type = this.SomeValueType; + switch (this.SomeValueType) { + default: break; + case union_value_collsion.Value.IntValue: + _o.SomeValue.Value_ = this.SomeValue().HasValue ? this.SomeValue().Value.UnPack() : null; + break; + } + _o.Value = new union_value_collsion.OtherUnion(); + _o.Value.Type = this.ValueType; + switch (this.ValueType) { + default: break; + case union_value_collsion.Other.IntValue: + _o.Value.Value = this.Value().HasValue ? this.Value().Value.UnPack() : null; + break; + } + _o.Collide = new List(); + for (var _j = 0; _j < this.CollideLength; ++_j) {_o.Collide.Add(this.Collide(_j).HasValue ? this.Collide(_j).Value.UnPack() : null);} + } + public static Offset Pack(FlatBufferBuilder builder, CollisionT _o) { + if (_o == null) return default(Offset); + var _some_value_type = _o.SomeValue == null ? union_value_collsion.Value.NONE : _o.SomeValue.Type; + var _some_value = _o.SomeValue == null ? 0 : union_value_collsion.ValueUnion.Pack(builder, _o.SomeValue); + var _value_type = _o.Value == null ? union_value_collsion.Other.NONE : _o.Value.Type; + var _value = _o.Value == null ? 0 : union_value_collsion.OtherUnion.Pack(builder, _o.Value); + var _collide = default(VectorOffset); + if (_o.Collide != null) { + var __collide = new Offset[_o.Collide.Count]; + for (var _j = 0; _j < __collide.Length; ++_j) { __collide[_j] = union_value_collsion.Collision.Pack(builder, _o.Collide[_j]); } + _collide = CreateCollideVector(builder, __collide); + } + return CreateCollision( + builder, + _some_value_type, + _some_value, + _value_type, + _value, + _collide); + } +} + +public class CollisionT +{ + [Newtonsoft.Json.JsonProperty("some_value_type")] + private union_value_collsion.Value SomeValueType { + get { + return this.SomeValue != null ? this.SomeValue.Type : union_value_collsion.Value.NONE; + } + set { + this.SomeValue = new union_value_collsion.ValueUnion(); + this.SomeValue.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("some_value")] + [Newtonsoft.Json.JsonConverter(typeof(union_value_collsion.ValueUnion_JsonConverter))] + public union_value_collsion.ValueUnion SomeValue { get; set; } + [Newtonsoft.Json.JsonProperty("value_type")] + private union_value_collsion.Other ValueType { + get { + return this.Value != null ? this.Value.Type : union_value_collsion.Other.NONE; + } + set { + this.Value = new union_value_collsion.OtherUnion(); + this.Value.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("value")] + [Newtonsoft.Json.JsonConverter(typeof(union_value_collsion.OtherUnion_JsonConverter))] + public union_value_collsion.OtherUnion Value { get; set; } + [Newtonsoft.Json.JsonProperty("collide")] + public List Collide { get; set; } + + public CollisionT() { + this.SomeValue = null; + this.Value = null; + this.Collide = null; + } + + public static CollisionT DeserializeFromJson(string jsonText) { + return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText); + } + public string SerializeToJson() { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + public static CollisionT DeserializeFromBinary(byte[] fbBuffer) { + return Collision.GetRootAsCollision(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + Collision.FinishCollisionBuffer(fbb, Collision.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class CollisionVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*SomeValueType*/, 1 /*union_value_collsion.Value*/, 1, false) + && verifier.VerifyUnion(tablePos, 4, 6 /*SomeValue*/, union_value_collsion.ValueVerify.Verify, false) + && verifier.VerifyField(tablePos, 8 /*ValueType*/, 1 /*union_value_collsion.Other*/, 1, false) + && verifier.VerifyUnion(tablePos, 8, 10 /*Value*/, union_value_collsion.OtherVerify.Verify, false) + && verifier.VerifyVectorOfTables(tablePos, 12 /*Collide*/, union_value_collsion.CollisionVerify.Verify, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/union_vector/Attacker.cs b/third_party/flatbuffers/tests/union_vector/Attacker.cs new file mode 100644 index 00000000000..b2e3b851cb2 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Attacker.cs @@ -0,0 +1,70 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Attacker : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Attacker GetRootAsAttacker(ByteBuffer _bb) { return GetRootAsAttacker(_bb, new Attacker()); } + public static Attacker GetRootAsAttacker(ByteBuffer _bb, Attacker obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Attacker __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int SwordAttackDamage { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateSwordAttackDamage(int sword_attack_damage) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, sword_attack_damage); return true; } else { return false; } } + + public static Offset CreateAttacker(FlatBufferBuilder builder, + int sword_attack_damage = 0) { + builder.StartTable(1); + Attacker.AddSwordAttackDamage(builder, sword_attack_damage); + return Attacker.EndAttacker(builder); + } + + public static void StartAttacker(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddSwordAttackDamage(FlatBufferBuilder builder, int swordAttackDamage) { builder.AddInt(0, swordAttackDamage, 0); } + public static Offset EndAttacker(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public AttackerT UnPack() { + var _o = new AttackerT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(AttackerT _o) { + _o.SwordAttackDamage = this.SwordAttackDamage; + } + public static Offset Pack(FlatBufferBuilder builder, AttackerT _o) { + if (_o == null) return default(Offset); + return CreateAttacker( + builder, + _o.SwordAttackDamage); + } +} + +public class AttackerT +{ + [Newtonsoft.Json.JsonProperty("sword_attack_damage")] + public int SwordAttackDamage { get; set; } + + public AttackerT() { + this.SwordAttackDamage = 0; + } +} + + +static public class AttackerVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*SwordAttackDamage*/, 4 /*int*/, 4, false) + && verifier.VerifyTableEnd(tablePos); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Attacker.java b/third_party/flatbuffers/tests/union_vector/Attacker.java new file mode 100644 index 00000000000..38bc52189d3 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Attacker.java @@ -0,0 +1,67 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Attacker extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Attacker getRootAsAttacker(ByteBuffer _bb) { return getRootAsAttacker(_bb, new Attacker()); } + public static Attacker getRootAsAttacker(ByteBuffer _bb, Attacker obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Attacker __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int swordAttackDamage() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean mutateSwordAttackDamage(int sword_attack_damage) { int o = __offset(4); if (o != 0) { bb.putInt(o + bb_pos, sword_attack_damage); return true; } else { return false; } } + + public static int createAttacker(FlatBufferBuilder builder, + int swordAttackDamage) { + builder.startTable(1); + Attacker.addSwordAttackDamage(builder, swordAttackDamage); + return Attacker.endAttacker(builder); + } + + public static void startAttacker(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addSwordAttackDamage(FlatBufferBuilder builder, int swordAttackDamage) { builder.addInt(0, swordAttackDamage, 0); } + public static int endAttacker(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Attacker get(int j) { return get(new Attacker(), j); } + public Attacker get(Attacker obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public AttackerT unpack() { + AttackerT _o = new AttackerT(); + unpackTo(_o); + return _o; + } + public void unpackTo(AttackerT _o) { + int _oSwordAttackDamage = swordAttackDamage(); + _o.setSwordAttackDamage(_oSwordAttackDamage); + } + public static int pack(FlatBufferBuilder builder, AttackerT _o) { + if (_o == null) return 0; + return createAttacker( + builder, + _o.getSwordAttackDamage()); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Attacker.kt b/third_party/flatbuffers/tests/union_vector/Attacker.kt new file mode 100644 index 00000000000..b560841fd9f --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Attacker.kt @@ -0,0 +1,62 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Attacker : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Attacker { + __init(_i, _bb) + return this + } + val swordAttackDamage : Int + get() { + val o = __offset(4) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + fun mutateSwordAttackDamage(swordAttackDamage: Int) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.putInt(o + bb_pos, swordAttackDamage) + true + } else { + false + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsAttacker(_bb: ByteBuffer): Attacker = getRootAsAttacker(_bb, Attacker()) + fun getRootAsAttacker(_bb: ByteBuffer, obj: Attacker): Attacker { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createAttacker(builder: FlatBufferBuilder, swordAttackDamage: Int) : Int { + builder.startTable(1) + addSwordAttackDamage(builder, swordAttackDamage) + return endAttacker(builder) + } + fun startAttacker(builder: FlatBufferBuilder) = builder.startTable(1) + fun addSwordAttackDamage(builder: FlatBufferBuilder, swordAttackDamage: Int) = builder.addInt(0, swordAttackDamage, 0) + fun endAttacker(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Attacker.php b/third_party/flatbuffers/tests/union_vector/Attacker.php new file mode 100644 index 00000000000..e3ebfe6cf80 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Attacker.php @@ -0,0 +1,92 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function AttackerIdentifier() + { + return "MOVI"; + } + + public static function AttackerBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::AttackerIdentifier()); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Attacker + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function getSwordAttackDamage() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startAttacker(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return Attacker + */ + public static function createAttacker(FlatBufferBuilder $builder, $sword_attack_damage) + { + $builder->startObject(1); + self::addSwordAttackDamage($builder, $sword_attack_damage); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addSwordAttackDamage(FlatBufferBuilder $builder, $swordAttackDamage) + { + $builder->addIntX(0, $swordAttackDamage, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endAttacker(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/union_vector/AttackerT.java b/third_party/flatbuffers/tests/union_vector/AttackerT.java new file mode 100644 index 00000000000..39e9b675749 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/AttackerT.java @@ -0,0 +1,32 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class AttackerT { + private int swordAttackDamage; + + public int getSwordAttackDamage() { return swordAttackDamage; } + + public void setSwordAttackDamage(int swordAttackDamage) { this.swordAttackDamage = swordAttackDamage; } + + + public AttackerT() { + this.swordAttackDamage = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/BookReader.cs b/third_party/flatbuffers/tests/union_vector/BookReader.cs new file mode 100644 index 00000000000..74dd32f27ed --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/BookReader.cs @@ -0,0 +1,49 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct BookReader : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public BookReader __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int BooksRead { get { return __p.bb.GetInt(__p.bb_pos + 0); } } + public void MutateBooksRead(int books_read) { __p.bb.PutInt(__p.bb_pos + 0, books_read); } + + public static Offset CreateBookReader(FlatBufferBuilder builder, int BooksRead) { + builder.Prep(4, 4); + builder.PutInt(BooksRead); + return new Offset(builder.Offset); + } + public BookReaderT UnPack() { + var _o = new BookReaderT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(BookReaderT _o) { + _o.BooksRead = this.BooksRead; + } + public static Offset Pack(FlatBufferBuilder builder, BookReaderT _o) { + if (_o == null) return default(Offset); + return CreateBookReader( + builder, + _o.BooksRead); + } +} + +public class BookReaderT +{ + [Newtonsoft.Json.JsonProperty("books_read")] + public int BooksRead { get; set; } + + public BookReaderT() { + this.BooksRead = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/BookReader.java b/third_party/flatbuffers/tests/union_vector/BookReader.java new file mode 100644 index 00000000000..3ff0df5402c --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/BookReader.java @@ -0,0 +1,56 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class BookReader extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public BookReader __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int booksRead() { return bb.getInt(bb_pos + 0); } + public void mutateBooksRead(int books_read) { bb.putInt(bb_pos + 0, books_read); } + + public static int createBookReader(FlatBufferBuilder builder, int booksRead) { + builder.prep(4, 4); + builder.putInt(booksRead); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public BookReader get(int j) { return get(new BookReader(), j); } + public BookReader get(BookReader obj, int j) { return obj.__assign(__element(j), bb); } + } + public BookReaderT unpack() { + BookReaderT _o = new BookReaderT(); + unpackTo(_o); + return _o; + } + public void unpackTo(BookReaderT _o) { + int _oBooksRead = booksRead(); + _o.setBooksRead(_oBooksRead); + } + public static int pack(FlatBufferBuilder builder, BookReaderT _o) { + if (_o == null) return 0; + return createBookReader( + builder, + _o.getBooksRead()); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/BookReader.kt b/third_party/flatbuffers/tests/union_vector/BookReader.kt new file mode 100644 index 00000000000..87dff73286b --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/BookReader.kt @@ -0,0 +1,38 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class BookReader : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : BookReader { + __init(_i, _bb) + return this + } + val booksRead : Int get() = bb.getInt(bb_pos + 0) + fun mutateBooksRead(booksRead: Int) : ByteBuffer = bb.putInt(bb_pos + 0, booksRead) + companion object { + fun createBookReader(builder: FlatBufferBuilder, booksRead: Int) : Int { + builder.prep(4, 4) + builder.putInt(booksRead) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/union_vector/BookReader.php b/third_party/flatbuffers/tests/union_vector/BookReader.php new file mode 100644 index 00000000000..1f8f8d8b5a2 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/BookReader.php @@ -0,0 +1,41 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function GetBooksRead() + { + return $this->bb->getInt($this->bb_pos + 0); + } + + + /** + * @return int offset + */ + public static function createBookReader(FlatBufferBuilder $builder, $booksRead) + { + $builder->prep(4, 4); + $builder->putInt($booksRead); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/BookReaderT.java b/third_party/flatbuffers/tests/union_vector/BookReaderT.java new file mode 100644 index 00000000000..f07d7c558c7 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/BookReaderT.java @@ -0,0 +1,32 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class BookReaderT { + private int booksRead; + + public int getBooksRead() { return booksRead; } + + public void setBooksRead(int booksRead) { this.booksRead = booksRead; } + + + public BookReaderT() { + this.booksRead = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Character.cs b/third_party/flatbuffers/tests/union_vector/Character.cs new file mode 100644 index 00000000000..f2e7339863f --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Character.cs @@ -0,0 +1,132 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Character : byte +{ + NONE = 0, + MuLan = 1, + Rapunzel = 2, + Belle = 3, + BookFan = 4, + Other = 5, + Unused = 6, +}; + +public class CharacterUnion { + public Character Type { get; set; } + public object Value { get; set; } + + public CharacterUnion() { + this.Type = Character.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public AttackerT AsMuLan() { return this.As(); } + public static CharacterUnion FromMuLan(AttackerT _mulan) { return new CharacterUnion{ Type = Character.MuLan, Value = _mulan }; } + public RapunzelT AsRapunzel() { return this.As(); } + public static CharacterUnion FromRapunzel(RapunzelT _rapunzel) { return new CharacterUnion{ Type = Character.Rapunzel, Value = _rapunzel }; } + public BookReaderT AsBelle() { return this.As(); } + public static CharacterUnion FromBelle(BookReaderT _belle) { return new CharacterUnion{ Type = Character.Belle, Value = _belle }; } + public BookReaderT AsBookFan() { return this.As(); } + public static CharacterUnion FromBookFan(BookReaderT _bookfan) { return new CharacterUnion{ Type = Character.BookFan, Value = _bookfan }; } + public string AsOther() { return this.As(); } + public static CharacterUnion FromOther(string _other) { return new CharacterUnion{ Type = Character.Other, Value = _other }; } + public string AsUnused() { return this.As(); } + public static CharacterUnion FromUnused(string _unused) { return new CharacterUnion{ Type = Character.Unused, Value = _unused }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, CharacterUnion _o) { + switch (_o.Type) { + default: return 0; + case Character.MuLan: return Attacker.Pack(builder, _o.AsMuLan()).Value; + case Character.Rapunzel: return Rapunzel.Pack(builder, _o.AsRapunzel()).Value; + case Character.Belle: return BookReader.Pack(builder, _o.AsBelle()).Value; + case Character.BookFan: return BookReader.Pack(builder, _o.AsBookFan()).Value; + case Character.Other: return builder.CreateString(_o.AsOther()).Value; + case Character.Unused: return builder.CreateString(_o.AsUnused()).Value; + } + } +} + +public class CharacterUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(CharacterUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as CharacterUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, CharacterUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as CharacterUnion, serializer); + } + } + public CharacterUnion ReadJson(Newtonsoft.Json.JsonReader reader, CharacterUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case Character.MuLan: _o.Value = serializer.Deserialize(reader); break; + case Character.Rapunzel: _o.Value = serializer.Deserialize(reader); break; + case Character.Belle: _o.Value = serializer.Deserialize(reader); break; + case Character.BookFan: _o.Value = serializer.Deserialize(reader); break; + case Character.Other: _o.Value = serializer.Deserialize(reader); break; + case Character.Unused: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class CharacterVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((Character)typeId) + { + case Character.MuLan: + result = AttackerVerify.Verify(verifier, tablePos); + break; + case Character.Rapunzel: + result = verifier.VerifyUnionData(tablePos, 4, 4); + break; + case Character.Belle: + result = verifier.VerifyUnionData(tablePos, 4, 4); + break; + case Character.BookFan: + result = verifier.VerifyUnionData(tablePos, 4, 4); + break; + case Character.Other: + result = verifier.VerifyUnionString(tablePos); + break; + case Character.Unused: + result = verifier.VerifyUnionString(tablePos); + break; + default: result = true; + break; + } + return result; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Character.java b/third_party/flatbuffers/tests/union_vector/Character.java new file mode 100644 index 00000000000..615958bb32b --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Character.java @@ -0,0 +1,18 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +@SuppressWarnings("unused") +public final class Character { + private Character() { } + public static final byte NONE = 0; + public static final byte MuLan = 1; + public static final byte Rapunzel = 2; + public static final byte Belle = 3; + public static final byte BookFan = 4; + public static final byte Other = 5; + public static final byte Unused = 6; + + public static final String[] names = { "NONE", "MuLan", "Rapunzel", "Belle", "BookFan", "Other", "Unused", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Character.kt b/third_party/flatbuffers/tests/union_vector/Character.kt new file mode 100644 index 00000000000..2e80a35f1fc --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Character.kt @@ -0,0 +1,16 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +@Suppress("unused") +class Character_ private constructor() { + companion object { + const val NONE: UByte = 0u + const val MuLan: UByte = 1u + const val Rapunzel: UByte = 2u + const val Belle: UByte = 3u + const val BookFan: UByte = 4u + const val Other: UByte = 5u + const val Unused: UByte = 6u + val names : Array = arrayOf("NONE", "MuLan", "Rapunzel", "Belle", "BookFan", "Other", "Unused") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Character.php b/third_party/flatbuffers/tests/union_vector/Character.php new file mode 100644 index 00000000000..755958bc603 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Character.php @@ -0,0 +1,31 @@ +"NONE", + Character::MuLan=>"MuLan", + Character::Rapunzel=>"Rapunzel", + Character::Belle=>"Belle", + Character::BookFan=>"BookFan", + Character::Other=>"Other", + Character::Unused=>"Unused", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/union_vector/CharacterUnion.java b/third_party/flatbuffers/tests/union_vector/CharacterUnion.java new file mode 100644 index 00000000000..424218b665b --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/CharacterUnion.java @@ -0,0 +1,41 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.FlatBufferBuilder; + +public class CharacterUnion { + private byte type; + private Object value; + + public byte getType() { return type; } + + public void setType(byte type) { this.type = type; } + + public Object getValue() { return value; } + + public void setValue(Object value) { this.value = value; } + + public CharacterUnion() { + this.type = Character.NONE; + this.value = null; + } + + public AttackerT asMuLan() { return (AttackerT) value; } + public RapunzelT asRapunzel() { return (RapunzelT) value; } + public BookReaderT asBelle() { return (BookReaderT) value; } + public BookReaderT asBookFan() { return (BookReaderT) value; } + public String asOther() { return (String) value; } + public String asUnused() { return (String) value; } + + public static int pack(FlatBufferBuilder builder, CharacterUnion _o) { + switch (_o.type) { + case Character.MuLan: return Attacker.pack(builder, _o.asMuLan()); + case Character.Rapunzel: return Rapunzel.pack(builder, _o.asRapunzel()); + case Character.Belle: return BookReader.pack(builder, _o.asBelle()); + case Character.BookFan: return BookReader.pack(builder, _o.asBookFan()); + case Character.Other: return builder.createString(_o.asOther()); + case Character.Unused: return builder.createString(_o.asUnused()); + default: return 0; + } + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/FallingTub.cs b/third_party/flatbuffers/tests/union_vector/FallingTub.cs new file mode 100644 index 00000000000..792dbedcd1f --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/FallingTub.cs @@ -0,0 +1,49 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct FallingTub : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public FallingTub __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int Weight { get { return __p.bb.GetInt(__p.bb_pos + 0); } } + public void MutateWeight(int weight) { __p.bb.PutInt(__p.bb_pos + 0, weight); } + + public static Offset CreateFallingTub(FlatBufferBuilder builder, int Weight) { + builder.Prep(4, 4); + builder.PutInt(Weight); + return new Offset(builder.Offset); + } + public FallingTubT UnPack() { + var _o = new FallingTubT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(FallingTubT _o) { + _o.Weight = this.Weight; + } + public static Offset Pack(FlatBufferBuilder builder, FallingTubT _o) { + if (_o == null) return default(Offset); + return CreateFallingTub( + builder, + _o.Weight); + } +} + +public class FallingTubT +{ + [Newtonsoft.Json.JsonProperty("weight")] + public int Weight { get; set; } + + public FallingTubT() { + this.Weight = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/FallingTub.java b/third_party/flatbuffers/tests/union_vector/FallingTub.java new file mode 100644 index 00000000000..70eabbf0f2f --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/FallingTub.java @@ -0,0 +1,56 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class FallingTub extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public FallingTub __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int weight() { return bb.getInt(bb_pos + 0); } + public void mutateWeight(int weight) { bb.putInt(bb_pos + 0, weight); } + + public static int createFallingTub(FlatBufferBuilder builder, int weight) { + builder.prep(4, 4); + builder.putInt(weight); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public FallingTub get(int j) { return get(new FallingTub(), j); } + public FallingTub get(FallingTub obj, int j) { return obj.__assign(__element(j), bb); } + } + public FallingTubT unpack() { + FallingTubT _o = new FallingTubT(); + unpackTo(_o); + return _o; + } + public void unpackTo(FallingTubT _o) { + int _oWeight = weight(); + _o.setWeight(_oWeight); + } + public static int pack(FlatBufferBuilder builder, FallingTubT _o) { + if (_o == null) return 0; + return createFallingTub( + builder, + _o.getWeight()); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/FallingTub.kt b/third_party/flatbuffers/tests/union_vector/FallingTub.kt new file mode 100644 index 00000000000..43e477a393f --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/FallingTub.kt @@ -0,0 +1,38 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class FallingTub : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : FallingTub { + __init(_i, _bb) + return this + } + val weight : Int get() = bb.getInt(bb_pos + 0) + fun mutateWeight(weight: Int) : ByteBuffer = bb.putInt(bb_pos + 0, weight) + companion object { + fun createFallingTub(builder: FlatBufferBuilder, weight: Int) : Int { + builder.prep(4, 4) + builder.putInt(weight) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/union_vector/FallingTub.php b/third_party/flatbuffers/tests/union_vector/FallingTub.php new file mode 100644 index 00000000000..3a6800d47c0 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/FallingTub.php @@ -0,0 +1,41 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function GetWeight() + { + return $this->bb->getInt($this->bb_pos + 0); + } + + + /** + * @return int offset + */ + public static function createFallingTub(FlatBufferBuilder $builder, $weight) + { + $builder->prep(4, 4); + $builder->putInt($weight); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/FallingTubT.java b/third_party/flatbuffers/tests/union_vector/FallingTubT.java new file mode 100644 index 00000000000..0f373fd796f --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/FallingTubT.java @@ -0,0 +1,32 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class FallingTubT { + private int weight; + + public int getWeight() { return weight; } + + public void setWeight(int weight) { this.weight = weight; } + + + public FallingTubT() { + this.weight = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Gadget.cs b/third_party/flatbuffers/tests/union_vector/Gadget.cs new file mode 100644 index 00000000000..883596ebc3c --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Gadget.cs @@ -0,0 +1,100 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +[Newtonsoft.Json.JsonConverter(typeof(Newtonsoft.Json.Converters.StringEnumConverter))] +public enum Gadget : byte +{ + NONE = 0, + FallingTub = 1, + HandFan = 2, +}; + +public class GadgetUnion { + public Gadget Type { get; set; } + public object Value { get; set; } + + public GadgetUnion() { + this.Type = Gadget.NONE; + this.Value = null; + } + + public T As() where T : class { return this.Value as T; } + public FallingTubT AsFallingTub() { return this.As(); } + public static GadgetUnion FromFallingTub(FallingTubT _fallingtub) { return new GadgetUnion{ Type = Gadget.FallingTub, Value = _fallingtub }; } + public HandFanT AsHandFan() { return this.As(); } + public static GadgetUnion FromHandFan(HandFanT _handfan) { return new GadgetUnion{ Type = Gadget.HandFan, Value = _handfan }; } + + public static int Pack(Google.FlatBuffers.FlatBufferBuilder builder, GadgetUnion _o) { + switch (_o.Type) { + default: return 0; + case Gadget.FallingTub: return FallingTub.Pack(builder, _o.AsFallingTub()).Value; + case Gadget.HandFan: return HandFan.Pack(builder, _o.AsHandFan()).Value; + } + } +} + +public class GadgetUnion_JsonConverter : Newtonsoft.Json.JsonConverter { + public override bool CanConvert(System.Type objectType) { + return objectType == typeof(GadgetUnion) || objectType == typeof(System.Collections.Generic.List); + } + public override void WriteJson(Newtonsoft.Json.JsonWriter writer, object value, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = value as System.Collections.Generic.List; + if (_olist != null) { + writer.WriteStartArray(); + foreach (var _o in _olist) { this.WriteJson(writer, _o, serializer); } + writer.WriteEndArray(); + } else { + this.WriteJson(writer, value as GadgetUnion, serializer); + } + } + public void WriteJson(Newtonsoft.Json.JsonWriter writer, GadgetUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return; + serializer.Serialize(writer, _o.Value); + } + public override object ReadJson(Newtonsoft.Json.JsonReader reader, System.Type objectType, object existingValue, Newtonsoft.Json.JsonSerializer serializer) { + var _olist = existingValue as System.Collections.Generic.List; + if (_olist != null) { + for (var _j = 0; _j < _olist.Count; ++_j) { + reader.Read(); + _olist[_j] = this.ReadJson(reader, _olist[_j], serializer); + } + reader.Read(); + return _olist; + } else { + return this.ReadJson(reader, existingValue as GadgetUnion, serializer); + } + } + public GadgetUnion ReadJson(Newtonsoft.Json.JsonReader reader, GadgetUnion _o, Newtonsoft.Json.JsonSerializer serializer) { + if (_o == null) return null; + switch (_o.Type) { + default: break; + case Gadget.FallingTub: _o.Value = serializer.Deserialize(reader); break; + case Gadget.HandFan: _o.Value = serializer.Deserialize(reader); break; + } + return _o; + } +} + + + +static public class GadgetVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, byte typeId, uint tablePos) + { + bool result = true; + switch((Gadget)typeId) + { + case Gadget.FallingTub: + result = verifier.VerifyUnionData(tablePos, 4, 4); + break; + case Gadget.HandFan: + result = HandFanVerify.Verify(verifier, tablePos); + break; + default: result = true; + break; + } + return result; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Gadget.java b/third_party/flatbuffers/tests/union_vector/Gadget.java new file mode 100644 index 00000000000..effc315c633 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Gadget.java @@ -0,0 +1,14 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +@SuppressWarnings("unused") +public final class Gadget { + private Gadget() { } + public static final byte NONE = 0; + public static final byte FallingTub = 1; + public static final byte HandFan = 2; + + public static final String[] names = { "NONE", "FallingTub", "HandFan", }; + + public static String name(int e) { return names[e]; } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Gadget.kt b/third_party/flatbuffers/tests/union_vector/Gadget.kt new file mode 100644 index 00000000000..4fb3b10070c --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Gadget.kt @@ -0,0 +1,12 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +@Suppress("unused") +class Gadget private constructor() { + companion object { + const val NONE: UByte = 0u + const val FallingTub: UByte = 1u + const val HandFan: UByte = 2u + val names : Array = arrayOf("NONE", "FallingTub", "HandFan") + fun name(e: Int) : String = names[e] + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Gadget.php b/third_party/flatbuffers/tests/union_vector/Gadget.php new file mode 100644 index 00000000000..069f82de080 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Gadget.php @@ -0,0 +1,23 @@ +"NONE", + Gadget::FallingTub=>"FallingTub", + Gadget::HandFan=>"HandFan", + ); + + public static function Name($e) + { + if (!isset(self::$names[$e])) { + throw new \Exception(); + } + return self::$names[$e]; + } +} diff --git a/third_party/flatbuffers/tests/union_vector/GadgetUnion.java b/third_party/flatbuffers/tests/union_vector/GadgetUnion.java new file mode 100644 index 00000000000..2ac274535ae --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/GadgetUnion.java @@ -0,0 +1,33 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.FlatBufferBuilder; + +public class GadgetUnion { + private byte type; + private Object value; + + public byte getType() { return type; } + + public void setType(byte type) { this.type = type; } + + public Object getValue() { return value; } + + public void setValue(Object value) { this.value = value; } + + public GadgetUnion() { + this.type = Gadget.NONE; + this.value = null; + } + + public FallingTubT asFallingTub() { return (FallingTubT) value; } + public HandFanT asHandFan() { return (HandFanT) value; } + + public static int pack(FlatBufferBuilder builder, GadgetUnion _o) { + switch (_o.type) { + case Gadget.FallingTub: return FallingTub.pack(builder, _o.asFallingTub()); + case Gadget.HandFan: return HandFan.pack(builder, _o.asHandFan()); + default: return 0; + } + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/HandFan.cs b/third_party/flatbuffers/tests/union_vector/HandFan.cs new file mode 100644 index 00000000000..98958697329 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/HandFan.cs @@ -0,0 +1,70 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct HandFan : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static HandFan GetRootAsHandFan(ByteBuffer _bb) { return GetRootAsHandFan(_bb, new HandFan()); } + public static HandFan GetRootAsHandFan(ByteBuffer _bb, HandFan obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public HandFan __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int Length { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + public bool MutateLength(int length) { int o = __p.__offset(4); if (o != 0) { __p.bb.PutInt(o + __p.bb_pos, length); return true; } else { return false; } } + + public static Offset CreateHandFan(FlatBufferBuilder builder, + int length = 0) { + builder.StartTable(1); + HandFan.AddLength(builder, length); + return HandFan.EndHandFan(builder); + } + + public static void StartHandFan(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddLength(FlatBufferBuilder builder, int length) { builder.AddInt(0, length, 0); } + public static Offset EndHandFan(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public HandFanT UnPack() { + var _o = new HandFanT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(HandFanT _o) { + _o.Length = this.Length; + } + public static Offset Pack(FlatBufferBuilder builder, HandFanT _o) { + if (_o == null) return default(Offset); + return CreateHandFan( + builder, + _o.Length); + } +} + +public class HandFanT +{ + [Newtonsoft.Json.JsonProperty("length")] + public int Length { get; set; } + + public HandFanT() { + this.Length = 0; + } +} + + +static public class HandFanVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Length*/, 4 /*int*/, 4, false) + && verifier.VerifyTableEnd(tablePos); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/HandFan.java b/third_party/flatbuffers/tests/union_vector/HandFan.java new file mode 100644 index 00000000000..84094248862 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/HandFan.java @@ -0,0 +1,67 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class HandFan extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static HandFan getRootAsHandFan(ByteBuffer _bb) { return getRootAsHandFan(_bb, new HandFan()); } + public static HandFan getRootAsHandFan(ByteBuffer _bb, HandFan obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public HandFan __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int length() { int o = __offset(4); return o != 0 ? bb.getInt(o + bb_pos) : 0; } + public boolean mutateLength(int length) { int o = __offset(4); if (o != 0) { bb.putInt(o + bb_pos, length); return true; } else { return false; } } + + public static int createHandFan(FlatBufferBuilder builder, + int length) { + builder.startTable(1); + HandFan.addLength(builder, length); + return HandFan.endHandFan(builder); + } + + public static void startHandFan(FlatBufferBuilder builder) { builder.startTable(1); } + public static void addLength(FlatBufferBuilder builder, int length) { builder.addInt(0, length, 0); } + public static int endHandFan(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public HandFan get(int j) { return get(new HandFan(), j); } + public HandFan get(HandFan obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public HandFanT unpack() { + HandFanT _o = new HandFanT(); + unpackTo(_o); + return _o; + } + public void unpackTo(HandFanT _o) { + int _oLength = length(); + _o.setLength(_oLength); + } + public static int pack(FlatBufferBuilder builder, HandFanT _o) { + if (_o == null) return 0; + return createHandFan( + builder, + _o.getLength()); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/HandFan.kt b/third_party/flatbuffers/tests/union_vector/HandFan.kt new file mode 100644 index 00000000000..8eba8a50669 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/HandFan.kt @@ -0,0 +1,62 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class HandFan : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : HandFan { + __init(_i, _bb) + return this + } + val length : Int + get() { + val o = __offset(4) + return if(o != 0) bb.getInt(o + bb_pos) else 0 + } + fun mutateLength(length: Int) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.putInt(o + bb_pos, length) + true + } else { + false + } + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsHandFan(_bb: ByteBuffer): HandFan = getRootAsHandFan(_bb, HandFan()) + fun getRootAsHandFan(_bb: ByteBuffer, obj: HandFan): HandFan { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun createHandFan(builder: FlatBufferBuilder, length: Int) : Int { + builder.startTable(1) + addLength(builder, length) + return endHandFan(builder) + } + fun startHandFan(builder: FlatBufferBuilder) = builder.startTable(1) + fun addLength(builder: FlatBufferBuilder, length: Int) = builder.addInt(0, length, 0) + fun endHandFan(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + } +} diff --git a/third_party/flatbuffers/tests/union_vector/HandFan.php b/third_party/flatbuffers/tests/union_vector/HandFan.php new file mode 100644 index 00000000000..673e336bed1 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/HandFan.php @@ -0,0 +1,92 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function HandFanIdentifier() + { + return "MOVI"; + } + + public static function HandFanBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::HandFanIdentifier()); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return HandFan + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function getLength() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getInt($o + $this->bb_pos) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startHandFan(FlatBufferBuilder $builder) + { + $builder->StartObject(1); + } + + /** + * @param FlatBufferBuilder $builder + * @return HandFan + */ + public static function createHandFan(FlatBufferBuilder $builder, $length) + { + $builder->startObject(1); + self::addLength($builder, $length); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param int + * @return void + */ + public static function addLength(FlatBufferBuilder $builder, $length) + { + $builder->addIntX(0, $length, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endHandFan(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } +} diff --git a/third_party/flatbuffers/tests/union_vector/HandFanT.java b/third_party/flatbuffers/tests/union_vector/HandFanT.java new file mode 100644 index 00000000000..d1ad4cf44b0 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/HandFanT.java @@ -0,0 +1,32 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class HandFanT { + private int length; + + public int getLength() { return length; } + + public void setLength(int length) { this.length = length; } + + + public HandFanT() { + this.length = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Movie.cs b/third_party/flatbuffers/tests/union_vector/Movie.cs new file mode 100644 index 00000000000..18796839944 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Movie.cs @@ -0,0 +1,226 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Movie : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Movie GetRootAsMovie(ByteBuffer _bb) { return GetRootAsMovie(_bb, new Movie()); } + public static Movie GetRootAsMovie(ByteBuffer _bb, Movie obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool MovieBufferHasIdentifier(ByteBuffer _bb) { return Table.__has_identifier(_bb, "MOVI"); } + public static bool VerifyMovie(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("MOVI", false, MovieVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Movie __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public Character MainCharacterType { get { int o = __p.__offset(4); return o != 0 ? (Character)__p.bb.Get(o + __p.bb_pos) : Character.NONE; } } + public TTable? MainCharacter() where TTable : struct, IFlatbufferObject { int o = __p.__offset(6); return o != 0 ? (TTable?)__p.__union(o + __p.bb_pos) : null; } + public string MainCharacterAsString() { int o = __p.__offset(6); return o != 0 ? __p.__string(o + __p.bb_pos) : null; } + public Attacker MainCharacterAsMuLan() { return MainCharacter().Value; } + public Rapunzel MainCharacterAsRapunzel() { return MainCharacter().Value; } + public BookReader MainCharacterAsBelle() { return MainCharacter().Value; } + public BookReader MainCharacterAsBookFan() { return MainCharacter().Value; } + public string MainCharacterAsOther() { return MainCharacterAsString(); } + public string MainCharacterAsUnused() { return MainCharacterAsString(); } + public Character CharactersType(int j) { int o = __p.__offset(8); return o != 0 ? (Character)__p.bb.Get(__p.__vector(o) + j * 1) : (Character)0; } + public int CharactersTypeLength { get { int o = __p.__offset(8); return o != 0 ? __p.__vector_len(o) : 0; } } +#if ENABLE_SPAN_T + public Span GetCharactersTypeBytes() { return __p.__vector_as_span(8, 1); } +#else + public ArraySegment? GetCharactersTypeBytes() { return __p.__vector_as_arraysegment(8); } +#endif + public Character[] GetCharactersTypeArray() { int o = __p.__offset(8); if (o == 0) return null; int p = __p.__vector(o); int l = __p.__vector_len(o); Character[] a = new Character[l]; for (int i = 0; i < l; i++) { a[i] = (Character)__p.bb.Get(p + i * 1); } return a; } + public TTable? Characters(int j) where TTable : struct, IFlatbufferObject { int o = __p.__offset(10); return o != 0 ? (TTable?)__p.__union(__p.__vector(o) + j * 4) : null; } + public string CharactersAsString(int j) { int o = __p.__offset(10); return o != 0 ? __p.__string(__p.__vector(o) + j * 4) : null; } + public int CharactersLength { get { int o = __p.__offset(10); return o != 0 ? __p.__vector_len(o) : 0; } } + + public static Offset CreateMovie(FlatBufferBuilder builder, + Character main_character_type = Character.NONE, + int main_characterOffset = 0, + VectorOffset characters_typeOffset = default(VectorOffset), + VectorOffset charactersOffset = default(VectorOffset)) { + builder.StartTable(4); + Movie.AddCharacters(builder, charactersOffset); + Movie.AddCharactersType(builder, characters_typeOffset); + Movie.AddMainCharacter(builder, main_characterOffset); + Movie.AddMainCharacterType(builder, main_character_type); + return Movie.EndMovie(builder); + } + + public static void StartMovie(FlatBufferBuilder builder) { builder.StartTable(4); } + public static void AddMainCharacterType(FlatBufferBuilder builder, Character mainCharacterType) { builder.AddByte(0, (byte)mainCharacterType, 0); } + public static void AddMainCharacter(FlatBufferBuilder builder, int mainCharacterOffset) { builder.AddOffset(1, mainCharacterOffset, 0); } + public static void AddCharactersType(FlatBufferBuilder builder, VectorOffset charactersTypeOffset) { builder.AddOffset(2, charactersTypeOffset.Value, 0); } + public static VectorOffset CreateCharactersTypeVector(FlatBufferBuilder builder, Character[] data) { builder.StartVector(1, data.Length, 1); for (int i = data.Length - 1; i >= 0; i--) builder.AddByte((byte)data[i]); return builder.EndVector(); } + public static VectorOffset CreateCharactersTypeVectorBlock(FlatBufferBuilder builder, Character[] data) { builder.StartVector(1, data.Length, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateCharactersTypeVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(1, data.Count, 1); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateCharactersTypeVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartCharactersTypeVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(1, numElems, 1); } + public static void AddCharacters(FlatBufferBuilder builder, VectorOffset charactersOffset) { builder.AddOffset(3, charactersOffset.Value, 0); } + public static VectorOffset CreateCharactersVector(FlatBufferBuilder builder, int[] data) { builder.StartVector(4, data.Length, 4); for (int i = data.Length - 1; i >= 0; i--) builder.AddOffset(data[i]); return builder.EndVector(); } + public static VectorOffset CreateCharactersVectorBlock(FlatBufferBuilder builder, int[] data) { builder.StartVector(4, data.Length, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateCharactersVectorBlock(FlatBufferBuilder builder, ArraySegment data) { builder.StartVector(4, data.Count, 4); builder.Add(data); return builder.EndVector(); } + public static VectorOffset CreateCharactersVectorBlock(FlatBufferBuilder builder, IntPtr dataPtr, int sizeInBytes) { builder.StartVector(1, sizeInBytes, 1); builder.Add(dataPtr, sizeInBytes); return builder.EndVector(); } + public static void StartCharactersVector(FlatBufferBuilder builder, int numElems) { builder.StartVector(4, numElems, 4); } + public static Offset EndMovie(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishMovieBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value, "MOVI"); } + public static void FinishSizePrefixedMovieBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value, "MOVI"); } + public MovieT UnPack() { + var _o = new MovieT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(MovieT _o) { + _o.MainCharacter = new CharacterUnion(); + _o.MainCharacter.Type = this.MainCharacterType; + switch (this.MainCharacterType) { + default: break; + case Character.MuLan: + _o.MainCharacter.Value = this.MainCharacter().HasValue ? this.MainCharacter().Value.UnPack() : null; + break; + case Character.Rapunzel: + _o.MainCharacter.Value = this.MainCharacter().HasValue ? this.MainCharacter().Value.UnPack() : null; + break; + case Character.Belle: + _o.MainCharacter.Value = this.MainCharacter().HasValue ? this.MainCharacter().Value.UnPack() : null; + break; + case Character.BookFan: + _o.MainCharacter.Value = this.MainCharacter().HasValue ? this.MainCharacter().Value.UnPack() : null; + break; + case Character.Other: + _o.MainCharacter.Value = this.MainCharacterAsString(); + break; + case Character.Unused: + _o.MainCharacter.Value = this.MainCharacterAsString(); + break; + } + _o.Characters = new List(); + for (var _j = 0; _j < this.CharactersLength; ++_j) { + var _o_Characters = new CharacterUnion(); + _o_Characters.Type = this.CharactersType(_j); + switch (this.CharactersType(_j)) { + default: break; + case Character.MuLan: + _o_Characters.Value = this.Characters(_j).HasValue ? this.Characters(_j).Value.UnPack() : null; + break; + case Character.Rapunzel: + _o_Characters.Value = this.Characters(_j).HasValue ? this.Characters(_j).Value.UnPack() : null; + break; + case Character.Belle: + _o_Characters.Value = this.Characters(_j).HasValue ? this.Characters(_j).Value.UnPack() : null; + break; + case Character.BookFan: + _o_Characters.Value = this.Characters(_j).HasValue ? this.Characters(_j).Value.UnPack() : null; + break; + case Character.Other: + _o_Characters.Value = this.CharactersAsString(_j); + break; + case Character.Unused: + _o_Characters.Value = this.CharactersAsString(_j); + break; + } + _o.Characters.Add(_o_Characters); + } + } + public static Offset Pack(FlatBufferBuilder builder, MovieT _o) { + if (_o == null) return default(Offset); + var _main_character_type = _o.MainCharacter == null ? Character.NONE : _o.MainCharacter.Type; + var _main_character = _o.MainCharacter == null ? 0 : CharacterUnion.Pack(builder, _o.MainCharacter); + var _characters_type = default(VectorOffset); + if (_o.Characters != null) { + var __characters_type = new Character[_o.Characters.Count]; + for (var _j = 0; _j < __characters_type.Length; ++_j) { __characters_type[_j] = _o.Characters[_j].Type; } + _characters_type = CreateCharactersTypeVector(builder, __characters_type); + } + var _characters = default(VectorOffset); + if (_o.Characters != null) { + var __characters = new int[_o.Characters.Count]; + for (var _j = 0; _j < __characters.Length; ++_j) { __characters[_j] = CharacterUnion.Pack(builder, _o.Characters[_j]); } + _characters = CreateCharactersVector(builder, __characters); + } + return CreateMovie( + builder, + _main_character_type, + _main_character, + _characters_type, + _characters); + } +} + +public class MovieT +{ + [Newtonsoft.Json.JsonProperty("main_character_type")] + private Character MainCharacterType { + get { + return this.MainCharacter != null ? this.MainCharacter.Type : Character.NONE; + } + set { + this.MainCharacter = new CharacterUnion(); + this.MainCharacter.Type = value; + } + } + [Newtonsoft.Json.JsonProperty("main_character")] + [Newtonsoft.Json.JsonConverter(typeof(CharacterUnion_JsonConverter))] + public CharacterUnion MainCharacter { get; set; } + [Newtonsoft.Json.JsonProperty("characters_type")] + private Character[] CharactersType { + get { + if (this.Characters == null) return null; + var _o = new Character[this.Characters.Count]; + for (var _j = 0; _j < _o.Length; ++_j) { _o[_j] = this.Characters[_j].Type; } + return _o; + } + set { + this.Characters = new List(); + for (var _j = 0; _j < value.Length; ++_j) { + var _o = new CharacterUnion(); + _o.Type = value[_j]; + this.Characters.Add(_o); + } + } + } + [Newtonsoft.Json.JsonProperty("characters")] + [Newtonsoft.Json.JsonConverter(typeof(CharacterUnion_JsonConverter))] + public List Characters { get; set; } + + public MovieT() { + this.MainCharacter = null; + this.Characters = null; + } + + public static MovieT DeserializeFromJson(string jsonText) { + return Newtonsoft.Json.JsonConvert.DeserializeObject(jsonText); + } + public string SerializeToJson() { + return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); + } + public static MovieT DeserializeFromBinary(byte[] fbBuffer) { + return Movie.GetRootAsMovie(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + Movie.FinishMovieBuffer(fbb, Movie.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class MovieVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*MainCharacterType*/, 1 /*Character*/, 1, false) + && verifier.VerifyUnion(tablePos, 4, 6 /*MainCharacter*/, CharacterVerify.Verify, false) + && verifier.VerifyVectorOfData(tablePos, 8 /*CharactersType*/, 1 /*Character*/, false) + && verifier.VerifyTableEnd(tablePos); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Movie.java b/third_party/flatbuffers/tests/union_vector/Movie.java new file mode 100644 index 00000000000..66988939eff --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Movie.java @@ -0,0 +1,138 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Movie extends Table { + public static void ValidateVersion() { Constants.FLATBUFFERS_25_2_10(); } + public static Movie getRootAsMovie(ByteBuffer _bb) { return getRootAsMovie(_bb, new Movie()); } + public static Movie getRootAsMovie(ByteBuffer _bb, Movie obj) { _bb.order(ByteOrder.LITTLE_ENDIAN); return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)); } + public static boolean MovieBufferHasIdentifier(ByteBuffer _bb) { return __has_identifier(_bb, "MOVI"); } + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Movie __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public byte mainCharacterType() { int o = __offset(4); return o != 0 ? bb.get(o + bb_pos) : 0; } + public Table mainCharacter(Table obj) { int o = __offset(6); return o != 0 ? __union(obj, o + bb_pos) : null; } + public byte charactersType(int j) { int o = __offset(8); return o != 0 ? bb.get(__vector(o) + j * 1) : 0; } + public int charactersTypeLength() { int o = __offset(8); return o != 0 ? __vector_len(o) : 0; } + public ByteVector charactersTypeVector() { return charactersTypeVector(new ByteVector()); } + public ByteVector charactersTypeVector(ByteVector obj) { int o = __offset(8); return o != 0 ? obj.__assign(__vector(o), bb) : null; } + public ByteBuffer charactersTypeAsByteBuffer() { return __vector_as_bytebuffer(8, 1); } + public ByteBuffer charactersTypeInByteBuffer(ByteBuffer _bb) { return __vector_in_bytebuffer(_bb, 8, 1); } + public Table characters(Table obj, int j) { int o = __offset(10); return o != 0 ? __union(obj, __vector(o) + j * 4) : null; } + public int charactersLength() { int o = __offset(10); return o != 0 ? __vector_len(o) : 0; } + public UnionVector charactersVector() { return charactersVector(new UnionVector()); } + public UnionVector charactersVector(UnionVector obj) { int o = __offset(10); return o != 0 ? obj.__assign(__vector(o), 4, bb) : null; } + + public static int createMovie(FlatBufferBuilder builder, + byte mainCharacterType, + int mainCharacterOffset, + int charactersTypeOffset, + int charactersOffset) { + builder.startTable(4); + Movie.addCharacters(builder, charactersOffset); + Movie.addCharactersType(builder, charactersTypeOffset); + Movie.addMainCharacter(builder, mainCharacterOffset); + Movie.addMainCharacterType(builder, mainCharacterType); + return Movie.endMovie(builder); + } + + public static void startMovie(FlatBufferBuilder builder) { builder.startTable(4); } + public static void addMainCharacterType(FlatBufferBuilder builder, byte mainCharacterType) { builder.addByte(0, mainCharacterType, 0); } + public static void addMainCharacter(FlatBufferBuilder builder, int mainCharacterOffset) { builder.addOffset(1, mainCharacterOffset, 0); } + public static void addCharactersType(FlatBufferBuilder builder, int charactersTypeOffset) { builder.addOffset(2, charactersTypeOffset, 0); } + public static int createCharactersTypeVector(FlatBufferBuilder builder, byte[] data) { builder.startVector(1, data.length, 1); for (int i = data.length - 1; i >= 0; i--) builder.addByte(data[i]); return builder.endVector(); } + public static void startCharactersTypeVector(FlatBufferBuilder builder, int numElems) { builder.startVector(1, numElems, 1); } + public static void addCharacters(FlatBufferBuilder builder, int charactersOffset) { builder.addOffset(3, charactersOffset, 0); } + public static int createCharactersVector(FlatBufferBuilder builder, int[] data) { builder.startVector(4, data.length, 4); for (int i = data.length - 1; i >= 0; i--) builder.addOffset(data[i]); return builder.endVector(); } + public static void startCharactersVector(FlatBufferBuilder builder, int numElems) { builder.startVector(4, numElems, 4); } + public static int endMovie(FlatBufferBuilder builder) { + int o = builder.endTable(); + return o; + } + public static void finishMovieBuffer(FlatBufferBuilder builder, int offset) { builder.finish(offset, "MOVI"); } + public static void finishSizePrefixedMovieBuffer(FlatBufferBuilder builder, int offset) { builder.finishSizePrefixed(offset, "MOVI"); } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Movie get(int j) { return get(new Movie(), j); } + public Movie get(Movie obj, int j) { return obj.__assign(__indirect(__element(j), bb), bb); } + } + public MovieT unpack() { + MovieT _o = new MovieT(); + unpackTo(_o); + return _o; + } + public void unpackTo(MovieT _o) { + CharacterUnion _oMainCharacter = new CharacterUnion(); + byte _oMainCharacterType = mainCharacterType(); + _oMainCharacter.setType(_oMainCharacterType); + Table _oMainCharacterValue; + switch (_oMainCharacterType) { + case Character.MuLan: + _oMainCharacterValue = mainCharacter(new Attacker()); + _oMainCharacter.setValue(_oMainCharacterValue != null ? ((Attacker) _oMainCharacterValue).unpack() : null); + break; + default: break; + } + _o.setMainCharacter(_oMainCharacter); + CharacterUnion[] _oCharacters = new CharacterUnion[charactersLength()]; + for (int _j = 0; _j < charactersLength(); ++_j) { + CharacterUnion _oCharactersElement = new CharacterUnion(); + byte _oCharactersElementType = charactersType(_j); + _oCharactersElement.setType(_oCharactersElementType); + Table _oCharactersElementValue; + switch (_oCharactersElementType) { + case Character.MuLan: + _oCharactersElementValue = characters(new Attacker(), _j); + _oCharactersElement.setValue(_oCharactersElementValue != null ? ((Attacker) _oCharactersElementValue).unpack() : null); + break; + default: break; + } + _oCharacters[_j] = _oCharactersElement; + } + _o.setCharacters(_oCharacters); + } + public static int pack(FlatBufferBuilder builder, MovieT _o) { + if (_o == null) return 0; + byte _mainCharacterType = _o.getMainCharacter() == null ? Character.NONE : _o.getMainCharacter().getType(); + int _mainCharacter = _o.getMainCharacter() == null ? 0 : CharacterUnion.pack(builder, _o.getMainCharacter()); + int _charactersType = 0; + if (_o.getCharacters() != null) { + byte[] __charactersType = new byte[_o.getCharacters().length]; + int _j = 0; + for (CharacterUnion _e : _o.getCharacters()) { __charactersType[_j] = _o.getCharacters()[_j].getType(); _j++;} + _charactersType = createCharactersTypeVector(builder, __charactersType); + } + int _characters = 0; + if (_o.getCharacters() != null) { + int[] __characters = new int[_o.getCharacters().length]; + int _j = 0; + for (CharacterUnion _e : _o.getCharacters()) { __characters[_j] = CharacterUnion.pack(builder, _o.getCharacters()[_j]); _j++;} + _characters = createCharactersVector(builder, __characters); + } + return createMovie( + builder, + _mainCharacterType, + _mainCharacter, + _charactersType, + _characters); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Movie.kt b/third_party/flatbuffers/tests/union_vector/Movie.kt new file mode 100644 index 00000000000..c1eb8d4619a --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Movie.kt @@ -0,0 +1,126 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Movie : Table() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Movie { + __init(_i, _bb) + return this + } + val mainCharacterType : UByte + get() { + val o = __offset(4) + return if(o != 0) bb.get(o + bb_pos).toUByte() else 0u + } + fun mutateMainCharacterType(mainCharacterType: UByte) : Boolean { + val o = __offset(4) + return if (o != 0) { + bb.put(o + bb_pos, mainCharacterType.toByte()) + true + } else { + false + } + } + fun mainCharacter(obj: Table) : Table? { + val o = __offset(6); return if (o != 0) __union(obj, o + bb_pos) else null + } + fun charactersType(j: Int) : UByte { + val o = __offset(8) + return if (o != 0) { + bb.get(__vector(o) + j * 1).toUByte() + } else { + 0u + } + } + val charactersTypeLength : Int + get() { + val o = __offset(8); return if (o != 0) __vector_len(o) else 0 + } + val charactersTypeAsByteBuffer : ByteBuffer get() = __vector_as_bytebuffer(8, 1) + fun charactersTypeInByteBuffer(_bb: ByteBuffer) : ByteBuffer = __vector_in_bytebuffer(_bb, 8, 1) + fun mutateCharactersType(j: Int, charactersType: UByte) : Boolean { + val o = __offset(8) + return if (o != 0) { + bb.put(__vector(o) + j * 1, charactersType.toByte()) + true + } else { + false + } + } + fun characters(obj: Table, j: Int) : Table? { + val o = __offset(10) + return if (o != 0) { + __union(obj, __vector(o) + j * 4) + } else { + null + } + } + val charactersLength : Int + get() { + val o = __offset(10); return if (o != 0) __vector_len(o) else 0 + } + companion object { + fun validateVersion() = Constants.FLATBUFFERS_25_2_10() + fun getRootAsMovie(_bb: ByteBuffer): Movie = getRootAsMovie(_bb, Movie()) + fun getRootAsMovie(_bb: ByteBuffer, obj: Movie): Movie { + _bb.order(ByteOrder.LITTLE_ENDIAN) + return (obj.__assign(_bb.getInt(_bb.position()) + _bb.position(), _bb)) + } + fun MovieBufferHasIdentifier(_bb: ByteBuffer) : Boolean = __has_identifier(_bb, "MOVI") + fun createMovie(builder: FlatBufferBuilder, mainCharacterType: UByte, mainCharacterOffset: Int, charactersTypeOffset: Int, charactersOffset: Int) : Int { + builder.startTable(4) + addCharacters(builder, charactersOffset) + addCharactersType(builder, charactersTypeOffset) + addMainCharacter(builder, mainCharacterOffset) + addMainCharacterType(builder, mainCharacterType) + return endMovie(builder) + } + fun startMovie(builder: FlatBufferBuilder) = builder.startTable(4) + fun addMainCharacterType(builder: FlatBufferBuilder, mainCharacterType: UByte) = builder.addByte(0, mainCharacterType.toByte(), 0) + fun addMainCharacter(builder: FlatBufferBuilder, mainCharacter: Int) = builder.addOffset(1, mainCharacter, 0) + fun addCharactersType(builder: FlatBufferBuilder, charactersType: Int) = builder.addOffset(2, charactersType, 0) + @kotlin.ExperimentalUnsignedTypes + fun createCharactersTypeVector(builder: FlatBufferBuilder, data: UByteArray) : Int { + builder.startVector(1, data.size, 1) + for (i in data.size - 1 downTo 0) { + builder.addByte(data[i].toByte()) + } + return builder.endVector() + } + fun startCharactersTypeVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(1, numElems, 1) + fun addCharacters(builder: FlatBufferBuilder, characters: Int) = builder.addOffset(3, characters, 0) + fun createCharactersVector(builder: FlatBufferBuilder, data: IntArray) : Int { + builder.startVector(4, data.size, 4) + for (i in data.size - 1 downTo 0) { + builder.addOffset(data[i]) + } + return builder.endVector() + } + fun startCharactersVector(builder: FlatBufferBuilder, numElems: Int) = builder.startVector(4, numElems, 4) + fun endMovie(builder: FlatBufferBuilder) : Int { + val o = builder.endTable() + return o + } + fun finishMovieBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finish(offset, "MOVI") + fun finishSizePrefixedMovieBuffer(builder: FlatBufferBuilder, offset: Int) = builder.finishSizePrefixed(offset, "MOVI") + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Movie.php b/third_party/flatbuffers/tests/union_vector/Movie.php new file mode 100644 index 00000000000..216cd288b29 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Movie.php @@ -0,0 +1,220 @@ +init($bb->getInt($bb->getPosition()) + $bb->getPosition(), $bb)); + } + + public static function MovieIdentifier() + { + return "MOVI"; + } + + public static function MovieBufferHasIdentifier(ByteBuffer $buf) + { + return self::__has_identifier($buf, self::MovieIdentifier()); + } + + /** + * @param int $_i offset + * @param ByteBuffer $_bb + * @return Movie + **/ + public function init($_i, ByteBuffer $_bb) + { + $this->bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return byte + */ + public function getMainCharacterType() + { + $o = $this->__offset(4); + return $o != 0 ? $this->bb->getByte($o + $this->bb_pos) : \Character::NONE; + } + + /** + * @returnint + */ + public function getMainCharacter($obj) + { + $o = $this->__offset(6); + return $o != 0 ? $this->__union($obj, $o) : null; + } + + /** + * @param int offset + * @return byte + */ + public function getCharactersType($j) + { + $o = $this->__offset(8); + return $o != 0 ? $this->bb->getByte($this->__vector($o) + $j * 1) : \Character::NONE; + } + + /** + * @return int + */ + public function getCharactersTypeLength() + { + $o = $this->__offset(8); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param int offset + * @return Table + */ + public function getCharacters($j, $obj) + { + $o = $this->__offset(10); + return $o != 0 ? $this->__union($obj, $this->__vector($o) + $j * 4 - $this->bb_pos) : null; + } + + /** + * @return int + */ + public function getCharactersLength() + { + $o = $this->__offset(10); + return $o != 0 ? $this->__vector_len($o) : 0; + } + + /** + * @param FlatBufferBuilder $builder + * @return void + */ + public static function startMovie(FlatBufferBuilder $builder) + { + $builder->StartObject(4); + } + + /** + * @param FlatBufferBuilder $builder + * @return Movie + */ + public static function createMovie(FlatBufferBuilder $builder, $main_character_type, $main_character, $characters_type, $characters) + { + $builder->startObject(4); + self::addMainCharacterType($builder, $main_character_type); + self::addMainCharacter($builder, $main_character); + self::addCharactersType($builder, $characters_type); + self::addCharacters($builder, $characters); + $o = $builder->endObject(); + return $o; + } + + /** + * @param FlatBufferBuilder $builder + * @param byte + * @return void + */ + public static function addMainCharacterType(FlatBufferBuilder $builder, $mainCharacterType) + { + $builder->addByteX(0, $mainCharacterType, 0); + } + + public static function addMainCharacter(FlatBufferBuilder $builder, $offset) + { + $builder->addOffsetX(1, $offset, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addCharactersType(FlatBufferBuilder $builder, $charactersType) + { + $builder->addOffsetX(2, $charactersType, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createCharactersTypeVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(1, count($data), 1); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putByte($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startCharactersTypeVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(1, $numElems, 1); + } + + /** + * @param FlatBufferBuilder $builder + * @param VectorOffset + * @return void + */ + public static function addCharacters(FlatBufferBuilder $builder, $characters) + { + $builder->addOffsetX(3, $characters, 0); + } + + /** + * @param FlatBufferBuilder $builder + * @param array offset array + * @return int vector offset + */ + public static function createCharactersVector(FlatBufferBuilder $builder, array $data) + { + $builder->startVector(4, count($data), 4); + for ($i = count($data) - 1; $i >= 0; $i--) { + $builder->putOffset($data[$i]); + } + return $builder->endVector(); + } + + /** + * @param FlatBufferBuilder $builder + * @param int $numElems + * @return void + */ + public static function startCharactersVector(FlatBufferBuilder $builder, $numElems) + { + $builder->startVector(4, $numElems, 4); + } + + /** + * @param FlatBufferBuilder $builder + * @return int table offset + */ + public static function endMovie(FlatBufferBuilder $builder) + { + $o = $builder->endObject(); + return $o; + } + + public static function finishMovieBuffer(FlatBufferBuilder $builder, $offset) + { + $builder->finish($offset, "MOVI"); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/MovieT.java b/third_party/flatbuffers/tests/union_vector/MovieT.java new file mode 100644 index 00000000000..0a3bb59a317 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/MovieT.java @@ -0,0 +1,46 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class MovieT { + private CharacterUnion mainCharacter; + private CharacterUnion[] characters; + + public CharacterUnion getMainCharacter() { return mainCharacter; } + + public void setMainCharacter(CharacterUnion mainCharacter) { this.mainCharacter = mainCharacter; } + + public CharacterUnion[] getCharacters() { return characters; } + + public void setCharacters(CharacterUnion[] characters) { this.characters = characters; } + + + public MovieT() { + this.mainCharacter = null; + this.characters = null; + } + public static MovieT deserializeFromBinary(byte[] fbBuffer) { + return Movie.getRootAsMovie(ByteBuffer.wrap(fbBuffer)).unpack(); + } + public byte[] serializeToBinary() { + FlatBufferBuilder fbb = new FlatBufferBuilder(); + Movie.finishMovieBuffer(fbb, Movie.pack(fbb, this)); + return fbb.sizedByteArray(); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Rapunzel.cs b/third_party/flatbuffers/tests/union_vector/Rapunzel.cs new file mode 100644 index 00000000000..b9559d33200 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Rapunzel.cs @@ -0,0 +1,49 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Rapunzel : IFlatbufferObject +{ + private Struct __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public void __init(int _i, ByteBuffer _bb) { __p = new Struct(_i, _bb); } + public Rapunzel __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int HairLength { get { return __p.bb.GetInt(__p.bb_pos + 0); } } + public void MutateHairLength(int hair_length) { __p.bb.PutInt(__p.bb_pos + 0, hair_length); } + + public static Offset CreateRapunzel(FlatBufferBuilder builder, int HairLength) { + builder.Prep(4, 4); + builder.PutInt(HairLength); + return new Offset(builder.Offset); + } + public RapunzelT UnPack() { + var _o = new RapunzelT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(RapunzelT _o) { + _o.HairLength = this.HairLength; + } + public static Offset Pack(FlatBufferBuilder builder, RapunzelT _o) { + if (_o == null) return default(Offset); + return CreateRapunzel( + builder, + _o.HairLength); + } +} + +public class RapunzelT +{ + [Newtonsoft.Json.JsonProperty("hair_length")] + public int HairLength { get; set; } + + public RapunzelT() { + this.HairLength = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Rapunzel.java b/third_party/flatbuffers/tests/union_vector/Rapunzel.java new file mode 100644 index 00000000000..422b4bf2e08 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Rapunzel.java @@ -0,0 +1,56 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +@SuppressWarnings("unused") +public final class Rapunzel extends Struct { + public void __init(int _i, ByteBuffer _bb) { __reset(_i, _bb); } + public Rapunzel __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int hairLength() { return bb.getInt(bb_pos + 0); } + public void mutateHairLength(int hair_length) { bb.putInt(bb_pos + 0, hair_length); } + + public static int createRapunzel(FlatBufferBuilder builder, int hairLength) { + builder.prep(4, 4); + builder.putInt(hairLength); + return builder.offset(); + } + + public static final class Vector extends BaseVector { + public Vector __assign(int _vector, int _element_size, ByteBuffer _bb) { __reset(_vector, _element_size, _bb); return this; } + + public Rapunzel get(int j) { return get(new Rapunzel(), j); } + public Rapunzel get(Rapunzel obj, int j) { return obj.__assign(__element(j), bb); } + } + public RapunzelT unpack() { + RapunzelT _o = new RapunzelT(); + unpackTo(_o); + return _o; + } + public void unpackTo(RapunzelT _o) { + int _oHairLength = hairLength(); + _o.setHairLength(_oHairLength); + } + public static int pack(FlatBufferBuilder builder, RapunzelT _o) { + if (_o == null) return 0; + return createRapunzel( + builder, + _o.getHairLength()); + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/Rapunzel.kt b/third_party/flatbuffers/tests/union_vector/Rapunzel.kt new file mode 100644 index 00000000000..e3296e1933a --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Rapunzel.kt @@ -0,0 +1,38 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector +import com.google.flatbuffers.BooleanVector +import com.google.flatbuffers.ByteVector +import com.google.flatbuffers.Constants +import com.google.flatbuffers.DoubleVector +import com.google.flatbuffers.FlatBufferBuilder +import com.google.flatbuffers.FloatVector +import com.google.flatbuffers.LongVector +import com.google.flatbuffers.StringVector +import com.google.flatbuffers.Struct +import com.google.flatbuffers.Table +import com.google.flatbuffers.UnionVector +import java.nio.ByteBuffer +import java.nio.ByteOrder +import kotlin.math.sign + +@Suppress("unused") +class Rapunzel : Struct() { + + fun __init(_i: Int, _bb: ByteBuffer) { + __reset(_i, _bb) + } + fun __assign(_i: Int, _bb: ByteBuffer) : Rapunzel { + __init(_i, _bb) + return this + } + val hairLength : Int get() = bb.getInt(bb_pos + 0) + fun mutateHairLength(hairLength: Int) : ByteBuffer = bb.putInt(bb_pos + 0, hairLength) + companion object { + fun createRapunzel(builder: FlatBufferBuilder, hairLength: Int) : Int { + builder.prep(4, 4) + builder.putInt(hairLength) + return builder.offset() + } + } +} diff --git a/third_party/flatbuffers/tests/union_vector/Rapunzel.php b/third_party/flatbuffers/tests/union_vector/Rapunzel.php new file mode 100644 index 00000000000..9842d95be04 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/Rapunzel.php @@ -0,0 +1,41 @@ +bb_pos = $_i; + $this->bb = $_bb; + return $this; + } + + /** + * @return int + */ + public function GetHairLength() + { + return $this->bb->getInt($this->bb_pos + 0); + } + + + /** + * @return int offset + */ + public static function createRapunzel(FlatBufferBuilder $builder, $hairLength) + { + $builder->prep(4, 4); + $builder->putInt($hairLength); + return $builder->offset(); + } +} diff --git a/third_party/flatbuffers/tests/union_vector/RapunzelT.java b/third_party/flatbuffers/tests/union_vector/RapunzelT.java new file mode 100644 index 00000000000..5adbcc67eec --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/RapunzelT.java @@ -0,0 +1,32 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +import com.google.flatbuffers.BaseVector; +import com.google.flatbuffers.BooleanVector; +import com.google.flatbuffers.ByteVector; +import com.google.flatbuffers.Constants; +import com.google.flatbuffers.DoubleVector; +import com.google.flatbuffers.FlatBufferBuilder; +import com.google.flatbuffers.FloatVector; +import com.google.flatbuffers.IntVector; +import com.google.flatbuffers.LongVector; +import com.google.flatbuffers.ShortVector; +import com.google.flatbuffers.StringVector; +import com.google.flatbuffers.Struct; +import com.google.flatbuffers.Table; +import com.google.flatbuffers.UnionVector; +import java.nio.ByteBuffer; +import java.nio.ByteOrder; + +public class RapunzelT { + private int hairLength; + + public int getHairLength() { return hairLength; } + + public void setHairLength(int hairLength) { this.hairLength = hairLength; } + + + public RapunzelT() { + this.hairLength = 0; + } +} + diff --git a/third_party/flatbuffers/tests/union_vector/union_vector.fbs b/third_party/flatbuffers/tests/union_vector/union_vector.fbs new file mode 100644 index 00000000000..3dd38482115 --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/union_vector.fbs @@ -0,0 +1,44 @@ +// Demonstrates the ability to have vectors of unions, and also to +// store structs and strings in unions. + +table Attacker { + sword_attack_damage: int; +} + +struct Rapunzel { + hair_length: int; +} + +struct BookReader { + books_read: int; +} + +union Character { + MuLan: Attacker, // Can have name be different from type. + Rapunzel, // Or just both the same, as before. + Belle: BookReader, + BookFan: BookReader, + Other: string, + Unused: string +} + +struct FallingTub { + weight: int; +} + +table HandFan { + length: int; +} + +union Gadget { + FallingTub, + HandFan, +} + +table Movie { + main_character: Character; + characters: [Character]; +} + +root_type Movie; +file_identifier "MOVI"; diff --git a/third_party/flatbuffers/tests/union_vector/union_vector.json b/third_party/flatbuffers/tests/union_vector/union_vector.json new file mode 100644 index 00000000000..af0c9cb297e --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/union_vector.json @@ -0,0 +1,26 @@ +{ + "main_character_type": "Rapunzel", + "main_character": { + "hair_length": 6 + }, + "characters_type": [ + "Belle", + "MuLan", + "BookFan", + "Other", + "Unused" + ], + "characters": [ + { + "books_read": 7 + }, + { + "sword_attack_damage": 5 + }, + { + "books_read": 2 + }, + "Other", + "Unused" + ] +} diff --git a/third_party/flatbuffers/tests/union_vector/union_vector_generated.h b/third_party/flatbuffers/tests/union_vector/union_vector_generated.h new file mode 100644 index 00000000000..d8236e04c1b --- /dev/null +++ b/third_party/flatbuffers/tests/union_vector/union_vector_generated.h @@ -0,0 +1,1289 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_UNIONVECTOR_H_ +#define FLATBUFFERS_GENERATED_UNIONVECTOR_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +struct Attacker; +struct AttackerBuilder; +struct AttackerT; + +struct Rapunzel; + +struct BookReader; + +struct FallingTub; + +struct HandFan; +struct HandFanBuilder; +struct HandFanT; + +struct Movie; +struct MovieBuilder; +struct MovieT; + +bool operator==(const AttackerT &lhs, const AttackerT &rhs); +bool operator!=(const AttackerT &lhs, const AttackerT &rhs); +bool operator==(const Rapunzel &lhs, const Rapunzel &rhs); +bool operator!=(const Rapunzel &lhs, const Rapunzel &rhs); +bool operator==(const BookReader &lhs, const BookReader &rhs); +bool operator!=(const BookReader &lhs, const BookReader &rhs); +bool operator==(const FallingTub &lhs, const FallingTub &rhs); +bool operator!=(const FallingTub &lhs, const FallingTub &rhs); +bool operator==(const HandFanT &lhs, const HandFanT &rhs); +bool operator!=(const HandFanT &lhs, const HandFanT &rhs); +bool operator==(const MovieT &lhs, const MovieT &rhs); +bool operator!=(const MovieT &lhs, const MovieT &rhs); + +inline const ::flatbuffers::TypeTable *AttackerTypeTable(); + +inline const ::flatbuffers::TypeTable *RapunzelTypeTable(); + +inline const ::flatbuffers::TypeTable *BookReaderTypeTable(); + +inline const ::flatbuffers::TypeTable *FallingTubTypeTable(); + +inline const ::flatbuffers::TypeTable *HandFanTypeTable(); + +inline const ::flatbuffers::TypeTable *MovieTypeTable(); + +enum Character : uint8_t { + Character_NONE = 0, + Character_MuLan = 1, + Character_Rapunzel = 2, + Character_Belle = 3, + Character_BookFan = 4, + Character_Other = 5, + Character_Unused = 6, + Character_MIN = Character_NONE, + Character_MAX = Character_Unused +}; + +inline const Character (&EnumValuesCharacter())[7] { + static const Character values[] = { + Character_NONE, + Character_MuLan, + Character_Rapunzel, + Character_Belle, + Character_BookFan, + Character_Other, + Character_Unused + }; + return values; +} + +inline const char * const *EnumNamesCharacter() { + static const char * const names[8] = { + "NONE", + "MuLan", + "Rapunzel", + "Belle", + "BookFan", + "Other", + "Unused", + nullptr + }; + return names; +} + +inline const char *EnumNameCharacter(Character e) { + if (::flatbuffers::IsOutRange(e, Character_NONE, Character_Unused)) return ""; + const size_t index = static_cast(e); + return EnumNamesCharacter()[index]; +} + +struct CharacterUnion { + Character type; + void *value; + + CharacterUnion() : type(Character_NONE), value(nullptr) {} + CharacterUnion(CharacterUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Character_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + CharacterUnion(const CharacterUnion &); + CharacterUnion &operator=(const CharacterUnion &u) + { CharacterUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + CharacterUnion &operator=(CharacterUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~CharacterUnion() { Reset(); } + + void Reset(); + + static void *UnPack(const void *obj, Character type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + AttackerT *AsMuLan() { + return type == Character_MuLan ? + reinterpret_cast(value) : nullptr; + } + const AttackerT *AsMuLan() const { + return type == Character_MuLan ? + reinterpret_cast(value) : nullptr; + } + Rapunzel *AsRapunzel() { + return type == Character_Rapunzel ? + reinterpret_cast(value) : nullptr; + } + const Rapunzel *AsRapunzel() const { + return type == Character_Rapunzel ? + reinterpret_cast(value) : nullptr; + } + BookReader *AsBelle() { + return type == Character_Belle ? + reinterpret_cast(value) : nullptr; + } + const BookReader *AsBelle() const { + return type == Character_Belle ? + reinterpret_cast(value) : nullptr; + } + BookReader *AsBookFan() { + return type == Character_BookFan ? + reinterpret_cast(value) : nullptr; + } + const BookReader *AsBookFan() const { + return type == Character_BookFan ? + reinterpret_cast(value) : nullptr; + } + std::string *AsOther() { + return type == Character_Other ? + reinterpret_cast(value) : nullptr; + } + const std::string *AsOther() const { + return type == Character_Other ? + reinterpret_cast(value) : nullptr; + } + std::string *AsUnused() { + return type == Character_Unused ? + reinterpret_cast(value) : nullptr; + } + const std::string *AsUnused() const { + return type == Character_Unused ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const CharacterUnion &lhs, const CharacterUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case Character_NONE: { + return true; + } + case Character_MuLan: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Character_Rapunzel: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Character_Belle: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Character_BookFan: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Character_Other: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Character_Unused: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const CharacterUnion &lhs, const CharacterUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyCharacter(::flatbuffers::Verifier &verifier, const void *obj, Character type); +bool VerifyCharacterVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +enum Gadget : uint8_t { + Gadget_NONE = 0, + Gadget_FallingTub = 1, + Gadget_HandFan = 2, + Gadget_MIN = Gadget_NONE, + Gadget_MAX = Gadget_HandFan +}; + +inline const Gadget (&EnumValuesGadget())[3] { + static const Gadget values[] = { + Gadget_NONE, + Gadget_FallingTub, + Gadget_HandFan + }; + return values; +} + +inline const char * const *EnumNamesGadget() { + static const char * const names[4] = { + "NONE", + "FallingTub", + "HandFan", + nullptr + }; + return names; +} + +inline const char *EnumNameGadget(Gadget e) { + if (::flatbuffers::IsOutRange(e, Gadget_NONE, Gadget_HandFan)) return ""; + const size_t index = static_cast(e); + return EnumNamesGadget()[index]; +} + +template struct GadgetTraits { + static const Gadget enum_value = Gadget_NONE; +}; + +template<> struct GadgetTraits { + static const Gadget enum_value = Gadget_FallingTub; +}; + +template<> struct GadgetTraits { + static const Gadget enum_value = Gadget_HandFan; +}; + +template struct GadgetUnionTraits { + static const Gadget enum_value = Gadget_NONE; +}; + +template<> struct GadgetUnionTraits { + static const Gadget enum_value = Gadget_FallingTub; +}; + +template<> struct GadgetUnionTraits { + static const Gadget enum_value = Gadget_HandFan; +}; + +struct GadgetUnion { + Gadget type; + void *value; + + GadgetUnion() : type(Gadget_NONE), value(nullptr) {} + GadgetUnion(GadgetUnion&& u) FLATBUFFERS_NOEXCEPT : + type(Gadget_NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + GadgetUnion(const GadgetUnion &); + GadgetUnion &operator=(const GadgetUnion &u) + { GadgetUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + GadgetUnion &operator=(GadgetUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~GadgetUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = GadgetUnionTraits::enum_value; + if (type != Gadget_NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, Gadget type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + FallingTub *AsFallingTub() { + return type == Gadget_FallingTub ? + reinterpret_cast(value) : nullptr; + } + const FallingTub *AsFallingTub() const { + return type == Gadget_FallingTub ? + reinterpret_cast(value) : nullptr; + } + HandFanT *AsHandFan() { + return type == Gadget_HandFan ? + reinterpret_cast(value) : nullptr; + } + const HandFanT *AsHandFan() const { + return type == Gadget_HandFan ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const GadgetUnion &lhs, const GadgetUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case Gadget_NONE: { + return true; + } + case Gadget_FallingTub: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case Gadget_HandFan: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const GadgetUnion &lhs, const GadgetUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyGadget(::flatbuffers::Verifier &verifier, const void *obj, Gadget type); +bool VerifyGadgetVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) Rapunzel FLATBUFFERS_FINAL_CLASS { + private: + int32_t hair_length_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return RapunzelTypeTable(); + } + Rapunzel() + : hair_length_(0) { + } + Rapunzel(int32_t _hair_length) + : hair_length_(::flatbuffers::EndianScalar(_hair_length)) { + } + int32_t hair_length() const { + return ::flatbuffers::EndianScalar(hair_length_); + } + void mutate_hair_length(int32_t _hair_length) { + ::flatbuffers::WriteScalar(&hair_length_, _hair_length); + } +}; +FLATBUFFERS_STRUCT_END(Rapunzel, 4); + +inline bool operator==(const Rapunzel &lhs, const Rapunzel &rhs) { + return + (lhs.hair_length() == rhs.hair_length()); +} + +inline bool operator!=(const Rapunzel &lhs, const Rapunzel &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) BookReader FLATBUFFERS_FINAL_CLASS { + private: + int32_t books_read_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return BookReaderTypeTable(); + } + BookReader() + : books_read_(0) { + } + BookReader(int32_t _books_read) + : books_read_(::flatbuffers::EndianScalar(_books_read)) { + } + int32_t books_read() const { + return ::flatbuffers::EndianScalar(books_read_); + } + void mutate_books_read(int32_t _books_read) { + ::flatbuffers::WriteScalar(&books_read_, _books_read); + } +}; +FLATBUFFERS_STRUCT_END(BookReader, 4); + +inline bool operator==(const BookReader &lhs, const BookReader &rhs) { + return + (lhs.books_read() == rhs.books_read()); +} + +inline bool operator!=(const BookReader &lhs, const BookReader &rhs) { + return !(lhs == rhs); +} + + +FLATBUFFERS_MANUALLY_ALIGNED_STRUCT(4) FallingTub FLATBUFFERS_FINAL_CLASS { + private: + int32_t weight_; + + public: + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return FallingTubTypeTable(); + } + FallingTub() + : weight_(0) { + } + FallingTub(int32_t _weight) + : weight_(::flatbuffers::EndianScalar(_weight)) { + } + int32_t weight() const { + return ::flatbuffers::EndianScalar(weight_); + } + void mutate_weight(int32_t _weight) { + ::flatbuffers::WriteScalar(&weight_, _weight); + } +}; +FLATBUFFERS_STRUCT_END(FallingTub, 4); + +inline bool operator==(const FallingTub &lhs, const FallingTub &rhs) { + return + (lhs.weight() == rhs.weight()); +} + +inline bool operator!=(const FallingTub &lhs, const FallingTub &rhs) { + return !(lhs == rhs); +} + + +struct AttackerT : public ::flatbuffers::NativeTable { + typedef Attacker TableType; + int32_t sword_attack_damage = 0; +}; + +struct Attacker FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef AttackerT NativeTableType; + typedef AttackerBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return AttackerTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_SWORD_ATTACK_DAMAGE = 4 + }; + int32_t sword_attack_damage() const { + return GetField(VT_SWORD_ATTACK_DAMAGE, 0); + } + bool mutate_sword_attack_damage(int32_t _sword_attack_damage = 0) { + return SetField(VT_SWORD_ATTACK_DAMAGE, _sword_attack_damage, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_SWORD_ATTACK_DAMAGE, 4) && + verifier.EndTable(); + } + AttackerT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(AttackerT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct AttackerBuilder { + typedef Attacker Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_sword_attack_damage(int32_t sword_attack_damage) { + fbb_.AddElement(Attacker::VT_SWORD_ATTACK_DAMAGE, sword_attack_damage, 0); + } + explicit AttackerBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateAttacker( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t sword_attack_damage = 0) { + AttackerBuilder builder_(_fbb); + builder_.add_sword_attack_damage(sword_attack_damage); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateAttacker(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct HandFanT : public ::flatbuffers::NativeTable { + typedef HandFan TableType; + int32_t length = 0; +}; + +struct HandFan FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef HandFanT NativeTableType; + typedef HandFanBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return HandFanTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_LENGTH = 4 + }; + int32_t length() const { + return GetField(VT_LENGTH, 0); + } + bool mutate_length(int32_t _length = 0) { + return SetField(VT_LENGTH, _length, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_LENGTH, 4) && + verifier.EndTable(); + } + HandFanT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(HandFanT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct HandFanBuilder { + typedef HandFan Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_length(int32_t length) { + fbb_.AddElement(HandFan::VT_LENGTH, length, 0); + } + explicit HandFanBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateHandFan( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t length = 0) { + HandFanBuilder builder_(_fbb); + builder_.add_length(length); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateHandFan(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct MovieT : public ::flatbuffers::NativeTable { + typedef Movie TableType; + CharacterUnion main_character{}; + std::vector characters{}; +}; + +struct Movie FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef MovieT NativeTableType; + typedef MovieBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return MovieTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_MAIN_CHARACTER_TYPE = 4, + VT_MAIN_CHARACTER = 6, + VT_CHARACTERS_TYPE = 8, + VT_CHARACTERS = 10 + }; + Character main_character_type() const { + return static_cast(GetField(VT_MAIN_CHARACTER_TYPE, 0)); + } + const void *main_character() const { + return GetPointer(VT_MAIN_CHARACTER); + } + const Attacker *main_character_as_MuLan() const { + return main_character_type() == Character_MuLan ? static_cast(main_character()) : nullptr; + } + const Rapunzel *main_character_as_Rapunzel() const { + return main_character_type() == Character_Rapunzel ? static_cast(main_character()) : nullptr; + } + const BookReader *main_character_as_Belle() const { + return main_character_type() == Character_Belle ? static_cast(main_character()) : nullptr; + } + const BookReader *main_character_as_BookFan() const { + return main_character_type() == Character_BookFan ? static_cast(main_character()) : nullptr; + } + const ::flatbuffers::String *main_character_as_Other() const { + return main_character_type() == Character_Other ? static_cast(main_character()) : nullptr; + } + const ::flatbuffers::String *main_character_as_Unused() const { + return main_character_type() == Character_Unused ? static_cast(main_character()) : nullptr; + } + void *mutable_main_character() { + return GetPointer(VT_MAIN_CHARACTER); + } + const ::flatbuffers::Vector *characters_type() const { + return GetPointer *>(VT_CHARACTERS_TYPE); + } + ::flatbuffers::Vector *mutable_characters_type() { + return GetPointer<::flatbuffers::Vector *>(VT_CHARACTERS_TYPE); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *characters() const { + return GetPointer> *>(VT_CHARACTERS); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_characters() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_CHARACTERS); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_MAIN_CHARACTER_TYPE, 1) && + VerifyOffset(verifier, VT_MAIN_CHARACTER) && + VerifyCharacter(verifier, main_character(), main_character_type()) && + VerifyOffset(verifier, VT_CHARACTERS_TYPE) && + verifier.VerifyVector(characters_type()) && + VerifyOffset(verifier, VT_CHARACTERS) && + verifier.VerifyVector(characters()) && + VerifyCharacterVector(verifier, characters(), characters_type()) && + verifier.EndTable(); + } + MovieT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(MovieT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct MovieBuilder { + typedef Movie Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_main_character_type(Character main_character_type) { + fbb_.AddElement(Movie::VT_MAIN_CHARACTER_TYPE, static_cast(main_character_type), 0); + } + void add_main_character(::flatbuffers::Offset main_character) { + fbb_.AddOffset(Movie::VT_MAIN_CHARACTER, main_character); + } + void add_characters_type(::flatbuffers::Offset<::flatbuffers::Vector> characters_type) { + fbb_.AddOffset(Movie::VT_CHARACTERS_TYPE, characters_type); + } + void add_characters(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> characters) { + fbb_.AddOffset(Movie::VT_CHARACTERS, characters); + } + explicit MovieBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateMovie( + ::flatbuffers::FlatBufferBuilder &_fbb, + Character main_character_type = Character_NONE, + ::flatbuffers::Offset main_character = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> characters_type = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> characters = 0) { + MovieBuilder builder_(_fbb); + builder_.add_characters(characters); + builder_.add_characters_type(characters_type); + builder_.add_main_character(main_character); + builder_.add_main_character_type(main_character_type); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateMovieDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + Character main_character_type = Character_NONE, + ::flatbuffers::Offset main_character = 0, + const std::vector *characters_type = nullptr, + const std::vector<::flatbuffers::Offset> *characters = nullptr) { + auto characters_type__ = characters_type ? _fbb.CreateVector(*characters_type) : 0; + auto characters__ = characters ? _fbb.CreateVector<::flatbuffers::Offset>(*characters) : 0; + return CreateMovie( + _fbb, + main_character_type, + main_character, + characters_type__, + characters__); +} + +::flatbuffers::Offset CreateMovie(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const AttackerT &lhs, const AttackerT &rhs) { + return + (lhs.sword_attack_damage == rhs.sword_attack_damage); +} + +inline bool operator!=(const AttackerT &lhs, const AttackerT &rhs) { + return !(lhs == rhs); +} + + +inline AttackerT *Attacker::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new AttackerT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Attacker::UnPackTo(AttackerT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = sword_attack_damage(); _o->sword_attack_damage = _e; } +} + +inline ::flatbuffers::Offset Attacker::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateAttacker(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateAttacker(::flatbuffers::FlatBufferBuilder &_fbb, const AttackerT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const AttackerT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _sword_attack_damage = _o->sword_attack_damage; + return CreateAttacker( + _fbb, + _sword_attack_damage); +} + + +inline bool operator==(const HandFanT &lhs, const HandFanT &rhs) { + return + (lhs.length == rhs.length); +} + +inline bool operator!=(const HandFanT &lhs, const HandFanT &rhs) { + return !(lhs == rhs); +} + + +inline HandFanT *HandFan::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new HandFanT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void HandFan::UnPackTo(HandFanT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = length(); _o->length = _e; } +} + +inline ::flatbuffers::Offset HandFan::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateHandFan(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateHandFan(::flatbuffers::FlatBufferBuilder &_fbb, const HandFanT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const HandFanT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _length = _o->length; + return CreateHandFan( + _fbb, + _length); +} + + +inline bool operator==(const MovieT &lhs, const MovieT &rhs) { + return + (lhs.main_character == rhs.main_character) && + (lhs.characters == rhs.characters); +} + +inline bool operator!=(const MovieT &lhs, const MovieT &rhs) { + return !(lhs == rhs); +} + + +inline MovieT *Movie::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new MovieT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void Movie::UnPackTo(MovieT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = main_character_type(); _o->main_character.type = _e; } + { auto _e = main_character(); if (_e) _o->main_character.value = CharacterUnion::UnPack(_e, main_character_type(), _resolver); } + { auto _e = characters_type(); if (_e) { _o->characters.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->characters[_i].type = static_cast(_e->Get(_i)); } } else { _o->characters.resize(0); } } + { auto _e = characters(); if (_e) { _o->characters.resize(_e->size()); for (::flatbuffers::uoffset_t _i = 0; _i < _e->size(); _i++) { _o->characters[_i].value = CharacterUnion::UnPack(_e->Get(_i), characters_type()->GetEnum(_i), _resolver); } } else { _o->characters.resize(0); } } +} + +inline ::flatbuffers::Offset Movie::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateMovie(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateMovie(::flatbuffers::FlatBufferBuilder &_fbb, const MovieT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const MovieT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _main_character_type = _o->main_character.type; + auto _main_character = _o->main_character.Pack(_fbb); + auto _characters_type = _o->characters.size() ? _fbb.CreateVector(_o->characters.size(), [](size_t i, _VectorArgs *__va) { return static_cast(__va->__o->characters[i].type); }, &_va) : 0; + auto _characters = _o->characters.size() ? _fbb.CreateVector<::flatbuffers::Offset>(_o->characters.size(), [](size_t i, _VectorArgs *__va) { return __va->__o->characters[i].Pack(*__va->__fbb, __va->__rehasher); }, &_va) : 0; + return CreateMovie( + _fbb, + _main_character_type, + _main_character, + _characters_type, + _characters); +} + +inline bool VerifyCharacter(::flatbuffers::Verifier &verifier, const void *obj, Character type) { + switch (type) { + case Character_NONE: { + return true; + } + case Character_MuLan: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + case Character_Rapunzel: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Character_Belle: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Character_BookFan: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Character_Other: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyString(ptr); + } + case Character_Unused: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyString(ptr); + } + default: return true; + } +} + +inline bool VerifyCharacterVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyCharacter( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *CharacterUnion::UnPack(const void *obj, Character type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Character_MuLan: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + case Character_Rapunzel: { + auto ptr = reinterpret_cast(obj); + return new Rapunzel(*ptr); + } + case Character_Belle: { + auto ptr = reinterpret_cast(obj); + return new BookReader(*ptr); + } + case Character_BookFan: { + auto ptr = reinterpret_cast(obj); + return new BookReader(*ptr); + } + case Character_Other: { + auto ptr = reinterpret_cast(obj); + return new std::string(ptr->c_str(), ptr->size()); + } + case Character_Unused: { + auto ptr = reinterpret_cast(obj); + return new std::string(ptr->c_str(), ptr->size()); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset CharacterUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Character_MuLan: { + auto ptr = reinterpret_cast(value); + return CreateAttacker(_fbb, ptr, _rehasher).Union(); + } + case Character_Rapunzel: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Character_Belle: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Character_BookFan: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Character_Other: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateString(*ptr).Union(); + } + case Character_Unused: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateString(*ptr).Union(); + } + default: return 0; + } +} + +inline CharacterUnion::CharacterUnion(const CharacterUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Character_MuLan: { + value = new AttackerT(*reinterpret_cast(u.value)); + break; + } + case Character_Rapunzel: { + value = new Rapunzel(*reinterpret_cast(u.value)); + break; + } + case Character_Belle: { + value = new BookReader(*reinterpret_cast(u.value)); + break; + } + case Character_BookFan: { + value = new BookReader(*reinterpret_cast(u.value)); + break; + } + case Character_Other: { + value = new std::string(*reinterpret_cast(u.value)); + break; + } + case Character_Unused: { + value = new std::string(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void CharacterUnion::Reset() { + switch (type) { + case Character_MuLan: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character_Rapunzel: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character_Belle: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character_BookFan: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character_Other: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Character_Unused: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Character_NONE; +} + +inline bool VerifyGadget(::flatbuffers::Verifier &verifier, const void *obj, Gadget type) { + switch (type) { + case Gadget_NONE: { + return true; + } + case Gadget_FallingTub: { + return verifier.VerifyField(static_cast(obj), 0, 4); + } + case Gadget_HandFan: { + auto ptr = reinterpret_cast(obj); + return verifier.VerifyTable(ptr); + } + default: return true; + } +} + +inline bool VerifyGadgetVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types) { + if (!values || !types) return !values && !types; + if (values->size() != types->size()) return false; + for (::flatbuffers::uoffset_t i = 0; i < values->size(); ++i) { + if (!VerifyGadget( + verifier, values->Get(i), types->GetEnum(i))) { + return false; + } + } + return true; +} + +inline void *GadgetUnion::UnPack(const void *obj, Gadget type, const ::flatbuffers::resolver_function_t *resolver) { + (void)resolver; + switch (type) { + case Gadget_FallingTub: { + auto ptr = reinterpret_cast(obj); + return new FallingTub(*ptr); + } + case Gadget_HandFan: { + auto ptr = reinterpret_cast(obj); + return ptr->UnPack(resolver); + } + default: return nullptr; + } +} + +inline ::flatbuffers::Offset GadgetUnion::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher) const { + (void)_rehasher; + switch (type) { + case Gadget_FallingTub: { + auto ptr = reinterpret_cast(value); + return _fbb.CreateStruct(*ptr).Union(); + } + case Gadget_HandFan: { + auto ptr = reinterpret_cast(value); + return CreateHandFan(_fbb, ptr, _rehasher).Union(); + } + default: return 0; + } +} + +inline GadgetUnion::GadgetUnion(const GadgetUnion &u) : type(u.type), value(nullptr) { + switch (type) { + case Gadget_FallingTub: { + value = new FallingTub(*reinterpret_cast(u.value)); + break; + } + case Gadget_HandFan: { + value = new HandFanT(*reinterpret_cast(u.value)); + break; + } + default: + break; + } +} + +inline void GadgetUnion::Reset() { + switch (type) { + case Gadget_FallingTub: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + case Gadget_HandFan: { + auto ptr = reinterpret_cast(value); + delete ptr; + break; + } + default: break; + } + value = nullptr; + type = Gadget_NONE; +} + +inline const ::flatbuffers::TypeTable *CharacterTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_SEQUENCE, 0, 2 }, + { ::flatbuffers::ET_STRING, 0, -1 }, + { ::flatbuffers::ET_STRING, 0, -1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + AttackerTypeTable, + RapunzelTypeTable, + BookReaderTypeTable + }; + static const char * const names[] = { + "NONE", + "MuLan", + "Rapunzel", + "Belle", + "BookFan", + "Other", + "Unused" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 7, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *GadgetTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_SEQUENCE, 0, -1 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 1 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + FallingTubTypeTable, + HandFanTypeTable + }; + static const char * const names[] = { + "NONE", + "FallingTub", + "HandFan" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_UNION, 3, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *AttackerTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "sword_attack_damage" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *RapunzelTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4 }; + static const char * const names[] = { + "hair_length" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *BookReaderTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4 }; + static const char * const names[] = { + "books_read" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *FallingTubTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const int64_t values[] = { 0, 4 }; + static const char * const names[] = { + "weight" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_STRUCT, 1, type_codes, nullptr, nullptr, values, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *HandFanTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_INT, 0, -1 } + }; + static const char * const names[] = { + "length" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 1, type_codes, nullptr, nullptr, nullptr, names + }; + return &tt; +} + +inline const ::flatbuffers::TypeTable *MovieTypeTable() { + static const ::flatbuffers::TypeCode type_codes[] = { + { ::flatbuffers::ET_UTYPE, 0, 0 }, + { ::flatbuffers::ET_SEQUENCE, 0, 0 }, + { ::flatbuffers::ET_UTYPE, 1, 0 }, + { ::flatbuffers::ET_SEQUENCE, 1, 0 } + }; + static const ::flatbuffers::TypeFunction type_refs[] = { + CharacterTypeTable + }; + static const char * const names[] = { + "main_character_type", + "main_character", + "characters_type", + "characters" + }; + static const ::flatbuffers::TypeTable tt = { + ::flatbuffers::ST_TABLE, 4, type_codes, type_refs, nullptr, nullptr, names + }; + return &tt; +} + +inline const Movie *GetMovie(const void *buf) { + return ::flatbuffers::GetRoot(buf); +} + +inline const Movie *GetSizePrefixedMovie(const void *buf) { + return ::flatbuffers::GetSizePrefixedRoot(buf); +} + +inline Movie *GetMutableMovie(void *buf) { + return ::flatbuffers::GetMutableRoot(buf); +} + +inline Movie *GetMutableSizePrefixedMovie(void *buf) { + return ::flatbuffers::GetMutableSizePrefixedRoot(buf); +} + +inline const char *MovieIdentifier() { + return "MOVI"; +} + +inline bool MovieBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MovieIdentifier()); +} + +inline bool SizePrefixedMovieBufferHasIdentifier(const void *buf) { + return ::flatbuffers::BufferHasIdentifier( + buf, MovieIdentifier(), true); +} + +inline bool VerifyMovieBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifyBuffer(MovieIdentifier()); +} + +inline bool VerifySizePrefixedMovieBuffer( + ::flatbuffers::Verifier &verifier) { + return verifier.VerifySizePrefixedBuffer(MovieIdentifier()); +} + +inline void FinishMovieBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.Finish(root, MovieIdentifier()); +} + +inline void FinishSizePrefixedMovieBuffer( + ::flatbuffers::FlatBufferBuilder &fbb, + ::flatbuffers::Offset root) { + fbb.FinishSizePrefixed(root, MovieIdentifier()); +} + +inline std::unique_ptr UnPackMovie( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetMovie(buf)->UnPack(res)); +} + +inline std::unique_ptr UnPackSizePrefixedMovie( + const void *buf, + const ::flatbuffers::resolver_function_t *res = nullptr) { + return std::unique_ptr(GetSizePrefixedMovie(buf)->UnPack(res)); +} + +#endif // FLATBUFFERS_GENERATED_UNIONVECTOR_H_ diff --git a/third_party/flatbuffers/tests/util_test.cpp b/third_party/flatbuffers/tests/util_test.cpp new file mode 100644 index 00000000000..924855d0c48 --- /dev/null +++ b/third_party/flatbuffers/tests/util_test.cpp @@ -0,0 +1,175 @@ +#include "util_test.h" + +#include "flatbuffers/util.h" +#include "test_assert.h" + +namespace flatbuffers { +namespace tests { +namespace { + +template +void NumericUtilsTestInteger(const char *lower, const char *upper) { + T x; + TEST_EQ(flatbuffers::StringToNumber("1q", &x), false); + TEST_EQ(x, 0); + TEST_EQ(flatbuffers::StringToNumber(upper, &x), false); + TEST_EQ(x, flatbuffers::numeric_limits::max()); + TEST_EQ(flatbuffers::StringToNumber(lower, &x), false); + auto expval = flatbuffers::is_unsigned::value + ? flatbuffers::numeric_limits::max() + : flatbuffers::numeric_limits::lowest(); + TEST_EQ(x, expval); +} + +template +void NumericUtilsTestFloat(const char *lower, const char *upper) { + T f; + TEST_EQ(flatbuffers::StringToNumber("", &f), false); + TEST_EQ(flatbuffers::StringToNumber("1q", &f), false); + TEST_EQ(f, 0); + TEST_EQ(flatbuffers::StringToNumber(upper, &f), true); + TEST_EQ(f, +flatbuffers::numeric_limits::infinity()); + TEST_EQ(flatbuffers::StringToNumber(lower, &f), true); + TEST_EQ(f, -flatbuffers::numeric_limits::infinity()); +} +} // namespace + +void NumericUtilsTest() { + NumericUtilsTestInteger("-1", "18446744073709551616"); + NumericUtilsTestInteger("-1", "256"); + NumericUtilsTestInteger("-9223372036854775809", + "9223372036854775808"); + NumericUtilsTestInteger("-129", "128"); + NumericUtilsTestFloat("-3.4029e+38", "+3.4029e+38"); + NumericUtilsTestFloat("-1.7977e+308", "+1.7977e+308"); +} + +void IsAsciiUtilsTest() { + char c = -128; + for (int cnt = 0; cnt < 256; cnt++) { + auto alpha = (('a' <= c) && (c <= 'z')) || (('A' <= c) && (c <= 'Z')); + auto dec = (('0' <= c) && (c <= '9')); + auto hex = (('a' <= c) && (c <= 'f')) || (('A' <= c) && (c <= 'F')); + TEST_EQ(flatbuffers::is_alpha(c), alpha); + TEST_EQ(flatbuffers::is_alnum(c), alpha || dec); + TEST_EQ(flatbuffers::is_digit(c), dec); + TEST_EQ(flatbuffers::is_xdigit(c), dec || hex); + c += 1; + } +} + +void UtilConvertCase() { + { + struct TestCase { + std::string input; + flatbuffers::Case output_case; + std::string expected_output; + }; + + std::vector cases; + + // Tests for the common cases + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kUpperCamel, + "TheQuickBrownFox" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kLowerCamel, + "theQuickBrownFox" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kSnake, + "the_quick_brown_fox" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kScreamingSnake, + "THE_QUICK_BROWN_FOX" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kAllLower, + "the_quick_brown_fox" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kAllUpper, + "THE_QUICK_BROWN_FOX" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kUnknown, + "the_quick_brown_fox" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kKeep, + "the_quick_brown_fox" }); + cases.push_back({ "the_quick_brown_fox", flatbuffers::Case::kSnake2, + "the_quick_brown_fox" }); + + // Tests for some snake_cases where the _ is oddly placed or + // missing. + cases.push_back({ "single", flatbuffers::Case::kUpperCamel, "Single" }); + cases.push_back({ "Single", flatbuffers::Case::kUpperCamel, "Single" }); + cases.push_back({ "_leading", flatbuffers::Case::kUpperCamel, "_Leading" }); + cases.push_back( + { "trailing_", flatbuffers::Case::kUpperCamel, "Trailing_" }); + cases.push_back({ "double__underscore", flatbuffers::Case::kUpperCamel, + "Double_underscore" }); + cases.push_back({ "single", flatbuffers::Case::kLowerCamel, "single" }); + cases.push_back({ "Single", flatbuffers::Case::kLowerCamel, "single" }); + cases.push_back({ "_leading", flatbuffers::Case::kLowerCamel, "_Leading" }); + cases.push_back( + { "trailing_", flatbuffers::Case::kLowerCamel, "trailing_" }); + cases.push_back({ "double__underscore", flatbuffers::Case::kLowerCamel, + "double_underscore" }); + + // Tests for some output snake_cases + cases.push_back({ "single", flatbuffers::Case::kSnake, "single" }); + cases.push_back({ "single", flatbuffers::Case::kScreamingSnake, "SINGLE" }); + cases.push_back( + { "_leading", flatbuffers::Case::kScreamingSnake, "_LEADING" }); + cases.push_back( + { "trailing_", flatbuffers::Case::kScreamingSnake, "TRAILING_" }); + cases.push_back({ "double__underscore", flatbuffers::Case::kScreamingSnake, + "DOUBLE__UNDERSCORE" }); + + for (auto &test_case : cases) { + TEST_EQ(test_case.expected_output, + flatbuffers::ConvertCase(test_case.input, test_case.output_case)); + } + } + + // Tests for the non snake_case inputs. + { + struct TestCase { + flatbuffers::Case input_case; + std::string input; + flatbuffers::Case output_case; + std::string expected_output; + }; + + std::vector cases; + + cases.push_back({ flatbuffers::Case::kUpperCamel, "TheQuickBrownFox", + flatbuffers::Case::kSnake, "the_quick_brown_fox" }); + cases.push_back({ flatbuffers::Case::kLowerCamel, "theQuickBrownFox", + flatbuffers::Case::kSnake, "the_quick_brown_fox" }); + cases.push_back({ flatbuffers::Case::kSnake, "the_quick_brown_fox", + flatbuffers::Case::kSnake, "the_quick_brown_fox" }); + cases.push_back({ flatbuffers::Case::kScreamingSnake, "THE_QUICK_BROWN_FOX", + flatbuffers::Case::kSnake, "THE_QUICK_BROWN_FOX" }); + cases.push_back({ flatbuffers::Case::kAllUpper, "SINGLE", + flatbuffers::Case::kSnake, "SINGLE" }); + cases.push_back({ flatbuffers::Case::kAllLower, "single", + flatbuffers::Case::kSnake, "single" }); + cases.push_back({ flatbuffers::Case::kUpperCamel, "ABCtest", + flatbuffers::Case::kSnake, "abctest" }); + cases.push_back({ flatbuffers::Case::kUpperCamel, "tHe_qUiCk_BrOwN_fOx", + flatbuffers::Case::kKeep, "tHe_qUiCk_BrOwN_fOx" }); + cases.push_back({ flatbuffers::Case::kLowerCamel, "theQuick12345Fox", + flatbuffers::Case::kSnake, "the_quick_12345_fox" }); + cases.push_back({ flatbuffers::Case::kLowerCamel, "a12b34c45", + flatbuffers::Case::kSnake, "a_12b_34c_45" }); + cases.push_back({ flatbuffers::Case::kLowerCamel, "a12b34c45", + flatbuffers::Case::kSnake2, "a12_b34_c45" }); + cases.push_back({ flatbuffers::Case::kUpperCamel, "Int32Stamped", + flatbuffers::Case::kSnake, "int_32_stamped" }); + cases.push_back({ flatbuffers::Case::kUpperCamel, "101DogsTest", + flatbuffers::Case::kSnake, "101_dogs_test" }); + cases.push_back({ flatbuffers::Case::kUpperCamel, "Int32Stamped", + flatbuffers::Case::kScreamingSnake, "INT_32_STAMPED" }); + cases.push_back({ flatbuffers::Case::kUpperCamel, "101DogsTest", + flatbuffers::Case::kScreamingSnake, "101_DOGS_TEST" }); + + for (auto &test_case : cases) { + TEST_EQ(test_case.expected_output, + flatbuffers::ConvertCase(test_case.input, test_case.output_case, + test_case.input_case)); + } + } +} + +} // namespace tests +} // namespace flatbuffers diff --git a/third_party/flatbuffers/tests/util_test.h b/third_party/flatbuffers/tests/util_test.h new file mode 100644 index 00000000000..9f2a257b5b6 --- /dev/null +++ b/third_party/flatbuffers/tests/util_test.h @@ -0,0 +1,15 @@ +#ifndef TESTS_UTIL_TEST_H +#define TESTS_UTIL_TEST_H + +namespace flatbuffers { +namespace tests { + +void NumericUtilsTest(); +void IsAsciiUtilsTest(); +void UtilConvertCase(); + + +} // namespace tests +} // namespace flatbuffers + +#endif diff --git a/third_party/flatbuffers/tests/vector_has_test.fbs b/third_party/flatbuffers/tests/vector_has_test.fbs new file mode 100644 index 00000000000..dbc7271e305 --- /dev/null +++ b/third_party/flatbuffers/tests/vector_has_test.fbs @@ -0,0 +1,10 @@ +namespace Swift.Tests; + +table Vectors +{ + none:[ulong]; + empty:[ulong]; + array:[ulong]; +} + +root_type Vectors; diff --git a/third_party/flatbuffers/ts/BUILD.bazel b/third_party/flatbuffers/ts/BUILD.bazel new file mode 100644 index 00000000000..827244a95b4 --- /dev/null +++ b/third_party/flatbuffers/ts/BUILD.bazel @@ -0,0 +1,83 @@ +load("@aspect_rules_js//npm:defs.bzl", "npm_package") +load("@aspect_rules_ts//ts:defs.bzl", "ts_project") +load("@flatbuffers_npm//:defs.bzl", "npm_link_all_packages") +load("@rules_shell//shell:sh_binary.bzl", "sh_binary") + +filegroup( + name = "distribution", + srcs = [ + "BUILD.bazel", + "compile_flat_file.sh", + "pnpm-lock.yaml", + ] + glob([ + "*.ts", + ]), + visibility = ["//visibility:public"], +) + +npm_link_all_packages(name = "node_modules") + +# Add an index to emulate the top-level package.json's "main" entry. +genrule( + name = "generate_index.ts", + outs = ["index.ts"], + cmd = """echo "export * from './flatbuffers.js'" > $(OUTS)""", +) + +ts_project( + name = "flatbuffers_ts", + srcs = [ + "builder.ts", + "byte-buffer.ts", + "constants.ts", + "encoding.ts", + "flatbuffers.ts", + "types.ts", + "utils.ts", + ":index.ts", + ], + declaration = True, + tsconfig = { + "compilerOptions": { + "module": "commonjs", + "declaration": True, + "moduleResolution": "node", + "lib": [ + "ES2015", + "ES2020.BigInt", + "DOM", + ], + "types": ["node"], + "strict": True, + }, + }, + visibility = ["//visibility:public"], + deps = [ + ":node_modules/@types/node", + ], +) + +npm_package( + name = "flatbuffers", + srcs = [":flatbuffers_ts"], + include_external_repositories = ["*"], + package = "flatbuffers", + visibility = ["//visibility:public"], +) + +sh_binary( + name = "compile_flat_file", + srcs = ["compile_flat_file.sh"], + data = [ + "//:flatc", + "@nodejs_linux_amd64//:node_bin", + ], + # We just depend directly on the linux amd64 nodejs binary, so only support + # running this script on amd64 for now. + target_compatible_with = [ + "@platforms//cpu:x86_64", + "@platforms//os:linux", + ], + visibility = ["//visibility:public"], + deps = ["@bazel_tools//tools/bash/runfiles"], +) diff --git a/third_party/flatbuffers/ts/builder.ts b/third_party/flatbuffers/ts/builder.ts new file mode 100644 index 00000000000..f7f69cfec4a --- /dev/null +++ b/third_party/flatbuffers/ts/builder.ts @@ -0,0 +1,607 @@ +import { ByteBuffer } from "./byte-buffer.js" +import { SIZEOF_SHORT, SIZE_PREFIX_LENGTH, SIZEOF_INT, FILE_IDENTIFIER_LENGTH } from "./constants.js" +import { Offset, IGeneratedObject } from "./types.js" + +export class Builder { + private bb: ByteBuffer + /** Remaining space in the ByteBuffer. */ + private space: number + /** Minimum alignment encountered so far. */ + private minalign = 1 + /** The vtable for the current table. */ + private vtable: number[] | null = null + /** The amount of fields we're actually using. */ + private vtable_in_use = 0 + /** Whether we are currently serializing a table. */ + private isNested = false; + /** Starting offset of the current struct/table. */ + private object_start = 0 + /** List of offsets of all vtables. */ + private vtables: number[] = [] + /** For the current vector being built. */ + private vector_num_elems = 0 + /** False omits default values from the serialized data */ + private force_defaults = false; + + private string_maps: Map | null = null; + private text_encoder = new TextEncoder(); + + /** + * Create a FlatBufferBuilder. + */ + constructor(opt_initial_size?: number) { + let initial_size: number; + + if (!opt_initial_size) { + initial_size = 1024; + } else { + initial_size = opt_initial_size; + } + + /** + * @type {ByteBuffer} + * @private + */ + this.bb = ByteBuffer.allocate(initial_size); + this.space = initial_size; + } + + + clear(): void { + this.bb.clear(); + this.space = this.bb.capacity(); + this.minalign = 1; + this.vtable = null; + this.vtable_in_use = 0; + this.isNested = false; + this.object_start = 0; + this.vtables = []; + this.vector_num_elems = 0; + this.force_defaults = false; + this.string_maps = null; + } + + /** + * In order to save space, fields that are set to their default value + * don't get serialized into the buffer. Forcing defaults provides a + * way to manually disable this optimization. + * + * @param forceDefaults true always serializes default values + */ + forceDefaults(forceDefaults: boolean): void { + this.force_defaults = forceDefaults; + } + + /** + * Get the ByteBuffer representing the FlatBuffer. Only call this after you've + * called finish(). The actual data starts at the ByteBuffer's current position, + * not necessarily at 0. + */ + dataBuffer(): ByteBuffer { + return this.bb; + } + + /** + * Get the bytes representing the FlatBuffer. Only call this after you've + * called finish(). + */ + asUint8Array(): Uint8Array { + return this.bb.bytes().subarray(this.bb.position(), this.bb.position() + this.offset()); + } + + /** + * Prepare to write an element of `size` after `additional_bytes` have been + * written, e.g. if you write a string, you need to align such the int length + * field is aligned to 4 bytes, and the string data follows it directly. If all + * you need to do is alignment, `additional_bytes` will be 0. + * + * @param size This is the of the new element to write + * @param additional_bytes The padding size + */ + prep(size: number, additional_bytes: number): void { + // Track the biggest thing we've ever aligned to. + if (size > this.minalign) { + this.minalign = size; + } + + // Find the amount of alignment needed such that `size` is properly + // aligned after `additional_bytes` + const align_size = ((~(this.bb.capacity() - this.space + additional_bytes)) + 1) & (size - 1); + + // Reallocate the buffer if needed. + while (this.space < align_size + size + additional_bytes) { + const old_buf_size = this.bb.capacity(); + this.bb = Builder.growByteBuffer(this.bb); + this.space += this.bb.capacity() - old_buf_size; + } + + this.pad(align_size); + } + + pad(byte_size: number): void { + for (let i = 0; i < byte_size; i++) { + this.bb.writeInt8(--this.space, 0); + } + } + + writeInt8(value: number): void { + this.bb.writeInt8(this.space -= 1, value); + } + + writeInt16(value: number): void { + this.bb.writeInt16(this.space -= 2, value); + } + + writeInt32(value: number): void { + this.bb.writeInt32(this.space -= 4, value); + } + + writeInt64(value: bigint): void { + this.bb.writeInt64(this.space -= 8, value); + } + + writeFloat32(value: number): void { + this.bb.writeFloat32(this.space -= 4, value); + } + + writeFloat64(value: number): void { + this.bb.writeFloat64(this.space -= 8, value); + } + + /** + * Add an `int8` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int8` to add the buffer. + */ + addInt8(value: number): void { + this.prep(1, 0); + this.writeInt8(value); + } + + /** + * Add an `int16` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int16` to add the buffer. + */ + addInt16(value: number): void { + this.prep(2, 0); + this.writeInt16(value); + } + + /** + * Add an `int32` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int32` to add the buffer. + */ + addInt32(value: number): void { + this.prep(4, 0); + this.writeInt32(value); + } + + /** + * Add an `int64` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `int64` to add the buffer. + */ + addInt64(value: bigint): void { + this.prep(8, 0); + this.writeInt64(value); + } + + /** + * Add a `float32` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `float32` to add the buffer. + */ + addFloat32(value: number): void { + this.prep(4, 0); + this.writeFloat32(value); + } + + /** + * Add a `float64` to the buffer, properly aligned, and grows the buffer (if necessary). + * @param value The `float64` to add the buffer. + */ + addFloat64(value: number): void { + this.prep(8, 0); + this.writeFloat64(value); + } + + addFieldInt8(voffset: number, value: number, defaultValue: number|null): void { + if (this.force_defaults || value != defaultValue) { + this.addInt8(value); + this.slot(voffset); + } + } + + addFieldInt16(voffset: number, value: number, defaultValue: number|null): void { + if (this.force_defaults || value != defaultValue) { + this.addInt16(value); + this.slot(voffset); + } + } + + addFieldInt32(voffset: number, value: number, defaultValue: number|null): void { + if (this.force_defaults || value != defaultValue) { + this.addInt32(value); + this.slot(voffset); + } + } + + addFieldInt64(voffset: number, value: bigint, defaultValue: bigint|null): void { + if (this.force_defaults || value !== defaultValue) { + this.addInt64(value); + this.slot(voffset); + } + } + + addFieldFloat32(voffset: number, value: number, defaultValue: number|null): void { + if (this.force_defaults || value != defaultValue) { + this.addFloat32(value); + this.slot(voffset); + } + } + + addFieldFloat64(voffset: number, value: number, defaultValue: number|null): void { + if (this.force_defaults || value != defaultValue) { + this.addFloat64(value); + this.slot(voffset); + } + } + + addFieldOffset(voffset: number, value: Offset, defaultValue: Offset): void { + if (this.force_defaults || value != defaultValue) { + this.addOffset(value); + this.slot(voffset); + } + } + + /** + * Structs are stored inline, so nothing additional is being added. `d` is always 0. + */ + addFieldStruct(voffset: number, value: Offset, defaultValue: Offset): void { + if (value != defaultValue) { + this.nested(value); + this.slot(voffset); + } + } + + /** + * Structures are always stored inline, they need to be created right + * where they're used. You'll get this assertion failure if you + * created it elsewhere. + */ + nested(obj: Offset): void { + if (obj != this.offset()) { + throw new TypeError('FlatBuffers: struct must be serialized inline.'); + } + } + + /** + * Should not be creating any other object, string or vector + * while an object is being constructed + */ + notNested(): void { + if (this.isNested) { + throw new TypeError('FlatBuffers: object serialization must not be nested.'); + } + } + + /** + * Set the current vtable at `voffset` to the current location in the buffer. + */ + slot(voffset: number): void { + if (this.vtable !== null) + this.vtable[voffset] = this.offset(); + } + + /** + * @returns Offset relative to the end of the buffer. + */ + offset(): Offset { + return this.bb.capacity() - this.space; + } + + /** + * Doubles the size of the backing ByteBuffer and copies the old data towards + * the end of the new buffer (since we build the buffer backwards). + * + * @param bb The current buffer with the existing data + * @returns A new byte buffer with the old data copied + * to it. The data is located at the end of the buffer. + * + * uint8Array.set() formally takes {Array|ArrayBufferView}, so to pass + * it a uint8Array we need to suppress the type check: + * @suppress {checkTypes} + */ + static growByteBuffer(bb: ByteBuffer): ByteBuffer { + const old_buf_size = bb.capacity(); + + // Ensure we don't grow beyond what fits in an int. + if (old_buf_size & 0xC0000000) { + throw new Error('FlatBuffers: cannot grow buffer beyond 2 gigabytes.'); + } + + const new_buf_size = old_buf_size << 1; + const nbb = ByteBuffer.allocate(new_buf_size); + nbb.setPosition(new_buf_size - old_buf_size); + nbb.bytes().set(bb.bytes(), new_buf_size - old_buf_size); + return nbb; + } + + /** + * Adds on offset, relative to where it will be written. + * + * @param offset The offset to add. + */ + addOffset(offset: Offset): void { + this.prep(SIZEOF_INT, 0); // Ensure alignment is already done. + this.writeInt32(this.offset() - offset + SIZEOF_INT); + } + + /** + * Start encoding a new object in the buffer. Users will not usually need to + * call this directly. The FlatBuffers compiler will generate helper methods + * that call this method internally. + */ + startObject(numfields: number): void { + this.notNested(); + if (this.vtable == null) { + this.vtable = []; + } + this.vtable_in_use = numfields; + for (let i = 0; i < numfields; i++) { + this.vtable[i] = 0; // This will push additional elements as needed + } + this.isNested = true; + this.object_start = this.offset(); + } + + /** + * Finish off writing the object that is under construction. + * + * @returns The offset to the object inside `dataBuffer` + */ + endObject(): Offset { + if (this.vtable == null || !this.isNested) { + throw new Error('FlatBuffers: endObject called without startObject'); + } + + this.addInt32(0); + const vtableloc = this.offset(); + + // Trim trailing zeroes. + let i = this.vtable_in_use - 1; + // eslint-disable-next-line no-empty + for (; i >= 0 && this.vtable[i] == 0; i--) {} + const trimmed_size = i + 1; + + // Write out the current vtable. + for (; i >= 0; i--) { + // Offset relative to the start of the table. + this.addInt16(this.vtable[i] != 0 ? vtableloc - this.vtable[i] : 0); + } + + const standard_fields = 2; // The fields below: + this.addInt16(vtableloc - this.object_start); + const len = (trimmed_size + standard_fields) * SIZEOF_SHORT; + this.addInt16(len); + + // Search for an existing vtable that matches the current one. + let existing_vtable = 0; + const vt1 = this.space; + outer_loop: + for (i = 0; i < this.vtables.length; i++) { + const vt2 = this.bb.capacity() - this.vtables[i]; + if (len == this.bb.readInt16(vt2)) { + for (let j = SIZEOF_SHORT; j < len; j += SIZEOF_SHORT) { + if (this.bb.readInt16(vt1 + j) != this.bb.readInt16(vt2 + j)) { + continue outer_loop; + } + } + existing_vtable = this.vtables[i]; + break; + } + } + + if (existing_vtable) { + // Found a match: + // Remove the current vtable. + this.space = this.bb.capacity() - vtableloc; + + // Point table to existing vtable. + this.bb.writeInt32(this.space, existing_vtable - vtableloc); + } else { + // No match: + // Add the location of the current vtable to the list of vtables. + this.vtables.push(this.offset()); + + // Point table to current vtable. + this.bb.writeInt32(this.bb.capacity() - vtableloc, this.offset() - vtableloc); + } + + this.isNested = false; + return vtableloc as Offset; + } + + /** + * Finalize a buffer, poiting to the given `root_table`. + */ + finish(root_table: Offset, opt_file_identifier?: string, opt_size_prefix?: boolean): void { + const size_prefix = opt_size_prefix ? SIZE_PREFIX_LENGTH : 0; + if (opt_file_identifier) { + const file_identifier = opt_file_identifier; + this.prep(this.minalign, SIZEOF_INT + + FILE_IDENTIFIER_LENGTH + size_prefix); + if (file_identifier.length != FILE_IDENTIFIER_LENGTH) { + throw new TypeError('FlatBuffers: file identifier must be length ' + + FILE_IDENTIFIER_LENGTH); + } + for (let i = FILE_IDENTIFIER_LENGTH - 1; i >= 0; i--) { + this.writeInt8(file_identifier.charCodeAt(i)); + } + } + this.prep(this.minalign, 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`. + */ + finishSizePrefixed(this: Builder, root_table: Offset, opt_file_identifier?: string): void { + this.finish(root_table, opt_file_identifier, true); + } + + /** + * This checks a required field has been set in a given table that has + * just been constructed. + */ + requiredField(table: Offset, field: number): void { + const table_start = this.bb.capacity() - table; + const vtable_start = table_start - this.bb.readInt32(table_start); + const ok = field < this.bb.readInt16(vtable_start) && + this.bb.readInt16(vtable_start + field) != 0; + + // If this fails, the caller will show what field needs to be set. + if (!ok) { + throw new TypeError('FlatBuffers: field ' + field + ' must be set'); + } + } + + /** + * Start a new array/vector of objects. Users usually will not call + * this directly. The FlatBuffers compiler will create a start/end + * method for vector types in generated code. + * + * @param elem_size The size of each element in the array + * @param num_elems The number of elements in the array + * @param alignment The alignment of the array + */ + startVector(elem_size: number, num_elems: number, alignment: number): void { + this.notNested(); + this.vector_num_elems = num_elems; + this.prep(SIZEOF_INT, elem_size * num_elems); + this.prep(alignment, elem_size * num_elems); // Just in case alignment > int. + } + + /** + * Finish off the creation of an array and all its elements. The array must be + * created with `startVector`. + * + * @returns The offset at which the newly created array + * starts. + */ + endVector(): Offset { + this.writeInt32(this.vector_num_elems); + return this.offset(); + } + + /** + * Encode the string `s` in the buffer using UTF-8. If the string passed has + * already been seen, we return the offset of the already written string + * + * @param s The string to encode + * @return The offset in the buffer where the encoded string starts + */ + createSharedString(s: string | Uint8Array): Offset { + if (!s) { return 0 } + + if (!this.string_maps) { + this.string_maps = new Map(); + } + + if (this.string_maps.has(s)) { + return this.string_maps.get(s) as Offset + } + const offset = this.createString(s) + this.string_maps.set(s, offset) + return offset + } + + /** + * Encode the string `s` in the buffer using UTF-8. If a Uint8Array is passed + * instead of a string, it is assumed to contain valid UTF-8 encoded data. + * + * @param s The string to encode + * @return The offset in the buffer where the encoded string starts + */ + createString(s: string | Uint8Array | null | undefined): Offset { + if (s === null || s === undefined) { + return 0; + } + + let utf8: string | Uint8Array | number[]; + if (s instanceof Uint8Array) { + utf8 = s; + } else { + utf8 = this.text_encoder.encode(s); + } + + this.addInt8(0); + this.startVector(1, utf8.length, 1); + this.bb.setPosition(this.space -= utf8.length); + this.bb.bytes().set(utf8, this.space); + return this.endVector(); + } + + /** + * Create a byte vector. + * + * @param v The bytes to add + * @returns The offset in the buffer where the byte vector starts + */ + createByteVector(v: Uint8Array | null | undefined): Offset { + if (v === null || v === undefined) { + return 0; + } + + this.startVector(1, v.length, 1); + this.bb.setPosition(this.space -= v.length); + this.bb.bytes().set(v, this.space); + return this.endVector(); + } + + /** + * A helper function to pack an object + * + * @returns offset of obj + */ + createObjectOffset(obj: string | IGeneratedObject | null): Offset { + if(obj === null) { + return 0 + } + + if(typeof obj === 'string') { + return this.createString(obj); + } else { + return obj.pack(this); + } + } + + /** + * A helper function to pack a list of object + * + * @returns list of offsets of each non null object + */ + createObjectOffsetList(list: (string | IGeneratedObject)[]): Offset[] { + const ret: number[] = []; + + for(let i = 0; i < list.length; ++i) { + const val = list[i]; + + if(val !== null) { + ret.push(this.createObjectOffset(val)); + } else { + throw new TypeError( + 'FlatBuffers: Argument for createObjectOffsetList cannot contain null.'); + } + } + + return ret; + } + + createStructOffsetList(list: (string | IGeneratedObject)[], startFunc: (builder: Builder, length: number) => void): Offset { + startFunc(this, list.length); + this.createObjectOffsetList(list.slice().reverse()); + return this.endVector(); + } + } diff --git a/third_party/flatbuffers/ts/byte-buffer.ts b/third_party/flatbuffers/ts/byte-buffer.ts new file mode 100644 index 00000000000..90a1a4dfa7f --- /dev/null +++ b/third_party/flatbuffers/ts/byte-buffer.ts @@ -0,0 +1,287 @@ +import { FILE_IDENTIFIER_LENGTH, SIZEOF_INT } from "./constants.js"; +import { int32, isLittleEndian, float32, float64 } from "./utils.js"; +import { Offset, Table, IGeneratedObject, IUnpackableObject } from "./types.js"; +import { Encoding } from "./encoding.js"; + +export class ByteBuffer { + private position_ = 0; + private text_decoder_ = new TextDecoder(); + + /** + * Create a new ByteBuffer with a given array of bytes (`Uint8Array`) + */ + constructor(private bytes_: Uint8Array) { } + + /** + * Create and allocate a new ByteBuffer with a given size. + */ + static allocate(byte_size: number): ByteBuffer { + return new ByteBuffer(new Uint8Array(byte_size)); + } + + clear(): void { + this.position_ = 0; + } + + /** + * Get the underlying `Uint8Array`. + */ + bytes(): Uint8Array { + return this.bytes_; + } + + /** + * Get the buffer's position. + */ + position(): number { + return this.position_; + } + + /** + * Set the buffer's position. + */ + setPosition(position: number): void { + this.position_ = position; + } + + /** + * Get the buffer's capacity. + */ + capacity(): number { + return this.bytes_.length; + } + + readInt8(offset: number): number { + return this.readUint8(offset) << 24 >> 24; + } + + readUint8(offset: number): number { + return this.bytes_[offset]; + } + + readInt16(offset: number): number { + return this.readUint16(offset) << 16 >> 16; + } + + readUint16(offset: number): number { + return this.bytes_[offset] | this.bytes_[offset + 1] << 8; + } + + readInt32(offset: number): number { + return this.bytes_[offset] | this.bytes_[offset + 1] << 8 | this.bytes_[offset + 2] << 16 | this.bytes_[offset + 3] << 24; + } + + readUint32(offset: number): number { + return this.readInt32(offset) >>> 0; + } + + readInt64(offset: number): bigint { + return BigInt.asIntN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32))); + } + + readUint64(offset: number): bigint { + return BigInt.asUintN(64, BigInt(this.readUint32(offset)) + (BigInt(this.readUint32(offset + 4)) << BigInt(32))); + } + + readFloat32(offset: number): number { + int32[0] = this.readInt32(offset); + return float32[0]; + } + + readFloat64(offset: number): number { + int32[isLittleEndian ? 0 : 1] = this.readInt32(offset); + int32[isLittleEndian ? 1 : 0] = this.readInt32(offset + 4); + return float64[0]; + } + + writeInt8(offset: number, value: number): void { + this.bytes_[offset] = value; + } + + writeUint8(offset: number, value: number): void { + this.bytes_[offset] = value; + } + + writeInt16(offset: number, value: number): void { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + } + + writeUint16(offset: number, value: number): void { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + } + + writeInt32(offset: number, value: number): void { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + this.bytes_[offset + 2] = value >> 16; + this.bytes_[offset + 3] = value >> 24; + } + + writeUint32(offset: number, value: number): void { + this.bytes_[offset] = value; + this.bytes_[offset + 1] = value >> 8; + this.bytes_[offset + 2] = value >> 16; + this.bytes_[offset + 3] = value >> 24; + } + + writeInt64(offset: number, value: bigint): void { + this.writeInt32(offset, Number(BigInt.asIntN(32, value))); + this.writeInt32(offset + 4, Number(BigInt.asIntN(32, value >> BigInt(32)))); + } + + writeUint64(offset: number, value: bigint): void { + this.writeUint32(offset, Number(BigInt.asUintN(32, value))); + this.writeUint32(offset + 4, Number(BigInt.asUintN(32, value >> BigInt(32)))); + } + + writeFloat32(offset: number, value: number): void { + float32[0] = value; + this.writeInt32(offset, int32[0]); + } + + writeFloat64(offset: number, value: number): void { + float64[0] = value; + this.writeInt32(offset, int32[isLittleEndian ? 0 : 1]); + this.writeInt32(offset + 4, int32[isLittleEndian ? 1 : 0]); + } + + /** + * Return the file identifier. Behavior is undefined for FlatBuffers whose + * schema does not include a file_identifier (likely points at padding or the + * start of a the root vtable). + */ + getBufferIdentifier(): string { + if (this.bytes_.length < this.position_ + SIZEOF_INT + + FILE_IDENTIFIER_LENGTH) { + throw new Error( + 'FlatBuffers: ByteBuffer is too short to contain an identifier.'); + } + let result = ""; + for (let i = 0; i < FILE_IDENTIFIER_LENGTH; i++) { + result += String.fromCharCode( + this.readInt8(this.position_ + SIZEOF_INT + i)); + } + return result; + } + + /** + * Look up a field in the vtable, return an offset into the object, or 0 if the + * field is not present. + */ + __offset(bb_pos: number, vtable_offset: number): Offset { + const vtable = bb_pos - this.readInt32(bb_pos); + return vtable_offset < this.readInt16(vtable) ? this.readInt16(vtable + vtable_offset) : 0; + } + + /** + * Initialize any Table-derived type to point to the union at the given offset. + */ + __union(t: Table, offset: number): Table { + t.bb_pos = offset + this.readInt32(offset); + t.bb = this; + return t; + } + + /** + * Create a JavaScript string from UTF-8 data stored inside the FlatBuffer. + * This allocates a new string and converts to wide chars upon each access. + * + * To avoid the conversion to string, pass Encoding.UTF8_BYTES as the + * "optionalEncoding" argument. This is useful for avoiding conversion when + * the data will just be packaged back up in another FlatBuffer later on. + * + * @param offset + * @param opt_encoding Defaults to UTF16_STRING + */ + __string(offset: number, opt_encoding?: Encoding): string | Uint8Array { + offset += this.readInt32(offset); + const length = this.readInt32(offset); + offset += SIZEOF_INT; + const utf8bytes = this.bytes_.subarray(offset, offset + length); + if (opt_encoding === Encoding.UTF8_BYTES) + return utf8bytes; + else + return this.text_decoder_.decode(utf8bytes); + } + + /** + * Handle unions that can contain string as its member, if a Table-derived type then initialize it, + * if a string then return a new one + * + * WARNING: strings are immutable in JS so we can't change the string that the user gave us, this + * makes the behaviour of __union_with_string different compared to __union + */ + __union_with_string(o: Table | string, offset: number) : Table | string { + if(typeof o === 'string') { + return this.__string(offset) as string; + } + return this.__union(o, offset); + } + + /** + * Retrieve the relative offset stored at "offset" + */ + __indirect(offset: Offset): Offset { + return offset + this.readInt32(offset); + } + + /** + * Get the start of data of a vector whose offset is stored at "offset" in this object. + */ + __vector(offset: Offset): Offset { + return offset + this.readInt32(offset) + SIZEOF_INT; // data starts after the length + } + + /** + * Get the length of a vector whose offset is stored at "offset" in this object. + */ + __vector_len(offset: Offset): Offset { + return this.readInt32(offset + this.readInt32(offset)); + } + + __has_identifier(ident: string): boolean { + if (ident.length != FILE_IDENTIFIER_LENGTH) { + throw new Error('FlatBuffers: file identifier must be length ' + + FILE_IDENTIFIER_LENGTH); + } + for (let i = 0; i < FILE_IDENTIFIER_LENGTH; i++) { + if (ident.charCodeAt(i) != this.readInt8(this.position() + SIZEOF_INT + i)) { + return false; + } + } + return true; + } + + /** + * A helper function for generating list for obj api + */ + createScalarList(listAccessor: (i: number) => T | null, listLength: number): T[] { + const ret: T[] = []; + for(let i = 0; i < listLength; ++i) { + const val = listAccessor(i); + if(val !== null) { + ret.push(val); + } + } + return ret; + } + + /** + * A helper function for generating list for obj api + * @param listAccessor function that accepts an index and return data at that index + * @param listLength listLength + * @param res result list + */ + createObjList, T2 extends IGeneratedObject>(listAccessor: (i: number) => T1 | null, listLength: number): T2[] { + const ret: T2[] = []; + for(let i = 0; i < listLength; ++i) { + const val = listAccessor(i); + if(val !== null) { + ret.push(val.unpack()); + } + } + return ret; + } + } diff --git a/third_party/flatbuffers/ts/compile_flat_file.sh b/third_party/flatbuffers/ts/compile_flat_file.sh new file mode 100755 index 00000000000..43e0c391aa1 --- /dev/null +++ b/third_party/flatbuffers/ts/compile_flat_file.sh @@ -0,0 +1,22 @@ +#!/bin/bash +# This is a script used by the typescript flatbuffer bazel rules to compile +# a flatbuffer schema (.fbs file) to typescript and then use esbuild to +# generate a single output. +# Note: This relies on parsing the stdout of flatc to figure out how to +# run esbuild. +# --- begin runfiles.bash initialization v2 --- +# Copy-pasted from the Bazel Bash runfiles library v2. +set -uo pipefail; set +e; f=bazel_tools/tools/bash/runfiles/runfiles.bash +source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \ + source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \ + source "$0.runfiles/$f" 2>/dev/null || \ + source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ + source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \ + { echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e +# --- end runfiles.bash initialization v2 --- +set -eu +runfiles_export_envvars +FLATC=$(rlocation com_github_google_flatbuffers/flatc) +TS_FILE=$(${FLATC} $@ | grep "Entry point.*generated" | grep -o "bazel-out.*ts") +export PATH="$(rlocation nodejs_linux_amd64/bin/nodejs/bin):${PATH}" +${ESBUILD_BIN} ${TS_FILE} --format=cjs --bundle --outfile="${OUTPUT_FILE}" --external:flatbuffers --log-level=warning diff --git a/third_party/flatbuffers/ts/constants.ts b/third_party/flatbuffers/ts/constants.ts new file mode 100644 index 00000000000..04510fbcf76 --- /dev/null +++ b/third_party/flatbuffers/ts/constants.ts @@ -0,0 +1,4 @@ +export const SIZEOF_SHORT = 2; +export const SIZEOF_INT = 4; +export const FILE_IDENTIFIER_LENGTH = 4; +export const SIZE_PREFIX_LENGTH = 4; \ No newline at end of file diff --git a/third_party/flatbuffers/ts/encoding.ts b/third_party/flatbuffers/ts/encoding.ts new file mode 100644 index 00000000000..856792ce207 --- /dev/null +++ b/third_party/flatbuffers/ts/encoding.ts @@ -0,0 +1,4 @@ +export enum Encoding { + UTF8_BYTES = 1, + UTF16_STRING = 2 +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/flatbuffers.ts b/third_party/flatbuffers/ts/flatbuffers.ts new file mode 100644 index 00000000000..a6085124513 --- /dev/null +++ b/third_party/flatbuffers/ts/flatbuffers.ts @@ -0,0 +1,12 @@ +export { SIZEOF_SHORT } from './constants.js' +export { SIZEOF_INT } from './constants.js' +export { FILE_IDENTIFIER_LENGTH } from './constants.js' +export { SIZE_PREFIX_LENGTH } from './constants.js' + +export { Table, Offset, IGeneratedObject, IUnpackableObject } from './types.js' + +export { int32, float32, float64, isLittleEndian } from './utils.js' + +export { Encoding } from './encoding.js' +export { Builder } from './builder.js' +export { ByteBuffer } from './byte-buffer.js' diff --git a/third_party/flatbuffers/ts/flexbuffers.ts b/third_party/flatbuffers/ts/flexbuffers.ts new file mode 100644 index 00000000000..a59d497cfc1 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers.ts @@ -0,0 +1,18 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +import { Builder } from './flexbuffers/builder.js' +import { toReference } from './flexbuffers/reference.js' +export { toReference } from './flexbuffers/reference.js' + +export function builder(): Builder { + return new Builder(); +} + +export function toObject(buffer: ArrayBuffer): unknown { + return toReference(buffer).toObject(); +} + +export function encode(object: unknown, size = 2048, deduplicateStrings = true, deduplicateKeys = true, deduplicateKeyVectors = true): Uint8Array { + const builder = new Builder(size > 0 ? size : 2048, deduplicateStrings, deduplicateKeys, deduplicateKeyVectors); + builder.add(object); + return builder.finish(); +} diff --git a/third_party/flatbuffers/ts/flexbuffers/bit-width-util.ts b/third_party/flatbuffers/ts/flexbuffers/bit-width-util.ts new file mode 100644 index 00000000000..3a295fdfb8f --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/bit-width-util.ts @@ -0,0 +1,34 @@ +import { BitWidth } from './bit-width.js' + +export function toByteWidth(bitWidth: BitWidth): number { + return 1 << bitWidth; +} + +export function iwidth(value: number | bigint): BitWidth { + if (value >= -128 && value <= 127) return BitWidth.WIDTH8; + if (value >= -32768 && value <= 32767) return BitWidth.WIDTH16; + if (value >= -2147483648 && value <= 2147483647) return BitWidth.WIDTH32; + return BitWidth.WIDTH64; +} + +export function fwidth(value: number): BitWidth { + return value === Math.fround(value) ? BitWidth.WIDTH32 : BitWidth.WIDTH64; +} + +export function uwidth(value: number): BitWidth { + if (value <= 255) return BitWidth.WIDTH8; + if (value <= 65535) return BitWidth.WIDTH16; + if (value <= 4294967295) return BitWidth.WIDTH32; + return BitWidth.WIDTH64; +} + +export function fromByteWidth(value: number): BitWidth { + if (value === 1) return BitWidth.WIDTH8; + if (value === 2) return BitWidth.WIDTH16; + if (value === 4) return BitWidth.WIDTH32; + return BitWidth.WIDTH64; +} + +export function paddingSize(bufSize: number, scalarSize: number): number { + return (~bufSize + 1) & (scalarSize - 1); +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/flexbuffers/bit-width.ts b/third_party/flatbuffers/ts/flexbuffers/bit-width.ts new file mode 100644 index 00000000000..5f85b613816 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/bit-width.ts @@ -0,0 +1,6 @@ +export enum BitWidth { + WIDTH8 = 0, + WIDTH16 = 1, + WIDTH32 = 2, + WIDTH64 = 3, +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/flexbuffers/builder.ts b/third_party/flatbuffers/ts/flexbuffers/builder.ts new file mode 100644 index 00000000000..9c2aa2ae03d --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/builder.ts @@ -0,0 +1,549 @@ +import { BitWidth } from './bit-width.js' +import { paddingSize, iwidth, uwidth, fwidth, toByteWidth, fromByteWidth } from './bit-width-util.js' +import { toUTF8Array } from './flexbuffers-util.js' +import { ValueType } from './value-type.js' +import { isNumber, isTypedVectorElement, toTypedVector } from './value-type-util.js' +import { StackValue } from './stack-value.js' + +interface StackPointer { + stackPosition: number, + isVector: boolean + presorted?: boolean +} + +export class Builder { + buffer: ArrayBuffer + view: DataView + + readonly stack: Array = []; + readonly stackPointers: Array = []; + offset = 0; + finished = false; + readonly stringLookup: Record = {}; + readonly keyLookup: Record = {}; + readonly keyVectorLookup: Record = {}; + readonly indirectIntLookup: Record = {}; + readonly indirectUIntLookup: Record = {}; + readonly indirectFloatLookup: Record = {}; + + constructor(size = 2048, private dedupStrings = true, private dedupKeys = true, private dedupKeyVectors = true) { + this.buffer = new ArrayBuffer(size > 0 ? size : 2048); + this.view = new DataView(this.buffer); + } + + private align(width: BitWidth) { + const byteWidth = toByteWidth(width); + this.offset += paddingSize(this.offset, byteWidth); + return byteWidth; + } + + computeOffset(newValueSize: number): number { + const targetOffset = this.offset + newValueSize; + let size = this.buffer.byteLength; + const prevSize = size; + while (size < targetOffset) { + size <<= 1; + } + if (prevSize < size) { + const prevBuffer = this.buffer; + this.buffer = new ArrayBuffer(size); + this.view = new DataView(this.buffer); + new Uint8Array(this.buffer).set(new Uint8Array(prevBuffer), 0); + } + return targetOffset; + } + + pushInt(value: number, width: BitWidth): void { + if (width === BitWidth.WIDTH8) { + this.view.setInt8(this.offset, value); + } else if (width === BitWidth.WIDTH16) { + this.view.setInt16(this.offset, value, true); + } else if (width === BitWidth.WIDTH32) { + this.view.setInt32(this.offset, value, true); + } else if (width === BitWidth.WIDTH64) { + this.view.setBigInt64(this.offset, BigInt(value), true); + } else { + throw `Unexpected width: ${width} for value: ${value}`; + } + } + + pushUInt(value: number, width: BitWidth): void { + if (width === BitWidth.WIDTH8) { + this.view.setUint8(this.offset, value); + } else if (width === BitWidth.WIDTH16) { + this.view.setUint16(this.offset, value, true); + } else if (width === BitWidth.WIDTH32) { + this.view.setUint32(this.offset, value, true); + } else if (width === BitWidth.WIDTH64) { + this.view.setBigUint64(this.offset, BigInt(value), true); + } else { + throw `Unexpected width: ${width} for value: ${value}`; + } + } + + private writeInt(value: number, byteWidth: number) { + const newOffset = this.computeOffset(byteWidth); + this.pushInt(value, fromByteWidth(byteWidth)); + this.offset = newOffset; + } + + private writeUInt(value: number, byteWidth: number) { + const newOffset = this.computeOffset(byteWidth); + this.pushUInt(value, fromByteWidth(byteWidth)); + this.offset = newOffset; + } + + private writeBlob(arrayBuffer: ArrayBuffer) { + const length = arrayBuffer.byteLength; + const bitWidth = uwidth(length); + const byteWidth = this.align(bitWidth); + this.writeUInt(length, byteWidth); + const blobOffset = this.offset; + const newOffset = this.computeOffset(length); + new Uint8Array(this.buffer).set(new Uint8Array(arrayBuffer), blobOffset); + this.stack.push(this.offsetStackValue(blobOffset, ValueType.BLOB, bitWidth)); + this.offset = newOffset; + } + + private writeString(str: string): void { + if (this.dedupStrings && Object.prototype.hasOwnProperty.call(this.stringLookup, str)) { + this.stack.push(this.stringLookup[str]); + return; + } + const utf8 = toUTF8Array(str); + const length = utf8.length; + const bitWidth = uwidth(length); + const byteWidth = this.align(bitWidth); + this.writeUInt(length, byteWidth); + const stringOffset = this.offset; + const newOffset = this.computeOffset(length + 1); + new Uint8Array(this.buffer).set(utf8, stringOffset); + const stackValue = this.offsetStackValue(stringOffset, ValueType.STRING, bitWidth); + this.stack.push(stackValue); + if (this.dedupStrings) { + this.stringLookup[str] = stackValue; + } + this.offset = newOffset; + } + + private writeKey(str: string): void { + if (this.dedupKeys && Object.prototype.hasOwnProperty.call(this.keyLookup, str)) { + this.stack.push(this.keyLookup[str]); + return; + } + const utf8 = toUTF8Array(str); + const length = utf8.length; + const newOffset = this.computeOffset(length + 1); + new Uint8Array(this.buffer).set(utf8, this.offset); + const stackValue = this.offsetStackValue(this.offset, ValueType.KEY, BitWidth.WIDTH8); + this.stack.push(stackValue); + if (this.dedupKeys) { + this.keyLookup[str] = stackValue; + } + this.offset = newOffset; + } + + private writeStackValue(value: StackValue, byteWidth: number): void { + const newOffset = this.computeOffset(byteWidth); + if (value.isOffset()) { + const relativeOffset = this.offset - value.offset; + if (byteWidth === 8 || BigInt(relativeOffset) < (BigInt(1) << BigInt(byteWidth * 8))) { + this.writeUInt(relativeOffset, byteWidth); + } else { + throw `Unexpected size ${byteWidth}. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new` + } + } else { + value.writeToBuffer(byteWidth); + } + this.offset = newOffset; + } + + private integrityCheckOnValueAddition() { + if (this.finished) { + throw "Adding values after finish is prohibited"; + } + if (this.stackPointers.length !== 0 && this.stackPointers[this.stackPointers.length - 1].isVector === false) { + if (this.stack[this.stack.length - 1].type !== ValueType.KEY) { + throw "Adding value to a map before adding a key is prohibited"; + } + } + } + + private integrityCheckOnKeyAddition() { + if (this.finished) { + throw "Adding values after finish is prohibited"; + } + if (this.stackPointers.length === 0 || this.stackPointers[this.stackPointers.length - 1].isVector) { + throw "Adding key before starting a map is prohibited"; + } + } + + startVector(): void { + this.stackPointers.push({ stackPosition: this.stack.length, isVector: true }); + } + + startMap(presorted = false): void { + this.stackPointers.push({ stackPosition: this.stack.length, isVector: false, presorted: presorted }); + } + + private endVector(stackPointer: StackPointer) { + const vecLength = this.stack.length - stackPointer.stackPosition; + const vec = this.createVector(stackPointer.stackPosition, vecLength, 1); + this.stack.splice(stackPointer.stackPosition, vecLength); + this.stack.push(vec); + } + + private endMap(stackPointer: StackPointer) { + if (!stackPointer.presorted) { + this.sort(stackPointer); + } + let keyVectorHash = ""; + for (let i = stackPointer.stackPosition; i < this.stack.length; i += 2) { + keyVectorHash += `,${this.stack[i].offset}`; + } + const vecLength = (this.stack.length - stackPointer.stackPosition) >> 1; + + if (this.dedupKeyVectors && !Object.prototype.hasOwnProperty.call(this.keyVectorLookup, keyVectorHash)) { + this.keyVectorLookup[keyVectorHash] = this.createVector(stackPointer.stackPosition, vecLength, 2); + } + const keysStackValue = this.dedupKeyVectors ? this.keyVectorLookup[keyVectorHash] : this.createVector(stackPointer.stackPosition, vecLength, 2); + const valuesStackValue = this.createVector(stackPointer.stackPosition + 1, vecLength, 2, keysStackValue); + this.stack.splice(stackPointer.stackPosition, vecLength << 1); + this.stack.push(valuesStackValue); + } + + private sort(stackPointer: StackPointer) { + const view = this.view + const stack = this.stack + + function shouldFlip(v1: StackValue, v2: StackValue) { + if (v1.type !== ValueType.KEY || v2.type !== ValueType.KEY) { + throw `Stack values are not keys ${v1} | ${v2}. Check if you combined [addKey] with add... method calls properly.` + } + let c1, c2; + let index = 0; + do { + c1 = view.getUint8(v1.offset + index); + c2 = view.getUint8(v2.offset + index); + if (c2 < c1) return true; + if (c1 < c2) return false; + index += 1; + } while (c1 !== 0 && c2 !== 0); + return false; + } + + function swap(stack: Array, flipIndex: number, i: number) { + if (flipIndex === i) return; + const k = stack[flipIndex]; + const v = stack[flipIndex + 1]; + stack[flipIndex] = stack[i]; + stack[flipIndex + 1] = stack[i + 1]; + stack[i] = k; + stack[i + 1] = v; + } + + function selectionSort() { + for (let i = stackPointer.stackPosition; i < stack.length; i += 2) { + let flipIndex = i; + for (let j = i + 2; j < stack.length; j += 2) { + if (shouldFlip(stack[flipIndex], stack[j])) { + flipIndex = j; + } + } + if (flipIndex !== i) { + swap(stack, flipIndex, i); + } + } + } + + function smaller(v1: StackValue, v2: StackValue) { + if (v1.type !== ValueType.KEY || v2.type !== ValueType.KEY) { + throw `Stack values are not keys ${v1} | ${v2}. Check if you combined [addKey] with add... method calls properly.` + } + if (v1.offset === v2.offset) { + return false; + } + let c1, c2; + let index = 0; + do { + c1 = view.getUint8(v1.offset + index); + c2 = view.getUint8(v2.offset + index); + if (c1 < c2) return true; + if (c2 < c1) return false; + index += 1; + } while (c1 !== 0 && c2 !== 0); + return false; + } + + function quickSort(left: number, right: number) { + + if (left < right) { + const mid = left + (((right - left) >> 2)) * 2; + const pivot = stack[mid]; + let left_new = left; + let right_new = right; + + do { + while (smaller(stack[left_new], pivot)) { + left_new += 2; + } + while (smaller(pivot, stack[right_new])) { + right_new -= 2; + } + if (left_new <= right_new) { + swap(stack, left_new, right_new); + left_new += 2; + right_new -= 2; + } + } while (left_new <= right_new); + + quickSort(left, right_new); + quickSort(left_new, right); + + } + } + + let sorted = true; + for (let i = stackPointer.stackPosition; i < this.stack.length - 2; i += 2) { + if (shouldFlip(this.stack[i], this.stack[i + 2])) { + sorted = false; + break; + } + } + + if (!sorted) { + if (this.stack.length - stackPointer.stackPosition > 40) { + quickSort(stackPointer.stackPosition, this.stack.length - 2); + } else { + selectionSort(); + } + } + } + + end(): void { + if (this.stackPointers.length < 1) return; + const pointer = this.stackPointers.pop() as StackPointer; + if (pointer.isVector) { + this.endVector(pointer); + } else { + this.endMap(pointer); + } + } + + private createVector(start: number, vecLength: number, step: number, keys: StackValue | null = null) { + let bitWidth = uwidth(vecLength); + let prefixElements = 1; + if (keys !== null) { + const elementWidth = keys.elementWidth(this.offset, 0); + if (elementWidth > bitWidth) { + bitWidth = elementWidth; + } + prefixElements += 2; + } + let vectorType = ValueType.KEY; + let typed = keys === null; + for (let i = start; i < this.stack.length; i += step) { + const elementWidth = this.stack[i].elementWidth(this.offset, i + prefixElements); + if (elementWidth > bitWidth) { + bitWidth = elementWidth; + } + if (i === start) { + vectorType = this.stack[i].type; + typed = typed && isTypedVectorElement(vectorType); + } else { + if (vectorType !== this.stack[i].type) { + typed = false; + } + } + } + const byteWidth = this.align(bitWidth); + const fix = typed && isNumber(vectorType) && vecLength >= 2 && vecLength <= 4; + if (keys !== null) { + this.writeStackValue(keys, byteWidth); + this.writeUInt(1 << keys.width, byteWidth); + } + if (!fix) { + this.writeUInt(vecLength, byteWidth); + } + const vecOffset = this.offset; + for (let i = start; i < this.stack.length; i += step) { + this.writeStackValue(this.stack[i], byteWidth); + } + if (!typed) { + for (let i = start; i < this.stack.length; i += step) { + this.writeUInt(this.stack[i].storedPackedType(), 1); + } + } + if (keys !== null) { + return this.offsetStackValue(vecOffset, ValueType.MAP, bitWidth); + } + if (typed) { + const vType = toTypedVector(vectorType, fix ? vecLength : 0); + return this.offsetStackValue(vecOffset, vType, bitWidth); + } + return this.offsetStackValue(vecOffset, ValueType.VECTOR, bitWidth); + } + + private nullStackValue() { + return new StackValue(this, ValueType.NULL, BitWidth.WIDTH8); + } + + private boolStackValue(value: boolean) { + return new StackValue(this, ValueType.BOOL, BitWidth.WIDTH8, value); + } + + private intStackValue(value: number | bigint) { + return new StackValue(this, ValueType.INT, iwidth(value), value as number); + } + + private uintStackValue(value: number) { + return new StackValue(this, ValueType.UINT, uwidth(value), value); + } + + private floatStackValue(value: number) { + return new StackValue(this, ValueType.FLOAT, fwidth(value), value); + } + + private offsetStackValue(offset: number, valueType: ValueType, bitWidth: BitWidth): StackValue { + return new StackValue(this, valueType, bitWidth, null, offset); + } + + private finishBuffer() { + if (this.stack.length !== 1) { + throw `Stack has to be exactly 1, but it is ${this.stack.length}. You have to end all started vectors and maps before calling [finish]`; + } + const value = this.stack[0]; + const byteWidth = this.align(value.elementWidth(this.offset, 0)); + this.writeStackValue(value, byteWidth); + this.writeUInt(value.storedPackedType(), 1); + this.writeUInt(byteWidth, 1); + this.finished = true; + } + + add(value: undefined | null | boolean | bigint | number | DataView | string | Array | Record | unknown): void { + this.integrityCheckOnValueAddition(); + if (typeof value === 'undefined') { + throw "You need to provide a value"; + } + if (value === null) { + this.stack.push(this.nullStackValue()); + } else if (typeof value === "boolean") { + this.stack.push(this.boolStackValue(value)); + } else if (typeof value === "bigint") { + this.stack.push(this.intStackValue(value)); + } else if (typeof value == 'number') { + if (Number.isInteger(value)) { + this.stack.push(this.intStackValue(value)); + } else { + this.stack.push(this.floatStackValue(value)); + } + } else if (ArrayBuffer.isView(value)) { + this.writeBlob(value.buffer); + } else if (typeof value === 'string' || value instanceof String) { + this.writeString(value as string); + } else if (Array.isArray(value)) { + this.startVector(); + for (let i = 0; i < value.length; i++) { + this.add(value[i]); + } + this.end(); + } else if (typeof value === 'object') { + const properties = Object.getOwnPropertyNames(value).sort(); + this.startMap(true); + for (let i = 0; i < properties.length; i++) { + const key = properties[i]; + this.addKey(key); + this.add((value as Record)[key]); + } + this.end(); + } else { + throw `Unexpected value input ${value}`; + } + } + + finish(): Uint8Array { + if (!this.finished) { + this.finishBuffer(); + } + const result = this.buffer.slice(0, this.offset); + return new Uint8Array(result); + } + + isFinished(): boolean { + return this.finished; + } + + addKey(key: string): void { + this.integrityCheckOnKeyAddition(); + this.writeKey(key); + } + + addInt(value: number, indirect = false, deduplicate = false): void { + this.integrityCheckOnValueAddition(); + if (!indirect) { + this.stack.push(this.intStackValue(value)); + return; + } + if (deduplicate && Object.prototype.hasOwnProperty.call(this.indirectIntLookup, value)) { + this.stack.push(this.indirectIntLookup[value]); + return; + } + const stackValue = this.intStackValue(value); + const byteWidth = this.align(stackValue.width); + const newOffset = this.computeOffset(byteWidth); + const valueOffset = this.offset; + stackValue.writeToBuffer(byteWidth); + const stackOffset = this.offsetStackValue(valueOffset, ValueType.INDIRECT_INT, stackValue.width); + this.stack.push(stackOffset); + this.offset = newOffset; + if (deduplicate) { + this.indirectIntLookup[value] = stackOffset; + } + } + + addUInt(value: number, indirect = false, deduplicate = false): void { + this.integrityCheckOnValueAddition(); + if (!indirect) { + this.stack.push(this.uintStackValue(value)); + return; + } + if (deduplicate && Object.prototype.hasOwnProperty.call(this.indirectUIntLookup, value)) { + this.stack.push(this.indirectUIntLookup[value]); + return; + } + const stackValue = this.uintStackValue(value); + const byteWidth = this.align(stackValue.width); + const newOffset = this.computeOffset(byteWidth); + const valueOffset = this.offset; + stackValue.writeToBuffer(byteWidth); + const stackOffset = this.offsetStackValue(valueOffset, ValueType.INDIRECT_UINT, stackValue.width); + this.stack.push(stackOffset); + this.offset = newOffset; + if (deduplicate) { + this.indirectUIntLookup[value] = stackOffset; + } + } + + addFloat(value: number, indirect = false, deduplicate = false): void { + this.integrityCheckOnValueAddition(); + if (!indirect) { + this.stack.push(this.floatStackValue(value)); + return; + } + if (deduplicate && Object.prototype.hasOwnProperty.call(this.indirectFloatLookup, value)) { + this.stack.push(this.indirectFloatLookup[value]); + return; + } + const stackValue = this.floatStackValue(value); + const byteWidth = this.align(stackValue.width); + const newOffset = this.computeOffset(byteWidth); + const valueOffset = this.offset; + stackValue.writeToBuffer(byteWidth); + const stackOffset = this.offsetStackValue(valueOffset, ValueType.INDIRECT_FLOAT, stackValue.width); + this.stack.push(stackOffset); + this.offset = newOffset; + if (deduplicate) { + this.indirectFloatLookup[value] = stackOffset; + } + } +} diff --git a/third_party/flatbuffers/ts/flexbuffers/flexbuffers-util.ts b/third_party/flatbuffers/ts/flexbuffers/flexbuffers-util.ts new file mode 100644 index 00000000000..83186e9dcfa --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/flexbuffers-util.ts @@ -0,0 +1,9 @@ +export function fromUTF8Array(data: BufferSource): string { + const decoder = new TextDecoder(); + return decoder.decode(data); +} + +export function toUTF8Array(str: string) : Uint8Array { + const encoder = new TextEncoder(); + return encoder.encode(str); +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/flexbuffers/reference-util.ts b/third_party/flatbuffers/ts/flexbuffers/reference-util.ts new file mode 100644 index 00000000000..52fb6007ff0 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/reference-util.ts @@ -0,0 +1,109 @@ +import { BitWidth } from './bit-width.js' +import { toByteWidth, fromByteWidth } from './bit-width-util.js' +import { toUTF8Array, fromUTF8Array } from './flexbuffers-util.js' + +export function validateOffset(dataView: DataView, offset: number, width: number): void { + if (dataView.byteLength <= offset + width || (offset & (toByteWidth(width) - 1)) !== 0) { + throw "Bad offset: " + offset + ", width: " + width; + } +} + +export function readInt(dataView: DataView, offset: number, width: number): number | bigint { + if (width < 2) { + if (width < 1) { + return dataView.getInt8(offset); + } else { + return dataView.getInt16(offset, true); + } + } else { + if (width < 3) { + return dataView.getInt32(offset, true) + } else { + if (dataView.setBigInt64 === undefined) { + return BigInt(dataView.getUint32(offset, true)) + (BigInt(dataView.getUint32(offset + 4, true)) << BigInt(32)); + } + return dataView.getBigInt64(offset, true) + } + } +} + +export function readUInt(dataView: DataView, offset: number, width: number): number | bigint { + if (width < 2) { + if (width < 1) { + return dataView.getUint8(offset); + } else { + return dataView.getUint16(offset, true); + } + } else { + if (width < 3) { + return dataView.getUint32(offset, true) + } else { + if (dataView.getBigUint64 === undefined) { + return BigInt(dataView.getUint32(offset, true)) + (BigInt(dataView.getUint32(offset + 4, true)) << BigInt(32)); + } + return dataView.getBigUint64(offset, true) + } + } +} + +export function readFloat(dataView: DataView, offset: number, width: number): number { + if (width < BitWidth.WIDTH32) { + throw "Bad width: " + width; + } + if (width === BitWidth.WIDTH32) { + return dataView.getFloat32(offset, true); + } + return dataView.getFloat64(offset, true); +} + +export function indirect(dataView: DataView, offset: number, width: number): number { + const step = readUInt(dataView, offset, width) as number; + return offset - step; +} + +export function keyIndex(key: string, dataView: DataView, offset: number, parentWidth: number, byteWidth: number, length: number): number | null { + const input = toUTF8Array(key); + const keysVectorOffset = indirect(dataView, offset, parentWidth) - byteWidth * 3; + const bitWidth = fromByteWidth(byteWidth); + const indirectOffset = keysVectorOffset - Number(readUInt(dataView, keysVectorOffset, bitWidth)); + const _byteWidth = Number(readUInt(dataView, keysVectorOffset + byteWidth, bitWidth)); + let low = 0; + let high = length - 1; + while (low <= high) { + const mid = (high + low) >> 1; + const dif = diffKeys(input, mid, dataView, indirectOffset, _byteWidth); + if (dif === 0) return mid; + if (dif < 0) { + high = mid - 1; + } else { + low = mid + 1; + } + } + return null; +} + +export function diffKeys(input: Uint8Array, index: number, dataView: DataView, offset: number, width: number): number { + const keyOffset = offset + index * width; + const keyIndirectOffset = keyOffset - Number(readUInt(dataView, keyOffset, fromByteWidth(width))); + for (let i = 0; i < input.length; i++) { + const dif = input[i] - dataView.getUint8(keyIndirectOffset + i); + if (dif !== 0) { + return dif; + } + } + return dataView.getUint8(keyIndirectOffset + input.length) === 0 ? 0 : -1; +} + +export function keyForIndex(index: number, dataView: DataView, offset: number, parentWidth: number, byteWidth: number): string { + const keysVectorOffset = indirect(dataView, offset, parentWidth) - byteWidth * 3; + const bitWidth = fromByteWidth(byteWidth); + const indirectOffset = keysVectorOffset - Number(readUInt(dataView, keysVectorOffset, bitWidth)); + const _byteWidth = Number(readUInt(dataView, keysVectorOffset + byteWidth, bitWidth)); + const keyOffset = indirectOffset + index * _byteWidth; + const keyIndirectOffset = keyOffset - Number(readUInt(dataView, keyOffset, fromByteWidth(_byteWidth))); + let length = 0; + while (dataView.getUint8(keyIndirectOffset + length) !== 0) { + length++; + } + return fromUTF8Array(new Uint8Array(dataView.buffer, keyIndirectOffset, length)); +} diff --git a/third_party/flatbuffers/ts/flexbuffers/reference.ts b/third_party/flatbuffers/ts/flexbuffers/reference.ts new file mode 100644 index 00000000000..38c2f0a94f1 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/reference.ts @@ -0,0 +1,191 @@ +import { fromByteWidth } from './bit-width-util.js' +import { ValueType } from './value-type.js' +import { isNumber, isIndirectNumber, isAVector, fixedTypedVectorElementSize, isFixedTypedVector, isTypedVector, typedVectorElementType, packedType, fixedTypedVectorElementType } from './value-type-util.js' +import { indirect, keyForIndex, keyIndex, readFloat, readInt, readUInt } from './reference-util.js' +import { fromUTF8Array } from './flexbuffers-util.js'; +import { BitWidth } from './bit-width.js'; + +export function toReference(buffer: ArrayBuffer): Reference { + const len = buffer.byteLength; + + if (len < 3) { + throw "Buffer needs to be bigger than 3"; + } + + const dataView = new DataView(buffer); + const byteWidth = dataView.getUint8(len - 1); + const packedType = dataView.getUint8(len - 2); + const parentWidth = fromByteWidth(byteWidth); + const offset = len - byteWidth - 2; + + return new Reference(dataView, offset, parentWidth, packedType, "/") +} + +function valueForIndexWithKey(index: number, key: string, dataView: DataView, offset: number, parentWidth: number, byteWidth: number, length: number, path: string): Reference { + const _indirect = indirect(dataView, offset, parentWidth); + const elementOffset = _indirect + index * byteWidth; + const packedType = dataView.getUint8(_indirect + length * byteWidth + index); + return new Reference(dataView, elementOffset, fromByteWidth(byteWidth), packedType, `${path}/${key}`) +} + +export class Reference { + private readonly byteWidth: number + private readonly valueType: ValueType + private _length = -1 + constructor(private dataView: DataView, private offset: number, private parentWidth: number, private packedType: ValueType, private path: string) { + this.byteWidth = 1 << (packedType & 3) + this.valueType = packedType >> 2 + } + + isNull(): boolean { return this.valueType === ValueType.NULL; } + isNumber(): boolean { return isNumber(this.valueType) || isIndirectNumber(this.valueType); } + isFloat(): boolean { return ValueType.FLOAT === this.valueType || ValueType.INDIRECT_FLOAT === this.valueType; } + isInt(): boolean { return this.isNumber() && !this.isFloat(); } + isString(): boolean { return ValueType.STRING === this.valueType || ValueType.KEY === this.valueType; } + isBool(): boolean { return ValueType.BOOL === this.valueType; } + isBlob(): boolean { return ValueType.BLOB === this.valueType; } + isVector(): boolean { return isAVector(this.valueType); } + isMap(): boolean { return ValueType.MAP === this.valueType; } + + boolValue(): boolean | null { + if (this.isBool()) { + return readInt(this.dataView, this.offset, this.parentWidth) > 0; + } + return null; + } + + intValue(): number | bigint | null { + if (this.valueType === ValueType.INT) { + return readInt(this.dataView, this.offset, this.parentWidth); + } + if (this.valueType === ValueType.UINT) { + return readUInt(this.dataView, this.offset, this.parentWidth); + } + if (this.valueType === ValueType.INDIRECT_INT) { + return readInt(this.dataView, indirect(this.dataView, this.offset, this.parentWidth), fromByteWidth(this.byteWidth)); + } + if (this.valueType === ValueType.INDIRECT_UINT) { + return readUInt(this.dataView, indirect(this.dataView, this.offset, this.parentWidth), fromByteWidth(this.byteWidth)); + } + return null; + } + + floatValue(): number | null { + if (this.valueType === ValueType.FLOAT) { + return readFloat(this.dataView, this.offset, this.parentWidth); + } + if (this.valueType === ValueType.INDIRECT_FLOAT) { + return readFloat(this.dataView, indirect(this.dataView, this.offset, this.parentWidth), fromByteWidth(this.byteWidth)); + } + return null; + } + + numericValue(): number | bigint | null { return this.floatValue() || this.intValue()} + + stringValue(): string | null { + if (this.valueType === ValueType.STRING || this.valueType === ValueType.KEY) { + const begin = indirect(this.dataView, this.offset, this.parentWidth); + return fromUTF8Array(new Uint8Array(this.dataView.buffer, begin, this.length())); + } + return null; + } + + blobValue(): Uint8Array | null { + if (this.isBlob()) { + const begin = indirect(this.dataView, this.offset, this.parentWidth); + return new Uint8Array(this.dataView.buffer, begin, this.length()); + } + return null; + } + + get(key: number): Reference { + const length = this.length(); + if (Number.isInteger(key) && isAVector(this.valueType)) { + if (key >= length || key < 0) { + throw `Key: [${key}] is not applicable on ${this.path} of ${this.valueType} length: ${length}`; + } + const _indirect = indirect(this.dataView, this.offset, this.parentWidth); + const elementOffset = _indirect + key * this.byteWidth; + let _packedType = this.dataView.getUint8(_indirect + length * this.byteWidth + key); + if (isTypedVector(this.valueType)) { + const _valueType = typedVectorElementType(this.valueType); + _packedType = packedType(_valueType, BitWidth.WIDTH8); + } else if (isFixedTypedVector(this.valueType)) { + const _valueType = fixedTypedVectorElementType(this.valueType); + _packedType = packedType(_valueType, BitWidth.WIDTH8); + } + return new Reference(this.dataView, elementOffset, fromByteWidth(this.byteWidth), _packedType, `${this.path}[${key}]`); + } + if (typeof key === 'string') { + const index = keyIndex(key, this.dataView, this.offset, this.parentWidth, this.byteWidth, length); + if (index !== null) { + return valueForIndexWithKey(index, key, this.dataView, this.offset, this.parentWidth, this.byteWidth, length, this.path) + } + } + throw `Key [${key}] is not applicable on ${this.path} of ${this.valueType}`; + } + + length(): number { + let size; + if (this._length > -1) { + return this._length; + } + if (isFixedTypedVector(this.valueType)) { + this._length = fixedTypedVectorElementSize(this.valueType); + } else if (this.valueType === ValueType.BLOB + || this.valueType === ValueType.MAP + || isAVector(this.valueType)) { + this._length = readUInt(this.dataView, indirect(this.dataView, this.offset, this.parentWidth) - this.byteWidth, fromByteWidth(this.byteWidth)) as number + } else if (this.valueType === ValueType.NULL) { + this._length = 0; + } else if (this.valueType === ValueType.STRING) { + const _indirect = indirect(this.dataView, this.offset, this.parentWidth); + let sizeByteWidth = this.byteWidth; + size = readUInt(this.dataView, _indirect - sizeByteWidth, fromByteWidth(this.byteWidth)); + while (this.dataView.getInt8(_indirect + (size as number)) !== 0) { + sizeByteWidth <<= 1; + size = readUInt(this.dataView, _indirect - sizeByteWidth, fromByteWidth(this.byteWidth)); + } + this._length = size as number; + } else if (this.valueType === ValueType.KEY) { + const _indirect = indirect(this.dataView, this.offset, this.parentWidth); + size = 1; + while (this.dataView.getInt8(_indirect + size) !== 0) { + size++; + } + this._length = size; + } else { + this._length = 1; + } + return Number(this._length); + } + + toObject(): unknown { + const length = this.length(); + if (this.isVector()) { + const result = []; + for (let i = 0; i < length; i++) { + result.push(this.get(i).toObject()); + } + return result; + } + if (this.isMap()) { + const result: Record = {}; + for (let i = 0; i < length; i++) { + const key = keyForIndex(i, this.dataView, this.offset, this.parentWidth, this.byteWidth); + result[key] = valueForIndexWithKey(i, key, this.dataView, this.offset, this.parentWidth, this.byteWidth, length, this.path).toObject(); + } + return result; + } + if (this.isNull()) { + return null; + } + if (this.isBool()) { + return this.boolValue(); + } + if (this.isNumber()) { + return this.numericValue(); + } + return this.blobValue() || this.stringValue(); + } +} diff --git a/third_party/flatbuffers/ts/flexbuffers/stack-value.ts b/third_party/flatbuffers/ts/flexbuffers/stack-value.ts new file mode 100644 index 00000000000..010641701b0 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/stack-value.ts @@ -0,0 +1,61 @@ +import { Builder } from './builder.js' +import { BitWidth } from './bit-width.js' +import { paddingSize, uwidth, fromByteWidth } from './bit-width-util.js' +import { ValueType } from './value-type.js' +import { isInline, packedType } from './value-type-util.js' + +export class StackValue { + constructor(private builder: Builder, public type: ValueType, public width: number, public value: number | boolean | null = null, public offset: number = 0) { + + } + + elementWidth(size: number, index: number): BitWidth { + if (isInline(this.type)) return this.width; + for (let i = 0; i < 4; i++) { + const width = 1 << i; + const offsetLoc = size + paddingSize(size, width) + index * width; + const offset = offsetLoc - this.offset; + const bitWidth = uwidth(offset); + if (1 << bitWidth === width) { + return bitWidth; + } + } + throw `Element is unknown. Size: ${size} at index: ${index}. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new`; + } + + writeToBuffer(byteWidth: number): void { + const newOffset = this.builder.computeOffset(byteWidth); + if (this.type === ValueType.FLOAT) { + if (this.width === BitWidth.WIDTH32) { + this.builder.view.setFloat32(this.builder.offset, this.value as number, true); + } else { + this.builder.view.setFloat64(this.builder.offset, this.value as number, true); + } + } else if (this.type === ValueType.INT) { + const bitWidth = fromByteWidth(byteWidth); + this.builder.pushInt(this.value as number, bitWidth); + } else if (this.type === ValueType.UINT) { + const bitWidth = fromByteWidth(byteWidth); + this.builder.pushUInt(this.value as number, bitWidth); + } else if (this.type === ValueType.NULL) { + this.builder.pushInt(0, this.width); + } else if (this.type === ValueType.BOOL) { + this.builder.pushInt(this.value ? 1 : 0, this.width); + } else { + throw `Unexpected type: ${this.type}. This might be a bug. Please create an issue https://github.com/google/flatbuffers/issues/new` + } + this.offset = newOffset; + } + + storedWidth(width = BitWidth.WIDTH8): BitWidth { + return isInline(this.type) ? Math.max(width, this.width) : this.width; + } + + storedPackedType(width = BitWidth.WIDTH8): ValueType { + return packedType(this.type, this.storedWidth(width)); + } + + isOffset(): boolean { + return !isInline(this.type) + } +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/flexbuffers/value-type-util.ts b/third_party/flatbuffers/ts/flexbuffers/value-type-util.ts new file mode 100644 index 00000000000..784977d4ba9 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/value-type-util.ts @@ -0,0 +1,64 @@ +import { ValueType } from './value-type.js' + +export function isInline(value: ValueType): boolean { + return value === ValueType.BOOL + || value <= ValueType.FLOAT; +} + +export function isNumber(value: ValueType): boolean { + return value >= ValueType.INT + && value <= ValueType.FLOAT; +} + +export function isIndirectNumber(value: ValueType): boolean { + return value >= ValueType.INDIRECT_INT + && value <= ValueType.INDIRECT_FLOAT; +} + +export function isTypedVectorElement(value: ValueType): boolean { + return value === ValueType.BOOL + || (value >= ValueType.INT + && value <= ValueType.STRING); +} + +export function isTypedVector(value: ValueType): boolean { + return value === ValueType.VECTOR_BOOL + || (value >= ValueType.VECTOR_INT + && value <= ValueType.VECTOR_STRING_DEPRECATED); +} + +export function isFixedTypedVector(value: ValueType): boolean { + return value >= ValueType.VECTOR_INT2 + && value <= ValueType.VECTOR_FLOAT4; +} + +export function isAVector(value: ValueType): boolean { + return isTypedVector(value) + || isFixedTypedVector(value) + || value === ValueType.VECTOR; +} + +export function toTypedVector(valueType: ValueType, length: number): ValueType { + if (length === 0) return valueType - ValueType.INT + ValueType.VECTOR_INT; + if (length === 2) return valueType - ValueType.INT + ValueType.VECTOR_INT2; + if (length === 3) return valueType - ValueType.INT + ValueType.VECTOR_INT3; + if (length === 4) return valueType - ValueType.INT + ValueType.VECTOR_INT4; + throw "Unexpected length " + length; +} + +export function typedVectorElementType(valueType: ValueType): ValueType { + return valueType - ValueType.VECTOR_INT + ValueType.INT; +} + +export function fixedTypedVectorElementType(valueType: ValueType): ValueType { + return ((valueType - ValueType.VECTOR_INT2) % 3) + ValueType.INT; +} + +export function fixedTypedVectorElementSize(valueType: ValueType): ValueType { + // The x / y >> 0 trick is to have an int division. Suppose to be faster than Math.floor() + return (((valueType - ValueType.VECTOR_INT2) / 3) >> 0) + 2; +} + +export function packedType(valueType: ValueType, bitWidth: number): ValueType { + return bitWidth | (valueType << 2); +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/flexbuffers/value-type.ts b/third_party/flatbuffers/ts/flexbuffers/value-type.ts new file mode 100644 index 00000000000..9c88ba26d21 --- /dev/null +++ b/third_party/flatbuffers/ts/flexbuffers/value-type.ts @@ -0,0 +1,30 @@ +export enum ValueType { + NULL = 0, + INT = 1, + UINT = 2, + FLOAT = 3, + KEY = 4, + STRING = 5, + INDIRECT_INT = 6, + INDIRECT_UINT = 7, + INDIRECT_FLOAT = 8, + MAP = 9, + VECTOR = 10, + VECTOR_INT = 11, + VECTOR_UINT = 12, + VECTOR_FLOAT = 13, + VECTOR_KEY = 14, + VECTOR_STRING_DEPRECATED = 15, + VECTOR_INT2 = 16, + VECTOR_UINT2 = 17, + VECTOR_FLOAT2 = 18, + VECTOR_INT3 = 19, + VECTOR_UINT3 = 20, + VECTOR_FLOAT3 = 21, + VECTOR_INT4 = 22, + VECTOR_UINT4 = 23, + VECTOR_FLOAT4 = 24, + BLOB = 25, + BOOL = 26, + VECTOR_BOOL = 36, +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/package.json b/third_party/flatbuffers/ts/package.json new file mode 120000 index 00000000000..4e26811d416 --- /dev/null +++ b/third_party/flatbuffers/ts/package.json @@ -0,0 +1 @@ +../package.json \ No newline at end of file diff --git a/third_party/flatbuffers/ts/pnpm-lock.yaml b/third_party/flatbuffers/ts/pnpm-lock.yaml new file mode 120000 index 00000000000..c8d5d6ebce4 --- /dev/null +++ b/third_party/flatbuffers/ts/pnpm-lock.yaml @@ -0,0 +1 @@ +../pnpm-lock.yaml \ No newline at end of file diff --git a/third_party/flatbuffers/ts/types.ts b/third_party/flatbuffers/ts/types.ts new file mode 100644 index 00000000000..851486c2100 --- /dev/null +++ b/third_party/flatbuffers/ts/types.ts @@ -0,0 +1,17 @@ +import { ByteBuffer } from './byte-buffer.js' +import { Builder } from './builder.js' + +export type Offset = number; + +export type Table = { + bb: ByteBuffer + bb_pos: number +}; + +export interface IGeneratedObject { + pack(builder:Builder): Offset +} + +export interface IUnpackableObject { + unpack(): T +} \ No newline at end of file diff --git a/third_party/flatbuffers/ts/utils.ts b/third_party/flatbuffers/ts/utils.ts new file mode 100644 index 00000000000..a2902e3cf6b --- /dev/null +++ b/third_party/flatbuffers/ts/utils.ts @@ -0,0 +1,4 @@ +export const int32 = new Int32Array(2); +export const float32 = new Float32Array(int32.buffer); +export const float64 = new Float64Array(int32.buffer); +export const isLittleEndian = new Uint16Array(new Uint8Array([1, 0]).buffer)[0] === 1; \ No newline at end of file diff --git a/third_party/flatbuffers/typescript.bzl b/third_party/flatbuffers/typescript.bzl index 63c1218c64a..c26211b3293 100644 --- a/third_party/flatbuffers/typescript.bzl +++ b/third_party/flatbuffers/typescript.bzl @@ -47,7 +47,7 @@ def flatbuffer_ts_library( reflection binaries for the schemas. """ srcs_lib = "%s_srcs" % (name) - out_base = [s.replace(".fbs", "").split("/")[-1].split(":")[-1] for s in srcs] + out_base = [native.package_relative_label(s).name.removesuffix(".fbs") for s in srcs] if len(srcs) != 1: fail("flatbuffer_ts_library only supports one .fbs file per target currently.") @@ -69,7 +69,7 @@ def flatbuffer_ts_library( reflection_name = reflection_name, reflection_visibility = visibility, target_compatible_with = target_compatible_with, - flatc_path = "@com_github_google_flatbuffers//ts:compile_flat_file", + flatc_path = Label("//ts:compile_flat_file"), toolchains = ["@aspect_rules_esbuild//esbuild:resolved_toolchain"], tools = ["@aspect_rules_esbuild//esbuild:resolved_toolchain"], )
{ + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):D { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsD(bb:flatbuffers.ByteBuffer, obj?:D):D { + return (obj || new D()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsD(bb:flatbuffers.ByteBuffer, obj?:D):D { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new D()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +testUnionType():ABC { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : ABC.NONE; +} + +testUnion(obj:any):any|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__union(obj, this.bb_pos + offset) : null; +} + +testVectorOfUnionType(index: number):ABC|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readInt32(this.bb!.__vector(this.bb_pos + offset) + index * 4) : 0; +} + +testVectorOfUnionTypeLength():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +testVectorOfUnionTypeArray():Int32Array|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? new Int32Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +testVectorOfUnion(index: number, obj:any):any|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__union(obj, this.bb!.__vector(this.bb_pos + offset) + index * 4) : null; +} + +testVectorOfUnionLength():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static getFullyQualifiedName():string { + return 'UnionUnderlyingType.D'; +} + +static startD(builder:flatbuffers.Builder) { + builder.startObject(4); +} + +static addTestUnionType(builder:flatbuffers.Builder, testUnionType:ABC) { + builder.addFieldInt32(0, testUnionType, ABC.NONE); +} + +static addTestUnion(builder:flatbuffers.Builder, testUnionOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, testUnionOffset, 0); +} + +static addTestVectorOfUnionType(builder:flatbuffers.Builder, testVectorOfUnionTypeOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, testVectorOfUnionTypeOffset, 0); +} + +static createTestVectorOfUnionTypeVector(builder:flatbuffers.Builder, data:ABC[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt32(data[i]!); + } + return builder.endVector(); +} + +static startTestVectorOfUnionTypeVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static addTestVectorOfUnion(builder:flatbuffers.Builder, testVectorOfUnionOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, testVectorOfUnionOffset, 0); +} + +static createTestVectorOfUnionVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startTestVectorOfUnionVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endD(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createD(builder:flatbuffers.Builder, testUnionType:ABC, testUnionOffset:flatbuffers.Offset, testVectorOfUnionTypeOffset:flatbuffers.Offset, testVectorOfUnionOffset:flatbuffers.Offset):flatbuffers.Offset { + D.startD(builder); + D.addTestUnionType(builder, testUnionType); + D.addTestUnion(builder, testUnionOffset); + D.addTestVectorOfUnionType(builder, testVectorOfUnionTypeOffset); + D.addTestVectorOfUnion(builder, testVectorOfUnionOffset); + return D.endD(builder); +} + +unpack(): DT { + return new DT( + this.testUnionType(), + (() => { + const temp = unionToAbc(this.testUnionType(), this.testUnion.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(), + this.bb!.createScalarList(this.testVectorOfUnionType.bind(this), this.testVectorOfUnionTypeLength()), + (() => { + const ret: (AT|BT|CT)[] = []; + for(let targetEnumIndex = 0; targetEnumIndex < this.testVectorOfUnionTypeLength(); ++targetEnumIndex) { + const targetEnum = this.testVectorOfUnionType(targetEnumIndex); + if(targetEnum === null || ABC[targetEnum!] === 'NONE') { continue; } + + const temp = unionListToAbc(targetEnum, this.testVectorOfUnion.bind(this), targetEnumIndex); + if(temp === null) { continue; } + ret.push(temp.unpack()); + } + return ret; + })() + ); +} + + +unpackTo(_o: DT): void { + _o.testUnionType = this.testUnionType(); + _o.testUnion = (() => { + const temp = unionToAbc(this.testUnionType(), this.testUnion.bind(this)); + if(temp === null) { return null; } + return temp.unpack() + })(); + _o.testVectorOfUnionType = this.bb!.createScalarList(this.testVectorOfUnionType.bind(this), this.testVectorOfUnionTypeLength()); + _o.testVectorOfUnion = (() => { + const ret: (AT|BT|CT)[] = []; + for(let targetEnumIndex = 0; targetEnumIndex < this.testVectorOfUnionTypeLength(); ++targetEnumIndex) { + const targetEnum = this.testVectorOfUnionType(targetEnumIndex); + if(targetEnum === null || ABC[targetEnum!] === 'NONE') { continue; } + + const temp = unionListToAbc(targetEnum, this.testVectorOfUnion.bind(this), targetEnumIndex); + if(temp === null) { continue; } + ret.push(temp.unpack()); + } + return ret; + })(); +} +} + +export class DT implements flatbuffers.IGeneratedObject { +constructor( + public testUnionType: ABC = ABC.NONE, + public testUnion: AT|BT|CT|null = null, + public testVectorOfUnionType: (ABC)[] = [], + public testVectorOfUnion: (AT|BT|CT)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const testUnion = builder.createObjectOffset(this.testUnion); + const testVectorOfUnionType = D.createTestVectorOfUnionTypeVector(builder, this.testVectorOfUnionType); + const testVectorOfUnion = D.createTestVectorOfUnionVector(builder, builder.createObjectOffsetList(this.testVectorOfUnion)); + + return D.createD(builder, + this.testUnionType, + testUnion, + testVectorOfUnionType, + testVectorOfUnion + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_underlying_type_test.d.ts b/third_party/flatbuffers/tests/ts/union_underlying_type_test.d.ts new file mode 100644 index 00000000000..2b5d2756b29 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_underlying_type_test.d.ts @@ -0,0 +1 @@ +export * as UnionUnderlyingType from './union-underlying-type.js'; diff --git a/third_party/flatbuffers/tests/ts/union_underlying_type_test.js b/third_party/flatbuffers/tests/ts/union_underlying_type_test.js new file mode 100644 index 00000000000..d4649b33622 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_underlying_type_test.js @@ -0,0 +1,3 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export * as UnionUnderlyingType from './union-underlying-type.js'; diff --git a/third_party/flatbuffers/tests/ts/union_underlying_type_test.ts b/third_party/flatbuffers/tests/ts/union_underlying_type_test.ts new file mode 100644 index 00000000000..973961609ab --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_underlying_type_test.ts @@ -0,0 +1,5 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export * as UnionUnderlyingType from './union-underlying-type.js'; diff --git a/third_party/flatbuffers/tests/ts/union_vector/attacker.d.ts b/third_party/flatbuffers/tests/ts/union_vector/attacker.d.ts new file mode 100644 index 00000000000..302e1d0e950 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/attacker.d.ts @@ -0,0 +1,22 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Attacker implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Attacker; + static getRootAsAttacker(bb: flatbuffers.ByteBuffer, obj?: Attacker): Attacker; + static getSizePrefixedRootAsAttacker(bb: flatbuffers.ByteBuffer, obj?: Attacker): Attacker; + swordAttackDamage(): number; + mutate_sword_attack_damage(value: number): boolean; + static getFullyQualifiedName(): string; + static startAttacker(builder: flatbuffers.Builder): void; + static addSwordAttackDamage(builder: flatbuffers.Builder, swordAttackDamage: number): void; + static endAttacker(builder: flatbuffers.Builder): flatbuffers.Offset; + static createAttacker(builder: flatbuffers.Builder, swordAttackDamage: number): flatbuffers.Offset; + unpack(): AttackerT; + unpackTo(_o: AttackerT): void; +} +export declare class AttackerT implements flatbuffers.IGeneratedObject { + swordAttackDamage: number; + constructor(swordAttackDamage?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/attacker.js b/third_party/flatbuffers/tests/ts/union_vector/attacker.js new file mode 100644 index 00000000000..28ffc4a77b8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/attacker.js @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class Attacker { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsAttacker(bb, obj) { + return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsAttacker(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + swordAttackDamage() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_sword_attack_damage(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'Attacker'; + } + static startAttacker(builder) { + builder.startObject(1); + } + static addSwordAttackDamage(builder, swordAttackDamage) { + builder.addFieldInt32(0, swordAttackDamage, 0); + } + static endAttacker(builder) { + const offset = builder.endObject(); + return offset; + } + static createAttacker(builder, swordAttackDamage) { + Attacker.startAttacker(builder); + Attacker.addSwordAttackDamage(builder, swordAttackDamage); + return Attacker.endAttacker(builder); + } + unpack() { + return new AttackerT(this.swordAttackDamage()); + } + unpackTo(_o) { + _o.swordAttackDamage = this.swordAttackDamage(); + } +} +export class AttackerT { + constructor(swordAttackDamage = 0) { + this.swordAttackDamage = swordAttackDamage; + } + pack(builder) { + return Attacker.createAttacker(builder, this.swordAttackDamage); + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/attacker.ts b/third_party/flatbuffers/tests/ts/union_vector/attacker.ts new file mode 100644 index 00000000000..32675bcd5ea --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/attacker.ts @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Attacker implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Attacker { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsAttacker(bb:flatbuffers.ByteBuffer, obj?:Attacker):Attacker { + return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsAttacker(bb:flatbuffers.ByteBuffer, obj?:Attacker):Attacker { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +swordAttackDamage():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_sword_attack_damage(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'Attacker'; +} + +static startAttacker(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addSwordAttackDamage(builder:flatbuffers.Builder, swordAttackDamage:number) { + builder.addFieldInt32(0, swordAttackDamage, 0); +} + +static endAttacker(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createAttacker(builder:flatbuffers.Builder, swordAttackDamage:number):flatbuffers.Offset { + Attacker.startAttacker(builder); + Attacker.addSwordAttackDamage(builder, swordAttackDamage); + return Attacker.endAttacker(builder); +} + +unpack(): AttackerT { + return new AttackerT( + this.swordAttackDamage() + ); +} + + +unpackTo(_o: AttackerT): void { + _o.swordAttackDamage = this.swordAttackDamage(); +} +} + +export class AttackerT implements flatbuffers.IGeneratedObject { +constructor( + public swordAttackDamage: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Attacker.createAttacker(builder, + this.swordAttackDamage + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/book-reader.d.ts b/third_party/flatbuffers/tests/ts/union_vector/book-reader.d.ts new file mode 100644 index 00000000000..42b7198fef1 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/book-reader.d.ts @@ -0,0 +1,18 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class BookReader implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): BookReader; + booksRead(): number; + mutate_books_read(value: number): boolean; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createBookReader(builder: flatbuffers.Builder, books_read: number): flatbuffers.Offset; + unpack(): BookReaderT; + unpackTo(_o: BookReaderT): void; +} +export declare class BookReaderT implements flatbuffers.IGeneratedObject { + booksRead: number; + constructor(booksRead?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/book-reader.js b/third_party/flatbuffers/tests/ts/union_vector/book-reader.js new file mode 100644 index 00000000000..0d9e1a57cd4 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/book-reader.js @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class BookReader { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + booksRead() { + return this.bb.readInt32(this.bb_pos); + } + mutate_books_read(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return 'BookReader'; + } + static sizeOf() { + return 4; + } + static createBookReader(builder, books_read) { + builder.prep(4, 4); + builder.writeInt32(books_read); + return builder.offset(); + } + unpack() { + return new BookReaderT(this.booksRead()); + } + unpackTo(_o) { + _o.booksRead = this.booksRead(); + } +} +export class BookReaderT { + constructor(booksRead = 0) { + this.booksRead = booksRead; + } + pack(builder) { + return BookReader.createBookReader(builder, this.booksRead); + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/book-reader.ts b/third_party/flatbuffers/tests/ts/union_vector/book-reader.ts new file mode 100644 index 00000000000..2052fdcb202 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/book-reader.ts @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class BookReader implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):BookReader { + this.bb_pos = i; + this.bb = bb; + return this; +} + +booksRead():number { + return this.bb!.readInt32(this.bb_pos); +} + +mutate_books_read(value:number):boolean { + this.bb!.writeInt32(this.bb_pos + 0, value); + return true; +} + +static getFullyQualifiedName():string { + return 'BookReader'; +} + +static sizeOf():number { + return 4; +} + +static createBookReader(builder:flatbuffers.Builder, books_read: number):flatbuffers.Offset { + builder.prep(4, 4); + builder.writeInt32(books_read); + return builder.offset(); +} + + +unpack(): BookReaderT { + return new BookReaderT( + this.booksRead() + ); +} + + +unpackTo(_o: BookReaderT): void { + _o.booksRead = this.booksRead(); +} +} + +export class BookReaderT implements flatbuffers.IGeneratedObject { +constructor( + public booksRead: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return BookReader.createBookReader(builder, + this.booksRead + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/character.d.ts b/third_party/flatbuffers/tests/ts/union_vector/character.d.ts new file mode 100644 index 00000000000..dbdb4d960c9 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/character.d.ts @@ -0,0 +1,14 @@ +import { Attacker } from './attacker.js'; +import { BookReader } from './book-reader.js'; +import { Rapunzel } from './rapunzel.js'; +export declare enum Character { + NONE = 0, + MuLan = 1, + Rapunzel = 2, + Belle = 3, + BookFan = 4, + Other = 5, + Unused = 6 +} +export declare function unionToCharacter(type: Character, accessor: (obj: Attacker | BookReader | Rapunzel | string) => Attacker | BookReader | Rapunzel | string | null): Attacker | BookReader | Rapunzel | string | null; +export declare function unionListToCharacter(type: Character, accessor: (index: number, obj: Attacker | BookReader | Rapunzel | string) => Attacker | BookReader | Rapunzel | string | null, index: number): Attacker | BookReader | Rapunzel | string | null; diff --git a/third_party/flatbuffers/tests/ts/union_vector/character.js b/third_party/flatbuffers/tests/ts/union_vector/character.js new file mode 100644 index 00000000000..dfa7a1914b3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/character.js @@ -0,0 +1,39 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import { Attacker } from './attacker.js'; +import { BookReader } from './book-reader.js'; +import { Rapunzel } from './rapunzel.js'; +export var Character; +(function (Character) { + Character[Character["NONE"] = 0] = "NONE"; + Character[Character["MuLan"] = 1] = "MuLan"; + Character[Character["Rapunzel"] = 2] = "Rapunzel"; + Character[Character["Belle"] = 3] = "Belle"; + Character[Character["BookFan"] = 4] = "BookFan"; + Character[Character["Other"] = 5] = "Other"; + Character[Character["Unused"] = 6] = "Unused"; +})(Character || (Character = {})); +export function unionToCharacter(type, accessor) { + switch (Character[type]) { + case 'NONE': return null; + case 'MuLan': return accessor(new Attacker()); + case 'Rapunzel': return accessor(new Rapunzel()); + case 'Belle': return accessor(new BookReader()); + case 'BookFan': return accessor(new BookReader()); + case 'Other': return accessor(''); + case 'Unused': return accessor(''); + default: return null; + } +} +export function unionListToCharacter(type, accessor, index) { + switch (Character[type]) { + case 'NONE': return null; + case 'MuLan': return accessor(index, new Attacker()); + case 'Rapunzel': return accessor(index, new Rapunzel()); + case 'Belle': return accessor(index, new BookReader()); + case 'BookFan': return accessor(index, new BookReader()); + case 'Other': return accessor(index, ''); + case 'Unused': return accessor(index, ''); + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/character.ts b/third_party/flatbuffers/tests/ts/union_vector/character.ts new file mode 100644 index 00000000000..6bb0ffd0067 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/character.ts @@ -0,0 +1,51 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import { Attacker, AttackerT } from './attacker.js'; +import { BookReader, BookReaderT } from './book-reader.js'; +import { Rapunzel, RapunzelT } from './rapunzel.js'; + + +export enum Character { + NONE = 0, + MuLan = 1, + Rapunzel = 2, + Belle = 3, + BookFan = 4, + Other = 5, + Unused = 6 +} + +export function unionToCharacter( + type: Character, + accessor: (obj:Attacker|BookReader|Rapunzel|string) => Attacker|BookReader|Rapunzel|string|null +): Attacker|BookReader|Rapunzel|string|null { + switch(Character[type]) { + case 'NONE': return null; + case 'MuLan': return accessor(new Attacker())! as Attacker; + case 'Rapunzel': return accessor(new Rapunzel())! as Rapunzel; + case 'Belle': return accessor(new BookReader())! as BookReader; + case 'BookFan': return accessor(new BookReader())! as BookReader; + case 'Other': return accessor('') as string; + case 'Unused': return accessor('') as string; + default: return null; + } +} + +export function unionListToCharacter( + type: Character, + accessor: (index: number, obj:Attacker|BookReader|Rapunzel|string) => Attacker|BookReader|Rapunzel|string|null, + index: number +): Attacker|BookReader|Rapunzel|string|null { + switch(Character[type]) { + case 'NONE': return null; + case 'MuLan': return accessor(index, new Attacker())! as Attacker; + case 'Rapunzel': return accessor(index, new Rapunzel())! as Rapunzel; + case 'Belle': return accessor(index, new BookReader())! as BookReader; + case 'BookFan': return accessor(index, new BookReader())! as BookReader; + case 'Other': return accessor(index, '') as string; + case 'Unused': return accessor(index, '') as string; + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/falling-tub.d.ts b/third_party/flatbuffers/tests/ts/union_vector/falling-tub.d.ts new file mode 100644 index 00000000000..3cde3fc7149 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/falling-tub.d.ts @@ -0,0 +1,18 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class FallingTub implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): FallingTub; + weight(): number; + mutate_weight(value: number): boolean; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createFallingTub(builder: flatbuffers.Builder, weight: number): flatbuffers.Offset; + unpack(): FallingTubT; + unpackTo(_o: FallingTubT): void; +} +export declare class FallingTubT implements flatbuffers.IGeneratedObject { + weight: number; + constructor(weight?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/falling-tub.js b/third_party/flatbuffers/tests/ts/union_vector/falling-tub.js new file mode 100644 index 00000000000..d3c4dfe05af --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/falling-tub.js @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class FallingTub { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + weight() { + return this.bb.readInt32(this.bb_pos); + } + mutate_weight(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return 'FallingTub'; + } + static sizeOf() { + return 4; + } + static createFallingTub(builder, weight) { + builder.prep(4, 4); + builder.writeInt32(weight); + return builder.offset(); + } + unpack() { + return new FallingTubT(this.weight()); + } + unpackTo(_o) { + _o.weight = this.weight(); + } +} +export class FallingTubT { + constructor(weight = 0) { + this.weight = weight; + } + pack(builder) { + return FallingTub.createFallingTub(builder, this.weight); + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/falling-tub.ts b/third_party/flatbuffers/tests/ts/union_vector/falling-tub.ts new file mode 100644 index 00000000000..32fb9fa4a15 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/falling-tub.ts @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class FallingTub implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):FallingTub { + this.bb_pos = i; + this.bb = bb; + return this; +} + +weight():number { + return this.bb!.readInt32(this.bb_pos); +} + +mutate_weight(value:number):boolean { + this.bb!.writeInt32(this.bb_pos + 0, value); + return true; +} + +static getFullyQualifiedName():string { + return 'FallingTub'; +} + +static sizeOf():number { + return 4; +} + +static createFallingTub(builder:flatbuffers.Builder, weight: number):flatbuffers.Offset { + builder.prep(4, 4); + builder.writeInt32(weight); + return builder.offset(); +} + + +unpack(): FallingTubT { + return new FallingTubT( + this.weight() + ); +} + + +unpackTo(_o: FallingTubT): void { + _o.weight = this.weight(); +} +} + +export class FallingTubT implements flatbuffers.IGeneratedObject { +constructor( + public weight: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return FallingTub.createFallingTub(builder, + this.weight + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/gadget.d.ts b/third_party/flatbuffers/tests/ts/union_vector/gadget.d.ts new file mode 100644 index 00000000000..46eaa5e7c6c --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/gadget.d.ts @@ -0,0 +1,9 @@ +import { FallingTub } from './falling-tub.js'; +import { HandFan } from './hand-fan.js'; +export declare enum Gadget { + NONE = 0, + FallingTub = 1, + HandFan = 2 +} +export declare function unionToGadget(type: Gadget, accessor: (obj: FallingTub | HandFan) => FallingTub | HandFan | null): FallingTub | HandFan | null; +export declare function unionListToGadget(type: Gadget, accessor: (index: number, obj: FallingTub | HandFan) => FallingTub | HandFan | null, index: number): FallingTub | HandFan | null; diff --git a/third_party/flatbuffers/tests/ts/union_vector/gadget.js b/third_party/flatbuffers/tests/ts/union_vector/gadget.js new file mode 100644 index 00000000000..1618ccce0fb --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/gadget.js @@ -0,0 +1,26 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import { FallingTub } from './falling-tub.js'; +import { HandFan } from './hand-fan.js'; +export var Gadget; +(function (Gadget) { + Gadget[Gadget["NONE"] = 0] = "NONE"; + Gadget[Gadget["FallingTub"] = 1] = "FallingTub"; + Gadget[Gadget["HandFan"] = 2] = "HandFan"; +})(Gadget || (Gadget = {})); +export function unionToGadget(type, accessor) { + switch (Gadget[type]) { + case 'NONE': return null; + case 'FallingTub': return accessor(new FallingTub()); + case 'HandFan': return accessor(new HandFan()); + default: return null; + } +} +export function unionListToGadget(type, accessor, index) { + switch (Gadget[type]) { + case 'NONE': return null; + case 'FallingTub': return accessor(index, new FallingTub()); + case 'HandFan': return accessor(index, new HandFan()); + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/gadget.ts b/third_party/flatbuffers/tests/ts/union_vector/gadget.ts new file mode 100644 index 00000000000..bff9702783e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/gadget.ts @@ -0,0 +1,38 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import { FallingTub, FallingTubT } from './falling-tub.js'; +import { HandFan, HandFanT } from './hand-fan.js'; + + +export enum Gadget { + NONE = 0, + FallingTub = 1, + HandFan = 2 +} + +export function unionToGadget( + type: Gadget, + accessor: (obj:FallingTub|HandFan) => FallingTub|HandFan|null +): FallingTub|HandFan|null { + switch(Gadget[type]) { + case 'NONE': return null; + case 'FallingTub': return accessor(new FallingTub())! as FallingTub; + case 'HandFan': return accessor(new HandFan())! as HandFan; + default: return null; + } +} + +export function unionListToGadget( + type: Gadget, + accessor: (index: number, obj:FallingTub|HandFan) => FallingTub|HandFan|null, + index: number +): FallingTub|HandFan|null { + switch(Gadget[type]) { + case 'NONE': return null; + case 'FallingTub': return accessor(index, new FallingTub())! as FallingTub; + case 'HandFan': return accessor(index, new HandFan())! as HandFan; + default: return null; + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/hand-fan.d.ts b/third_party/flatbuffers/tests/ts/union_vector/hand-fan.d.ts new file mode 100644 index 00000000000..a1981dfdfd5 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/hand-fan.d.ts @@ -0,0 +1,22 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class HandFan implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): HandFan; + static getRootAsHandFan(bb: flatbuffers.ByteBuffer, obj?: HandFan): HandFan; + static getSizePrefixedRootAsHandFan(bb: flatbuffers.ByteBuffer, obj?: HandFan): HandFan; + length(): number; + mutate_length(value: number): boolean; + static getFullyQualifiedName(): string; + static startHandFan(builder: flatbuffers.Builder): void; + static addLength(builder: flatbuffers.Builder, length: number): void; + static endHandFan(builder: flatbuffers.Builder): flatbuffers.Offset; + static createHandFan(builder: flatbuffers.Builder, length: number): flatbuffers.Offset; + unpack(): HandFanT; + unpackTo(_o: HandFanT): void; +} +export declare class HandFanT implements flatbuffers.IGeneratedObject { + length: number; + constructor(length?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/hand-fan.js b/third_party/flatbuffers/tests/ts/union_vector/hand-fan.js new file mode 100644 index 00000000000..b85b6d38caa --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/hand-fan.js @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +export class HandFan { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsHandFan(bb, obj) { + return (obj || new HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsHandFan(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + length() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_length(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return 'HandFan'; + } + static startHandFan(builder) { + builder.startObject(1); + } + static addLength(builder, length) { + builder.addFieldInt32(0, length, 0); + } + static endHandFan(builder) { + const offset = builder.endObject(); + return offset; + } + static createHandFan(builder, length) { + HandFan.startHandFan(builder); + HandFan.addLength(builder, length); + return HandFan.endHandFan(builder); + } + unpack() { + return new HandFanT(this.length()); + } + unpackTo(_o) { + _o.length = this.length(); + } +} +export class HandFanT { + constructor(length = 0) { + this.length = length; + } + pack(builder) { + return HandFan.createHandFan(builder, this.length); + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/hand-fan.ts b/third_party/flatbuffers/tests/ts/union_vector/hand-fan.ts new file mode 100644 index 00000000000..03b809d3d31 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/hand-fan.ts @@ -0,0 +1,89 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class HandFan implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):HandFan { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsHandFan(bb:flatbuffers.ByteBuffer, obj?:HandFan):HandFan { + return (obj || new HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsHandFan(bb:flatbuffers.ByteBuffer, obj?:HandFan):HandFan { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +length():number { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readInt32(this.bb_pos + offset) : 0; +} + +mutate_length(value:number):boolean { + const offset = this.bb!.__offset(this.bb_pos, 4); + + if (offset === 0) { + return false; + } + + this.bb!.writeInt32(this.bb_pos + offset, value); + return true; +} + +static getFullyQualifiedName():string { + return 'HandFan'; +} + +static startHandFan(builder:flatbuffers.Builder) { + builder.startObject(1); +} + +static addLength(builder:flatbuffers.Builder, length:number) { + builder.addFieldInt32(0, length, 0); +} + +static endHandFan(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static createHandFan(builder:flatbuffers.Builder, length:number):flatbuffers.Offset { + HandFan.startHandFan(builder); + HandFan.addLength(builder, length); + return HandFan.endHandFan(builder); +} + +unpack(): HandFanT { + return new HandFanT( + this.length() + ); +} + + +unpackTo(_o: HandFanT): void { + _o.length = this.length(); +} +} + +export class HandFanT implements flatbuffers.IGeneratedObject { +constructor( + public length: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return HandFan.createHandFan(builder, + this.length + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/movie.d.ts b/third_party/flatbuffers/tests/ts/union_vector/movie.d.ts new file mode 100644 index 00000000000..68c9e1671d8 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/movie.d.ts @@ -0,0 +1,44 @@ +import * as flatbuffers from 'flatbuffers'; +import { AttackerT } from './attacker.js'; +import { BookReaderT } from './book-reader.js'; +import { Character } from './character.js'; +import { RapunzelT } from './rapunzel.js'; +export declare class Movie implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Movie; + static getRootAsMovie(bb: flatbuffers.ByteBuffer, obj?: Movie): Movie; + static getSizePrefixedRootAsMovie(bb: flatbuffers.ByteBuffer, obj?: Movie): Movie; + static bufferHasIdentifier(bb: flatbuffers.ByteBuffer): boolean; + mainCharacterType(): Character; + mainCharacter(obj: any | string): any | string | null; + charactersType(index: number): Character | null; + charactersTypeLength(): number; + charactersTypeArray(): Uint8Array | null; + characters(index: number, obj: any | string): any | string | null; + charactersLength(): number; + static getFullyQualifiedName(): string; + static startMovie(builder: flatbuffers.Builder): void; + static addMainCharacterType(builder: flatbuffers.Builder, mainCharacterType: Character): void; + static addMainCharacter(builder: flatbuffers.Builder, mainCharacterOffset: flatbuffers.Offset): void; + static addCharactersType(builder: flatbuffers.Builder, charactersTypeOffset: flatbuffers.Offset): void; + static createCharactersTypeVector(builder: flatbuffers.Builder, data: Character[]): flatbuffers.Offset; + static startCharactersTypeVector(builder: flatbuffers.Builder, numElems: number): void; + static addCharacters(builder: flatbuffers.Builder, charactersOffset: flatbuffers.Offset): void; + static createCharactersVector(builder: flatbuffers.Builder, data: flatbuffers.Offset[]): flatbuffers.Offset; + static startCharactersVector(builder: flatbuffers.Builder, numElems: number): void; + static endMovie(builder: flatbuffers.Builder): flatbuffers.Offset; + static finishMovieBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static finishSizePrefixedMovieBuffer(builder: flatbuffers.Builder, offset: flatbuffers.Offset): void; + static createMovie(builder: flatbuffers.Builder, mainCharacterType: Character, mainCharacterOffset: flatbuffers.Offset, charactersTypeOffset: flatbuffers.Offset, charactersOffset: flatbuffers.Offset): flatbuffers.Offset; + unpack(): MovieT; + unpackTo(_o: MovieT): void; +} +export declare class MovieT implements flatbuffers.IGeneratedObject { + mainCharacterType: Character; + mainCharacter: AttackerT | BookReaderT | RapunzelT | string | null; + charactersType: (Character)[]; + characters: (AttackerT | BookReaderT | RapunzelT | string)[]; + constructor(mainCharacterType?: Character, mainCharacter?: AttackerT | BookReaderT | RapunzelT | string | null, charactersType?: (Character)[], characters?: (AttackerT | BookReaderT | RapunzelT | string)[]); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/movie.js b/third_party/flatbuffers/tests/ts/union_vector/movie.js new file mode 100644 index 00000000000..da5d1fadaa4 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/movie.js @@ -0,0 +1,186 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +import * as flatbuffers from 'flatbuffers'; +import { Character, unionToCharacter, unionListToCharacter } from './character.js'; +export class Movie { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMovie(bb, obj) { + return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMovie(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier('MOVI'); + } + mainCharacterType() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Character.NONE; + } + mainCharacter(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__union_with_string(obj, this.bb_pos + offset) : null; + } + charactersType(index) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + charactersTypeLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + charactersTypeArray() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + characters(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__union_with_string(obj, this.bb.__vector(this.bb_pos + offset) + index * 4) : null; + } + charactersLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return 'Movie'; + } + static startMovie(builder) { + builder.startObject(4); + } + static addMainCharacterType(builder, mainCharacterType) { + builder.addFieldInt8(0, mainCharacterType, Character.NONE); + } + static addMainCharacter(builder, mainCharacterOffset) { + builder.addFieldOffset(1, mainCharacterOffset, 0); + } + static addCharactersType(builder, charactersTypeOffset) { + builder.addFieldOffset(2, charactersTypeOffset, 0); + } + static createCharactersTypeVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startCharactersTypeVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addCharacters(builder, charactersOffset) { + builder.addFieldOffset(3, charactersOffset, 0); + } + static createCharactersVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCharactersVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endMovie(builder) { + const offset = builder.endObject(); + return offset; + } + static finishMovieBuffer(builder, offset) { + builder.finish(offset, 'MOVI'); + } + static finishSizePrefixedMovieBuffer(builder, offset) { + builder.finish(offset, 'MOVI', true); + } + static createMovie(builder, mainCharacterType, mainCharacterOffset, charactersTypeOffset, charactersOffset) { + Movie.startMovie(builder); + Movie.addMainCharacterType(builder, mainCharacterType); + Movie.addMainCharacter(builder, mainCharacterOffset); + Movie.addCharactersType(builder, charactersTypeOffset); + Movie.addCharacters(builder, charactersOffset); + return Movie.endMovie(builder); + } + unpack() { + return new MovieT(this.mainCharacterType(), (() => { + const temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this)); + if (temp === null) { + return null; + } + if (typeof temp === 'string') { + return temp; + } + return temp.unpack(); + })(), this.bb.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()), (() => { + const ret = []; + for (let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) { + const targetEnum = this.charactersType(targetEnumIndex); + if (targetEnum === null || Character[targetEnum] === 'NONE') { + continue; + } + const temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex); + if (temp === null) { + continue; + } + if (typeof temp === 'string') { + ret.push(temp); + continue; + } + ret.push(temp.unpack()); + } + return ret; + })()); + } + unpackTo(_o) { + _o.mainCharacterType = this.mainCharacterType(); + _o.mainCharacter = (() => { + const temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this)); + if (temp === null) { + return null; + } + if (typeof temp === 'string') { + return temp; + } + return temp.unpack(); + })(); + _o.charactersType = this.bb.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()); + _o.characters = (() => { + const ret = []; + for (let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) { + const targetEnum = this.charactersType(targetEnumIndex); + if (targetEnum === null || Character[targetEnum] === 'NONE') { + continue; + } + const temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex); + if (temp === null) { + continue; + } + if (typeof temp === 'string') { + ret.push(temp); + continue; + } + ret.push(temp.unpack()); + } + return ret; + })(); + } +} +export class MovieT { + constructor(mainCharacterType = Character.NONE, mainCharacter = null, charactersType = [], characters = []) { + this.mainCharacterType = mainCharacterType; + this.mainCharacter = mainCharacter; + this.charactersType = charactersType; + this.characters = characters; + } + pack(builder) { + const mainCharacter = builder.createObjectOffset(this.mainCharacter); + const charactersType = Movie.createCharactersTypeVector(builder, this.charactersType); + const characters = Movie.createCharactersVector(builder, builder.createObjectOffsetList(this.characters)); + return Movie.createMovie(builder, this.mainCharacterType, mainCharacter, charactersType, characters); + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/movie.ts b/third_party/flatbuffers/tests/ts/union_vector/movie.ts new file mode 100644 index 00000000000..0e2370a89d2 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/movie.ts @@ -0,0 +1,213 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + +import { Attacker, AttackerT } from './attacker.js'; +import { BookReader, BookReaderT } from './book-reader.js'; +import { Character, unionToCharacter, unionListToCharacter } from './character.js'; +import { Rapunzel, RapunzelT } from './rapunzel.js'; + + +export class Movie implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Movie { + this.bb_pos = i; + this.bb = bb; + return this; +} + +static getRootAsMovie(bb:flatbuffers.ByteBuffer, obj?:Movie):Movie { + return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static getSizePrefixedRootAsMovie(bb:flatbuffers.ByteBuffer, obj?:Movie):Movie { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb); +} + +static bufferHasIdentifier(bb:flatbuffers.ByteBuffer):boolean { + return bb.__has_identifier('MOVI'); +} + +mainCharacterType():Character { + const offset = this.bb!.__offset(this.bb_pos, 4); + return offset ? this.bb!.readUint8(this.bb_pos + offset) : Character.NONE; +} + +mainCharacter(obj:any|string):any|string|null { + const offset = this.bb!.__offset(this.bb_pos, 6); + return offset ? this.bb!.__union_with_string(obj, this.bb_pos + offset) : null; +} + +charactersType(index: number):Character|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.readUint8(this.bb!.__vector(this.bb_pos + offset) + index) : 0; +} + +charactersTypeLength():number { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +charactersTypeArray():Uint8Array|null { + const offset = this.bb!.__offset(this.bb_pos, 8); + return offset ? new Uint8Array(this.bb!.bytes().buffer, this.bb!.bytes().byteOffset + this.bb!.__vector(this.bb_pos + offset), this.bb!.__vector_len(this.bb_pos + offset)) : null; +} + +characters(index: number, obj:any|string):any|string|null { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__union_with_string(obj, this.bb!.__vector(this.bb_pos + offset) + index * 4) : null; +} + +charactersLength():number { + const offset = this.bb!.__offset(this.bb_pos, 10); + return offset ? this.bb!.__vector_len(this.bb_pos + offset) : 0; +} + +static getFullyQualifiedName():string { + return 'Movie'; +} + +static startMovie(builder:flatbuffers.Builder) { + builder.startObject(4); +} + +static addMainCharacterType(builder:flatbuffers.Builder, mainCharacterType:Character) { + builder.addFieldInt8(0, mainCharacterType, Character.NONE); +} + +static addMainCharacter(builder:flatbuffers.Builder, mainCharacterOffset:flatbuffers.Offset) { + builder.addFieldOffset(1, mainCharacterOffset, 0); +} + +static addCharactersType(builder:flatbuffers.Builder, charactersTypeOffset:flatbuffers.Offset) { + builder.addFieldOffset(2, charactersTypeOffset, 0); +} + +static createCharactersTypeVector(builder:flatbuffers.Builder, data:Character[]):flatbuffers.Offset { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]!); + } + return builder.endVector(); +} + +static startCharactersTypeVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(1, numElems, 1); +} + +static addCharacters(builder:flatbuffers.Builder, charactersOffset:flatbuffers.Offset) { + builder.addFieldOffset(3, charactersOffset, 0); +} + +static createCharactersVector(builder:flatbuffers.Builder, data:flatbuffers.Offset[]):flatbuffers.Offset { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]!); + } + return builder.endVector(); +} + +static startCharactersVector(builder:flatbuffers.Builder, numElems:number) { + builder.startVector(4, numElems, 4); +} + +static endMovie(builder:flatbuffers.Builder):flatbuffers.Offset { + const offset = builder.endObject(); + return offset; +} + +static finishMovieBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'MOVI'); +} + +static finishSizePrefixedMovieBuffer(builder:flatbuffers.Builder, offset:flatbuffers.Offset) { + builder.finish(offset, 'MOVI', true); +} + +static createMovie(builder:flatbuffers.Builder, mainCharacterType:Character, mainCharacterOffset:flatbuffers.Offset, charactersTypeOffset:flatbuffers.Offset, charactersOffset:flatbuffers.Offset):flatbuffers.Offset { + Movie.startMovie(builder); + Movie.addMainCharacterType(builder, mainCharacterType); + Movie.addMainCharacter(builder, mainCharacterOffset); + Movie.addCharactersType(builder, charactersTypeOffset); + Movie.addCharacters(builder, charactersOffset); + return Movie.endMovie(builder); +} + +unpack(): MovieT { + return new MovieT( + this.mainCharacterType(), + (() => { + const temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this)); + if(temp === null) { return null; } + if(typeof temp === 'string') { return temp; } + return temp.unpack() + })(), + this.bb!.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()), + (() => { + const ret: (AttackerT|BookReaderT|RapunzelT|string)[] = []; + for(let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) { + const targetEnum = this.charactersType(targetEnumIndex); + if(targetEnum === null || Character[targetEnum!] === 'NONE') { continue; } + + const temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex); + if(temp === null) { continue; } + if(typeof temp === 'string') { ret.push(temp); continue; } + ret.push(temp.unpack()); + } + return ret; + })() + ); +} + + +unpackTo(_o: MovieT): void { + _o.mainCharacterType = this.mainCharacterType(); + _o.mainCharacter = (() => { + const temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this)); + if(temp === null) { return null; } + if(typeof temp === 'string') { return temp; } + return temp.unpack() + })(); + _o.charactersType = this.bb!.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()); + _o.characters = (() => { + const ret: (AttackerT|BookReaderT|RapunzelT|string)[] = []; + for(let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) { + const targetEnum = this.charactersType(targetEnumIndex); + if(targetEnum === null || Character[targetEnum!] === 'NONE') { continue; } + + const temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex); + if(temp === null) { continue; } + if(typeof temp === 'string') { ret.push(temp); continue; } + ret.push(temp.unpack()); + } + return ret; + })(); +} +} + +export class MovieT implements flatbuffers.IGeneratedObject { +constructor( + public mainCharacterType: Character = Character.NONE, + public mainCharacter: AttackerT|BookReaderT|RapunzelT|string|null = null, + public charactersType: (Character)[] = [], + public characters: (AttackerT|BookReaderT|RapunzelT|string)[] = [] +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + const mainCharacter = builder.createObjectOffset(this.mainCharacter); + const charactersType = Movie.createCharactersTypeVector(builder, this.charactersType); + const characters = Movie.createCharactersVector(builder, builder.createObjectOffsetList(this.characters)); + + return Movie.createMovie(builder, + this.mainCharacterType, + mainCharacter, + charactersType, + characters + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/rapunzel.d.ts b/third_party/flatbuffers/tests/ts/union_vector/rapunzel.d.ts new file mode 100644 index 00000000000..c28f1b87d0d --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/rapunzel.d.ts @@ -0,0 +1,18 @@ +import * as flatbuffers from 'flatbuffers'; +export declare class Rapunzel implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer | null; + bb_pos: number; + __init(i: number, bb: flatbuffers.ByteBuffer): Rapunzel; + hairLength(): number; + mutate_hair_length(value: number): boolean; + static getFullyQualifiedName(): string; + static sizeOf(): number; + static createRapunzel(builder: flatbuffers.Builder, hair_length: number): flatbuffers.Offset; + unpack(): RapunzelT; + unpackTo(_o: RapunzelT): void; +} +export declare class RapunzelT implements flatbuffers.IGeneratedObject { + hairLength: number; + constructor(hairLength?: number); + pack(builder: flatbuffers.Builder): flatbuffers.Offset; +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/rapunzel.js b/third_party/flatbuffers/tests/ts/union_vector/rapunzel.js new file mode 100644 index 00000000000..67a5e4453b3 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/rapunzel.js @@ -0,0 +1,44 @@ +// automatically generated by the FlatBuffers compiler, do not modify +export class Rapunzel { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + hairLength() { + return this.bb.readInt32(this.bb_pos); + } + mutate_hair_length(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return 'Rapunzel'; + } + static sizeOf() { + return 4; + } + static createRapunzel(builder, hair_length) { + builder.prep(4, 4); + builder.writeInt32(hair_length); + return builder.offset(); + } + unpack() { + return new RapunzelT(this.hairLength()); + } + unpackTo(_o) { + _o.hairLength = this.hairLength(); + } +} +export class RapunzelT { + constructor(hairLength = 0) { + this.hairLength = hairLength; + } + pack(builder) { + return Rapunzel.createRapunzel(builder, this.hairLength); + } +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/rapunzel.ts b/third_party/flatbuffers/tests/ts/union_vector/rapunzel.ts new file mode 100644 index 00000000000..433106a6564 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/rapunzel.ts @@ -0,0 +1,65 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +import * as flatbuffers from 'flatbuffers'; + + + +export class Rapunzel implements flatbuffers.IUnpackableObject { + bb: flatbuffers.ByteBuffer|null = null; + bb_pos = 0; + __init(i:number, bb:flatbuffers.ByteBuffer):Rapunzel { + this.bb_pos = i; + this.bb = bb; + return this; +} + +hairLength():number { + return this.bb!.readInt32(this.bb_pos); +} + +mutate_hair_length(value:number):boolean { + this.bb!.writeInt32(this.bb_pos + 0, value); + return true; +} + +static getFullyQualifiedName():string { + return 'Rapunzel'; +} + +static sizeOf():number { + return 4; +} + +static createRapunzel(builder:flatbuffers.Builder, hair_length: number):flatbuffers.Offset { + builder.prep(4, 4); + builder.writeInt32(hair_length); + return builder.offset(); +} + + +unpack(): RapunzelT { + return new RapunzelT( + this.hairLength() + ); +} + + +unpackTo(_o: RapunzelT): void { + _o.hairLength = this.hairLength(); +} +} + +export class RapunzelT implements flatbuffers.IGeneratedObject { +constructor( + public hairLength: number = 0 +){} + + +pack(builder:flatbuffers.Builder): flatbuffers.Offset { + return Rapunzel.createRapunzel(builder, + this.hairLength + ); +} +} diff --git a/third_party/flatbuffers/tests/ts/union_vector/union_vector.d.ts b/third_party/flatbuffers/tests/ts/union_vector/union_vector.d.ts new file mode 100644 index 00000000000..ebd93797f71 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/union_vector.d.ts @@ -0,0 +1,8 @@ +export { Attacker, AttackerT } from './attacker.js'; +export { BookReader, BookReaderT } from './book-reader.js'; +export { Character } from './character.js'; +export { FallingTub, FallingTubT } from './falling-tub.js'; +export { Gadget } from './gadget.js'; +export { HandFan, HandFanT } from './hand-fan.js'; +export { Movie, MovieT } from './movie.js'; +export { Rapunzel, RapunzelT } from './rapunzel.js'; diff --git a/third_party/flatbuffers/tests/ts/union_vector/union_vector.js b/third_party/flatbuffers/tests/ts/union_vector/union_vector.js new file mode 100644 index 00000000000..63b782e7d19 --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/union_vector.js @@ -0,0 +1,10 @@ +// automatically generated by the FlatBuffers compiler, do not modify +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ +export { Attacker, AttackerT } from './attacker.js'; +export { BookReader, BookReaderT } from './book-reader.js'; +export { Character } from './character.js'; +export { FallingTub, FallingTubT } from './falling-tub.js'; +export { Gadget } from './gadget.js'; +export { HandFan, HandFanT } from './hand-fan.js'; +export { Movie, MovieT } from './movie.js'; +export { Rapunzel, RapunzelT } from './rapunzel.js'; diff --git a/third_party/flatbuffers/tests/ts/union_vector/union_vector.ts b/third_party/flatbuffers/tests/ts/union_vector/union_vector.ts new file mode 100644 index 00000000000..d6e0b608e1e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/union_vector.ts @@ -0,0 +1,12 @@ +// automatically generated by the FlatBuffers compiler, do not modify + +/* eslint-disable @typescript-eslint/no-unused-vars, @typescript-eslint/no-explicit-any, @typescript-eslint/no-non-null-assertion */ + +export { Attacker, AttackerT } from './attacker.js'; +export { BookReader, BookReaderT } from './book-reader.js'; +export { Character } from './character.js'; +export { FallingTub, FallingTubT } from './falling-tub.js'; +export { Gadget } from './gadget.js'; +export { HandFan, HandFanT } from './hand-fan.js'; +export { Movie, MovieT } from './movie.js'; +export { Rapunzel, RapunzelT } from './rapunzel.js'; diff --git a/third_party/flatbuffers/tests/ts/union_vector/union_vector_generated.cjs b/third_party/flatbuffers/tests/ts/union_vector/union_vector_generated.cjs new file mode 100644 index 00000000000..3144fdaa16e --- /dev/null +++ b/third_party/flatbuffers/tests/ts/union_vector/union_vector_generated.cjs @@ -0,0 +1,558 @@ +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// union_vector/union_vector.ts +var union_vector_exports = {}; +__export(union_vector_exports, { + Attacker: () => Attacker, + AttackerT: () => AttackerT, + BookReader: () => BookReader, + BookReaderT: () => BookReaderT, + Character: () => Character, + FallingTub: () => FallingTub, + FallingTubT: () => FallingTubT, + Gadget: () => Gadget, + HandFan: () => HandFan, + HandFanT: () => HandFanT, + Movie: () => Movie, + MovieT: () => MovieT, + Rapunzel: () => Rapunzel, + RapunzelT: () => RapunzelT +}); +module.exports = __toCommonJS(union_vector_exports); + +// union_vector/attacker.js +var flatbuffers = __toESM(require("flatbuffers"), 1); +var Attacker = class _Attacker { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsAttacker(bb, obj) { + return (obj || new _Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsAttacker(bb, obj) { + bb.setPosition(bb.position() + flatbuffers.SIZE_PREFIX_LENGTH); + return (obj || new _Attacker()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + swordAttackDamage() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_sword_attack_damage(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "Attacker"; + } + static startAttacker(builder) { + builder.startObject(1); + } + static addSwordAttackDamage(builder, swordAttackDamage) { + builder.addFieldInt32(0, swordAttackDamage, 0); + } + static endAttacker(builder) { + const offset = builder.endObject(); + return offset; + } + static createAttacker(builder, swordAttackDamage) { + _Attacker.startAttacker(builder); + _Attacker.addSwordAttackDamage(builder, swordAttackDamage); + return _Attacker.endAttacker(builder); + } + unpack() { + return new AttackerT(this.swordAttackDamage()); + } + unpackTo(_o) { + _o.swordAttackDamage = this.swordAttackDamage(); + } +}; +var AttackerT = class { + constructor(swordAttackDamage = 0) { + this.swordAttackDamage = swordAttackDamage; + } + pack(builder) { + return Attacker.createAttacker(builder, this.swordAttackDamage); + } +}; + +// union_vector/book-reader.js +var BookReader = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + booksRead() { + return this.bb.readInt32(this.bb_pos); + } + mutate_books_read(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return "BookReader"; + } + static sizeOf() { + return 4; + } + static createBookReader(builder, books_read) { + builder.prep(4, 4); + builder.writeInt32(books_read); + return builder.offset(); + } + unpack() { + return new BookReaderT(this.booksRead()); + } + unpackTo(_o) { + _o.booksRead = this.booksRead(); + } +}; +var BookReaderT = class { + constructor(booksRead = 0) { + this.booksRead = booksRead; + } + pack(builder) { + return BookReader.createBookReader(builder, this.booksRead); + } +}; + +// union_vector/rapunzel.js +var Rapunzel = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + hairLength() { + return this.bb.readInt32(this.bb_pos); + } + mutate_hair_length(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return "Rapunzel"; + } + static sizeOf() { + return 4; + } + static createRapunzel(builder, hair_length) { + builder.prep(4, 4); + builder.writeInt32(hair_length); + return builder.offset(); + } + unpack() { + return new RapunzelT(this.hairLength()); + } + unpackTo(_o) { + _o.hairLength = this.hairLength(); + } +}; +var RapunzelT = class { + constructor(hairLength = 0) { + this.hairLength = hairLength; + } + pack(builder) { + return Rapunzel.createRapunzel(builder, this.hairLength); + } +}; + +// union_vector/character.js +var Character; +(function(Character2) { + Character2[Character2["NONE"] = 0] = "NONE"; + Character2[Character2["MuLan"] = 1] = "MuLan"; + Character2[Character2["Rapunzel"] = 2] = "Rapunzel"; + Character2[Character2["Belle"] = 3] = "Belle"; + Character2[Character2["BookFan"] = 4] = "BookFan"; + Character2[Character2["Other"] = 5] = "Other"; + Character2[Character2["Unused"] = 6] = "Unused"; +})(Character || (Character = {})); +function unionToCharacter(type, accessor) { + switch (Character[type]) { + case "NONE": + return null; + case "MuLan": + return accessor(new Attacker()); + case "Rapunzel": + return accessor(new Rapunzel()); + case "Belle": + return accessor(new BookReader()); + case "BookFan": + return accessor(new BookReader()); + case "Other": + return accessor(""); + case "Unused": + return accessor(""); + default: + return null; + } +} +function unionListToCharacter(type, accessor, index) { + switch (Character[type]) { + case "NONE": + return null; + case "MuLan": + return accessor(index, new Attacker()); + case "Rapunzel": + return accessor(index, new Rapunzel()); + case "Belle": + return accessor(index, new BookReader()); + case "BookFan": + return accessor(index, new BookReader()); + case "Other": + return accessor(index, ""); + case "Unused": + return accessor(index, ""); + default: + return null; + } +} + +// union_vector/falling-tub.js +var FallingTub = class { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + weight() { + return this.bb.readInt32(this.bb_pos); + } + mutate_weight(value) { + this.bb.writeInt32(this.bb_pos + 0, value); + return true; + } + static getFullyQualifiedName() { + return "FallingTub"; + } + static sizeOf() { + return 4; + } + static createFallingTub(builder, weight) { + builder.prep(4, 4); + builder.writeInt32(weight); + return builder.offset(); + } + unpack() { + return new FallingTubT(this.weight()); + } + unpackTo(_o) { + _o.weight = this.weight(); + } +}; +var FallingTubT = class { + constructor(weight = 0) { + this.weight = weight; + } + pack(builder) { + return FallingTub.createFallingTub(builder, this.weight); + } +}; + +// union_vector/hand-fan.js +var flatbuffers2 = __toESM(require("flatbuffers"), 1); +var HandFan = class _HandFan { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsHandFan(bb, obj) { + return (obj || new _HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsHandFan(bb, obj) { + bb.setPosition(bb.position() + flatbuffers2.SIZE_PREFIX_LENGTH); + return (obj || new _HandFan()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + length() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readInt32(this.bb_pos + offset) : 0; + } + mutate_length(value) { + const offset = this.bb.__offset(this.bb_pos, 4); + if (offset === 0) { + return false; + } + this.bb.writeInt32(this.bb_pos + offset, value); + return true; + } + static getFullyQualifiedName() { + return "HandFan"; + } + static startHandFan(builder) { + builder.startObject(1); + } + static addLength(builder, length) { + builder.addFieldInt32(0, length, 0); + } + static endHandFan(builder) { + const offset = builder.endObject(); + return offset; + } + static createHandFan(builder, length) { + _HandFan.startHandFan(builder); + _HandFan.addLength(builder, length); + return _HandFan.endHandFan(builder); + } + unpack() { + return new HandFanT(this.length()); + } + unpackTo(_o) { + _o.length = this.length(); + } +}; +var HandFanT = class { + constructor(length = 0) { + this.length = length; + } + pack(builder) { + return HandFan.createHandFan(builder, this.length); + } +}; + +// union_vector/gadget.js +var Gadget; +(function(Gadget2) { + Gadget2[Gadget2["NONE"] = 0] = "NONE"; + Gadget2[Gadget2["FallingTub"] = 1] = "FallingTub"; + Gadget2[Gadget2["HandFan"] = 2] = "HandFan"; +})(Gadget || (Gadget = {})); + +// union_vector/movie.js +var flatbuffers3 = __toESM(require("flatbuffers"), 1); +var Movie = class _Movie { + constructor() { + this.bb = null; + this.bb_pos = 0; + } + __init(i, bb) { + this.bb_pos = i; + this.bb = bb; + return this; + } + static getRootAsMovie(bb, obj) { + return (obj || new _Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static getSizePrefixedRootAsMovie(bb, obj) { + bb.setPosition(bb.position() + flatbuffers3.SIZE_PREFIX_LENGTH); + return (obj || new _Movie()).__init(bb.readInt32(bb.position()) + bb.position(), bb); + } + static bufferHasIdentifier(bb) { + return bb.__has_identifier("MOVI"); + } + mainCharacterType() { + const offset = this.bb.__offset(this.bb_pos, 4); + return offset ? this.bb.readUint8(this.bb_pos + offset) : Character.NONE; + } + mainCharacter(obj) { + const offset = this.bb.__offset(this.bb_pos, 6); + return offset ? this.bb.__union_with_string(obj, this.bb_pos + offset) : null; + } + charactersType(index) { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.readUint8(this.bb.__vector(this.bb_pos + offset) + index) : 0; + } + charactersTypeLength() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + charactersTypeArray() { + const offset = this.bb.__offset(this.bb_pos, 8); + return offset ? new Uint8Array(this.bb.bytes().buffer, this.bb.bytes().byteOffset + this.bb.__vector(this.bb_pos + offset), this.bb.__vector_len(this.bb_pos + offset)) : null; + } + characters(index, obj) { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__union_with_string(obj, this.bb.__vector(this.bb_pos + offset) + index * 4) : null; + } + charactersLength() { + const offset = this.bb.__offset(this.bb_pos, 10); + return offset ? this.bb.__vector_len(this.bb_pos + offset) : 0; + } + static getFullyQualifiedName() { + return "Movie"; + } + static startMovie(builder) { + builder.startObject(4); + } + static addMainCharacterType(builder, mainCharacterType) { + builder.addFieldInt8(0, mainCharacterType, Character.NONE); + } + static addMainCharacter(builder, mainCharacterOffset) { + builder.addFieldOffset(1, mainCharacterOffset, 0); + } + static addCharactersType(builder, charactersTypeOffset) { + builder.addFieldOffset(2, charactersTypeOffset, 0); + } + static createCharactersTypeVector(builder, data) { + builder.startVector(1, data.length, 1); + for (let i = data.length - 1; i >= 0; i--) { + builder.addInt8(data[i]); + } + return builder.endVector(); + } + static startCharactersTypeVector(builder, numElems) { + builder.startVector(1, numElems, 1); + } + static addCharacters(builder, charactersOffset) { + builder.addFieldOffset(3, charactersOffset, 0); + } + static createCharactersVector(builder, data) { + builder.startVector(4, data.length, 4); + for (let i = data.length - 1; i >= 0; i--) { + builder.addOffset(data[i]); + } + return builder.endVector(); + } + static startCharactersVector(builder, numElems) { + builder.startVector(4, numElems, 4); + } + static endMovie(builder) { + const offset = builder.endObject(); + return offset; + } + static finishMovieBuffer(builder, offset) { + builder.finish(offset, "MOVI"); + } + static finishSizePrefixedMovieBuffer(builder, offset) { + builder.finish(offset, "MOVI", true); + } + static createMovie(builder, mainCharacterType, mainCharacterOffset, charactersTypeOffset, charactersOffset) { + _Movie.startMovie(builder); + _Movie.addMainCharacterType(builder, mainCharacterType); + _Movie.addMainCharacter(builder, mainCharacterOffset); + _Movie.addCharactersType(builder, charactersTypeOffset); + _Movie.addCharacters(builder, charactersOffset); + return _Movie.endMovie(builder); + } + unpack() { + return new MovieT(this.mainCharacterType(), (() => { + const temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this)); + if (temp === null) { + return null; + } + if (typeof temp === "string") { + return temp; + } + return temp.unpack(); + })(), this.bb.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()), (() => { + const ret = []; + for (let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) { + const targetEnum = this.charactersType(targetEnumIndex); + if (targetEnum === null || Character[targetEnum] === "NONE") { + continue; + } + const temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex); + if (temp === null) { + continue; + } + if (typeof temp === "string") { + ret.push(temp); + continue; + } + ret.push(temp.unpack()); + } + return ret; + })()); + } + unpackTo(_o) { + _o.mainCharacterType = this.mainCharacterType(); + _o.mainCharacter = (() => { + const temp = unionToCharacter(this.mainCharacterType(), this.mainCharacter.bind(this)); + if (temp === null) { + return null; + } + if (typeof temp === "string") { + return temp; + } + return temp.unpack(); + })(); + _o.charactersType = this.bb.createScalarList(this.charactersType.bind(this), this.charactersTypeLength()); + _o.characters = (() => { + const ret = []; + for (let targetEnumIndex = 0; targetEnumIndex < this.charactersTypeLength(); ++targetEnumIndex) { + const targetEnum = this.charactersType(targetEnumIndex); + if (targetEnum === null || Character[targetEnum] === "NONE") { + continue; + } + const temp = unionListToCharacter(targetEnum, this.characters.bind(this), targetEnumIndex); + if (temp === null) { + continue; + } + if (typeof temp === "string") { + ret.push(temp); + continue; + } + ret.push(temp.unpack()); + } + return ret; + })(); + } +}; +var MovieT = class { + constructor(mainCharacterType = Character.NONE, mainCharacter = null, charactersType = [], characters = []) { + this.mainCharacterType = mainCharacterType; + this.mainCharacter = mainCharacter; + this.charactersType = charactersType; + this.characters = characters; + } + pack(builder) { + const mainCharacter = builder.createObjectOffset(this.mainCharacter); + const charactersType = Movie.createCharactersTypeVector(builder, this.charactersType); + const characters = Movie.createCharactersVector(builder, builder.createObjectOffsetList(this.characters)); + return Movie.createMovie(builder, this.mainCharacterType, mainCharacter, charactersType, characters); + } +}; diff --git a/third_party/flatbuffers/tests/type_field_collsion.fbs b/third_party/flatbuffers/tests/type_field_collsion.fbs new file mode 100644 index 00000000000..ec7354428b9 --- /dev/null +++ b/third_party/flatbuffers/tests/type_field_collsion.fbs @@ -0,0 +1,8 @@ +namespace type_field_collsion; + +// This table tests collsions of identifiers. +table Collision { + collision : int; +} + +root_type Collision; diff --git a/third_party/flatbuffers/tests/type_field_collsion/Collision.cs b/third_party/flatbuffers/tests/type_field_collsion/Collision.cs new file mode 100644 index 00000000000..0f060191fd5 --- /dev/null +++ b/third_party/flatbuffers/tests/type_field_collsion/Collision.cs @@ -0,0 +1,84 @@ +// +// automatically generated by the FlatBuffers compiler, do not modify +// + +namespace type_field_collsion +{ + +using global::System; +using global::System.Collections.Generic; +using global::Google.FlatBuffers; + +public struct Collision : IFlatbufferObject +{ + private Table __p; + public ByteBuffer ByteBuffer { get { return __p.bb; } } + public static void ValidateVersion() { FlatBufferConstants.FLATBUFFERS_25_2_10(); } + public static Collision GetRootAsCollision(ByteBuffer _bb) { return GetRootAsCollision(_bb, new Collision()); } + public static Collision GetRootAsCollision(ByteBuffer _bb, Collision obj) { return (obj.__assign(_bb.GetInt(_bb.Position) + _bb.Position, _bb)); } + public static bool VerifyCollision(ByteBuffer _bb) {Google.FlatBuffers.Verifier verifier = new Google.FlatBuffers.Verifier(_bb); return verifier.VerifyBuffer("", false, CollisionVerify.Verify); } + public void __init(int _i, ByteBuffer _bb) { __p = new Table(_i, _bb); } + public Collision __assign(int _i, ByteBuffer _bb) { __init(_i, _bb); return this; } + + public int Collision_ { get { int o = __p.__offset(4); return o != 0 ? __p.bb.GetInt(o + __p.bb_pos) : (int)0; } } + + public static Offset CreateCollision(FlatBufferBuilder builder, + int collision = 0) { + builder.StartTable(1); + Collision.AddCollision(builder, collision); + return Collision.EndCollision(builder); + } + + public static void StartCollision(FlatBufferBuilder builder) { builder.StartTable(1); } + public static void AddCollision(FlatBufferBuilder builder, int collision) { builder.AddInt(0, collision, 0); } + public static Offset EndCollision(FlatBufferBuilder builder) { + int o = builder.EndTable(); + return new Offset(o); + } + public static void FinishCollisionBuffer(FlatBufferBuilder builder, Offset offset) { builder.Finish(offset.Value); } + public static void FinishSizePrefixedCollisionBuffer(FlatBufferBuilder builder, Offset offset) { builder.FinishSizePrefixed(offset.Value); } + public CollisionT UnPack() { + var _o = new CollisionT(); + this.UnPackTo(_o); + return _o; + } + public void UnPackTo(CollisionT _o) { + _o.Collision_ = this.Collision_; + } + public static Offset Pack(FlatBufferBuilder builder, CollisionT _o) { + if (_o == null) return default(Offset); + return CreateCollision( + builder, + _o.Collision_); + } +} + +public class CollisionT +{ + public int Collision_ { get; set; } + + public CollisionT() { + this.Collision_ = 0; + } + public static CollisionT DeserializeFromBinary(byte[] fbBuffer) { + return Collision.GetRootAsCollision(new ByteBuffer(fbBuffer)).UnPack(); + } + public byte[] SerializeToBinary() { + var fbb = new FlatBufferBuilder(0x10000); + Collision.FinishCollisionBuffer(fbb, Collision.Pack(fbb, this)); + return fbb.DataBuffer.ToSizedArray(); + } +} + + +static public class CollisionVerify +{ + static public bool Verify(Google.FlatBuffers.Verifier verifier, uint tablePos) + { + return verifier.VerifyTableStart(tablePos) + && verifier.VerifyField(tablePos, 4 /*Collision*/, 4 /*int*/, 4, false) + && verifier.VerifyTableEnd(tablePos); + } +} + +} diff --git a/third_party/flatbuffers/tests/unicode_test.json b/third_party/flatbuffers/tests/unicode_test.json new file mode 100644 index 00000000000..7bd267121d2 --- /dev/null +++ b/third_party/flatbuffers/tests/unicode_test.json @@ -0,0 +1,31 @@ +{ + "name": "unicode_test", + "testarrayofstring": [ + "Цлїςσδε", + "フムアムカモケモ", + "フムヤムカモケモ", + "㊀㊁㊂㊃㊄", + "☳☶☲", + "𡇙𝌆" + ], + "testarrayoftables": [ + { + "name": "Цлїςσδε" + }, + { + "name": "☳☶☲" + }, + { + "name": "フムヤムカモケモ" + }, + { + "name": "㊀㊁㊂㊃㊄" + }, + { + "name": "フムアムカモケモ" + }, + { + "name": "𡇙𝌆" + } + ] +} diff --git a/third_party/flatbuffers/tests/unicode_test.mon b/third_party/flatbuffers/tests/unicode_test.mon new file mode 100644 index 00000000000..14f5fb4d266 Binary files /dev/null and b/third_party/flatbuffers/tests/unicode_test.mon differ diff --git a/third_party/flatbuffers/tests/union_underlying_type_test.fbs b/third_party/flatbuffers/tests/union_underlying_type_test.fbs new file mode 100644 index 00000000000..2f4ed12e2d6 --- /dev/null +++ b/third_party/flatbuffers/tests/union_underlying_type_test.fbs @@ -0,0 +1,17 @@ + +namespace UnionUnderlyingType; + +table A { + a: int; +} +table B { + b: string; +} +table C { + c: bool; +} +union ABC: int { A = 555, B = 666, C = 777} +table D { + test_union: ABC; + test_vector_of_union: [ABC]; +} diff --git a/third_party/flatbuffers/tests/union_underlying_type_test_generated.h b/third_party/flatbuffers/tests/union_underlying_type_test_generated.h new file mode 100644 index 00000000000..03d2ff7da70 --- /dev/null +++ b/third_party/flatbuffers/tests/union_underlying_type_test_generated.h @@ -0,0 +1,880 @@ +// automatically generated by the FlatBuffers compiler, do not modify + + +#ifndef FLATBUFFERS_GENERATED_UNIONUNDERLYINGTYPETEST_UNIONUNDERLYINGTYPE_H_ +#define FLATBUFFERS_GENERATED_UNIONUNDERLYINGTYPETEST_UNIONUNDERLYINGTYPE_H_ + +#include "flatbuffers/flatbuffers.h" + +// Ensure the included flatbuffers.h is the same version as when this file was +// generated, otherwise it may not be compatible. +static_assert(FLATBUFFERS_VERSION_MAJOR == 25 && + FLATBUFFERS_VERSION_MINOR == 2 && + FLATBUFFERS_VERSION_REVISION == 10, + "Non-compatible flatbuffers version included"); + +namespace UnionUnderlyingType { + +struct A; +struct ABuilder; +struct AT; + +struct B; +struct BBuilder; +struct BT; + +struct C; +struct CBuilder; +struct CT; + +struct D; +struct DBuilder; +struct DT; + +bool operator==(const AT &lhs, const AT &rhs); +bool operator!=(const AT &lhs, const AT &rhs); +bool operator==(const BT &lhs, const BT &rhs); +bool operator!=(const BT &lhs, const BT &rhs); +bool operator==(const CT &lhs, const CT &rhs); +bool operator!=(const CT &lhs, const CT &rhs); +bool operator==(const DT &lhs, const DT &rhs); +bool operator!=(const DT &lhs, const DT &rhs); + +inline const ::flatbuffers::TypeTable *ATypeTable(); + +inline const ::flatbuffers::TypeTable *BTypeTable(); + +inline const ::flatbuffers::TypeTable *CTypeTable(); + +inline const ::flatbuffers::TypeTable *DTypeTable(); + +enum class ABC : int32_t { + NONE = 0, + A = 555, + B = 666, + C = 777, + MIN = NONE, + MAX = C +}; + +inline const ABC (&EnumValuesABC())[4] { + static const ABC values[] = { + ABC::NONE, + ABC::A, + ABC::B, + ABC::C + }; + return values; +} + +inline const char *EnumNameABC(ABC e) { + switch (e) { + case ABC::NONE: return "NONE"; + case ABC::A: return "A"; + case ABC::B: return "B"; + case ABC::C: return "C"; + default: return ""; + } +} + +template struct ABCTraits { + static const ABC enum_value = ABC::NONE; +}; + +template<> struct ABCTraits { + static const ABC enum_value = ABC::A; +}; + +template<> struct ABCTraits { + static const ABC enum_value = ABC::B; +}; + +template<> struct ABCTraits { + static const ABC enum_value = ABC::C; +}; + +template struct ABCUnionTraits { + static const ABC enum_value = ABC::NONE; +}; + +template<> struct ABCUnionTraits { + static const ABC enum_value = ABC::A; +}; + +template<> struct ABCUnionTraits { + static const ABC enum_value = ABC::B; +}; + +template<> struct ABCUnionTraits { + static const ABC enum_value = ABC::C; +}; + +struct ABCUnion { + ABC type; + void *value; + + ABCUnion() : type(ABC::NONE), value(nullptr) {} + ABCUnion(ABCUnion&& u) FLATBUFFERS_NOEXCEPT : + type(ABC::NONE), value(nullptr) + { std::swap(type, u.type); std::swap(value, u.value); } + ABCUnion(const ABCUnion &); + ABCUnion &operator=(const ABCUnion &u) + { ABCUnion t(u); std::swap(type, t.type); std::swap(value, t.value); return *this; } + ABCUnion &operator=(ABCUnion &&u) FLATBUFFERS_NOEXCEPT + { std::swap(type, u.type); std::swap(value, u.value); return *this; } + ~ABCUnion() { Reset(); } + + void Reset(); + + template + void Set(T&& val) { + typedef typename std::remove_reference::type RT; + Reset(); + type = ABCUnionTraits::enum_value; + if (type != ABC::NONE) { + value = new RT(std::forward(val)); + } + } + + static void *UnPack(const void *obj, ABC type, const ::flatbuffers::resolver_function_t *resolver); + ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr) const; + + UnionUnderlyingType::AT *AsA() { + return type == ABC::A ? + reinterpret_cast(value) : nullptr; + } + const UnionUnderlyingType::AT *AsA() const { + return type == ABC::A ? + reinterpret_cast(value) : nullptr; + } + UnionUnderlyingType::BT *AsB() { + return type == ABC::B ? + reinterpret_cast(value) : nullptr; + } + const UnionUnderlyingType::BT *AsB() const { + return type == ABC::B ? + reinterpret_cast(value) : nullptr; + } + UnionUnderlyingType::CT *AsC() { + return type == ABC::C ? + reinterpret_cast(value) : nullptr; + } + const UnionUnderlyingType::CT *AsC() const { + return type == ABC::C ? + reinterpret_cast(value) : nullptr; + } +}; + + +inline bool operator==(const ABCUnion &lhs, const ABCUnion &rhs) { + if (lhs.type != rhs.type) return false; + switch (lhs.type) { + case ABC::NONE: { + return true; + } + case ABC::A: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case ABC::B: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + case ABC::C: { + return *(reinterpret_cast(lhs.value)) == + *(reinterpret_cast(rhs.value)); + } + default: { + return false; + } + } +} + +inline bool operator!=(const ABCUnion &lhs, const ABCUnion &rhs) { + return !(lhs == rhs); +} + +bool VerifyABC(::flatbuffers::Verifier &verifier, const void *obj, ABC type); +bool VerifyABCVector(::flatbuffers::Verifier &verifier, const ::flatbuffers::Vector<::flatbuffers::Offset> *values, const ::flatbuffers::Vector *types); + +struct AT : public ::flatbuffers::NativeTable { + typedef A TableType; + int32_t a = 0; +}; + +struct A FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef AT NativeTableType; + typedef ABuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return ATypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_A = 4 + }; + int32_t a() const { + return GetField(VT_A, 0); + } + bool mutate_a(int32_t _a = 0) { + return SetField(VT_A, _a, 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_A, 4) && + verifier.EndTable(); + } + AT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(AT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const AT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct ABuilder { + typedef A Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_a(int32_t a) { + fbb_.AddElement(A::VT_A, a, 0); + } + explicit ABuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateA( + ::flatbuffers::FlatBufferBuilder &_fbb, + int32_t a = 0) { + ABuilder builder_(_fbb); + builder_.add_a(a); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateA(::flatbuffers::FlatBufferBuilder &_fbb, const AT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct BT : public ::flatbuffers::NativeTable { + typedef B TableType; + std::string b{}; +}; + +struct B FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef BT NativeTableType; + typedef BBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return BTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_B = 4 + }; + const ::flatbuffers::String *b() const { + return GetPointer(VT_B); + } + ::flatbuffers::String *mutable_b() { + return GetPointer<::flatbuffers::String *>(VT_B); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyOffset(verifier, VT_B) && + verifier.VerifyString(b()) && + verifier.EndTable(); + } + BT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(BT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const BT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct BBuilder { + typedef B Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_b(::flatbuffers::Offset<::flatbuffers::String> b) { + fbb_.AddOffset(B::VT_B, b); + } + explicit BBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateB( + ::flatbuffers::FlatBufferBuilder &_fbb, + ::flatbuffers::Offset<::flatbuffers::String> b = 0) { + BBuilder builder_(_fbb); + builder_.add_b(b); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateBDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + const char *b = nullptr) { + auto b__ = b ? _fbb.CreateString(b) : 0; + return UnionUnderlyingType::CreateB( + _fbb, + b__); +} + +::flatbuffers::Offset CreateB(::flatbuffers::FlatBufferBuilder &_fbb, const BT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct CT : public ::flatbuffers::NativeTable { + typedef C TableType; + bool c = false; +}; + +struct C FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef CT NativeTableType; + typedef CBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return CTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_C = 4 + }; + bool c() const { + return GetField(VT_C, 0) != 0; + } + bool mutate_c(bool _c = 0) { + return SetField(VT_C, static_cast(_c), 0); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_C, 1) && + verifier.EndTable(); + } + CT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(CT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const CT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +struct CBuilder { + typedef C Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_c(bool c) { + fbb_.AddElement(C::VT_C, static_cast(c), 0); + } + explicit CBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateC( + ::flatbuffers::FlatBufferBuilder &_fbb, + bool c = false) { + CBuilder builder_(_fbb); + builder_.add_c(c); + return builder_.Finish(); +} + +::flatbuffers::Offset CreateC(::flatbuffers::FlatBufferBuilder &_fbb, const CT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + +struct DT : public ::flatbuffers::NativeTable { + typedef D TableType; + UnionUnderlyingType::ABCUnion test_union{}; + std::vector test_vector_of_union{}; +}; + +struct D FLATBUFFERS_FINAL_CLASS : private ::flatbuffers::Table { + typedef DT NativeTableType; + typedef DBuilder Builder; + static const ::flatbuffers::TypeTable *MiniReflectTypeTable() { + return DTypeTable(); + } + enum FlatBuffersVTableOffset FLATBUFFERS_VTABLE_UNDERLYING_TYPE { + VT_TEST_UNION_TYPE = 4, + VT_TEST_UNION = 6, + VT_TEST_VECTOR_OF_UNION_TYPE = 8, + VT_TEST_VECTOR_OF_UNION = 10 + }; + UnionUnderlyingType::ABC test_union_type() const { + return static_cast(GetField(VT_TEST_UNION_TYPE, 0)); + } + const void *test_union() const { + return GetPointer(VT_TEST_UNION); + } + template const T *test_union_as() const; + const UnionUnderlyingType::A *test_union_as_A() const { + return test_union_type() == UnionUnderlyingType::ABC::A ? static_cast(test_union()) : nullptr; + } + const UnionUnderlyingType::B *test_union_as_B() const { + return test_union_type() == UnionUnderlyingType::ABC::B ? static_cast(test_union()) : nullptr; + } + const UnionUnderlyingType::C *test_union_as_C() const { + return test_union_type() == UnionUnderlyingType::ABC::C ? static_cast(test_union()) : nullptr; + } + void *mutable_test_union() { + return GetPointer(VT_TEST_UNION); + } + const ::flatbuffers::Vector *test_vector_of_union_type() const { + return GetPointer *>(VT_TEST_VECTOR_OF_UNION_TYPE); + } + ::flatbuffers::Vector *mutable_test_vector_of_union_type() { + return GetPointer<::flatbuffers::Vector *>(VT_TEST_VECTOR_OF_UNION_TYPE); + } + const ::flatbuffers::Vector<::flatbuffers::Offset> *test_vector_of_union() const { + return GetPointer> *>(VT_TEST_VECTOR_OF_UNION); + } + ::flatbuffers::Vector<::flatbuffers::Offset> *mutable_test_vector_of_union() { + return GetPointer<::flatbuffers::Vector<::flatbuffers::Offset> *>(VT_TEST_VECTOR_OF_UNION); + } + bool Verify(::flatbuffers::Verifier &verifier) const { + return VerifyTableStart(verifier) && + VerifyField(verifier, VT_TEST_UNION_TYPE, 1) && + VerifyOffset(verifier, VT_TEST_UNION) && + VerifyABC(verifier, test_union(), test_union_type()) && + VerifyOffset(verifier, VT_TEST_VECTOR_OF_UNION_TYPE) && + verifier.VerifyVector(test_vector_of_union_type()) && + VerifyOffset(verifier, VT_TEST_VECTOR_OF_UNION) && + verifier.VerifyVector(test_vector_of_union()) && + VerifyABCVector(verifier, test_vector_of_union(), test_vector_of_union_type()) && + verifier.EndTable(); + } + DT *UnPack(const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + void UnPackTo(DT *_o, const ::flatbuffers::resolver_function_t *_resolver = nullptr) const; + static ::flatbuffers::Offset Pack(::flatbuffers::FlatBufferBuilder &_fbb, const DT* _o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); +}; + +template<> inline const UnionUnderlyingType::A *D::test_union_as() const { + return test_union_as_A(); +} + +template<> inline const UnionUnderlyingType::B *D::test_union_as() const { + return test_union_as_B(); +} + +template<> inline const UnionUnderlyingType::C *D::test_union_as() const { + return test_union_as_C(); +} + +struct DBuilder { + typedef D Table; + ::flatbuffers::FlatBufferBuilder &fbb_; + ::flatbuffers::uoffset_t start_; + void add_test_union_type(UnionUnderlyingType::ABC test_union_type) { + fbb_.AddElement(D::VT_TEST_UNION_TYPE, static_cast(test_union_type), 0); + } + void add_test_union(::flatbuffers::Offset test_union) { + fbb_.AddOffset(D::VT_TEST_UNION, test_union); + } + void add_test_vector_of_union_type(::flatbuffers::Offset<::flatbuffers::Vector> test_vector_of_union_type) { + fbb_.AddOffset(D::VT_TEST_VECTOR_OF_UNION_TYPE, test_vector_of_union_type); + } + void add_test_vector_of_union(::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> test_vector_of_union) { + fbb_.AddOffset(D::VT_TEST_VECTOR_OF_UNION, test_vector_of_union); + } + explicit DBuilder(::flatbuffers::FlatBufferBuilder &_fbb) + : fbb_(_fbb) { + start_ = fbb_.StartTable(); + } + ::flatbuffers::Offset Finish() { + const auto end = fbb_.EndTable(start_); + auto o = ::flatbuffers::Offset(end); + return o; + } +}; + +inline ::flatbuffers::Offset CreateD( + ::flatbuffers::FlatBufferBuilder &_fbb, + UnionUnderlyingType::ABC test_union_type = UnionUnderlyingType::ABC::NONE, + ::flatbuffers::Offset test_union = 0, + ::flatbuffers::Offset<::flatbuffers::Vector> test_vector_of_union_type = 0, + ::flatbuffers::Offset<::flatbuffers::Vector<::flatbuffers::Offset>> test_vector_of_union = 0) { + DBuilder builder_(_fbb); + builder_.add_test_vector_of_union(test_vector_of_union); + builder_.add_test_vector_of_union_type(test_vector_of_union_type); + builder_.add_test_union(test_union); + builder_.add_test_union_type(test_union_type); + return builder_.Finish(); +} + +inline ::flatbuffers::Offset CreateDDirect( + ::flatbuffers::FlatBufferBuilder &_fbb, + UnionUnderlyingType::ABC test_union_type = UnionUnderlyingType::ABC::NONE, + ::flatbuffers::Offset test_union = 0, + const std::vector *test_vector_of_union_type = nullptr, + const std::vector<::flatbuffers::Offset> *test_vector_of_union = nullptr) { + auto test_vector_of_union_type__ = test_vector_of_union_type ? _fbb.CreateVector(*test_vector_of_union_type) : 0; + auto test_vector_of_union__ = test_vector_of_union ? _fbb.CreateVector<::flatbuffers::Offset>(*test_vector_of_union) : 0; + return UnionUnderlyingType::CreateD( + _fbb, + test_union_type, + test_union, + test_vector_of_union_type__, + test_vector_of_union__); +} + +::flatbuffers::Offset CreateD(::flatbuffers::FlatBufferBuilder &_fbb, const DT *_o, const ::flatbuffers::rehasher_function_t *_rehasher = nullptr); + + +inline bool operator==(const AT &lhs, const AT &rhs) { + return + (lhs.a == rhs.a); +} + +inline bool operator!=(const AT &lhs, const AT &rhs) { + return !(lhs == rhs); +} + + +inline AT *A::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new AT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void A::UnPackTo(AT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = a(); _o->a = _e; } +} + +inline ::flatbuffers::Offset A::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const AT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateA(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateA(::flatbuffers::FlatBufferBuilder &_fbb, const AT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const AT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _a = _o->a; + return UnionUnderlyingType::CreateA( + _fbb, + _a); +} + + +inline bool operator==(const BT &lhs, const BT &rhs) { + return + (lhs.b == rhs.b); +} + +inline bool operator!=(const BT &lhs, const BT &rhs) { + return !(lhs == rhs); +} + + +inline BT *B::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new BT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void B::UnPackTo(BT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = b(); if (_e) _o->b = _e->str(); } +} + +inline ::flatbuffers::Offset B::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const BT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateB(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateB(::flatbuffers::FlatBufferBuilder &_fbb, const BT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const BT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _b = _o->b.empty() ? 0 : _fbb.CreateString(_o->b); + return UnionUnderlyingType::CreateB( + _fbb, + _b); +} + + +inline bool operator==(const CT &lhs, const CT &rhs) { + return + (lhs.c == rhs.c); +} + +inline bool operator!=(const CT &lhs, const CT &rhs) { + return !(lhs == rhs); +} + + +inline CT *C::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr(new CT()); + UnPackTo(_o.get(), _resolver); + return _o.release(); +} + +inline void C::UnPackTo(CT *_o, const ::flatbuffers::resolver_function_t *_resolver) const { + (void)_o; + (void)_resolver; + { auto _e = c(); _o->c = _e; } +} + +inline ::flatbuffers::Offset C::Pack(::flatbuffers::FlatBufferBuilder &_fbb, const CT* _o, const ::flatbuffers::rehasher_function_t *_rehasher) { + return CreateC(_fbb, _o, _rehasher); +} + +inline ::flatbuffers::Offset CreateC(::flatbuffers::FlatBufferBuilder &_fbb, const CT *_o, const ::flatbuffers::rehasher_function_t *_rehasher) { + (void)_rehasher; + (void)_o; + struct _VectorArgs { ::flatbuffers::FlatBufferBuilder *__fbb; const CT* __o; const ::flatbuffers::rehasher_function_t *__rehasher; } _va = { &_fbb, _o, _rehasher}; (void)_va; + auto _c = _o->c; + return UnionUnderlyingType::CreateC( + _fbb, + _c); +} + + +inline bool operator==(const DT &lhs, const DT &rhs) { + return + (lhs.test_union == rhs.test_union) && + (lhs.test_vector_of_union == rhs.test_vector_of_union); +} + +inline bool operator!=(const DT &lhs, const DT &rhs) { + return !(lhs == rhs); +} + + +inline DT *D::UnPack(const ::flatbuffers::resolver_function_t *_resolver) const { + auto _o = std::unique_ptr